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.

281316 lines
7.6MB

  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. #elif defined (JUCE_ANDROID)
  55. #undef JUCE_ANDROID
  56. #define JUCE_ANDROID 1
  57. #else
  58. #error "Unknown platform!"
  59. #endif
  60. #if JUCE_WINDOWS
  61. #ifdef _MSC_VER
  62. #ifdef _WIN64
  63. #define JUCE_64BIT 1
  64. #else
  65. #define JUCE_32BIT 1
  66. #endif
  67. #endif
  68. #ifdef _DEBUG
  69. #define JUCE_DEBUG 1
  70. #endif
  71. #ifdef __MINGW32__
  72. #define JUCE_MINGW 1
  73. #endif
  74. /** If defined, this indicates that the processor is little-endian. */
  75. #define JUCE_LITTLE_ENDIAN 1
  76. #define JUCE_INTEL 1
  77. #endif
  78. #if JUCE_MAC || JUCE_IOS
  79. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  80. #define JUCE_DEBUG 1
  81. #endif
  82. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  83. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  84. #endif
  85. #ifdef __LITTLE_ENDIAN__
  86. #define JUCE_LITTLE_ENDIAN 1
  87. #else
  88. #define JUCE_BIG_ENDIAN 1
  89. #endif
  90. #endif
  91. #if JUCE_MAC
  92. #if defined (__ppc__) || defined (__ppc64__)
  93. #define JUCE_PPC 1
  94. #else
  95. #define JUCE_INTEL 1
  96. #endif
  97. #ifdef __LP64__
  98. #define JUCE_64BIT 1
  99. #else
  100. #define JUCE_32BIT 1
  101. #endif
  102. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  103. #error "Building for OSX 10.3 is no longer supported!"
  104. #endif
  105. #ifndef MAC_OS_X_VERSION_10_5
  106. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  107. #endif
  108. #endif
  109. #if JUCE_LINUX || JUCE_ANDROID
  110. #ifdef _DEBUG
  111. #define JUCE_DEBUG 1
  112. #endif
  113. // Allow override for big-endian Linux platforms
  114. #if defined (__LITTLE_ENDIAN__) || ! defined (JUCE_BIG_ENDIAN)
  115. #define JUCE_LITTLE_ENDIAN 1
  116. #undef JUCE_BIG_ENDIAN
  117. #else
  118. #undef JUCE_LITTLE_ENDIAN
  119. #define JUCE_BIG_ENDIAN 1
  120. #endif
  121. #if defined (__LP64__) || defined (_LP64)
  122. #define JUCE_64BIT 1
  123. #else
  124. #define JUCE_32BIT 1
  125. #endif
  126. #if __MMX__ || __SSE__ || __amd64__
  127. #define JUCE_INTEL 1
  128. #endif
  129. #endif
  130. // Compiler type macros.
  131. #ifdef __GNUC__
  132. #define JUCE_GCC 1
  133. #elif defined (_MSC_VER)
  134. #define JUCE_MSVC 1
  135. #if _MSC_VER < 1500
  136. #define JUCE_VC8_OR_EARLIER 1
  137. #if _MSC_VER < 1400
  138. #define JUCE_VC7_OR_EARLIER 1
  139. #if _MSC_VER < 1300
  140. #define JUCE_VC6 1
  141. #endif
  142. #endif
  143. #endif
  144. #if ! JUCE_VC7_OR_EARLIER && ! defined (__INTEL_COMPILER)
  145. #define JUCE_USE_INTRINSICS 1
  146. #endif
  147. #else
  148. #error unknown compiler
  149. #endif
  150. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  151. /*** End of inlined file: juce_TargetPlatform.h ***/
  152. // FORCE_AMALGAMATOR_INCLUDE
  153. /*** Start of inlined file: juce_Config.h ***/
  154. #ifndef __JUCE_CONFIG_JUCEHEADER__
  155. #define __JUCE_CONFIG_JUCEHEADER__
  156. /*
  157. This file contains macros that enable/disable various JUCE features.
  158. */
  159. /** The name of the namespace that all Juce classes and functions will be
  160. put inside. If this is not defined, no namespace will be used.
  161. */
  162. #ifndef JUCE_NAMESPACE
  163. #define JUCE_NAMESPACE juce
  164. #endif
  165. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  166. project settings, but if you define this value, you can override this to force
  167. it to be true or false.
  168. */
  169. #ifndef JUCE_FORCE_DEBUG
  170. //#define JUCE_FORCE_DEBUG 0
  171. #endif
  172. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  173. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  174. Enabling it will also leave this turned on in release builds. When it's disabled,
  175. however, the jassert and jassertfalse macros will not be compiled in a
  176. release build.
  177. @see jassert, jassertfalse, Logger
  178. */
  179. #ifndef JUCE_LOG_ASSERTIONS
  180. #define JUCE_LOG_ASSERTIONS 0
  181. #endif
  182. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  183. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  184. on your Windows build machine.
  185. See the comments in the ASIOAudioIODevice class's header file for more
  186. info about this.
  187. */
  188. #ifndef JUCE_ASIO
  189. #define JUCE_ASIO 0
  190. #endif
  191. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  192. */
  193. #ifndef JUCE_WASAPI
  194. #define JUCE_WASAPI 0
  195. #endif
  196. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  197. */
  198. #ifndef JUCE_DIRECTSOUND
  199. #define JUCE_DIRECTSOUND 1
  200. #endif
  201. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  202. #ifndef JUCE_ALSA
  203. #define JUCE_ALSA 1
  204. #endif
  205. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  206. #ifndef JUCE_JACK
  207. #define JUCE_JACK 0
  208. #endif
  209. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  210. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  211. installed, and its header files will need to be on your include path.
  212. */
  213. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || JUCE_ANDROID || (JUCE_WINDOWS && ! JUCE_MSVC))
  214. #define JUCE_QUICKTIME 0
  215. #endif
  216. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  217. #undef JUCE_QUICKTIME
  218. #endif
  219. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  220. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  221. */
  222. #if ! (defined (JUCE_OPENGL) || JUCE_ANDROID)
  223. #define JUCE_OPENGL 1
  224. #endif
  225. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  226. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  227. */
  228. #ifndef JUCE_DIRECT2D
  229. #define JUCE_DIRECT2D 0
  230. #endif
  231. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  232. If your app doesn't need to read FLAC files, you might want to disable this to
  233. reduce the size of your codebase and build time.
  234. */
  235. #ifndef JUCE_USE_FLAC
  236. #define JUCE_USE_FLAC 1
  237. #endif
  238. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  239. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  240. reduce the size of your codebase and build time.
  241. */
  242. #ifndef JUCE_USE_OGGVORBIS
  243. #define JUCE_USE_OGGVORBIS 1
  244. #endif
  245. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  246. Unless you're using CD-burning, you should probably turn this flag off to
  247. reduce code size.
  248. */
  249. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  250. #define JUCE_USE_CDBURNER 1
  251. #endif
  252. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  253. Unless you're using CD-reading, you should probably turn this flag off to
  254. reduce code size.
  255. */
  256. #ifndef JUCE_USE_CDREADER
  257. #define JUCE_USE_CDREADER 1
  258. #endif
  259. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  260. */
  261. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  262. #define JUCE_USE_CAMERA 0
  263. #endif
  264. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  265. gets repainted will flash in a random colour, so that you can check exactly how much and how
  266. often your components are being drawn.
  267. */
  268. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  269. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  270. #endif
  271. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  272. Unless you specifically want to disable this, it's best to leave this option turned on.
  273. */
  274. #ifndef JUCE_USE_XINERAMA
  275. #define JUCE_USE_XINERAMA 1
  276. #endif
  277. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  278. turned on unless you have a good reason to disable it.
  279. */
  280. #ifndef JUCE_USE_XSHM
  281. #define JUCE_USE_XSHM 1
  282. #endif
  283. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  284. */
  285. #ifndef JUCE_USE_XRENDER
  286. #define JUCE_USE_XRENDER 0
  287. #endif
  288. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  289. unless you have a good reason to disable it.
  290. */
  291. #ifndef JUCE_USE_XCURSOR
  292. #define JUCE_USE_XCURSOR 1
  293. #endif
  294. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  295. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  296. you're building a plugin hosting app.
  297. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  298. */
  299. #ifndef JUCE_PLUGINHOST_VST
  300. #define JUCE_PLUGINHOST_VST 0
  301. #endif
  302. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  303. of course, and should only be enabled if you're building a plugin hosting app.
  304. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  305. */
  306. #ifndef JUCE_PLUGINHOST_AU
  307. #define JUCE_PLUGINHOST_AU 0
  308. #endif
  309. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  310. This should be enabled if you're writing a console application.
  311. */
  312. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  313. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  314. #endif
  315. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  316. If you're not using any embedded web-pages, turning this off may reduce your code size.
  317. */
  318. #ifndef JUCE_WEB_BROWSER
  319. #define JUCE_WEB_BROWSER 1
  320. #endif
  321. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  322. Carbon isn't required for a normal app, but may be needed by specialised classes like
  323. plugin-hosts, which support older APIs.
  324. */
  325. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  326. #define JUCE_SUPPORT_CARBON 1
  327. #endif
  328. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  329. You might need to tweak this if you're linking to an external zlib library in your app,
  330. but for normal apps, this option should be left alone.
  331. */
  332. #ifndef JUCE_INCLUDE_ZLIB_CODE
  333. #define JUCE_INCLUDE_ZLIB_CODE 1
  334. #endif
  335. #ifndef JUCE_INCLUDE_FLAC_CODE
  336. #define JUCE_INCLUDE_FLAC_CODE 1
  337. #endif
  338. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  339. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  340. #endif
  341. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  342. #define JUCE_INCLUDE_PNGLIB_CODE 1
  343. #endif
  344. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  345. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  346. #endif
  347. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  348. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  349. macro for more details about enabling leak checking for specific classes.
  350. */
  351. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  352. #define JUCE_CHECK_MEMORY_LEAKS 1
  353. #endif
  354. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  355. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  356. are passed to the JUCEApplication::unhandledException() callback for logging.
  357. */
  358. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  359. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  360. #endif
  361. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  362. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  363. #undef JUCE_QUICKTIME
  364. #define JUCE_QUICKTIME 0
  365. #undef JUCE_OPENGL
  366. #define JUCE_OPENGL 0
  367. #undef JUCE_USE_CDBURNER
  368. #define JUCE_USE_CDBURNER 0
  369. #undef JUCE_USE_CDREADER
  370. #define JUCE_USE_CDREADER 0
  371. #undef JUCE_WEB_BROWSER
  372. #define JUCE_WEB_BROWSER 0
  373. #undef JUCE_PLUGINHOST_AU
  374. #define JUCE_PLUGINHOST_AU 0
  375. #undef JUCE_PLUGINHOST_VST
  376. #define JUCE_PLUGINHOST_VST 0
  377. #endif
  378. #endif
  379. /*** End of inlined file: juce_Config.h ***/
  380. // FORCE_AMALGAMATOR_INCLUDE
  381. #ifndef JUCE_BUILD_CORE
  382. #define JUCE_BUILD_CORE 1
  383. #endif
  384. #ifndef JUCE_BUILD_MISC
  385. #define JUCE_BUILD_MISC 1
  386. #endif
  387. #ifndef JUCE_BUILD_GUI
  388. #define JUCE_BUILD_GUI 1
  389. #endif
  390. #ifndef JUCE_BUILD_NATIVE
  391. #define JUCE_BUILD_NATIVE 1
  392. #endif
  393. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  394. #undef JUCE_BUILD_MISC
  395. #undef JUCE_BUILD_GUI
  396. #endif
  397. //==============================================================================
  398. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  399. #if JUCE_WINDOWS
  400. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  401. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  402. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  403. #ifndef STRICT
  404. #define STRICT 1
  405. #endif
  406. #undef WIN32_LEAN_AND_MEAN
  407. #define WIN32_LEAN_AND_MEAN 1
  408. #if JUCE_MSVC
  409. #pragma warning (push)
  410. #pragma warning (disable : 4100 4201 4514 4312 4995)
  411. #endif
  412. #define _WIN32_WINNT 0x0500
  413. #define _UNICODE 1
  414. #define UNICODE 1
  415. #ifndef _WIN32_IE
  416. #define _WIN32_IE 0x0400
  417. #endif
  418. #include <windows.h>
  419. #include <windowsx.h>
  420. #include <commdlg.h>
  421. #include <shellapi.h>
  422. #include <mmsystem.h>
  423. #include <vfw.h>
  424. #include <tchar.h>
  425. #include <stddef.h>
  426. #include <ctime>
  427. #include <wininet.h>
  428. #include <nb30.h>
  429. #include <iphlpapi.h>
  430. #include <mapi.h>
  431. #include <float.h>
  432. #include <process.h>
  433. #include <Exdisp.h>
  434. #include <exdispid.h>
  435. #include <shlobj.h>
  436. #include <shlwapi.h>
  437. #if ! JUCE_MINGW
  438. #include <crtdbg.h>
  439. #include <comutil.h>
  440. #endif
  441. #if JUCE_OPENGL
  442. #include <gl/gl.h>
  443. #endif
  444. #undef PACKED
  445. #if JUCE_ASIO && JUCE_BUILD_NATIVE
  446. /*
  447. This is very frustrating - we only need to use a handful of definitions from
  448. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  449. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  450. implementation...
  451. ..unfortunately that would break Steinberg's license agreement for use of
  452. their SDK, so I'm not allowed to do this.
  453. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  454. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  455. (see www.steinberg.net/Steinberg/Developers.asp).
  456. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  457. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  458. if you prefer). Make sure that your header search path will find the
  459. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  460. files are actually needed - so to simplify things, you could just copy
  461. these into your JUCE directory).
  462. If you're compiling and you get an error here because you don't have the
  463. ASIO SDK installed, you can disable ASIO support by commenting-out the
  464. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  465. */
  466. #include <iasiodrv.h>
  467. #endif
  468. #if JUCE_USE_CDBURNER && JUCE_BUILD_NATIVE
  469. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  470. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  471. flag in juce_Config.h to avoid these includes.
  472. */
  473. #include <imapi.h>
  474. #include <imapierror.h>
  475. #endif
  476. #if JUCE_USE_CAMERA && JUCE_BUILD_NATIVE
  477. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  478. These files are provided in the normal Windows SDK, but some Microsoft plonker
  479. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  480. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  481. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  482. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  483. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  484. The dummy file just needs to contain the following content:
  485. #define __IDxtCompositor_INTERFACE_DEFINED__
  486. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  487. #define __IDxtJpeg_INTERFACE_DEFINED__
  488. #define __IDxtKey_INTERFACE_DEFINED__
  489. ..and that should be enough to convince qedit.h that you have the SDK!
  490. */
  491. #include <dshow.h>
  492. #include <qedit.h>
  493. #include <dshowasf.h>
  494. #endif
  495. #if JUCE_WASAPI && JUCE_BUILD_NATIVE
  496. #include <MMReg.h>
  497. #include <mmdeviceapi.h>
  498. #include <Audioclient.h>
  499. #include <Avrt.h>
  500. #include <functiondiscoverykeys.h>
  501. #endif
  502. #if JUCE_QUICKTIME
  503. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  504. add its header directory to your include path.
  505. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  506. flag in juce_Config.h
  507. */
  508. #include <Movies.h>
  509. #include <QTML.h>
  510. #include <QuickTimeComponents.h>
  511. #include <MediaHandlers.h>
  512. #include <ImageCodec.h>
  513. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  514. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  515. your include search path to make these import statements work.
  516. */
  517. #import <QTOLibrary.dll>
  518. #import <QTOControl.dll>
  519. #endif
  520. #if JUCE_MSVC
  521. #pragma warning (pop)
  522. #endif
  523. #if JUCE_DIRECT2D && JUCE_BUILD_NATIVE
  524. #include <d2d1.h>
  525. #include <dwrite.h>
  526. #endif
  527. /** A simple COM smart pointer.
  528. Avoids having to include ATL just to get one of these.
  529. */
  530. template <class ComClass>
  531. class ComSmartPtr
  532. {
  533. public:
  534. ComSmartPtr() throw() : p (0) {}
  535. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  536. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  537. ~ComSmartPtr() { release(); }
  538. operator ComClass*() const throw() { return p; }
  539. ComClass& operator*() const throw() { return *p; }
  540. ComClass* operator->() const throw() { return p; }
  541. ComSmartPtr& operator= (ComClass* const newP)
  542. {
  543. if (newP != 0) newP->AddRef();
  544. release();
  545. p = newP;
  546. return *this;
  547. }
  548. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  549. // Releases and nullifies this pointer and returns its address
  550. ComClass** resetAndGetPointerAddress()
  551. {
  552. release();
  553. p = 0;
  554. return &p;
  555. }
  556. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  557. {
  558. #ifndef __MINGW32__
  559. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  560. #else
  561. return E_NOTIMPL;
  562. #endif
  563. }
  564. template <class OtherComClass>
  565. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  566. {
  567. if (p == 0)
  568. return E_POINTER;
  569. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  570. }
  571. private:
  572. ComClass* p;
  573. void release() { if (p != 0) p->Release(); }
  574. ComClass** operator&() throw(); // private to avoid it being used accidentally
  575. };
  576. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  577. */
  578. template <class ComClass>
  579. class ComBaseClassHelper : public ComClass
  580. {
  581. public:
  582. ComBaseClassHelper() : refCount (1) {}
  583. virtual ~ComBaseClassHelper() {}
  584. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  585. {
  586. #ifndef __MINGW32__
  587. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  588. #endif
  589. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  590. *result = 0;
  591. return E_NOINTERFACE;
  592. }
  593. ULONG __stdcall AddRef() { return ++refCount; }
  594. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  595. protected:
  596. int refCount;
  597. };
  598. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  599. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  600. #elif JUCE_LINUX
  601. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  602. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  603. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  604. /*
  605. This file wraps together all the linux-specific headers, so
  606. that we can include them all just once, and compile all our
  607. platform-specific stuff in one big lump, keeping it out of the
  608. way of the rest of the codebase.
  609. */
  610. #include <sched.h>
  611. #include <pthread.h>
  612. #include <sys/time.h>
  613. #include <errno.h>
  614. #include <sys/stat.h>
  615. #include <sys/dir.h>
  616. #include <sys/ptrace.h>
  617. #include <sys/vfs.h>
  618. #include <sys/wait.h>
  619. #include <fnmatch.h>
  620. #include <utime.h>
  621. #include <pwd.h>
  622. #include <fcntl.h>
  623. #include <dlfcn.h>
  624. #include <netdb.h>
  625. #include <arpa/inet.h>
  626. #include <netinet/in.h>
  627. #include <sys/types.h>
  628. #include <sys/ioctl.h>
  629. #include <sys/socket.h>
  630. #include <net/if.h>
  631. #include <sys/sysinfo.h>
  632. #include <sys/file.h>
  633. #include <signal.h>
  634. /* Got a build error here? You'll need to install the freetype library...
  635. The name of the package to install is "libfreetype6-dev".
  636. */
  637. #include <ft2build.h>
  638. #include FT_FREETYPE_H
  639. #include <X11/Xlib.h>
  640. #include <X11/Xatom.h>
  641. #include <X11/Xresource.h>
  642. #include <X11/Xutil.h>
  643. #include <X11/Xmd.h>
  644. #include <X11/keysym.h>
  645. #include <X11/cursorfont.h>
  646. #if JUCE_USE_XINERAMA
  647. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  648. #include <X11/extensions/Xinerama.h>
  649. #endif
  650. #if JUCE_USE_XSHM
  651. #include <X11/extensions/XShm.h>
  652. #include <sys/shm.h>
  653. #include <sys/ipc.h>
  654. #endif
  655. #if JUCE_USE_XRENDER
  656. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  657. #include <X11/extensions/Xrender.h>
  658. #include <X11/extensions/Xcomposite.h>
  659. #endif
  660. #if JUCE_USE_XCURSOR
  661. // If you're missing this header, try installing the libxcursor-dev package
  662. #include <X11/Xcursor/Xcursor.h>
  663. #endif
  664. #if JUCE_OPENGL
  665. /* Got an include error here?
  666. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  667. and "freeglut3-dev".
  668. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  669. want to disable it.
  670. */
  671. #include <GL/glx.h>
  672. #endif
  673. #undef KeyPress
  674. #if JUCE_ALSA
  675. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  676. not got your paths set up correctly to find its header files.
  677. The package you need to install to get ASLA support is "libasound2-dev".
  678. If you don't have the ALSA library and don't want to build Juce with audio support,
  679. just disable the JUCE_ALSA flag in juce_Config.h
  680. */
  681. #include <alsa/asoundlib.h>
  682. #endif
  683. #if JUCE_JACK
  684. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  685. installed, or you've not got your paths set up correctly to find its header files.
  686. The package you need to install to get JACK support is "libjack-dev".
  687. If you don't have the jack-audio-connection-kit library and don't want to build
  688. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  689. */
  690. #include <jack/jack.h>
  691. //#include <jack/transport.h>
  692. #endif
  693. #undef SIZEOF
  694. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  695. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  696. #elif JUCE_MAC || JUCE_IOS
  697. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  698. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  699. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  700. #define USE_COREGRAPHICS_RENDERING 1
  701. #if JUCE_IOS
  702. #import <Foundation/Foundation.h>
  703. #import <UIKit/UIKit.h>
  704. #import <AudioToolbox/AudioToolbox.h>
  705. #import <AVFoundation/AVFoundation.h>
  706. #import <CoreData/CoreData.h>
  707. #import <MobileCoreServices/MobileCoreServices.h>
  708. #import <QuartzCore/QuartzCore.h>
  709. #include <sys/fcntl.h>
  710. #if JUCE_OPENGL
  711. #include <OpenGLES/ES1/gl.h>
  712. #include <OpenGLES/ES1/glext.h>
  713. #endif
  714. #else
  715. #import <Cocoa/Cocoa.h>
  716. #import <CoreAudio/HostTime.h>
  717. #if JUCE_BUILD_NATIVE
  718. #import <CoreAudio/AudioHardware.h>
  719. #import <CoreMIDI/MIDIServices.h>
  720. #import <QTKit/QTKit.h>
  721. #import <WebKit/WebKit.h>
  722. #import <DiscRecording/DiscRecording.h>
  723. #import <IOKit/IOKitLib.h>
  724. #import <IOKit/IOCFPlugIn.h>
  725. #import <IOKit/hid/IOHIDLib.h>
  726. #import <IOKit/hid/IOHIDKeys.h>
  727. #import <IOKit/pwr_mgt/IOPMLib.h>
  728. #endif
  729. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  730. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  731. #include <Carbon/Carbon.h>
  732. #endif
  733. #include <sys/dir.h>
  734. #endif
  735. #include <sys/socket.h>
  736. #include <sys/sysctl.h>
  737. #include <sys/stat.h>
  738. #include <sys/param.h>
  739. #include <sys/mount.h>
  740. #include <fnmatch.h>
  741. #include <utime.h>
  742. #include <dlfcn.h>
  743. #include <ifaddrs.h>
  744. #include <net/if_dl.h>
  745. #include <mach/mach_time.h>
  746. #include <mach-o/dyld.h>
  747. #if MACOS_10_4_OR_EARLIER
  748. #include <GLUT/glut.h>
  749. #endif
  750. #if ! CGFLOAT_DEFINED
  751. #define CGFloat float
  752. #endif
  753. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  754. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  755. #elif JUCE_ANDROID
  756. /*** Start of inlined file: juce_android_NativeIncludes.h ***/
  757. #ifndef __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  758. #define __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  759. #include <jni.h>
  760. #include <pthread.h>
  761. #include <sched.h>
  762. #include <sys/time.h>
  763. #include <utime.h>
  764. #include <errno.h>
  765. #include <fcntl.h>
  766. #include <dlfcn.h>
  767. #include <sys/stat.h>
  768. #include <sys/statfs.h>
  769. #include <sys/ptrace.h>
  770. #include <sys/sysinfo.h>
  771. #include <pwd.h>
  772. #include <dirent.h>
  773. #include <fnmatch.h>
  774. #if JUCE_OPENGL
  775. #include <GLES/gl.h>
  776. #endif
  777. #endif // __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  778. /*** End of inlined file: juce_android_NativeIncludes.h ***/
  779. #else
  780. #error "Unknown platform!"
  781. #endif
  782. #endif
  783. //==============================================================================
  784. #define DONT_SET_USING_JUCE_NAMESPACE 1
  785. #undef max
  786. #undef min
  787. #define NO_DUMMY_DECL
  788. #define JUCE_AMALGAMATED_TEMPLATE 1
  789. #if JUCE_BUILD_NATIVE
  790. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  791. #endif
  792. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  793. #pragma warning (disable: 4309 4305)
  794. #endif
  795. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  796. BEGIN_JUCE_NAMESPACE
  797. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  798. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  799. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  800. /**
  801. Creates a floating carbon window that can be used to hold a carbon UI.
  802. This is a handy class that's designed to be inlined where needed, e.g.
  803. in the audio plugin hosting code.
  804. */
  805. class CarbonViewWrapperComponent : public Component,
  806. public ComponentMovementWatcher,
  807. public Timer
  808. {
  809. public:
  810. CarbonViewWrapperComponent()
  811. : ComponentMovementWatcher (this),
  812. wrapperWindow (0),
  813. carbonWindow (0),
  814. embeddedView (0),
  815. recursiveResize (false)
  816. {
  817. }
  818. virtual ~CarbonViewWrapperComponent()
  819. {
  820. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  821. }
  822. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  823. virtual void removeView (HIViewRef embeddedView) = 0;
  824. virtual void mouseDown (int, int) {}
  825. virtual void paint() {}
  826. virtual bool getEmbeddedViewSize (int& w, int& h)
  827. {
  828. if (embeddedView == 0)
  829. return false;
  830. HIRect bounds;
  831. HIViewGetBounds (embeddedView, &bounds);
  832. w = jmax (1, roundToInt (bounds.size.width));
  833. h = jmax (1, roundToInt (bounds.size.height));
  834. return true;
  835. }
  836. void createWindow()
  837. {
  838. if (wrapperWindow == 0)
  839. {
  840. Rect r;
  841. r.left = getScreenX();
  842. r.top = getScreenY();
  843. r.right = r.left + getWidth();
  844. r.bottom = r.top + getHeight();
  845. CreateNewWindow (kDocumentWindowClass,
  846. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  847. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  848. &r, &wrapperWindow);
  849. jassert (wrapperWindow != 0);
  850. if (wrapperWindow == 0)
  851. return;
  852. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  853. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  854. [ownerWindow addChildWindow: carbonWindow
  855. ordered: NSWindowAbove];
  856. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  857. EventTypeSpec windowEventTypes[] =
  858. {
  859. { kEventClassWindow, kEventWindowGetClickActivation },
  860. { kEventClassWindow, kEventWindowHandleDeactivate },
  861. { kEventClassWindow, kEventWindowBoundsChanging },
  862. { kEventClassMouse, kEventMouseDown },
  863. { kEventClassMouse, kEventMouseMoved },
  864. { kEventClassMouse, kEventMouseDragged },
  865. { kEventClassMouse, kEventMouseUp},
  866. { kEventClassWindow, kEventWindowDrawContent },
  867. { kEventClassWindow, kEventWindowShown },
  868. { kEventClassWindow, kEventWindowHidden }
  869. };
  870. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  871. InstallWindowEventHandler (wrapperWindow, upp,
  872. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  873. windowEventTypes, this, &eventHandlerRef);
  874. setOurSizeToEmbeddedViewSize();
  875. setEmbeddedWindowToOurSize();
  876. creationTime = Time::getCurrentTime();
  877. }
  878. }
  879. void deleteWindow()
  880. {
  881. removeView (embeddedView);
  882. embeddedView = 0;
  883. if (wrapperWindow != 0)
  884. {
  885. RemoveEventHandler (eventHandlerRef);
  886. DisposeWindow (wrapperWindow);
  887. wrapperWindow = 0;
  888. }
  889. }
  890. void setOurSizeToEmbeddedViewSize()
  891. {
  892. int w, h;
  893. if (getEmbeddedViewSize (w, h))
  894. {
  895. if (w != getWidth() || h != getHeight())
  896. {
  897. startTimer (50);
  898. setSize (w, h);
  899. if (getParentComponent() != 0)
  900. getParentComponent()->setSize (w, h);
  901. }
  902. else
  903. {
  904. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  905. }
  906. }
  907. else
  908. {
  909. stopTimer();
  910. }
  911. }
  912. void setEmbeddedWindowToOurSize()
  913. {
  914. if (! recursiveResize)
  915. {
  916. recursiveResize = true;
  917. if (embeddedView != 0)
  918. {
  919. HIRect r;
  920. r.origin.x = 0;
  921. r.origin.y = 0;
  922. r.size.width = (float) getWidth();
  923. r.size.height = (float) getHeight();
  924. HIViewSetFrame (embeddedView, &r);
  925. }
  926. if (wrapperWindow != 0)
  927. {
  928. Rect wr;
  929. wr.left = getScreenX();
  930. wr.top = getScreenY();
  931. wr.right = wr.left + getWidth();
  932. wr.bottom = wr.top + getHeight();
  933. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  934. ShowWindow (wrapperWindow);
  935. }
  936. recursiveResize = false;
  937. }
  938. }
  939. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  940. {
  941. setEmbeddedWindowToOurSize();
  942. }
  943. void componentPeerChanged()
  944. {
  945. deleteWindow();
  946. createWindow();
  947. }
  948. void componentVisibilityChanged()
  949. {
  950. if (isShowing())
  951. createWindow();
  952. else
  953. deleteWindow();
  954. setEmbeddedWindowToOurSize();
  955. }
  956. static void recursiveHIViewRepaint (HIViewRef view)
  957. {
  958. HIViewSetNeedsDisplay (view, true);
  959. HIViewRef child = HIViewGetFirstSubview (view);
  960. while (child != 0)
  961. {
  962. recursiveHIViewRepaint (child);
  963. child = HIViewGetNextView (child);
  964. }
  965. }
  966. void timerCallback()
  967. {
  968. setOurSizeToEmbeddedViewSize();
  969. // To avoid strange overpainting problems when the UI is first opened, we'll
  970. // repaint it a few times during the first second that it's on-screen..
  971. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  972. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  973. }
  974. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  975. {
  976. switch (GetEventKind (event))
  977. {
  978. case kEventWindowHandleDeactivate:
  979. ActivateWindow (wrapperWindow, TRUE);
  980. return noErr;
  981. case kEventWindowGetClickActivation:
  982. {
  983. getTopLevelComponent()->toFront (false);
  984. [carbonWindow makeKeyAndOrderFront: nil];
  985. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  986. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  987. sizeof (ClickActivationResult), &howToHandleClick);
  988. HIViewSetNeedsDisplay (embeddedView, true);
  989. return noErr;
  990. }
  991. }
  992. return eventNotHandledErr;
  993. }
  994. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  995. {
  996. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  997. }
  998. protected:
  999. WindowRef wrapperWindow;
  1000. NSWindow* carbonWindow;
  1001. HIViewRef embeddedView;
  1002. bool recursiveResize;
  1003. Time creationTime;
  1004. EventHandlerRef eventHandlerRef;
  1005. };
  1006. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  1007. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  1008. END_JUCE_NAMESPACE
  1009. #endif
  1010. //==============================================================================
  1011. #if JUCE_BUILD_CORE
  1012. /*** Start of inlined file: juce_FileLogger.cpp ***/
  1013. BEGIN_JUCE_NAMESPACE
  1014. FileLogger::FileLogger (const File& logFile_,
  1015. const String& welcomeMessage,
  1016. const int maxInitialFileSizeBytes)
  1017. : logFile (logFile_)
  1018. {
  1019. if (maxInitialFileSizeBytes >= 0)
  1020. trimFileSize (maxInitialFileSizeBytes);
  1021. if (! logFile_.exists())
  1022. {
  1023. // do this so that the parent directories get created..
  1024. logFile_.create();
  1025. }
  1026. String welcome;
  1027. welcome << newLine
  1028. << "**********************************************************" << newLine
  1029. << welcomeMessage << newLine
  1030. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1031. logMessage (welcome);
  1032. }
  1033. FileLogger::~FileLogger()
  1034. {
  1035. }
  1036. void FileLogger::logMessage (const String& message)
  1037. {
  1038. DBG (message);
  1039. const ScopedLock sl (logLock);
  1040. FileOutputStream out (logFile, 256);
  1041. out << message << newLine;
  1042. }
  1043. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1044. {
  1045. if (maxFileSizeBytes <= 0)
  1046. {
  1047. logFile.deleteFile();
  1048. }
  1049. else
  1050. {
  1051. const int64 fileSize = logFile.getSize();
  1052. if (fileSize > maxFileSizeBytes)
  1053. {
  1054. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1055. jassert (in != 0);
  1056. if (in != 0)
  1057. {
  1058. in->setPosition (fileSize - maxFileSizeBytes);
  1059. String content;
  1060. {
  1061. MemoryBlock contentToSave;
  1062. contentToSave.setSize (maxFileSizeBytes + 4);
  1063. contentToSave.fillWith (0);
  1064. in->read (contentToSave.getData(), maxFileSizeBytes);
  1065. in = 0;
  1066. content = contentToSave.toString();
  1067. }
  1068. int newStart = 0;
  1069. while (newStart < fileSize
  1070. && content[newStart] != '\n'
  1071. && content[newStart] != '\r')
  1072. ++newStart;
  1073. logFile.deleteFile();
  1074. logFile.appendText (content.substring (newStart), false, false);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1080. const String& logFileName,
  1081. const String& welcomeMessage,
  1082. const int maxInitialFileSizeBytes)
  1083. {
  1084. #if JUCE_MAC
  1085. File logFile ("~/Library/Logs");
  1086. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1087. .getChildFile (logFileName);
  1088. #else
  1089. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1090. if (logFile.isDirectory())
  1091. {
  1092. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1093. .getChildFile (logFileName);
  1094. }
  1095. #endif
  1096. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1097. }
  1098. END_JUCE_NAMESPACE
  1099. /*** End of inlined file: juce_FileLogger.cpp ***/
  1100. /*** Start of inlined file: juce_Logger.cpp ***/
  1101. BEGIN_JUCE_NAMESPACE
  1102. Logger::Logger()
  1103. {
  1104. }
  1105. Logger::~Logger()
  1106. {
  1107. }
  1108. Logger* Logger::currentLogger = 0;
  1109. void Logger::setCurrentLogger (Logger* const newLogger,
  1110. const bool deleteOldLogger)
  1111. {
  1112. Logger* const oldLogger = currentLogger;
  1113. currentLogger = newLogger;
  1114. if (deleteOldLogger)
  1115. delete oldLogger;
  1116. }
  1117. void Logger::writeToLog (const String& message)
  1118. {
  1119. if (currentLogger != 0)
  1120. currentLogger->logMessage (message);
  1121. else
  1122. outputDebugString (message);
  1123. }
  1124. #if JUCE_LOG_ASSERTIONS
  1125. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1126. {
  1127. String m ("JUCE Assertion failure in ");
  1128. m << filename << ", line " << lineNum;
  1129. Logger::writeToLog (m);
  1130. }
  1131. #endif
  1132. END_JUCE_NAMESPACE
  1133. /*** End of inlined file: juce_Logger.cpp ***/
  1134. /*** Start of inlined file: juce_Random.cpp ***/
  1135. BEGIN_JUCE_NAMESPACE
  1136. Random::Random (const int64 seedValue) throw()
  1137. : seed (seedValue)
  1138. {
  1139. }
  1140. Random::~Random() throw()
  1141. {
  1142. }
  1143. void Random::setSeed (const int64 newSeed) throw()
  1144. {
  1145. seed = newSeed;
  1146. }
  1147. void Random::combineSeed (const int64 seedValue) throw()
  1148. {
  1149. seed ^= nextInt64() ^ seedValue;
  1150. }
  1151. void Random::setSeedRandomly()
  1152. {
  1153. combineSeed ((int64) (pointer_sized_int) this);
  1154. combineSeed (Time::getMillisecondCounter());
  1155. combineSeed (Time::getHighResolutionTicks());
  1156. combineSeed (Time::getHighResolutionTicksPerSecond());
  1157. combineSeed (Time::currentTimeMillis());
  1158. }
  1159. int Random::nextInt() throw()
  1160. {
  1161. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1162. return (int) (seed >> 16);
  1163. }
  1164. int Random::nextInt (const int maxValue) throw()
  1165. {
  1166. jassert (maxValue > 0);
  1167. return (nextInt() & 0x7fffffff) % maxValue;
  1168. }
  1169. int64 Random::nextInt64() throw()
  1170. {
  1171. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1172. }
  1173. bool Random::nextBool() throw()
  1174. {
  1175. return (nextInt() & 0x80000000) != 0;
  1176. }
  1177. float Random::nextFloat() throw()
  1178. {
  1179. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1180. }
  1181. double Random::nextDouble() throw()
  1182. {
  1183. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1184. }
  1185. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1186. {
  1187. BigInteger n;
  1188. do
  1189. {
  1190. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1191. }
  1192. while (n >= maximumValue);
  1193. return n;
  1194. }
  1195. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1196. {
  1197. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1198. while ((startBit & 31) != 0 && numBits > 0)
  1199. {
  1200. arrayToChange.setBit (startBit++, nextBool());
  1201. --numBits;
  1202. }
  1203. while (numBits >= 32)
  1204. {
  1205. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1206. startBit += 32;
  1207. numBits -= 32;
  1208. }
  1209. while (--numBits >= 0)
  1210. arrayToChange.setBit (startBit + numBits, nextBool());
  1211. }
  1212. Random& Random::getSystemRandom() throw()
  1213. {
  1214. static Random sysRand (1);
  1215. return sysRand;
  1216. }
  1217. END_JUCE_NAMESPACE
  1218. /*** End of inlined file: juce_Random.cpp ***/
  1219. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1220. BEGIN_JUCE_NAMESPACE
  1221. RelativeTime::RelativeTime (const double seconds_) throw()
  1222. : seconds (seconds_)
  1223. {
  1224. }
  1225. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1226. : seconds (other.seconds)
  1227. {
  1228. }
  1229. RelativeTime::~RelativeTime() throw()
  1230. {
  1231. }
  1232. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1233. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1234. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1235. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1236. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1237. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1238. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1239. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1240. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1241. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1242. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1243. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1244. {
  1245. if (seconds < 0.001 && seconds > -0.001)
  1246. return returnValueForZeroTime;
  1247. String result;
  1248. result.preallocateStorage (16);
  1249. if (seconds < 0)
  1250. result << '-';
  1251. int fieldsShown = 0;
  1252. int n = std::abs ((int) inWeeks());
  1253. if (n > 0)
  1254. {
  1255. result << n << (n == 1 ? TRANS(" week ")
  1256. : TRANS(" weeks "));
  1257. ++fieldsShown;
  1258. }
  1259. n = std::abs ((int) inDays()) % 7;
  1260. if (n > 0)
  1261. {
  1262. result << n << (n == 1 ? TRANS(" day ")
  1263. : TRANS(" days "));
  1264. ++fieldsShown;
  1265. }
  1266. if (fieldsShown < 2)
  1267. {
  1268. n = std::abs ((int) inHours()) % 24;
  1269. if (n > 0)
  1270. {
  1271. result << n << (n == 1 ? TRANS(" hr ")
  1272. : TRANS(" hrs "));
  1273. ++fieldsShown;
  1274. }
  1275. if (fieldsShown < 2)
  1276. {
  1277. n = std::abs ((int) inMinutes()) % 60;
  1278. if (n > 0)
  1279. {
  1280. result << n << (n == 1 ? TRANS(" min ")
  1281. : TRANS(" mins "));
  1282. ++fieldsShown;
  1283. }
  1284. if (fieldsShown < 2)
  1285. {
  1286. n = std::abs ((int) inSeconds()) % 60;
  1287. if (n > 0)
  1288. {
  1289. result << n << (n == 1 ? TRANS(" sec ")
  1290. : TRANS(" secs "));
  1291. ++fieldsShown;
  1292. }
  1293. if (fieldsShown == 0)
  1294. {
  1295. n = std::abs ((int) inMilliseconds()) % 1000;
  1296. if (n > 0)
  1297. result << n << TRANS(" ms");
  1298. }
  1299. }
  1300. }
  1301. }
  1302. return result.trimEnd();
  1303. }
  1304. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1305. {
  1306. seconds = other.seconds;
  1307. return *this;
  1308. }
  1309. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1310. {
  1311. seconds += timeToAdd.seconds;
  1312. return *this;
  1313. }
  1314. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1315. {
  1316. seconds -= timeToSubtract.seconds;
  1317. return *this;
  1318. }
  1319. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1320. {
  1321. seconds += secondsToAdd;
  1322. return *this;
  1323. }
  1324. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1325. {
  1326. seconds -= secondsToSubtract;
  1327. return *this;
  1328. }
  1329. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  1330. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() != t2.inSeconds(); }
  1331. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() > t2.inSeconds(); }
  1332. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() < t2.inSeconds(); }
  1333. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() >= t2.inSeconds(); }
  1334. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() <= t2.inSeconds(); }
  1335. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1336. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1337. END_JUCE_NAMESPACE
  1338. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1339. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1340. BEGIN_JUCE_NAMESPACE
  1341. SystemStats::CPUFlags SystemStats::cpuFlags;
  1342. const String SystemStats::getJUCEVersion()
  1343. {
  1344. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1345. + "." + String (JUCE_MINOR_VERSION)
  1346. + "." + String (JUCE_BUILDNUMBER);
  1347. }
  1348. #ifdef JUCE_DLL
  1349. void* juce_Malloc (int size) { return malloc (size); }
  1350. void* juce_Calloc (int size) { return calloc (1, size); }
  1351. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1352. void juce_Free (void* block) { free (block); }
  1353. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1354. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1355. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1356. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1357. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1358. #endif
  1359. #endif
  1360. END_JUCE_NAMESPACE
  1361. /*** End of inlined file: juce_SystemStats.cpp ***/
  1362. /*** Start of inlined file: juce_Time.cpp ***/
  1363. #if JUCE_MSVC
  1364. #pragma warning (push)
  1365. #pragma warning (disable: 4514)
  1366. #endif
  1367. #ifndef JUCE_WINDOWS
  1368. #include <sys/time.h>
  1369. #else
  1370. #include <ctime>
  1371. #endif
  1372. #include <sys/timeb.h>
  1373. #if JUCE_MSVC
  1374. #pragma warning (pop)
  1375. #ifdef _INC_TIME_INL
  1376. #define USE_NEW_SECURE_TIME_FNS
  1377. #endif
  1378. #endif
  1379. BEGIN_JUCE_NAMESPACE
  1380. namespace TimeHelpers
  1381. {
  1382. static struct tm millisToLocal (const int64 millis) throw()
  1383. {
  1384. struct tm result;
  1385. const int64 seconds = millis / 1000;
  1386. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1387. {
  1388. // use extended maths for dates beyond 1970 to 2037..
  1389. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1390. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1391. const int days = (int) (jdm / literal64bit (86400));
  1392. const int a = 32044 + days;
  1393. const int b = (4 * a + 3) / 146097;
  1394. const int c = a - (b * 146097) / 4;
  1395. const int d = (4 * c + 3) / 1461;
  1396. const int e = c - (d * 1461) / 4;
  1397. const int m = (5 * e + 2) / 153;
  1398. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1399. result.tm_mon = m + 2 - 12 * (m / 10);
  1400. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1401. result.tm_wday = (days + 1) % 7;
  1402. result.tm_yday = -1;
  1403. int t = (int) (jdm % literal64bit (86400));
  1404. result.tm_hour = t / 3600;
  1405. t %= 3600;
  1406. result.tm_min = t / 60;
  1407. result.tm_sec = t % 60;
  1408. result.tm_isdst = -1;
  1409. }
  1410. else
  1411. {
  1412. time_t now = static_cast <time_t> (seconds);
  1413. #if JUCE_WINDOWS
  1414. #ifdef USE_NEW_SECURE_TIME_FNS
  1415. if (now >= 0 && now <= 0x793406fff)
  1416. localtime_s (&result, &now);
  1417. else
  1418. zeromem (&result, sizeof (result));
  1419. #else
  1420. result = *localtime (&now);
  1421. #endif
  1422. #else
  1423. // more thread-safe
  1424. localtime_r (&now, &result);
  1425. #endif
  1426. }
  1427. return result;
  1428. }
  1429. static int extendedModulo (const int64 value, const int modulo) throw()
  1430. {
  1431. return (int) (value >= 0 ? (value % modulo)
  1432. : (value - ((value / modulo) + 1) * modulo));
  1433. }
  1434. static uint32 lastMSCounterValue = 0;
  1435. }
  1436. Time::Time() throw()
  1437. : millisSinceEpoch (0)
  1438. {
  1439. }
  1440. Time::Time (const Time& other) throw()
  1441. : millisSinceEpoch (other.millisSinceEpoch)
  1442. {
  1443. }
  1444. Time::Time (const int64 ms) throw()
  1445. : millisSinceEpoch (ms)
  1446. {
  1447. }
  1448. Time::Time (const int year,
  1449. const int month,
  1450. const int day,
  1451. const int hours,
  1452. const int minutes,
  1453. const int seconds,
  1454. const int milliseconds,
  1455. const bool useLocalTime) throw()
  1456. {
  1457. jassert (year > 100); // year must be a 4-digit version
  1458. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1459. {
  1460. // use extended maths for dates beyond 1970 to 2037..
  1461. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1462. : 0;
  1463. const int a = (13 - month) / 12;
  1464. const int y = year + 4800 - a;
  1465. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1466. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1467. - 32045;
  1468. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1469. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1470. + milliseconds;
  1471. }
  1472. else
  1473. {
  1474. struct tm t;
  1475. t.tm_year = year - 1900;
  1476. t.tm_mon = month;
  1477. t.tm_mday = day;
  1478. t.tm_hour = hours;
  1479. t.tm_min = minutes;
  1480. t.tm_sec = seconds;
  1481. t.tm_isdst = -1;
  1482. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1483. if (millisSinceEpoch < 0)
  1484. millisSinceEpoch = 0;
  1485. else
  1486. millisSinceEpoch += milliseconds;
  1487. }
  1488. }
  1489. Time::~Time() throw()
  1490. {
  1491. }
  1492. Time& Time::operator= (const Time& other) throw()
  1493. {
  1494. millisSinceEpoch = other.millisSinceEpoch;
  1495. return *this;
  1496. }
  1497. int64 Time::currentTimeMillis() throw()
  1498. {
  1499. static uint32 lastCounterResult = 0xffffffff;
  1500. static int64 correction = 0;
  1501. const uint32 now = getMillisecondCounter();
  1502. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1503. if (now < lastCounterResult)
  1504. {
  1505. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1506. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1507. {
  1508. // get the time once using normal library calls, and store the difference needed to
  1509. // turn the millisecond counter into a real time.
  1510. #if JUCE_WINDOWS
  1511. struct _timeb t;
  1512. #ifdef USE_NEW_SECURE_TIME_FNS
  1513. _ftime_s (&t);
  1514. #else
  1515. _ftime (&t);
  1516. #endif
  1517. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1518. #else
  1519. struct timeval tv;
  1520. struct timezone tz;
  1521. gettimeofday (&tv, &tz);
  1522. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1523. #endif
  1524. }
  1525. }
  1526. lastCounterResult = now;
  1527. return correction + now;
  1528. }
  1529. uint32 juce_millisecondsSinceStartup() throw();
  1530. uint32 Time::getMillisecondCounter() throw()
  1531. {
  1532. const uint32 now = juce_millisecondsSinceStartup();
  1533. if (now < TimeHelpers::lastMSCounterValue)
  1534. {
  1535. // in multi-threaded apps this might be called concurrently, so
  1536. // make sure that our last counter value only increases and doesn't
  1537. // go backwards..
  1538. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1539. TimeHelpers::lastMSCounterValue = now;
  1540. }
  1541. else
  1542. {
  1543. TimeHelpers::lastMSCounterValue = now;
  1544. }
  1545. return now;
  1546. }
  1547. uint32 Time::getApproximateMillisecondCounter() throw()
  1548. {
  1549. jassert (TimeHelpers::lastMSCounterValue != 0);
  1550. return TimeHelpers::lastMSCounterValue;
  1551. }
  1552. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1553. {
  1554. for (;;)
  1555. {
  1556. const uint32 now = getMillisecondCounter();
  1557. if (now >= targetTime)
  1558. break;
  1559. const int toWait = targetTime - now;
  1560. if (toWait > 2)
  1561. {
  1562. Thread::sleep (jmin (20, toWait >> 1));
  1563. }
  1564. else
  1565. {
  1566. // xxx should consider using mutex_pause on the mac as it apparently
  1567. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1568. for (int i = 10; --i >= 0;)
  1569. Thread::yield();
  1570. }
  1571. }
  1572. }
  1573. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1574. {
  1575. return ticks / (double) getHighResolutionTicksPerSecond();
  1576. }
  1577. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1578. {
  1579. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1580. }
  1581. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1582. {
  1583. return Time (currentTimeMillis());
  1584. }
  1585. const String Time::toString (const bool includeDate,
  1586. const bool includeTime,
  1587. const bool includeSeconds,
  1588. const bool use24HourClock) const throw()
  1589. {
  1590. String result;
  1591. if (includeDate)
  1592. {
  1593. result << getDayOfMonth() << ' '
  1594. << getMonthName (true) << ' '
  1595. << getYear();
  1596. if (includeTime)
  1597. result << ' ';
  1598. }
  1599. if (includeTime)
  1600. {
  1601. const int mins = getMinutes();
  1602. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1603. << (mins < 10 ? ":0" : ":") << mins;
  1604. if (includeSeconds)
  1605. {
  1606. const int secs = getSeconds();
  1607. result << (secs < 10 ? ":0" : ":") << secs;
  1608. }
  1609. if (! use24HourClock)
  1610. result << (isAfternoon() ? "pm" : "am");
  1611. }
  1612. return result.trimEnd();
  1613. }
  1614. const String Time::formatted (const String& format) const
  1615. {
  1616. String buffer;
  1617. int bufferSize = 128;
  1618. buffer.preallocateStorage (bufferSize);
  1619. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1620. while (CharacterFunctions::ftime (buffer.getCharPointer().getAddress(), bufferSize, format.getCharPointer(), &t) <= 0)
  1621. {
  1622. bufferSize += 128;
  1623. buffer.preallocateStorage (bufferSize);
  1624. }
  1625. return buffer;
  1626. }
  1627. int Time::getYear() const throw()
  1628. {
  1629. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1630. }
  1631. int Time::getMonth() const throw()
  1632. {
  1633. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1634. }
  1635. int Time::getDayOfMonth() const throw()
  1636. {
  1637. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1638. }
  1639. int Time::getDayOfWeek() const throw()
  1640. {
  1641. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1642. }
  1643. int Time::getHours() const throw()
  1644. {
  1645. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1646. }
  1647. int Time::getHoursInAmPmFormat() const throw()
  1648. {
  1649. const int hours = getHours();
  1650. if (hours == 0)
  1651. return 12;
  1652. else if (hours <= 12)
  1653. return hours;
  1654. else
  1655. return hours - 12;
  1656. }
  1657. bool Time::isAfternoon() const throw()
  1658. {
  1659. return getHours() >= 12;
  1660. }
  1661. int Time::getMinutes() const throw()
  1662. {
  1663. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1664. }
  1665. int Time::getSeconds() const throw()
  1666. {
  1667. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1668. }
  1669. int Time::getMilliseconds() const throw()
  1670. {
  1671. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1672. }
  1673. bool Time::isDaylightSavingTime() const throw()
  1674. {
  1675. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1676. }
  1677. const String Time::getTimeZone() const throw()
  1678. {
  1679. String zone[2];
  1680. #if JUCE_WINDOWS
  1681. _tzset();
  1682. #ifdef USE_NEW_SECURE_TIME_FNS
  1683. {
  1684. char name [128];
  1685. size_t length;
  1686. for (int i = 0; i < 2; ++i)
  1687. {
  1688. zeromem (name, sizeof (name));
  1689. _get_tzname (&length, name, 127, i);
  1690. zone[i] = name;
  1691. }
  1692. }
  1693. #else
  1694. const char** const zonePtr = (const char**) _tzname;
  1695. zone[0] = zonePtr[0];
  1696. zone[1] = zonePtr[1];
  1697. #endif
  1698. #else
  1699. tzset();
  1700. const char** const zonePtr = (const char**) tzname;
  1701. zone[0] = zonePtr[0];
  1702. zone[1] = zonePtr[1];
  1703. #endif
  1704. if (isDaylightSavingTime())
  1705. {
  1706. zone[0] = zone[1];
  1707. if (zone[0].length() > 3
  1708. && zone[0].containsIgnoreCase ("daylight")
  1709. && zone[0].contains ("GMT"))
  1710. zone[0] = "BST";
  1711. }
  1712. return zone[0].substring (0, 3);
  1713. }
  1714. const String Time::getMonthName (const bool threeLetterVersion) const
  1715. {
  1716. return getMonthName (getMonth(), threeLetterVersion);
  1717. }
  1718. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1719. {
  1720. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1721. }
  1722. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1723. {
  1724. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1725. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1726. monthNumber %= 12;
  1727. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1728. : longMonthNames [monthNumber]);
  1729. }
  1730. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1731. {
  1732. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1733. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1734. day %= 7;
  1735. return TRANS (threeLetterVersion ? shortDayNames [day]
  1736. : longDayNames [day]);
  1737. }
  1738. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1739. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1740. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1741. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1742. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1743. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1744. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  1745. bool operator!= (const Time& time1, const Time& time2) { return time1.toMilliseconds() != time2.toMilliseconds(); }
  1746. bool operator< (const Time& time1, const Time& time2) { return time1.toMilliseconds() < time2.toMilliseconds(); }
  1747. bool operator> (const Time& time1, const Time& time2) { return time1.toMilliseconds() > time2.toMilliseconds(); }
  1748. bool operator<= (const Time& time1, const Time& time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  1749. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  1750. END_JUCE_NAMESPACE
  1751. /*** End of inlined file: juce_Time.cpp ***/
  1752. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1753. BEGIN_JUCE_NAMESPACE
  1754. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1755. #endif
  1756. #if JUCE_WINDOWS
  1757. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1758. #endif
  1759. #if JUCE_DEBUG
  1760. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1761. #endif
  1762. static bool juceInitialisedNonGUI = false;
  1763. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1764. {
  1765. if (! juceInitialisedNonGUI)
  1766. {
  1767. juceInitialisedNonGUI = true;
  1768. JUCE_AUTORELEASEPOOL
  1769. DBG (SystemStats::getJUCEVersion());
  1770. SystemStats::initialiseStats();
  1771. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1772. }
  1773. // Some basic tests, to keep an eye on things and make sure these types work ok
  1774. // on all platforms. Let me know if any of these assertions fail on your system!
  1775. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1776. static_jassert (sizeof (int8) == 1);
  1777. static_jassert (sizeof (uint8) == 1);
  1778. static_jassert (sizeof (int16) == 2);
  1779. static_jassert (sizeof (uint16) == 2);
  1780. static_jassert (sizeof (int32) == 4);
  1781. static_jassert (sizeof (uint32) == 4);
  1782. static_jassert (sizeof (int64) == 8);
  1783. static_jassert (sizeof (uint64) == 8);
  1784. }
  1785. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1786. {
  1787. if (juceInitialisedNonGUI)
  1788. {
  1789. juceInitialisedNonGUI = false;
  1790. JUCE_AUTORELEASEPOOL
  1791. LocalisedStrings::setCurrentMappings (0);
  1792. Thread::stopAllThreads (3000);
  1793. #if JUCE_WINDOWS
  1794. juce_shutdownWin32Sockets();
  1795. #endif
  1796. #if JUCE_DEBUG
  1797. juce_CheckForDanglingStreams();
  1798. #endif
  1799. }
  1800. }
  1801. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1802. static bool juceInitialisedGUI = false;
  1803. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1804. {
  1805. if (! juceInitialisedGUI)
  1806. {
  1807. juceInitialisedGUI = true;
  1808. JUCE_AUTORELEASEPOOL
  1809. initialiseJuce_NonGUI();
  1810. MessageManager::getInstance();
  1811. LookAndFeel::setDefaultLookAndFeel (0);
  1812. #if JUCE_DEBUG
  1813. try // This section is just a safety-net for catching builds without RTTI enabled..
  1814. {
  1815. MemoryOutputStream mo;
  1816. OutputStream* o = &mo;
  1817. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1818. o = dynamic_cast <MemoryOutputStream*> (o);
  1819. jassert (o != 0);
  1820. }
  1821. catch (...)
  1822. {
  1823. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1824. jassertfalse;
  1825. }
  1826. #endif
  1827. }
  1828. }
  1829. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1830. {
  1831. if (juceInitialisedGUI)
  1832. {
  1833. juceInitialisedGUI = false;
  1834. JUCE_AUTORELEASEPOOL
  1835. DeletedAtShutdown::deleteAll();
  1836. LookAndFeel::clearDefaultLookAndFeel();
  1837. delete MessageManager::getInstance();
  1838. shutdownJuce_NonGUI();
  1839. }
  1840. }
  1841. #endif
  1842. #if JUCE_UNIT_TESTS
  1843. class AtomicTests : public UnitTest
  1844. {
  1845. public:
  1846. AtomicTests() : UnitTest ("Atomics") {}
  1847. void runTest()
  1848. {
  1849. beginTest ("Misc");
  1850. char a1[7];
  1851. expect (numElementsInArray(a1) == 7);
  1852. int a2[3];
  1853. expect (numElementsInArray(a2) == 3);
  1854. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1855. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1856. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1857. beginTest ("Atomic types");
  1858. AtomicTester <int>::testInteger (*this);
  1859. AtomicTester <unsigned int>::testInteger (*this);
  1860. AtomicTester <int32>::testInteger (*this);
  1861. AtomicTester <uint32>::testInteger (*this);
  1862. AtomicTester <long>::testInteger (*this);
  1863. AtomicTester <void*>::testInteger (*this);
  1864. AtomicTester <int*>::testInteger (*this);
  1865. AtomicTester <float>::testFloat (*this);
  1866. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1867. AtomicTester <int64>::testInteger (*this);
  1868. AtomicTester <uint64>::testInteger (*this);
  1869. AtomicTester <double>::testFloat (*this);
  1870. #endif
  1871. }
  1872. template <typename Type>
  1873. class AtomicTester
  1874. {
  1875. public:
  1876. AtomicTester() {}
  1877. static void testInteger (UnitTest& test)
  1878. {
  1879. Atomic<Type> a, b;
  1880. a.set ((Type) 10);
  1881. a += (Type) 15;
  1882. a.memoryBarrier();
  1883. a -= (Type) 5;
  1884. ++a; ++a; --a;
  1885. a.memoryBarrier();
  1886. testFloat (test);
  1887. }
  1888. static void testFloat (UnitTest& test)
  1889. {
  1890. Atomic<Type> a, b;
  1891. a = (Type) 21;
  1892. a.memoryBarrier();
  1893. /* These are some simple test cases to check the atomics - let me know
  1894. if any of these assertions fail on your system!
  1895. */
  1896. test.expect (a.get() == (Type) 21);
  1897. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1898. test.expect (a.get() == (Type) 21);
  1899. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1900. test.expect (a.get() == (Type) 101);
  1901. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1902. test.expect (a.get() == (Type) 101);
  1903. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1904. test.expect (a.get() == (Type) 200);
  1905. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1906. test.expect (a.get() == (Type) 300);
  1907. b = a;
  1908. test.expect (b.get() == a.get());
  1909. }
  1910. };
  1911. };
  1912. static AtomicTests atomicUnitTests;
  1913. #endif
  1914. END_JUCE_NAMESPACE
  1915. /*** End of inlined file: juce_Initialisation.cpp ***/
  1916. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1917. BEGIN_JUCE_NAMESPACE
  1918. AbstractFifo::AbstractFifo (const int capacity) throw()
  1919. : bufferSize (capacity)
  1920. {
  1921. jassert (bufferSize > 0);
  1922. }
  1923. AbstractFifo::~AbstractFifo() {}
  1924. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1925. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1926. int AbstractFifo::getNumReady() const throw()
  1927. {
  1928. const int vs = validStart.get();
  1929. const int ve = validEnd.get();
  1930. return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1931. }
  1932. void AbstractFifo::reset() throw()
  1933. {
  1934. validEnd = 0;
  1935. validStart = 0;
  1936. }
  1937. void AbstractFifo::setTotalSize (int newSize) throw()
  1938. {
  1939. jassert (newSize > 0);
  1940. reset();
  1941. bufferSize = newSize;
  1942. }
  1943. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1944. {
  1945. const int vs = validStart.get();
  1946. const int ve = validEnd.value;
  1947. const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve);
  1948. numToWrite = jmin (numToWrite, freeSpace - 1);
  1949. if (numToWrite <= 0)
  1950. {
  1951. startIndex1 = 0;
  1952. startIndex2 = 0;
  1953. blockSize1 = 0;
  1954. blockSize2 = 0;
  1955. }
  1956. else
  1957. {
  1958. startIndex1 = ve;
  1959. startIndex2 = 0;
  1960. blockSize1 = jmin (bufferSize - ve, numToWrite);
  1961. numToWrite -= blockSize1;
  1962. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs);
  1963. }
  1964. }
  1965. void AbstractFifo::finishedWrite (int numWritten) throw()
  1966. {
  1967. jassert (numWritten >= 0 && numWritten < bufferSize);
  1968. int newEnd = validEnd.value + numWritten;
  1969. if (newEnd >= bufferSize)
  1970. newEnd -= bufferSize;
  1971. validEnd = newEnd;
  1972. }
  1973. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1974. {
  1975. const int vs = validStart.value;
  1976. const int ve = validEnd.get();
  1977. const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1978. numWanted = jmin (numWanted, numReady);
  1979. if (numWanted <= 0)
  1980. {
  1981. startIndex1 = 0;
  1982. startIndex2 = 0;
  1983. blockSize1 = 0;
  1984. blockSize2 = 0;
  1985. }
  1986. else
  1987. {
  1988. startIndex1 = vs;
  1989. startIndex2 = 0;
  1990. blockSize1 = jmin (bufferSize - vs, numWanted);
  1991. numWanted -= blockSize1;
  1992. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve);
  1993. }
  1994. }
  1995. void AbstractFifo::finishedRead (int numRead) throw()
  1996. {
  1997. jassert (numRead >= 0 && numRead <= bufferSize);
  1998. int newStart = validStart.value + numRead;
  1999. if (newStart >= bufferSize)
  2000. newStart -= bufferSize;
  2001. validStart = newStart;
  2002. }
  2003. #if JUCE_UNIT_TESTS
  2004. class AbstractFifoTests : public UnitTest
  2005. {
  2006. public:
  2007. AbstractFifoTests() : UnitTest ("Abstract Fifo") {}
  2008. class WriteThread : public Thread
  2009. {
  2010. public:
  2011. WriteThread (AbstractFifo& fifo_, int* buffer_)
  2012. : Thread ("fifo writer"), fifo (fifo_), buffer (buffer_)
  2013. {
  2014. startThread();
  2015. }
  2016. ~WriteThread()
  2017. {
  2018. stopThread (5000);
  2019. }
  2020. void run()
  2021. {
  2022. int n = 0;
  2023. while (! threadShouldExit())
  2024. {
  2025. int num = Random::getSystemRandom().nextInt (2000) + 1;
  2026. int start1, size1, start2, size2;
  2027. fifo.prepareToWrite (num, start1, size1, start2, size2);
  2028. jassert (size1 >= 0 && size2 >= 0);
  2029. jassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()));
  2030. jassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()));
  2031. int i;
  2032. for (i = 0; i < size1; ++i)
  2033. buffer [start1 + i] = n++;
  2034. for (i = 0; i < size2; ++i)
  2035. buffer [start2 + i] = n++;
  2036. fifo.finishedWrite (size1 + size2);
  2037. }
  2038. }
  2039. private:
  2040. AbstractFifo& fifo;
  2041. int* buffer;
  2042. };
  2043. void runTest()
  2044. {
  2045. beginTest ("AbstractFifo");
  2046. int buffer [5000];
  2047. AbstractFifo fifo (numElementsInArray (buffer));
  2048. WriteThread writer (fifo, buffer);
  2049. int n = 0;
  2050. for (int count = 1000000; --count >= 0;)
  2051. {
  2052. int num = Random::getSystemRandom().nextInt (6000) + 1;
  2053. int start1, size1, start2, size2;
  2054. fifo.prepareToRead (num, start1, size1, start2, size2);
  2055. if (! (size1 >= 0 && size2 >= 0)
  2056. && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()))
  2057. && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize())))
  2058. {
  2059. expect (false, "prepareToRead returned -ve values");
  2060. break;
  2061. }
  2062. bool failed = false;
  2063. int i;
  2064. for (i = 0; i < size1; ++i)
  2065. failed = (buffer [start1 + i] != n++) || failed;
  2066. for (i = 0; i < size2; ++i)
  2067. failed = (buffer [start2 + i] != n++) || failed;
  2068. if (failed)
  2069. {
  2070. expect (false, "read values were incorrect");
  2071. break;
  2072. }
  2073. fifo.finishedRead (size1 + size2);
  2074. }
  2075. }
  2076. };
  2077. static AbstractFifoTests fifoUnitTests;
  2078. #endif
  2079. END_JUCE_NAMESPACE
  2080. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2081. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2082. BEGIN_JUCE_NAMESPACE
  2083. BigInteger::BigInteger()
  2084. : numValues (4),
  2085. highestBit (-1),
  2086. negative (false)
  2087. {
  2088. values.calloc (numValues + 1);
  2089. }
  2090. BigInteger::BigInteger (const int32 value)
  2091. : numValues (4),
  2092. highestBit (31),
  2093. negative (value < 0)
  2094. {
  2095. values.calloc (numValues + 1);
  2096. values[0] = abs (value);
  2097. highestBit = getHighestBit();
  2098. }
  2099. BigInteger::BigInteger (const uint32 value)
  2100. : numValues (4),
  2101. highestBit (31),
  2102. negative (false)
  2103. {
  2104. values.calloc (numValues + 1);
  2105. values[0] = value;
  2106. highestBit = getHighestBit();
  2107. }
  2108. BigInteger::BigInteger (int64 value)
  2109. : numValues (4),
  2110. highestBit (63),
  2111. negative (value < 0)
  2112. {
  2113. values.calloc (numValues + 1);
  2114. if (value < 0)
  2115. value = -value;
  2116. values[0] = (uint32) value;
  2117. values[1] = (uint32) (value >> 32);
  2118. highestBit = getHighestBit();
  2119. }
  2120. BigInteger::BigInteger (const BigInteger& other)
  2121. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2122. highestBit (other.getHighestBit()),
  2123. negative (other.negative)
  2124. {
  2125. values.malloc (numValues + 1);
  2126. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2127. }
  2128. BigInteger::~BigInteger()
  2129. {
  2130. }
  2131. void BigInteger::swapWith (BigInteger& other) throw()
  2132. {
  2133. values.swapWith (other.values);
  2134. swapVariables (numValues, other.numValues);
  2135. swapVariables (highestBit, other.highestBit);
  2136. swapVariables (negative, other.negative);
  2137. }
  2138. BigInteger& BigInteger::operator= (const BigInteger& other)
  2139. {
  2140. if (this != &other)
  2141. {
  2142. highestBit = other.getHighestBit();
  2143. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2144. negative = other.negative;
  2145. values.malloc (numValues + 1);
  2146. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2147. }
  2148. return *this;
  2149. }
  2150. void BigInteger::ensureSize (const int numVals)
  2151. {
  2152. if (numVals + 2 >= numValues)
  2153. {
  2154. int oldSize = numValues;
  2155. numValues = ((numVals + 2) * 3) / 2;
  2156. values.realloc (numValues + 1);
  2157. while (oldSize < numValues)
  2158. values [oldSize++] = 0;
  2159. }
  2160. }
  2161. bool BigInteger::operator[] (const int bit) const throw()
  2162. {
  2163. return bit <= highestBit && bit >= 0
  2164. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2165. }
  2166. int BigInteger::toInteger() const throw()
  2167. {
  2168. const int n = (int) (values[0] & 0x7fffffff);
  2169. return negative ? -n : n;
  2170. }
  2171. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2172. {
  2173. BigInteger r;
  2174. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2175. r.ensureSize (bitToIndex (numBits));
  2176. r.highestBit = numBits;
  2177. int i = 0;
  2178. while (numBits > 0)
  2179. {
  2180. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2181. numBits -= 32;
  2182. startBit += 32;
  2183. }
  2184. r.highestBit = r.getHighestBit();
  2185. return r;
  2186. }
  2187. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2188. {
  2189. if (numBits > 32)
  2190. {
  2191. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2192. numBits = 32;
  2193. }
  2194. numBits = jmin (numBits, highestBit + 1 - startBit);
  2195. if (numBits <= 0)
  2196. return 0;
  2197. const int pos = bitToIndex (startBit);
  2198. const int offset = startBit & 31;
  2199. const int endSpace = 32 - numBits;
  2200. uint32 n = ((uint32) values [pos]) >> offset;
  2201. if (offset > endSpace)
  2202. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2203. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2204. }
  2205. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2206. {
  2207. if (numBits > 32)
  2208. {
  2209. jassertfalse;
  2210. numBits = 32;
  2211. }
  2212. for (int i = 0; i < numBits; ++i)
  2213. {
  2214. setBit (startBit + i, (valueToSet & 1) != 0);
  2215. valueToSet >>= 1;
  2216. }
  2217. }
  2218. void BigInteger::clear()
  2219. {
  2220. if (numValues > 16)
  2221. {
  2222. numValues = 4;
  2223. values.calloc (numValues + 1);
  2224. }
  2225. else
  2226. {
  2227. zeromem (values, sizeof (uint32) * (numValues + 1));
  2228. }
  2229. highestBit = -1;
  2230. negative = false;
  2231. }
  2232. void BigInteger::setBit (const int bit)
  2233. {
  2234. if (bit >= 0)
  2235. {
  2236. if (bit > highestBit)
  2237. {
  2238. ensureSize (bitToIndex (bit));
  2239. highestBit = bit;
  2240. }
  2241. values [bitToIndex (bit)] |= bitToMask (bit);
  2242. }
  2243. }
  2244. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2245. {
  2246. if (shouldBeSet)
  2247. setBit (bit);
  2248. else
  2249. clearBit (bit);
  2250. }
  2251. void BigInteger::clearBit (const int bit) throw()
  2252. {
  2253. if (bit >= 0 && bit <= highestBit)
  2254. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2255. }
  2256. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2257. {
  2258. while (--numBits >= 0)
  2259. setBit (startBit++, shouldBeSet);
  2260. }
  2261. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2262. {
  2263. if (bit >= 0)
  2264. shiftBits (1, bit);
  2265. setBit (bit, shouldBeSet);
  2266. }
  2267. bool BigInteger::isZero() const throw()
  2268. {
  2269. return getHighestBit() < 0;
  2270. }
  2271. bool BigInteger::isOne() const throw()
  2272. {
  2273. return getHighestBit() == 0 && ! negative;
  2274. }
  2275. bool BigInteger::isNegative() const throw()
  2276. {
  2277. return negative && ! isZero();
  2278. }
  2279. void BigInteger::setNegative (const bool neg) throw()
  2280. {
  2281. negative = neg;
  2282. }
  2283. void BigInteger::negate() throw()
  2284. {
  2285. negative = (! negative) && ! isZero();
  2286. }
  2287. #if JUCE_USE_INTRINSICS
  2288. #pragma intrinsic (_BitScanReverse)
  2289. #endif
  2290. namespace BitFunctions
  2291. {
  2292. inline int countBitsInInt32 (uint32 n) throw()
  2293. {
  2294. n -= ((n >> 1) & 0x55555555);
  2295. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2296. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2297. n += (n >> 8);
  2298. n += (n >> 16);
  2299. return n & 0x3f;
  2300. }
  2301. inline int highestBitInInt (uint32 n) throw()
  2302. {
  2303. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2304. #if JUCE_GCC
  2305. return 31 - __builtin_clz (n);
  2306. #elif JUCE_USE_INTRINSICS
  2307. unsigned long highest;
  2308. _BitScanReverse (&highest, n);
  2309. return (int) highest;
  2310. #else
  2311. n |= (n >> 1);
  2312. n |= (n >> 2);
  2313. n |= (n >> 4);
  2314. n |= (n >> 8);
  2315. n |= (n >> 16);
  2316. return countBitsInInt32 (n >> 1);
  2317. #endif
  2318. }
  2319. }
  2320. int BigInteger::countNumberOfSetBits() const throw()
  2321. {
  2322. int total = 0;
  2323. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2324. total += BitFunctions::countBitsInInt32 (values[i]);
  2325. return total;
  2326. }
  2327. int BigInteger::getHighestBit() const throw()
  2328. {
  2329. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2330. {
  2331. const uint32 n = values[i];
  2332. if (n != 0)
  2333. return BitFunctions::highestBitInInt (n) + (i << 5);
  2334. }
  2335. return -1;
  2336. }
  2337. int BigInteger::findNextSetBit (int i) const throw()
  2338. {
  2339. for (; i <= highestBit; ++i)
  2340. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2341. return i;
  2342. return -1;
  2343. }
  2344. int BigInteger::findNextClearBit (int i) const throw()
  2345. {
  2346. for (; i <= highestBit; ++i)
  2347. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2348. break;
  2349. return i;
  2350. }
  2351. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2352. {
  2353. if (other.isNegative())
  2354. return operator-= (-other);
  2355. if (isNegative())
  2356. {
  2357. if (compareAbsolute (other) < 0)
  2358. {
  2359. BigInteger temp (*this);
  2360. temp.negate();
  2361. *this = other;
  2362. operator-= (temp);
  2363. }
  2364. else
  2365. {
  2366. negate();
  2367. operator-= (other);
  2368. negate();
  2369. }
  2370. }
  2371. else
  2372. {
  2373. if (other.highestBit > highestBit)
  2374. highestBit = other.highestBit;
  2375. ++highestBit;
  2376. const int numInts = bitToIndex (highestBit) + 1;
  2377. ensureSize (numInts);
  2378. int64 remainder = 0;
  2379. for (int i = 0; i <= numInts; ++i)
  2380. {
  2381. if (i < numValues)
  2382. remainder += values[i];
  2383. if (i < other.numValues)
  2384. remainder += other.values[i];
  2385. values[i] = (uint32) remainder;
  2386. remainder >>= 32;
  2387. }
  2388. jassert (remainder == 0);
  2389. highestBit = getHighestBit();
  2390. }
  2391. return *this;
  2392. }
  2393. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2394. {
  2395. if (other.isNegative())
  2396. return operator+= (-other);
  2397. if (! isNegative())
  2398. {
  2399. if (compareAbsolute (other) < 0)
  2400. {
  2401. BigInteger temp (other);
  2402. swapWith (temp);
  2403. operator-= (temp);
  2404. negate();
  2405. return *this;
  2406. }
  2407. }
  2408. else
  2409. {
  2410. negate();
  2411. operator+= (other);
  2412. negate();
  2413. return *this;
  2414. }
  2415. const int numInts = bitToIndex (highestBit) + 1;
  2416. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2417. int64 amountToSubtract = 0;
  2418. for (int i = 0; i <= numInts; ++i)
  2419. {
  2420. if (i <= maxOtherInts)
  2421. amountToSubtract += (int64) other.values[i];
  2422. if (values[i] >= amountToSubtract)
  2423. {
  2424. values[i] = (uint32) (values[i] - amountToSubtract);
  2425. amountToSubtract = 0;
  2426. }
  2427. else
  2428. {
  2429. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2430. values[i] = (uint32) n;
  2431. amountToSubtract = 1;
  2432. }
  2433. }
  2434. return *this;
  2435. }
  2436. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2437. {
  2438. BigInteger total;
  2439. highestBit = getHighestBit();
  2440. const bool wasNegative = isNegative();
  2441. setNegative (false);
  2442. for (int i = 0; i <= highestBit; ++i)
  2443. {
  2444. if (operator[](i))
  2445. {
  2446. BigInteger n (other);
  2447. n.setNegative (false);
  2448. n <<= i;
  2449. total += n;
  2450. }
  2451. }
  2452. total.setNegative (wasNegative ^ other.isNegative());
  2453. swapWith (total);
  2454. return *this;
  2455. }
  2456. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2457. {
  2458. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2459. const int divHB = divisor.getHighestBit();
  2460. const int ourHB = getHighestBit();
  2461. if (divHB < 0 || ourHB < 0)
  2462. {
  2463. // division by zero
  2464. remainder.clear();
  2465. clear();
  2466. }
  2467. else
  2468. {
  2469. const bool wasNegative = isNegative();
  2470. swapWith (remainder);
  2471. remainder.setNegative (false);
  2472. clear();
  2473. BigInteger temp (divisor);
  2474. temp.setNegative (false);
  2475. int leftShift = ourHB - divHB;
  2476. temp <<= leftShift;
  2477. while (leftShift >= 0)
  2478. {
  2479. if (remainder.compareAbsolute (temp) >= 0)
  2480. {
  2481. remainder -= temp;
  2482. setBit (leftShift);
  2483. }
  2484. if (--leftShift >= 0)
  2485. temp >>= 1;
  2486. }
  2487. negative = wasNegative ^ divisor.isNegative();
  2488. remainder.setNegative (wasNegative);
  2489. }
  2490. }
  2491. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2492. {
  2493. BigInteger remainder;
  2494. divideBy (other, remainder);
  2495. return *this;
  2496. }
  2497. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2498. {
  2499. // this operation doesn't take into account negative values..
  2500. jassert (isNegative() == other.isNegative());
  2501. if (other.highestBit >= 0)
  2502. {
  2503. ensureSize (bitToIndex (other.highestBit));
  2504. int n = bitToIndex (other.highestBit) + 1;
  2505. while (--n >= 0)
  2506. values[n] |= other.values[n];
  2507. if (other.highestBit > highestBit)
  2508. highestBit = other.highestBit;
  2509. highestBit = getHighestBit();
  2510. }
  2511. return *this;
  2512. }
  2513. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2514. {
  2515. // this operation doesn't take into account negative values..
  2516. jassert (isNegative() == other.isNegative());
  2517. int n = numValues;
  2518. while (n > other.numValues)
  2519. values[--n] = 0;
  2520. while (--n >= 0)
  2521. values[n] &= other.values[n];
  2522. if (other.highestBit < highestBit)
  2523. highestBit = other.highestBit;
  2524. highestBit = getHighestBit();
  2525. return *this;
  2526. }
  2527. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2528. {
  2529. // this operation will only work with the absolute values
  2530. jassert (isNegative() == other.isNegative());
  2531. if (other.highestBit >= 0)
  2532. {
  2533. ensureSize (bitToIndex (other.highestBit));
  2534. int n = bitToIndex (other.highestBit) + 1;
  2535. while (--n >= 0)
  2536. values[n] ^= other.values[n];
  2537. if (other.highestBit > highestBit)
  2538. highestBit = other.highestBit;
  2539. highestBit = getHighestBit();
  2540. }
  2541. return *this;
  2542. }
  2543. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2544. {
  2545. BigInteger remainder;
  2546. divideBy (divisor, remainder);
  2547. swapWith (remainder);
  2548. return *this;
  2549. }
  2550. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2551. {
  2552. shiftBits (numBitsToShift, 0);
  2553. return *this;
  2554. }
  2555. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2556. {
  2557. return operator<<= (-numBitsToShift);
  2558. }
  2559. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2560. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2561. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2562. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2563. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2564. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2565. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2566. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2567. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2568. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2569. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2570. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2571. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2572. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2573. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2574. int BigInteger::compare (const BigInteger& other) const throw()
  2575. {
  2576. if (isNegative() == other.isNegative())
  2577. {
  2578. const int absComp = compareAbsolute (other);
  2579. return isNegative() ? -absComp : absComp;
  2580. }
  2581. else
  2582. {
  2583. return isNegative() ? -1 : 1;
  2584. }
  2585. }
  2586. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2587. {
  2588. const int h1 = getHighestBit();
  2589. const int h2 = other.getHighestBit();
  2590. if (h1 > h2)
  2591. return 1;
  2592. else if (h1 < h2)
  2593. return -1;
  2594. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2595. if (values[i] != other.values[i])
  2596. return (values[i] > other.values[i]) ? 1 : -1;
  2597. return 0;
  2598. }
  2599. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2600. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2601. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2602. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2603. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2604. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2605. void BigInteger::shiftBits (int bits, const int startBit)
  2606. {
  2607. if (highestBit < 0)
  2608. return;
  2609. if (startBit > 0)
  2610. {
  2611. if (bits < 0)
  2612. {
  2613. // right shift
  2614. for (int i = startBit; i <= highestBit; ++i)
  2615. setBit (i, operator[] (i - bits));
  2616. highestBit = getHighestBit();
  2617. }
  2618. else if (bits > 0)
  2619. {
  2620. // left shift
  2621. for (int i = highestBit + 1; --i >= startBit;)
  2622. setBit (i + bits, operator[] (i));
  2623. while (--bits >= 0)
  2624. clearBit (bits + startBit);
  2625. }
  2626. }
  2627. else
  2628. {
  2629. if (bits < 0)
  2630. {
  2631. // right shift
  2632. bits = -bits;
  2633. if (bits > highestBit)
  2634. {
  2635. clear();
  2636. }
  2637. else
  2638. {
  2639. const int wordsToMove = bitToIndex (bits);
  2640. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2641. highestBit -= bits;
  2642. if (wordsToMove > 0)
  2643. {
  2644. int i;
  2645. for (i = 0; i < top; ++i)
  2646. values [i] = values [i + wordsToMove];
  2647. for (i = 0; i < wordsToMove; ++i)
  2648. values [top + i] = 0;
  2649. bits &= 31;
  2650. }
  2651. if (bits != 0)
  2652. {
  2653. const int invBits = 32 - bits;
  2654. --top;
  2655. for (int i = 0; i < top; ++i)
  2656. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2657. values[top] = (values[top] >> bits);
  2658. }
  2659. highestBit = getHighestBit();
  2660. }
  2661. }
  2662. else if (bits > 0)
  2663. {
  2664. // left shift
  2665. ensureSize (bitToIndex (highestBit + bits) + 1);
  2666. const int wordsToMove = bitToIndex (bits);
  2667. int top = 1 + bitToIndex (highestBit);
  2668. highestBit += bits;
  2669. if (wordsToMove > 0)
  2670. {
  2671. int i;
  2672. for (i = top; --i >= 0;)
  2673. values [i + wordsToMove] = values [i];
  2674. for (i = 0; i < wordsToMove; ++i)
  2675. values [i] = 0;
  2676. bits &= 31;
  2677. }
  2678. if (bits != 0)
  2679. {
  2680. const int invBits = 32 - bits;
  2681. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2682. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2683. values [wordsToMove] = values [wordsToMove] << bits;
  2684. }
  2685. highestBit = getHighestBit();
  2686. }
  2687. }
  2688. }
  2689. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2690. {
  2691. while (! m->isZero())
  2692. {
  2693. if (n->compareAbsolute (*m) > 0)
  2694. swapVariables (m, n);
  2695. *m -= *n;
  2696. }
  2697. return *n;
  2698. }
  2699. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2700. {
  2701. BigInteger m (*this);
  2702. while (! n.isZero())
  2703. {
  2704. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2705. return simpleGCD (&m, &n);
  2706. BigInteger temp1 (m), temp2;
  2707. temp1.divideBy (n, temp2);
  2708. m = n;
  2709. n = temp2;
  2710. }
  2711. return m;
  2712. }
  2713. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2714. {
  2715. BigInteger exp (exponent);
  2716. exp %= modulus;
  2717. BigInteger value (1);
  2718. swapWith (value);
  2719. value %= modulus;
  2720. while (! exp.isZero())
  2721. {
  2722. if (exp [0])
  2723. {
  2724. operator*= (value);
  2725. operator%= (modulus);
  2726. }
  2727. value *= value;
  2728. value %= modulus;
  2729. exp >>= 1;
  2730. }
  2731. }
  2732. void BigInteger::inverseModulo (const BigInteger& modulus)
  2733. {
  2734. if (modulus.isOne() || modulus.isNegative())
  2735. {
  2736. clear();
  2737. return;
  2738. }
  2739. if (isNegative() || compareAbsolute (modulus) >= 0)
  2740. operator%= (modulus);
  2741. if (isOne())
  2742. return;
  2743. if (! (*this)[0])
  2744. {
  2745. // not invertible
  2746. clear();
  2747. return;
  2748. }
  2749. BigInteger a1 (modulus);
  2750. BigInteger a2 (*this);
  2751. BigInteger b1 (modulus);
  2752. BigInteger b2 (1);
  2753. while (! a2.isOne())
  2754. {
  2755. BigInteger temp1, temp2, multiplier (a1);
  2756. multiplier.divideBy (a2, temp1);
  2757. temp1 = a2;
  2758. temp1 *= multiplier;
  2759. temp2 = a1;
  2760. temp2 -= temp1;
  2761. a1 = a2;
  2762. a2 = temp2;
  2763. temp1 = b2;
  2764. temp1 *= multiplier;
  2765. temp2 = b1;
  2766. temp2 -= temp1;
  2767. b1 = b2;
  2768. b2 = temp2;
  2769. }
  2770. while (b2.isNegative())
  2771. b2 += modulus;
  2772. b2 %= modulus;
  2773. swapWith (b2);
  2774. }
  2775. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2776. {
  2777. return stream << value.toString (10);
  2778. }
  2779. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2780. {
  2781. String s;
  2782. BigInteger v (*this);
  2783. if (base == 2 || base == 8 || base == 16)
  2784. {
  2785. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2786. static const char* const hexDigits = "0123456789abcdef";
  2787. for (;;)
  2788. {
  2789. const int remainder = v.getBitRangeAsInt (0, bits);
  2790. v >>= bits;
  2791. if (remainder == 0 && v.isZero())
  2792. break;
  2793. s = String::charToString (hexDigits [remainder]) + s;
  2794. }
  2795. }
  2796. else if (base == 10)
  2797. {
  2798. const BigInteger ten (10);
  2799. BigInteger remainder;
  2800. for (;;)
  2801. {
  2802. v.divideBy (ten, remainder);
  2803. if (remainder.isZero() && v.isZero())
  2804. break;
  2805. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2806. }
  2807. }
  2808. else
  2809. {
  2810. jassertfalse; // can't do the specified base!
  2811. return String::empty;
  2812. }
  2813. s = s.paddedLeft ('0', minimumNumCharacters);
  2814. return isNegative() ? "-" + s : s;
  2815. }
  2816. void BigInteger::parseString (const String& text, const int base)
  2817. {
  2818. clear();
  2819. String::CharPointerType t (text.getCharPointer());
  2820. if (base == 2 || base == 8 || base == 16)
  2821. {
  2822. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2823. for (;;)
  2824. {
  2825. const juce_wchar c = t.getAndAdvance();
  2826. const int digit = CharacterFunctions::getHexDigitValue (c);
  2827. if (((uint32) digit) < (uint32) base)
  2828. {
  2829. operator<<= (bits);
  2830. operator+= (digit);
  2831. }
  2832. else if (c == 0)
  2833. {
  2834. break;
  2835. }
  2836. }
  2837. }
  2838. else if (base == 10)
  2839. {
  2840. const BigInteger ten ((uint32) 10);
  2841. for (;;)
  2842. {
  2843. const juce_wchar c = t.getAndAdvance();
  2844. if (c >= '0' && c <= '9')
  2845. {
  2846. operator*= (ten);
  2847. operator+= ((int) (c - '0'));
  2848. }
  2849. else if (c == 0)
  2850. {
  2851. break;
  2852. }
  2853. }
  2854. }
  2855. setNegative (text.trimStart().startsWithChar ('-'));
  2856. }
  2857. const MemoryBlock BigInteger::toMemoryBlock() const
  2858. {
  2859. const int numBytes = (getHighestBit() + 8) >> 3;
  2860. MemoryBlock mb ((size_t) numBytes);
  2861. for (int i = 0; i < numBytes; ++i)
  2862. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2863. return mb;
  2864. }
  2865. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2866. {
  2867. clear();
  2868. for (int i = (int) data.getSize(); --i >= 0;)
  2869. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2870. }
  2871. END_JUCE_NAMESPACE
  2872. /*** End of inlined file: juce_BigInteger.cpp ***/
  2873. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2874. BEGIN_JUCE_NAMESPACE
  2875. MemoryBlock::MemoryBlock() throw()
  2876. : size (0)
  2877. {
  2878. }
  2879. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2880. {
  2881. if (initialSize > 0)
  2882. {
  2883. size = initialSize;
  2884. data.allocate (initialSize, initialiseToZero);
  2885. }
  2886. else
  2887. {
  2888. size = 0;
  2889. }
  2890. }
  2891. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2892. : size (other.size)
  2893. {
  2894. if (size > 0)
  2895. {
  2896. jassert (other.data != 0);
  2897. data.malloc (size);
  2898. memcpy (data, other.data, size);
  2899. }
  2900. }
  2901. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2902. : size (jmax ((size_t) 0, sizeInBytes))
  2903. {
  2904. jassert (sizeInBytes >= 0);
  2905. if (size > 0)
  2906. {
  2907. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2908. data.malloc (size);
  2909. if (dataToInitialiseFrom != 0)
  2910. memcpy (data, dataToInitialiseFrom, size);
  2911. }
  2912. }
  2913. MemoryBlock::~MemoryBlock() throw()
  2914. {
  2915. jassert (size >= 0); // should never happen
  2916. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2917. }
  2918. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2919. {
  2920. if (this != &other)
  2921. {
  2922. setSize (other.size, false);
  2923. memcpy (data, other.data, size);
  2924. }
  2925. return *this;
  2926. }
  2927. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2928. {
  2929. return matches (other.data, other.size);
  2930. }
  2931. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2932. {
  2933. return ! operator== (other);
  2934. }
  2935. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2936. {
  2937. return size == dataSize
  2938. && memcmp (data, dataToCompare, size) == 0;
  2939. }
  2940. // this will resize the block to this size
  2941. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2942. {
  2943. if (size != newSize)
  2944. {
  2945. if (newSize <= 0)
  2946. {
  2947. data.free();
  2948. size = 0;
  2949. }
  2950. else
  2951. {
  2952. if (data != 0)
  2953. {
  2954. data.realloc (newSize);
  2955. if (initialiseToZero && (newSize > size))
  2956. zeromem (data + size, newSize - size);
  2957. }
  2958. else
  2959. {
  2960. data.allocate (newSize, initialiseToZero);
  2961. }
  2962. size = newSize;
  2963. }
  2964. }
  2965. }
  2966. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2967. {
  2968. if (size < minimumSize)
  2969. setSize (minimumSize, initialiseToZero);
  2970. }
  2971. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2972. {
  2973. swapVariables (size, other.size);
  2974. data.swapWith (other.data);
  2975. }
  2976. void MemoryBlock::fillWith (const uint8 value) throw()
  2977. {
  2978. memset (data, (int) value, size);
  2979. }
  2980. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2981. {
  2982. if (numBytes > 0)
  2983. {
  2984. const size_t oldSize = size;
  2985. setSize (size + numBytes);
  2986. memcpy (data + oldSize, srcData, numBytes);
  2987. }
  2988. }
  2989. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2990. {
  2991. const char* d = static_cast<const char*> (src);
  2992. if (offset < 0)
  2993. {
  2994. d -= offset;
  2995. num -= offset;
  2996. offset = 0;
  2997. }
  2998. if (offset + num > size)
  2999. num = size - offset;
  3000. if (num > 0)
  3001. memcpy (data + offset, d, num);
  3002. }
  3003. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  3004. {
  3005. char* d = static_cast<char*> (dst);
  3006. if (offset < 0)
  3007. {
  3008. zeromem (d, -offset);
  3009. d -= offset;
  3010. num += offset;
  3011. offset = 0;
  3012. }
  3013. if (offset + num > size)
  3014. {
  3015. const size_t newNum = size - offset;
  3016. zeromem (d + newNum, num - newNum);
  3017. num = newNum;
  3018. }
  3019. if (num > 0)
  3020. memcpy (d, data + offset, num);
  3021. }
  3022. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  3023. {
  3024. if (startByte + numBytesToRemove >= size)
  3025. {
  3026. setSize (startByte);
  3027. }
  3028. else if (numBytesToRemove > 0)
  3029. {
  3030. memmove (data + startByte,
  3031. data + startByte + numBytesToRemove,
  3032. size - (startByte + numBytesToRemove));
  3033. setSize (size - numBytesToRemove);
  3034. }
  3035. }
  3036. const String MemoryBlock::toString() const
  3037. {
  3038. return String (static_cast <const char*> (getData()), size);
  3039. }
  3040. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  3041. {
  3042. int res = 0;
  3043. size_t byte = bitRangeStart >> 3;
  3044. int offsetInByte = (int) bitRangeStart & 7;
  3045. size_t bitsSoFar = 0;
  3046. while (numBits > 0 && (size_t) byte < size)
  3047. {
  3048. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3049. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  3050. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  3051. bitsSoFar += bitsThisTime;
  3052. numBits -= bitsThisTime;
  3053. ++byte;
  3054. offsetInByte = 0;
  3055. }
  3056. return res;
  3057. }
  3058. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  3059. {
  3060. size_t byte = bitRangeStart >> 3;
  3061. int offsetInByte = (int) bitRangeStart & 7;
  3062. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3063. while (numBits > 0 && (size_t) byte < size)
  3064. {
  3065. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3066. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3067. const unsigned int tempBits = bitsToSet << offsetInByte;
  3068. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3069. ++byte;
  3070. numBits -= bitsThisTime;
  3071. bitsToSet >>= bitsThisTime;
  3072. mask >>= bitsThisTime;
  3073. offsetInByte = 0;
  3074. }
  3075. }
  3076. void MemoryBlock::loadFromHexString (const String& hex)
  3077. {
  3078. ensureSize (hex.length() >> 1);
  3079. char* dest = data;
  3080. int i = 0;
  3081. for (;;)
  3082. {
  3083. int byte = 0;
  3084. for (int loop = 2; --loop >= 0;)
  3085. {
  3086. byte <<= 4;
  3087. for (;;)
  3088. {
  3089. const juce_wchar c = hex [i++];
  3090. if (c >= '0' && c <= '9')
  3091. {
  3092. byte |= c - '0';
  3093. break;
  3094. }
  3095. else if (c >= 'a' && c <= 'z')
  3096. {
  3097. byte |= c - ('a' - 10);
  3098. break;
  3099. }
  3100. else if (c >= 'A' && c <= 'Z')
  3101. {
  3102. byte |= c - ('A' - 10);
  3103. break;
  3104. }
  3105. else if (c == 0)
  3106. {
  3107. setSize (static_cast <size_t> (dest - data));
  3108. return;
  3109. }
  3110. }
  3111. }
  3112. *dest++ = (char) byte;
  3113. }
  3114. }
  3115. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3116. const String MemoryBlock::toBase64Encoding() const
  3117. {
  3118. const size_t numChars = ((size << 3) + 5) / 6;
  3119. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3120. const int initialLen = destString.length();
  3121. destString.preallocateStorage (initialLen + 2 + numChars);
  3122. String::CharPointerType d (destString.getCharPointer());
  3123. d += initialLen;
  3124. d.write ('.');
  3125. for (size_t i = 0; i < numChars; ++i)
  3126. d.write (encodingTable [getBitRange (i * 6, 6)]);
  3127. d.writeNull();
  3128. return destString;
  3129. }
  3130. bool MemoryBlock::fromBase64Encoding (const String& s)
  3131. {
  3132. const int startPos = s.indexOfChar ('.') + 1;
  3133. if (startPos <= 0)
  3134. return false;
  3135. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3136. setSize (numBytesNeeded, true);
  3137. const int numChars = s.length() - startPos;
  3138. String::CharPointerType srcChars (s.getCharPointer());
  3139. srcChars += startPos;
  3140. int pos = 0;
  3141. for (int i = 0; i < numChars; ++i)
  3142. {
  3143. const char c = (char) srcChars.getAndAdvance();
  3144. for (int j = 0; j < 64; ++j)
  3145. {
  3146. if (encodingTable[j] == c)
  3147. {
  3148. setBitRange (pos, 6, j);
  3149. pos += 6;
  3150. break;
  3151. }
  3152. }
  3153. }
  3154. return true;
  3155. }
  3156. END_JUCE_NAMESPACE
  3157. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3158. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3159. BEGIN_JUCE_NAMESPACE
  3160. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3161. : properties (ignoreCaseOfKeyNames),
  3162. fallbackProperties (0),
  3163. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3164. {
  3165. }
  3166. PropertySet::PropertySet (const PropertySet& other)
  3167. : properties (other.properties),
  3168. fallbackProperties (other.fallbackProperties),
  3169. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3170. {
  3171. }
  3172. PropertySet& PropertySet::operator= (const PropertySet& other)
  3173. {
  3174. properties = other.properties;
  3175. fallbackProperties = other.fallbackProperties;
  3176. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3177. propertyChanged();
  3178. return *this;
  3179. }
  3180. PropertySet::~PropertySet()
  3181. {
  3182. }
  3183. void PropertySet::clear()
  3184. {
  3185. const ScopedLock sl (lock);
  3186. if (properties.size() > 0)
  3187. {
  3188. properties.clear();
  3189. propertyChanged();
  3190. }
  3191. }
  3192. const String PropertySet::getValue (const String& keyName,
  3193. const String& defaultValue) const throw()
  3194. {
  3195. const ScopedLock sl (lock);
  3196. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3197. if (index >= 0)
  3198. return properties.getAllValues() [index];
  3199. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3200. : defaultValue;
  3201. }
  3202. int PropertySet::getIntValue (const String& keyName,
  3203. const int defaultValue) const throw()
  3204. {
  3205. const ScopedLock sl (lock);
  3206. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3207. if (index >= 0)
  3208. return properties.getAllValues() [index].getIntValue();
  3209. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3210. : defaultValue;
  3211. }
  3212. double PropertySet::getDoubleValue (const String& keyName,
  3213. const double defaultValue) const throw()
  3214. {
  3215. const ScopedLock sl (lock);
  3216. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3217. if (index >= 0)
  3218. return properties.getAllValues()[index].getDoubleValue();
  3219. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3220. : defaultValue;
  3221. }
  3222. bool PropertySet::getBoolValue (const String& keyName,
  3223. const bool defaultValue) const throw()
  3224. {
  3225. const ScopedLock sl (lock);
  3226. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3227. if (index >= 0)
  3228. return properties.getAllValues() [index].getIntValue() != 0;
  3229. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3230. : defaultValue;
  3231. }
  3232. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3233. {
  3234. return XmlDocument::parse (getValue (keyName));
  3235. }
  3236. void PropertySet::setValue (const String& keyName, const var& v)
  3237. {
  3238. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3239. if (keyName.isNotEmpty())
  3240. {
  3241. const String value (v.toString());
  3242. const ScopedLock sl (lock);
  3243. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3244. if (index < 0 || properties.getAllValues() [index] != value)
  3245. {
  3246. properties.set (keyName, value);
  3247. propertyChanged();
  3248. }
  3249. }
  3250. }
  3251. void PropertySet::removeValue (const String& keyName)
  3252. {
  3253. if (keyName.isNotEmpty())
  3254. {
  3255. const ScopedLock sl (lock);
  3256. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3257. if (index >= 0)
  3258. {
  3259. properties.remove (keyName);
  3260. propertyChanged();
  3261. }
  3262. }
  3263. }
  3264. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3265. {
  3266. setValue (keyName, xml == 0 ? var::null
  3267. : var (xml->createDocument (String::empty, true)));
  3268. }
  3269. bool PropertySet::containsKey (const String& keyName) const throw()
  3270. {
  3271. const ScopedLock sl (lock);
  3272. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3273. }
  3274. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3275. {
  3276. const ScopedLock sl (lock);
  3277. fallbackProperties = fallbackProperties_;
  3278. }
  3279. XmlElement* PropertySet::createXml (const String& nodeName) const
  3280. {
  3281. const ScopedLock sl (lock);
  3282. XmlElement* const xml = new XmlElement (nodeName);
  3283. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3284. {
  3285. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3286. e->setAttribute ("name", properties.getAllKeys()[i]);
  3287. e->setAttribute ("val", properties.getAllValues()[i]);
  3288. }
  3289. return xml;
  3290. }
  3291. void PropertySet::restoreFromXml (const XmlElement& xml)
  3292. {
  3293. const ScopedLock sl (lock);
  3294. clear();
  3295. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3296. {
  3297. if (e->hasAttribute ("name")
  3298. && e->hasAttribute ("val"))
  3299. {
  3300. properties.set (e->getStringAttribute ("name"),
  3301. e->getStringAttribute ("val"));
  3302. }
  3303. }
  3304. if (properties.size() > 0)
  3305. propertyChanged();
  3306. }
  3307. void PropertySet::propertyChanged()
  3308. {
  3309. }
  3310. END_JUCE_NAMESPACE
  3311. /*** End of inlined file: juce_PropertySet.cpp ***/
  3312. /*** Start of inlined file: juce_Identifier.cpp ***/
  3313. BEGIN_JUCE_NAMESPACE
  3314. StringPool& Identifier::getPool()
  3315. {
  3316. static StringPool pool;
  3317. return pool;
  3318. }
  3319. Identifier::Identifier() throw()
  3320. : name (0)
  3321. {
  3322. }
  3323. Identifier::Identifier (const Identifier& other) throw()
  3324. : name (other.name)
  3325. {
  3326. }
  3327. Identifier& Identifier::operator= (const Identifier& other) throw()
  3328. {
  3329. name = other.name;
  3330. return *this;
  3331. }
  3332. Identifier::Identifier (const String& name_)
  3333. : name (Identifier::getPool().getPooledString (name_))
  3334. {
  3335. /* An Identifier string must be suitable for use as a script variable or XML
  3336. attribute, so it can only contain this limited set of characters.. */
  3337. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3338. }
  3339. Identifier::Identifier (const char* const name_)
  3340. : name (Identifier::getPool().getPooledString (name_))
  3341. {
  3342. /* An Identifier string must be suitable for use as a script variable or XML
  3343. attribute, so it can only contain this limited set of characters.. */
  3344. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3345. }
  3346. Identifier::~Identifier()
  3347. {
  3348. }
  3349. END_JUCE_NAMESPACE
  3350. /*** End of inlined file: juce_Identifier.cpp ***/
  3351. /*** Start of inlined file: juce_Variant.cpp ***/
  3352. BEGIN_JUCE_NAMESPACE
  3353. class var::VariantType
  3354. {
  3355. public:
  3356. VariantType() {}
  3357. virtual ~VariantType() {}
  3358. virtual int toInt (const ValueUnion&) const { return 0; }
  3359. virtual double toDouble (const ValueUnion&) const { return 0; }
  3360. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3361. virtual bool toBool (const ValueUnion&) const { return false; }
  3362. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3363. virtual bool isVoid() const throw() { return false; }
  3364. virtual bool isInt() const throw() { return false; }
  3365. virtual bool isBool() const throw() { return false; }
  3366. virtual bool isDouble() const throw() { return false; }
  3367. virtual bool isString() const throw() { return false; }
  3368. virtual bool isObject() const throw() { return false; }
  3369. virtual bool isMethod() const throw() { return false; }
  3370. virtual void cleanUp (ValueUnion&) const throw() {}
  3371. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3372. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3373. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3374. };
  3375. class var::VariantType_Void : public var::VariantType
  3376. {
  3377. public:
  3378. VariantType_Void() {}
  3379. static const VariantType_Void instance;
  3380. bool isVoid() const throw() { return true; }
  3381. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3382. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3383. };
  3384. class var::VariantType_Int : public var::VariantType
  3385. {
  3386. public:
  3387. VariantType_Int() {}
  3388. static const VariantType_Int instance;
  3389. int toInt (const ValueUnion& data) const { return data.intValue; };
  3390. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3391. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3392. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3393. bool isInt() const throw() { return true; }
  3394. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3395. {
  3396. return otherType.toInt (otherData) == data.intValue;
  3397. }
  3398. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3399. {
  3400. output.writeCompressedInt (5);
  3401. output.writeByte (1);
  3402. output.writeInt (data.intValue);
  3403. }
  3404. };
  3405. class var::VariantType_Double : public var::VariantType
  3406. {
  3407. public:
  3408. VariantType_Double() {}
  3409. static const VariantType_Double instance;
  3410. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3411. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3412. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3413. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3414. bool isDouble() const throw() { return true; }
  3415. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3416. {
  3417. return otherType.toDouble (otherData) == data.doubleValue;
  3418. }
  3419. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3420. {
  3421. output.writeCompressedInt (9);
  3422. output.writeByte (4);
  3423. output.writeDouble (data.doubleValue);
  3424. }
  3425. };
  3426. class var::VariantType_Bool : public var::VariantType
  3427. {
  3428. public:
  3429. VariantType_Bool() {}
  3430. static const VariantType_Bool instance;
  3431. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3432. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3433. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3434. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3435. bool isBool() const throw() { return true; }
  3436. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3437. {
  3438. return otherType.toBool (otherData) == data.boolValue;
  3439. }
  3440. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3441. {
  3442. output.writeCompressedInt (1);
  3443. output.writeByte (data.boolValue ? 2 : 3);
  3444. }
  3445. };
  3446. class var::VariantType_String : public var::VariantType
  3447. {
  3448. public:
  3449. VariantType_String() {}
  3450. static const VariantType_String instance;
  3451. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3452. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3453. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3454. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3455. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3456. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3457. || data.stringValue->trim().equalsIgnoreCase ("true")
  3458. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3459. bool isString() const throw() { return true; }
  3460. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3461. {
  3462. return otherType.toString (otherData) == *data.stringValue;
  3463. }
  3464. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3465. {
  3466. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3467. output.writeCompressedInt (len + 1);
  3468. output.writeByte (5);
  3469. HeapBlock<char> temp (len);
  3470. data.stringValue->copyToUTF8 (temp, len);
  3471. output.write (temp, len);
  3472. }
  3473. };
  3474. class var::VariantType_Object : public var::VariantType
  3475. {
  3476. public:
  3477. VariantType_Object() {}
  3478. static const VariantType_Object instance;
  3479. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3480. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3481. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3482. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3483. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3484. bool isObject() const throw() { return true; }
  3485. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3486. {
  3487. return otherType.toObject (otherData) == data.objectValue;
  3488. }
  3489. void writeToStream (const ValueUnion&, OutputStream& output) const
  3490. {
  3491. jassertfalse; // Can't write an object to a stream!
  3492. output.writeCompressedInt (0);
  3493. }
  3494. };
  3495. class var::VariantType_Method : public var::VariantType
  3496. {
  3497. public:
  3498. VariantType_Method() {}
  3499. static const VariantType_Method instance;
  3500. const String toString (const ValueUnion&) const { return "Method"; }
  3501. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3502. bool isMethod() const throw() { return true; }
  3503. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3504. {
  3505. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3506. }
  3507. void writeToStream (const ValueUnion&, OutputStream& output) const
  3508. {
  3509. jassertfalse; // Can't write a method to a stream!
  3510. output.writeCompressedInt (0);
  3511. }
  3512. };
  3513. const var::VariantType_Void var::VariantType_Void::instance;
  3514. const var::VariantType_Int var::VariantType_Int::instance;
  3515. const var::VariantType_Bool var::VariantType_Bool::instance;
  3516. const var::VariantType_Double var::VariantType_Double::instance;
  3517. const var::VariantType_String var::VariantType_String::instance;
  3518. const var::VariantType_Object var::VariantType_Object::instance;
  3519. const var::VariantType_Method var::VariantType_Method::instance;
  3520. var::var() throw() : type (&VariantType_Void::instance)
  3521. {
  3522. }
  3523. var::~var() throw()
  3524. {
  3525. type->cleanUp (value);
  3526. }
  3527. const var var::null;
  3528. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3529. {
  3530. type->createCopy (value, valueToCopy.value);
  3531. }
  3532. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3533. {
  3534. value.intValue = value_;
  3535. }
  3536. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3537. {
  3538. value.boolValue = value_;
  3539. }
  3540. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3541. {
  3542. value.doubleValue = value_;
  3543. }
  3544. var::var (const String& value_) : type (&VariantType_String::instance)
  3545. {
  3546. value.stringValue = new String (value_);
  3547. }
  3548. var::var (const char* const value_) : type (&VariantType_String::instance)
  3549. {
  3550. value.stringValue = new String (value_);
  3551. }
  3552. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3553. {
  3554. value.stringValue = new String (value_);
  3555. }
  3556. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3557. {
  3558. value.objectValue = object;
  3559. if (object != 0)
  3560. object->incReferenceCount();
  3561. }
  3562. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3563. {
  3564. value.methodValue = method_;
  3565. }
  3566. bool var::isVoid() const throw() { return type->isVoid(); }
  3567. bool var::isInt() const throw() { return type->isInt(); }
  3568. bool var::isBool() const throw() { return type->isBool(); }
  3569. bool var::isDouble() const throw() { return type->isDouble(); }
  3570. bool var::isString() const throw() { return type->isString(); }
  3571. bool var::isObject() const throw() { return type->isObject(); }
  3572. bool var::isMethod() const throw() { return type->isMethod(); }
  3573. var::operator int() const { return type->toInt (value); }
  3574. var::operator bool() const { return type->toBool (value); }
  3575. var::operator float() const { return (float) type->toDouble (value); }
  3576. var::operator double() const { return type->toDouble (value); }
  3577. const String var::toString() const { return type->toString (value); }
  3578. var::operator const String() const { return type->toString (value); }
  3579. DynamicObject* var::getObject() const { return type->toObject (value); }
  3580. void var::swapWith (var& other) throw()
  3581. {
  3582. swapVariables (type, other.type);
  3583. swapVariables (value, other.value);
  3584. }
  3585. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3586. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3587. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3588. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3589. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3590. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3591. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3592. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3593. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3594. bool var::equals (const var& other) const throw()
  3595. {
  3596. return type->equals (value, other.value, *other.type);
  3597. }
  3598. bool var::equalsWithSameType (const var& other) const throw()
  3599. {
  3600. return type == other.type && equals (other);
  3601. }
  3602. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3603. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3604. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3605. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3606. void var::writeToStream (OutputStream& output) const
  3607. {
  3608. type->writeToStream (value, output);
  3609. }
  3610. const var var::readFromStream (InputStream& input)
  3611. {
  3612. const int numBytes = input.readCompressedInt();
  3613. if (numBytes > 0)
  3614. {
  3615. switch (input.readByte())
  3616. {
  3617. case 1: return var (input.readInt());
  3618. case 2: return var (true);
  3619. case 3: return var (false);
  3620. case 4: return var (input.readDouble());
  3621. case 5:
  3622. {
  3623. MemoryOutputStream mo;
  3624. mo.writeFromInputStream (input, numBytes - 1);
  3625. return var (mo.toUTF8());
  3626. }
  3627. default: input.skipNextBytes (numBytes - 1); break;
  3628. }
  3629. }
  3630. return var::null;
  3631. }
  3632. const var var::operator[] (const Identifier& propertyName) const
  3633. {
  3634. DynamicObject* const o = getObject();
  3635. return o != 0 ? o->getProperty (propertyName) : var::null;
  3636. }
  3637. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3638. {
  3639. DynamicObject* const o = getObject();
  3640. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3641. }
  3642. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3643. {
  3644. if (isMethod())
  3645. {
  3646. DynamicObject* const target = targetObject.getObject();
  3647. if (target != 0)
  3648. return (target->*(value.methodValue)) (arguments, numArguments);
  3649. }
  3650. return var::null;
  3651. }
  3652. const var var::call (const Identifier& method) const
  3653. {
  3654. return invoke (method, 0, 0);
  3655. }
  3656. const var var::call (const Identifier& method, const var& arg1) const
  3657. {
  3658. return invoke (method, &arg1, 1);
  3659. }
  3660. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3661. {
  3662. var args[] = { arg1, arg2 };
  3663. return invoke (method, args, 2);
  3664. }
  3665. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3666. {
  3667. var args[] = { arg1, arg2, arg3 };
  3668. return invoke (method, args, 3);
  3669. }
  3670. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3671. {
  3672. var args[] = { arg1, arg2, arg3, arg4 };
  3673. return invoke (method, args, 4);
  3674. }
  3675. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3676. {
  3677. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3678. return invoke (method, args, 5);
  3679. }
  3680. END_JUCE_NAMESPACE
  3681. /*** End of inlined file: juce_Variant.cpp ***/
  3682. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3683. BEGIN_JUCE_NAMESPACE
  3684. NamedValueSet::NamedValue::NamedValue() throw()
  3685. {
  3686. }
  3687. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3688. : name (name_), value (value_)
  3689. {
  3690. }
  3691. NamedValueSet::NamedValue::NamedValue (const NamedValue& other)
  3692. : name (other.name), value (other.value)
  3693. {
  3694. }
  3695. NamedValueSet::NamedValue& NamedValueSet::NamedValue::operator= (const NamedValueSet::NamedValue& other)
  3696. {
  3697. name = other.name;
  3698. value = other.value;
  3699. return *this;
  3700. }
  3701. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3702. {
  3703. return name == other.name && value == other.value;
  3704. }
  3705. NamedValueSet::NamedValueSet() throw()
  3706. {
  3707. }
  3708. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3709. {
  3710. values.addCopyOfList (other.values);
  3711. }
  3712. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3713. {
  3714. clear();
  3715. values.addCopyOfList (other.values);
  3716. return *this;
  3717. }
  3718. NamedValueSet::~NamedValueSet()
  3719. {
  3720. clear();
  3721. }
  3722. void NamedValueSet::clear()
  3723. {
  3724. values.deleteAll();
  3725. }
  3726. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3727. {
  3728. const NamedValue* i1 = values;
  3729. const NamedValue* i2 = other.values;
  3730. while (i1 != 0 && i2 != 0)
  3731. {
  3732. if (! (*i1 == *i2))
  3733. return false;
  3734. i1 = i1->nextListItem;
  3735. i2 = i2->nextListItem;
  3736. }
  3737. return true;
  3738. }
  3739. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3740. {
  3741. return ! operator== (other);
  3742. }
  3743. int NamedValueSet::size() const throw()
  3744. {
  3745. return values.size();
  3746. }
  3747. const var& NamedValueSet::operator[] (const Identifier& name) const
  3748. {
  3749. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3750. if (i->name == name)
  3751. return i->value;
  3752. return var::null;
  3753. }
  3754. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3755. {
  3756. const var* v = getVarPointer (name);
  3757. return v != 0 ? *v : defaultReturnValue;
  3758. }
  3759. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3760. {
  3761. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3762. if (i->name == name)
  3763. return &(i->value);
  3764. return 0;
  3765. }
  3766. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3767. {
  3768. LinkedListPointer<NamedValue>* i = &values;
  3769. while (i->get() != 0)
  3770. {
  3771. NamedValue* const v = i->get();
  3772. if (v->name == name)
  3773. {
  3774. if (v->value == newValue)
  3775. return false;
  3776. v->value = newValue;
  3777. return true;
  3778. }
  3779. i = &(v->nextListItem);
  3780. }
  3781. i->insertNext (new NamedValue (name, newValue));
  3782. return true;
  3783. }
  3784. bool NamedValueSet::contains (const Identifier& name) const
  3785. {
  3786. return getVarPointer (name) != 0;
  3787. }
  3788. bool NamedValueSet::remove (const Identifier& name)
  3789. {
  3790. LinkedListPointer<NamedValue>* i = &values;
  3791. for (;;)
  3792. {
  3793. NamedValue* const v = i->get();
  3794. if (v == 0)
  3795. break;
  3796. if (v->name == name)
  3797. {
  3798. delete i->removeNext();
  3799. return true;
  3800. }
  3801. i = &(v->nextListItem);
  3802. }
  3803. return false;
  3804. }
  3805. const Identifier NamedValueSet::getName (const int index) const
  3806. {
  3807. const NamedValue* const v = values[index];
  3808. jassert (v != 0);
  3809. return v->name;
  3810. }
  3811. const var NamedValueSet::getValueAt (const int index) const
  3812. {
  3813. const NamedValue* const v = values[index];
  3814. jassert (v != 0);
  3815. return v->value;
  3816. }
  3817. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3818. {
  3819. clear();
  3820. LinkedListPointer<NamedValue>::Appender appender (values);
  3821. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3822. for (int i = 0; i < numAtts; ++i)
  3823. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3824. }
  3825. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3826. {
  3827. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3828. {
  3829. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3830. xml.setAttribute (i->name.toString(),
  3831. i->value.toString());
  3832. }
  3833. }
  3834. END_JUCE_NAMESPACE
  3835. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3836. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3837. BEGIN_JUCE_NAMESPACE
  3838. DynamicObject::DynamicObject()
  3839. {
  3840. }
  3841. DynamicObject::~DynamicObject()
  3842. {
  3843. }
  3844. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3845. {
  3846. var* const v = properties.getVarPointer (propertyName);
  3847. return v != 0 && ! v->isMethod();
  3848. }
  3849. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3850. {
  3851. return properties [propertyName];
  3852. }
  3853. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3854. {
  3855. properties.set (propertyName, newValue);
  3856. }
  3857. void DynamicObject::removeProperty (const Identifier& propertyName)
  3858. {
  3859. properties.remove (propertyName);
  3860. }
  3861. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3862. {
  3863. return getProperty (methodName).isMethod();
  3864. }
  3865. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3866. const var* parameters,
  3867. int numParameters)
  3868. {
  3869. return properties [methodName].invoke (var (this), parameters, numParameters);
  3870. }
  3871. void DynamicObject::setMethod (const Identifier& name,
  3872. var::MethodFunction methodFunction)
  3873. {
  3874. properties.set (name, var (methodFunction));
  3875. }
  3876. void DynamicObject::clear()
  3877. {
  3878. properties.clear();
  3879. }
  3880. END_JUCE_NAMESPACE
  3881. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3882. /*** Start of inlined file: juce_Expression.cpp ***/
  3883. BEGIN_JUCE_NAMESPACE
  3884. class Expression::Term : public ReferenceCountedObject
  3885. {
  3886. public:
  3887. Term() {}
  3888. virtual ~Term() {}
  3889. virtual Type getType() const throw() = 0;
  3890. virtual Term* clone() const = 0;
  3891. virtual const ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  3892. virtual const String toString() const = 0;
  3893. virtual double toDouble() const { return 0; }
  3894. virtual int getInputIndexFor (const Term*) const { return -1; }
  3895. virtual int getOperatorPrecedence() const { return 0; }
  3896. virtual int getNumInputs() const { return 0; }
  3897. virtual Term* getInput (int) const { return 0; }
  3898. virtual const ReferenceCountedObjectPtr<Term> negated();
  3899. virtual const ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  3900. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  3901. {
  3902. jassertfalse;
  3903. return 0;
  3904. }
  3905. virtual const String getName() const
  3906. {
  3907. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  3908. return String::empty;
  3909. }
  3910. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  3911. {
  3912. for (int i = getNumInputs(); --i >= 0;)
  3913. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  3914. }
  3915. class SymbolVisitor
  3916. {
  3917. public:
  3918. virtual ~SymbolVisitor() {}
  3919. virtual void useSymbol (const Symbol&) = 0;
  3920. };
  3921. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  3922. {
  3923. for (int i = getNumInputs(); --i >= 0;)
  3924. getInput(i)->visitAllSymbols (visitor, scope, recursionDepth);
  3925. }
  3926. private:
  3927. JUCE_DECLARE_NON_COPYABLE (Term);
  3928. };
  3929. class Expression::Helpers
  3930. {
  3931. public:
  3932. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3933. // This helper function is needed to work around VC6 scoping bugs
  3934. static inline const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3935. static void checkRecursionDepth (const int depth)
  3936. {
  3937. if (depth > 256)
  3938. throw EvaluationError ("Recursive symbol references");
  3939. }
  3940. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3941. /** An exception that can be thrown by Expression::evaluate(). */
  3942. class EvaluationError : public std::exception
  3943. {
  3944. public:
  3945. EvaluationError (const String& description_)
  3946. : description (description_)
  3947. {
  3948. DBG ("Expression::EvaluationError: " + description);
  3949. }
  3950. String description;
  3951. };
  3952. class Constant : public Term
  3953. {
  3954. public:
  3955. Constant (const double value_, const bool isResolutionTarget_)
  3956. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3957. Type getType() const throw() { return constantType; }
  3958. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3959. const TermPtr resolve (const Scope&, int) { return this; }
  3960. double toDouble() const { return value; }
  3961. const TermPtr negated() { return new Constant (-value, isResolutionTarget); }
  3962. const String toString() const
  3963. {
  3964. String s (value);
  3965. if (isResolutionTarget)
  3966. s = "@" + s;
  3967. return s;
  3968. }
  3969. double value;
  3970. bool isResolutionTarget;
  3971. };
  3972. class BinaryTerm : public Term
  3973. {
  3974. public:
  3975. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3976. {
  3977. jassert (left_ != 0 && right_ != 0);
  3978. }
  3979. int getInputIndexFor (const Term* possibleInput) const
  3980. {
  3981. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3982. }
  3983. Type getType() const throw() { return operatorType; }
  3984. int getNumInputs() const { return 2; }
  3985. Term* getInput (int index) const { return index == 0 ? left.getObject() : (index == 1 ? right.getObject() : 0); }
  3986. virtual double performFunction (double left, double right) const = 0;
  3987. virtual void writeOperator (String& dest) const = 0;
  3988. const TermPtr resolve (const Scope& scope, int recursionDepth)
  3989. {
  3990. return new Constant (performFunction (left->resolve (scope, recursionDepth)->toDouble(),
  3991. right->resolve (scope, recursionDepth)->toDouble()), false);
  3992. }
  3993. const String toString() const
  3994. {
  3995. String s;
  3996. const int ourPrecendence = getOperatorPrecedence();
  3997. if (left->getOperatorPrecedence() > ourPrecendence)
  3998. s << '(' << left->toString() << ')';
  3999. else
  4000. s = left->toString();
  4001. writeOperator (s);
  4002. if (right->getOperatorPrecedence() >= ourPrecendence)
  4003. s << '(' << right->toString() << ')';
  4004. else
  4005. s << right->toString();
  4006. return s;
  4007. }
  4008. protected:
  4009. const TermPtr left, right;
  4010. const TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4011. {
  4012. jassert (input == left || input == right);
  4013. if (input != left && input != right)
  4014. return 0;
  4015. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4016. if (dest == 0)
  4017. return new Constant (overallTarget, false);
  4018. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  4019. }
  4020. };
  4021. class SymbolTerm : public Term
  4022. {
  4023. public:
  4024. explicit SymbolTerm (const String& symbol_) : symbol (symbol_) {}
  4025. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4026. {
  4027. checkRecursionDepth (recursionDepth);
  4028. return getTermFor (scope.getSymbolValue (symbol))->resolve (scope, recursionDepth + 1);
  4029. }
  4030. Type getType() const throw() { return symbolType; }
  4031. Term* clone() const { return new SymbolTerm (symbol); }
  4032. const String toString() const { return symbol; }
  4033. const String getName() const { return symbol; }
  4034. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4035. {
  4036. checkRecursionDepth (recursionDepth);
  4037. visitor.useSymbol (Symbol (scope.getScopeUID(), symbol));
  4038. getTermFor (scope.getSymbolValue (symbol))->visitAllSymbols (visitor, scope, recursionDepth + 1);
  4039. }
  4040. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/)
  4041. {
  4042. if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID)
  4043. symbol = newName;
  4044. }
  4045. String symbol;
  4046. };
  4047. class Function : public Term
  4048. {
  4049. public:
  4050. explicit Function (const String& functionName_) : functionName (functionName_) {}
  4051. Function (const String& functionName_, const Array<Expression>& parameters_)
  4052. : functionName (functionName_), parameters (parameters_)
  4053. {}
  4054. Type getType() const throw() { return functionType; }
  4055. Term* clone() const { return new Function (functionName, parameters); }
  4056. int getNumInputs() const { return parameters.size(); }
  4057. Term* getInput (int i) const { return getTermFor (parameters [i]); }
  4058. const String getName() const { return functionName; }
  4059. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4060. {
  4061. checkRecursionDepth (recursionDepth);
  4062. double result = 0;
  4063. const int numParams = parameters.size();
  4064. if (numParams > 0)
  4065. {
  4066. HeapBlock<double> params (numParams);
  4067. for (int i = 0; i < numParams; ++i)
  4068. params[i] = getTermFor (parameters.getReference(i))->resolve (scope, recursionDepth + 1)->toDouble();
  4069. result = scope.evaluateFunction (functionName, params, numParams);
  4070. }
  4071. else
  4072. {
  4073. result = scope.evaluateFunction (functionName, 0, 0);
  4074. }
  4075. return new Constant (result, false);
  4076. }
  4077. int getInputIndexFor (const Term* possibleInput) const
  4078. {
  4079. for (int i = 0; i < parameters.size(); ++i)
  4080. if (getTermFor (parameters.getReference(i)) == possibleInput)
  4081. return i;
  4082. return -1;
  4083. }
  4084. const String toString() const
  4085. {
  4086. if (parameters.size() == 0)
  4087. return functionName + "()";
  4088. String s (functionName + " (");
  4089. for (int i = 0; i < parameters.size(); ++i)
  4090. {
  4091. s << getTermFor (parameters.getReference(i))->toString();
  4092. if (i < parameters.size() - 1)
  4093. s << ", ";
  4094. }
  4095. s << ')';
  4096. return s;
  4097. }
  4098. const String functionName;
  4099. Array<Expression> parameters;
  4100. };
  4101. class DotOperator : public BinaryTerm
  4102. {
  4103. public:
  4104. DotOperator (SymbolTerm* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4105. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4106. {
  4107. checkRecursionDepth (recursionDepth);
  4108. EvaluationVisitor visitor (right, recursionDepth + 1);
  4109. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4110. return visitor.output;
  4111. }
  4112. Term* clone() const { return new DotOperator (getSymbol(), right); }
  4113. const String getName() const { return "."; }
  4114. int getOperatorPrecedence() const { return 1; }
  4115. void writeOperator (String& dest) const { dest << '.'; }
  4116. double performFunction (double, double) const { return 0.0; }
  4117. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4118. {
  4119. checkRecursionDepth (recursionDepth);
  4120. visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol));
  4121. SymbolVisitingVisitor v (right, visitor, recursionDepth + 1);
  4122. try
  4123. {
  4124. scope.visitRelativeScope (getSymbol()->symbol, v);
  4125. }
  4126. catch (...) {}
  4127. }
  4128. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  4129. {
  4130. checkRecursionDepth (recursionDepth);
  4131. getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  4132. SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1);
  4133. try
  4134. {
  4135. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4136. }
  4137. catch (...) {}
  4138. }
  4139. private:
  4140. class EvaluationVisitor : public Scope::Visitor
  4141. {
  4142. public:
  4143. EvaluationVisitor (const TermPtr& input_, const int recursionCount_)
  4144. : input (input_), output (input_), recursionCount (recursionCount_) {}
  4145. void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); }
  4146. const TermPtr input;
  4147. TermPtr output;
  4148. const int recursionCount;
  4149. private:
  4150. JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor);
  4151. };
  4152. class SymbolVisitingVisitor : public Scope::Visitor
  4153. {
  4154. public:
  4155. SymbolVisitingVisitor (const TermPtr& input_, SymbolVisitor& visitor_, const int recursionCount_)
  4156. : input (input_), visitor (visitor_), recursionCount (recursionCount_) {}
  4157. void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); }
  4158. private:
  4159. const TermPtr input;
  4160. SymbolVisitor& visitor;
  4161. const int recursionCount;
  4162. JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor);
  4163. };
  4164. class SymbolRenamingVisitor : public Scope::Visitor
  4165. {
  4166. public:
  4167. SymbolRenamingVisitor (const TermPtr& input_, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_)
  4168. : input (input_), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {}
  4169. void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); }
  4170. private:
  4171. const TermPtr input;
  4172. const Symbol& symbol;
  4173. const String newName;
  4174. const int recursionCount;
  4175. JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor);
  4176. };
  4177. SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.getObject()); }
  4178. JUCE_DECLARE_NON_COPYABLE (DotOperator);
  4179. };
  4180. class Negate : public Term
  4181. {
  4182. public:
  4183. explicit Negate (const TermPtr& input_) : input (input_)
  4184. {
  4185. jassert (input_ != 0);
  4186. }
  4187. Type getType() const throw() { return operatorType; }
  4188. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  4189. int getNumInputs() const { return 1; }
  4190. Term* getInput (int index) const { return index == 0 ? input.getObject() : 0; }
  4191. Term* clone() const { return new Negate (input->clone()); }
  4192. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4193. {
  4194. return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false);
  4195. }
  4196. const String getName() const { return "-"; }
  4197. const TermPtr negated() { return input; }
  4198. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input_, double overallTarget, Term* topLevelTerm) const
  4199. {
  4200. (void) input_;
  4201. jassert (input_ == input);
  4202. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4203. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  4204. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  4205. }
  4206. const String toString() const
  4207. {
  4208. if (input->getOperatorPrecedence() > 0)
  4209. return "-(" + input->toString() + ")";
  4210. else
  4211. return "-" + input->toString();
  4212. }
  4213. private:
  4214. const TermPtr input;
  4215. };
  4216. class Add : public BinaryTerm
  4217. {
  4218. public:
  4219. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4220. Term* clone() const { return new Add (left->clone(), right->clone()); }
  4221. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  4222. int getOperatorPrecedence() const { return 3; }
  4223. const String getName() const { return "+"; }
  4224. void writeOperator (String& dest) const { dest << " + "; }
  4225. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4226. {
  4227. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4228. if (newDest == 0)
  4229. return 0;
  4230. return new Subtract (newDest, (input == left ? right : left)->clone());
  4231. }
  4232. private:
  4233. JUCE_DECLARE_NON_COPYABLE (Add);
  4234. };
  4235. class Subtract : public BinaryTerm
  4236. {
  4237. public:
  4238. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4239. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4240. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  4241. int getOperatorPrecedence() const { return 3; }
  4242. const String getName() const { return "-"; }
  4243. void writeOperator (String& dest) const { dest << " - "; }
  4244. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4245. {
  4246. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4247. if (newDest == 0)
  4248. return 0;
  4249. if (input == left)
  4250. return new Add (newDest, right->clone());
  4251. else
  4252. return new Subtract (left->clone(), newDest);
  4253. }
  4254. private:
  4255. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4256. };
  4257. class Multiply : public BinaryTerm
  4258. {
  4259. public:
  4260. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4261. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4262. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  4263. const String getName() const { return "*"; }
  4264. void writeOperator (String& dest) const { dest << " * "; }
  4265. int getOperatorPrecedence() const { return 2; }
  4266. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4267. {
  4268. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4269. if (newDest == 0)
  4270. return 0;
  4271. return new Divide (newDest, (input == left ? right : left)->clone());
  4272. }
  4273. private:
  4274. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4275. };
  4276. class Divide : public BinaryTerm
  4277. {
  4278. public:
  4279. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4280. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4281. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  4282. const String getName() const { return "/"; }
  4283. void writeOperator (String& dest) const { dest << " / "; }
  4284. int getOperatorPrecedence() const { return 2; }
  4285. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4286. {
  4287. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4288. if (newDest == 0)
  4289. return 0;
  4290. if (input == left)
  4291. return new Multiply (newDest, right->clone());
  4292. else
  4293. return new Divide (left->clone(), newDest);
  4294. }
  4295. private:
  4296. JUCE_DECLARE_NON_COPYABLE (Divide);
  4297. };
  4298. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4299. {
  4300. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4301. if (inputIndex >= 0)
  4302. return topLevel;
  4303. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4304. {
  4305. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4306. if (t != 0)
  4307. return t;
  4308. }
  4309. return 0;
  4310. }
  4311. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4312. {
  4313. {
  4314. Constant* const c = dynamic_cast<Constant*> (term);
  4315. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4316. return c;
  4317. }
  4318. if (dynamic_cast<Function*> (term) != 0)
  4319. return 0;
  4320. int i;
  4321. const int numIns = term->getNumInputs();
  4322. for (i = 0; i < numIns; ++i)
  4323. {
  4324. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4325. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4326. return c;
  4327. }
  4328. for (i = 0; i < numIns; ++i)
  4329. {
  4330. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4331. if (c != 0)
  4332. return c;
  4333. }
  4334. return 0;
  4335. }
  4336. static bool containsAnySymbols (const Term* const t)
  4337. {
  4338. if (t->getType() == Expression::symbolType)
  4339. return true;
  4340. for (int i = t->getNumInputs(); --i >= 0;)
  4341. if (containsAnySymbols (t->getInput (i)))
  4342. return true;
  4343. return false;
  4344. }
  4345. class SymbolCheckVisitor : public Term::SymbolVisitor
  4346. {
  4347. public:
  4348. SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {}
  4349. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  4350. bool wasFound;
  4351. private:
  4352. const Symbol& symbol;
  4353. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor);
  4354. };
  4355. class SymbolListVisitor : public Term::SymbolVisitor
  4356. {
  4357. public:
  4358. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  4359. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  4360. private:
  4361. Array<Symbol>& list;
  4362. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor);
  4363. };
  4364. class Parser
  4365. {
  4366. public:
  4367. Parser (String::CharPointerType& stringToParse)
  4368. : text (stringToParse)
  4369. {
  4370. }
  4371. const TermPtr readUpToComma()
  4372. {
  4373. if (text.isEmpty())
  4374. return new Constant (0.0, false);
  4375. const TermPtr e (readExpression());
  4376. if (e == 0 || ((! readOperator (",")) && ! text.isEmpty()))
  4377. throw ParseError ("Syntax error: \"" + String (text) + "\"");
  4378. return e;
  4379. }
  4380. private:
  4381. String::CharPointerType& text;
  4382. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4383. {
  4384. return c >= '0' && c <= '9';
  4385. }
  4386. bool readChar (const juce_wchar required) throw()
  4387. {
  4388. if (*text == required)
  4389. {
  4390. ++text;
  4391. return true;
  4392. }
  4393. return false;
  4394. }
  4395. bool readOperator (const char* ops, char* const opType = 0) throw()
  4396. {
  4397. text = text.findEndOfWhitespace();
  4398. while (*ops != 0)
  4399. {
  4400. if (readChar (*ops))
  4401. {
  4402. if (opType != 0)
  4403. *opType = *ops;
  4404. return true;
  4405. }
  4406. ++ops;
  4407. }
  4408. return false;
  4409. }
  4410. bool readIdentifier (String& identifier) throw()
  4411. {
  4412. text = text.findEndOfWhitespace();
  4413. String::CharPointerType t (text);
  4414. int numChars = 0;
  4415. if (t.isLetter() || *t == '_')
  4416. {
  4417. ++t;
  4418. ++numChars;
  4419. while (t.isLetterOrDigit() || *t == '_')
  4420. {
  4421. ++t;
  4422. ++numChars;
  4423. }
  4424. }
  4425. if (numChars > 0)
  4426. {
  4427. identifier = String (text, numChars);
  4428. text = t;
  4429. return true;
  4430. }
  4431. return false;
  4432. }
  4433. Term* readNumber() throw()
  4434. {
  4435. text = text.findEndOfWhitespace();
  4436. String::CharPointerType t (text);
  4437. const bool isResolutionTarget = (*t == '@');
  4438. if (isResolutionTarget)
  4439. {
  4440. ++t;
  4441. t = t.findEndOfWhitespace();
  4442. text = t;
  4443. }
  4444. if (*t == '-')
  4445. {
  4446. ++t;
  4447. t = t.findEndOfWhitespace();
  4448. }
  4449. if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1])))
  4450. return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget);
  4451. return 0;
  4452. }
  4453. const TermPtr readExpression()
  4454. {
  4455. TermPtr lhs (readMultiplyOrDivideExpression());
  4456. char opType;
  4457. while (lhs != 0 && readOperator ("+-", &opType))
  4458. {
  4459. TermPtr rhs (readMultiplyOrDivideExpression());
  4460. if (rhs == 0)
  4461. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4462. if (opType == '+')
  4463. lhs = new Add (lhs, rhs);
  4464. else
  4465. lhs = new Subtract (lhs, rhs);
  4466. }
  4467. return lhs;
  4468. }
  4469. const TermPtr readMultiplyOrDivideExpression()
  4470. {
  4471. TermPtr lhs (readUnaryExpression());
  4472. char opType;
  4473. while (lhs != 0 && readOperator ("*/", &opType))
  4474. {
  4475. TermPtr rhs (readUnaryExpression());
  4476. if (rhs == 0)
  4477. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4478. if (opType == '*')
  4479. lhs = new Multiply (lhs, rhs);
  4480. else
  4481. lhs = new Divide (lhs, rhs);
  4482. }
  4483. return lhs;
  4484. }
  4485. const TermPtr readUnaryExpression()
  4486. {
  4487. char opType;
  4488. if (readOperator ("+-", &opType))
  4489. {
  4490. TermPtr term (readUnaryExpression());
  4491. if (term == 0)
  4492. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4493. if (opType == '-')
  4494. term = term->negated();
  4495. return term;
  4496. }
  4497. return readPrimaryExpression();
  4498. }
  4499. const TermPtr readPrimaryExpression()
  4500. {
  4501. TermPtr e (readParenthesisedExpression());
  4502. if (e != 0)
  4503. return e;
  4504. e = readNumber();
  4505. if (e != 0)
  4506. return e;
  4507. return readSymbolOrFunction();
  4508. }
  4509. const TermPtr readSymbolOrFunction()
  4510. {
  4511. String identifier;
  4512. if (readIdentifier (identifier))
  4513. {
  4514. if (readOperator ("(")) // method call...
  4515. {
  4516. Function* const f = new Function (identifier);
  4517. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4518. TermPtr param (readExpression());
  4519. if (param == 0)
  4520. {
  4521. if (readOperator (")"))
  4522. return func.release();
  4523. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4524. }
  4525. f->parameters.add (Expression (param));
  4526. while (readOperator (","))
  4527. {
  4528. param = readExpression();
  4529. if (param == 0)
  4530. throw ParseError ("Expected expression after \",\"");
  4531. f->parameters.add (Expression (param));
  4532. }
  4533. if (readOperator (")"))
  4534. return func.release();
  4535. throw ParseError ("Expected \")\"");
  4536. }
  4537. else if (readOperator ("."))
  4538. {
  4539. TermPtr rhs (readSymbolOrFunction());
  4540. if (rhs == 0)
  4541. throw ParseError ("Expected symbol or function after \".\"");
  4542. if (identifier == "this")
  4543. return rhs;
  4544. return new DotOperator (new SymbolTerm (identifier), rhs);
  4545. }
  4546. else // just a symbol..
  4547. {
  4548. jassert (identifier.trim() == identifier);
  4549. return new SymbolTerm (identifier);
  4550. }
  4551. }
  4552. return 0;
  4553. }
  4554. const TermPtr readParenthesisedExpression()
  4555. {
  4556. if (! readOperator ("("))
  4557. return 0;
  4558. const TermPtr e (readExpression());
  4559. if (e == 0 || ! readOperator (")"))
  4560. return 0;
  4561. return e;
  4562. }
  4563. JUCE_DECLARE_NON_COPYABLE (Parser);
  4564. };
  4565. };
  4566. Expression::Expression()
  4567. : term (new Expression::Helpers::Constant (0, false))
  4568. {
  4569. }
  4570. Expression::~Expression()
  4571. {
  4572. }
  4573. Expression::Expression (Term* const term_)
  4574. : term (term_)
  4575. {
  4576. jassert (term != 0);
  4577. }
  4578. Expression::Expression (const double constant)
  4579. : term (new Expression::Helpers::Constant (constant, false))
  4580. {
  4581. }
  4582. Expression::Expression (const Expression& other)
  4583. : term (other.term)
  4584. {
  4585. }
  4586. Expression& Expression::operator= (const Expression& other)
  4587. {
  4588. term = other.term;
  4589. return *this;
  4590. }
  4591. Expression::Expression (const String& stringToParse)
  4592. {
  4593. String::CharPointerType text (stringToParse.getCharPointer());
  4594. Helpers::Parser parser (text);
  4595. term = parser.readUpToComma();
  4596. }
  4597. const Expression Expression::parse (String::CharPointerType& stringToParse)
  4598. {
  4599. Helpers::Parser parser (stringToParse);
  4600. return Expression (parser.readUpToComma());
  4601. }
  4602. double Expression::evaluate() const
  4603. {
  4604. return evaluate (Expression::Scope());
  4605. }
  4606. double Expression::evaluate (const Expression::Scope& scope) const
  4607. {
  4608. try
  4609. {
  4610. return term->resolve (scope, 0)->toDouble();
  4611. }
  4612. catch (Helpers::EvaluationError&)
  4613. {}
  4614. return 0;
  4615. }
  4616. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  4617. {
  4618. try
  4619. {
  4620. return term->resolve (scope, 0)->toDouble();
  4621. }
  4622. catch (Helpers::EvaluationError& e)
  4623. {
  4624. evaluationError = e.description;
  4625. }
  4626. return 0;
  4627. }
  4628. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4629. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4630. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4631. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4632. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4633. const Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  4634. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4635. {
  4636. return Expression (new Helpers::Function (functionName, parameters));
  4637. }
  4638. const Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  4639. {
  4640. ScopedPointer<Term> newTerm (term->clone());
  4641. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4642. if (termToAdjust == 0)
  4643. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4644. if (termToAdjust == 0)
  4645. {
  4646. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4647. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4648. }
  4649. jassert (termToAdjust != 0);
  4650. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4651. if (parent == 0)
  4652. {
  4653. termToAdjust->value = targetValue;
  4654. }
  4655. else
  4656. {
  4657. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm));
  4658. if (reverseTerm == 0)
  4659. return Expression (targetValue);
  4660. termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble();
  4661. }
  4662. return Expression (newTerm.release());
  4663. }
  4664. const Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  4665. {
  4666. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4667. if (oldSymbol.symbolName == newName)
  4668. return *this;
  4669. Expression e (term->clone());
  4670. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  4671. return e;
  4672. }
  4673. bool Expression::referencesSymbol (const Expression::Symbol& symbol, const Scope& scope) const
  4674. {
  4675. Helpers::SymbolCheckVisitor visitor (symbol);
  4676. try
  4677. {
  4678. term->visitAllSymbols (visitor, scope, 0);
  4679. }
  4680. catch (Helpers::EvaluationError&)
  4681. {}
  4682. return visitor.wasFound;
  4683. }
  4684. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  4685. {
  4686. try
  4687. {
  4688. Helpers::SymbolListVisitor visitor (results);
  4689. term->visitAllSymbols (visitor, scope, 0);
  4690. }
  4691. catch (Helpers::EvaluationError&)
  4692. {}
  4693. }
  4694. const String Expression::toString() const { return term->toString(); }
  4695. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); }
  4696. Expression::Type Expression::getType() const throw() { return term->getType(); }
  4697. const String Expression::getSymbolOrFunction() const { return term->getName(); }
  4698. int Expression::getNumInputs() const { return term->getNumInputs(); }
  4699. const Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  4700. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4701. {
  4702. return new Helpers::Negate (this);
  4703. }
  4704. Expression::ParseError::ParseError (const String& message)
  4705. : description (message)
  4706. {
  4707. DBG ("Expression::ParseError: " + message);
  4708. }
  4709. Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_)
  4710. : scopeUID (scopeUID_), symbolName (symbolName_)
  4711. {
  4712. }
  4713. bool Expression::Symbol::operator== (const Symbol& other) const throw()
  4714. {
  4715. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  4716. }
  4717. bool Expression::Symbol::operator!= (const Symbol& other) const throw()
  4718. {
  4719. return ! operator== (other);
  4720. }
  4721. Expression::Scope::Scope() {}
  4722. Expression::Scope::~Scope() {}
  4723. const Expression Expression::Scope::getSymbolValue (const String& symbol) const
  4724. {
  4725. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  4726. }
  4727. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4728. {
  4729. if (numParams > 0)
  4730. {
  4731. if (functionName == "min")
  4732. {
  4733. double v = parameters[0];
  4734. for (int i = 1; i < numParams; ++i)
  4735. v = jmin (v, parameters[i]);
  4736. return v;
  4737. }
  4738. else if (functionName == "max")
  4739. {
  4740. double v = parameters[0];
  4741. for (int i = 1; i < numParams; ++i)
  4742. v = jmax (v, parameters[i]);
  4743. return v;
  4744. }
  4745. else if (numParams == 1)
  4746. {
  4747. if (functionName == "sin") return sin (parameters[0]);
  4748. else if (functionName == "cos") return cos (parameters[0]);
  4749. else if (functionName == "tan") return tan (parameters[0]);
  4750. else if (functionName == "abs") return std::abs (parameters[0]);
  4751. }
  4752. }
  4753. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  4754. }
  4755. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  4756. {
  4757. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  4758. }
  4759. const String Expression::Scope::getScopeUID() const
  4760. {
  4761. return String::empty;
  4762. }
  4763. END_JUCE_NAMESPACE
  4764. /*** End of inlined file: juce_Expression.cpp ***/
  4765. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4766. BEGIN_JUCE_NAMESPACE
  4767. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4768. {
  4769. jassert (keyData != 0);
  4770. jassert (keyBytes > 0);
  4771. static const uint32 initialPValues [18] =
  4772. {
  4773. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4774. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4775. 0x9216d5d9, 0x8979fb1b
  4776. };
  4777. static const uint32 initialSValues [4 * 256] =
  4778. {
  4779. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4780. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4781. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4782. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4783. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4784. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4785. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4786. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4787. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4788. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4789. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4790. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4791. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4792. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4793. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4794. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4795. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4796. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4797. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4798. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4799. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4800. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4801. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4802. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4803. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4804. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4805. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4806. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4807. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4808. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4809. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4810. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4811. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4812. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4813. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4814. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4815. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4816. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4817. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4818. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4819. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4820. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4821. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4822. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4823. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4824. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4825. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4826. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4827. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4828. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4829. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4830. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4831. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4832. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4833. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4834. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4835. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4836. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4837. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4838. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4839. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4840. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4841. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4842. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4843. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4844. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4845. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4846. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4847. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4848. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4849. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4850. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4851. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4852. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4853. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4854. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4855. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4856. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4857. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4858. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4859. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4860. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4861. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4862. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4863. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4864. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4865. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4866. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4867. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4868. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4869. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4870. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4871. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4872. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4873. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4874. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4875. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4876. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4877. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4878. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4879. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4880. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4881. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4882. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4883. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4884. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4885. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4886. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4887. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4888. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4889. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4890. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4891. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4892. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4893. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4894. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4895. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4896. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4897. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4898. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4899. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4900. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4901. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4902. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4903. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4904. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4905. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4906. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4907. };
  4908. memcpy (p, initialPValues, sizeof (p));
  4909. int i, j = 0;
  4910. for (i = 4; --i >= 0;)
  4911. {
  4912. s[i].malloc (256);
  4913. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4914. }
  4915. for (i = 0; i < 18; ++i)
  4916. {
  4917. uint32 d = 0;
  4918. for (int k = 0; k < 4; ++k)
  4919. {
  4920. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4921. if (++j >= keyBytes)
  4922. j = 0;
  4923. }
  4924. p[i] = initialPValues[i] ^ d;
  4925. }
  4926. uint32 l = 0, r = 0;
  4927. for (i = 0; i < 18; i += 2)
  4928. {
  4929. encrypt (l, r);
  4930. p[i] = l;
  4931. p[i + 1] = r;
  4932. }
  4933. for (i = 0; i < 4; ++i)
  4934. {
  4935. for (j = 0; j < 256; j += 2)
  4936. {
  4937. encrypt (l, r);
  4938. s[i][j] = l;
  4939. s[i][j + 1] = r;
  4940. }
  4941. }
  4942. }
  4943. BlowFish::BlowFish (const BlowFish& other)
  4944. {
  4945. for (int i = 4; --i >= 0;)
  4946. s[i].malloc (256);
  4947. operator= (other);
  4948. }
  4949. BlowFish& BlowFish::operator= (const BlowFish& other)
  4950. {
  4951. memcpy (p, other.p, sizeof (p));
  4952. for (int i = 4; --i >= 0;)
  4953. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4954. return *this;
  4955. }
  4956. BlowFish::~BlowFish()
  4957. {
  4958. }
  4959. uint32 BlowFish::F (const uint32 x) const throw()
  4960. {
  4961. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4962. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4963. }
  4964. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4965. {
  4966. uint32 l = data1;
  4967. uint32 r = data2;
  4968. for (int i = 0; i < 16; ++i)
  4969. {
  4970. l ^= p[i];
  4971. r ^= F(l);
  4972. swapVariables (l, r);
  4973. }
  4974. data1 = r ^ p[17];
  4975. data2 = l ^ p[16];
  4976. }
  4977. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4978. {
  4979. uint32 l = data1;
  4980. uint32 r = data2;
  4981. for (int i = 17; i > 1; --i)
  4982. {
  4983. l ^= p[i];
  4984. r ^= F(l);
  4985. swapVariables (l, r);
  4986. }
  4987. data1 = r ^ p[0];
  4988. data2 = l ^ p[1];
  4989. }
  4990. END_JUCE_NAMESPACE
  4991. /*** End of inlined file: juce_BlowFish.cpp ***/
  4992. /*** Start of inlined file: juce_MD5.cpp ***/
  4993. BEGIN_JUCE_NAMESPACE
  4994. MD5::MD5()
  4995. {
  4996. zerostruct (result);
  4997. }
  4998. MD5::MD5 (const MD5& other)
  4999. {
  5000. memcpy (result, other.result, sizeof (result));
  5001. }
  5002. MD5& MD5::operator= (const MD5& other)
  5003. {
  5004. memcpy (result, other.result, sizeof (result));
  5005. return *this;
  5006. }
  5007. MD5::MD5 (const MemoryBlock& data)
  5008. {
  5009. ProcessContext context;
  5010. context.processBlock (data.getData(), data.getSize());
  5011. context.finish (result);
  5012. }
  5013. MD5::MD5 (const void* data, const size_t numBytes)
  5014. {
  5015. ProcessContext context;
  5016. context.processBlock (data, numBytes);
  5017. context.finish (result);
  5018. }
  5019. MD5::MD5 (const String& text)
  5020. {
  5021. ProcessContext context;
  5022. String::CharPointerType t (text.getCharPointer());
  5023. while (! t.isEmpty())
  5024. {
  5025. // force the string into integer-sized unicode characters, to try to make it
  5026. // get the same results on all platforms + compilers.
  5027. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t.getAndAdvance());
  5028. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  5029. }
  5030. context.finish (result);
  5031. }
  5032. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  5033. {
  5034. ProcessContext context;
  5035. if (numBytesToRead < 0)
  5036. numBytesToRead = std::numeric_limits<int64>::max();
  5037. while (numBytesToRead > 0)
  5038. {
  5039. uint8 tempBuffer [512];
  5040. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  5041. if (bytesRead <= 0)
  5042. break;
  5043. numBytesToRead -= bytesRead;
  5044. context.processBlock (tempBuffer, bytesRead);
  5045. }
  5046. context.finish (result);
  5047. }
  5048. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  5049. {
  5050. processStream (input, numBytesToRead);
  5051. }
  5052. MD5::MD5 (const File& file)
  5053. {
  5054. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  5055. if (fin != 0)
  5056. processStream (*fin, -1);
  5057. else
  5058. zerostruct (result);
  5059. }
  5060. MD5::~MD5()
  5061. {
  5062. }
  5063. namespace MD5Functions
  5064. {
  5065. void encode (void* const output, const void* const input, const int numBytes) throw()
  5066. {
  5067. for (int i = 0; i < (numBytes >> 2); ++i)
  5068. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  5069. }
  5070. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  5071. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  5072. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  5073. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  5074. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  5075. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5076. {
  5077. a += F (b, c, d) + x + ac;
  5078. a = rotateLeft (a, s) + b;
  5079. }
  5080. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5081. {
  5082. a += G (b, c, d) + x + ac;
  5083. a = rotateLeft (a, s) + b;
  5084. }
  5085. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5086. {
  5087. a += H (b, c, d) + x + ac;
  5088. a = rotateLeft (a, s) + b;
  5089. }
  5090. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5091. {
  5092. a += I (b, c, d) + x + ac;
  5093. a = rotateLeft (a, s) + b;
  5094. }
  5095. }
  5096. MD5::ProcessContext::ProcessContext()
  5097. {
  5098. state[0] = 0x67452301;
  5099. state[1] = 0xefcdab89;
  5100. state[2] = 0x98badcfe;
  5101. state[3] = 0x10325476;
  5102. count[0] = 0;
  5103. count[1] = 0;
  5104. }
  5105. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  5106. {
  5107. int bufferPos = ((count[0] >> 3) & 0x3F);
  5108. count[0] += (uint32) (dataSize << 3);
  5109. if (count[0] < ((uint32) dataSize << 3))
  5110. count[1]++;
  5111. count[1] += (uint32) (dataSize >> 29);
  5112. const size_t spaceLeft = 64 - bufferPos;
  5113. size_t i = 0;
  5114. if (dataSize >= spaceLeft)
  5115. {
  5116. memcpy (buffer + bufferPos, data, spaceLeft);
  5117. transform (buffer);
  5118. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  5119. transform (static_cast <const char*> (data) + i);
  5120. bufferPos = 0;
  5121. }
  5122. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  5123. }
  5124. void MD5::ProcessContext::finish (void* const result)
  5125. {
  5126. unsigned char encodedLength[8];
  5127. MD5Functions::encode (encodedLength, count, 8);
  5128. // Pad out to 56 mod 64.
  5129. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  5130. const int paddingLength = (index < 56) ? (56 - index)
  5131. : (120 - index);
  5132. uint8 paddingBuffer [64];
  5133. zeromem (paddingBuffer, paddingLength);
  5134. paddingBuffer [0] = 0x80;
  5135. processBlock (paddingBuffer, paddingLength);
  5136. processBlock (encodedLength, 8);
  5137. MD5Functions::encode (result, state, 16);
  5138. zerostruct (buffer);
  5139. }
  5140. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  5141. {
  5142. using namespace MD5Functions;
  5143. uint32 a = state[0];
  5144. uint32 b = state[1];
  5145. uint32 c = state[2];
  5146. uint32 d = state[3];
  5147. uint32 x[16];
  5148. encode (x, bufferToTransform, 64);
  5149. enum Constants
  5150. {
  5151. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  5152. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  5153. };
  5154. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  5155. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  5156. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  5157. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  5158. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  5159. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  5160. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  5161. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  5162. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  5163. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  5164. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  5165. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  5166. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  5167. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  5168. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  5169. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  5170. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  5171. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  5172. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  5173. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  5174. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  5175. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  5176. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  5177. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  5178. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  5179. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  5180. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  5181. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  5182. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  5183. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  5184. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  5185. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  5186. state[0] += a;
  5187. state[1] += b;
  5188. state[2] += c;
  5189. state[3] += d;
  5190. zerostruct (x);
  5191. }
  5192. const MemoryBlock MD5::getRawChecksumData() const
  5193. {
  5194. return MemoryBlock (result, sizeof (result));
  5195. }
  5196. const String MD5::toHexString() const
  5197. {
  5198. return String::toHexString (result, sizeof (result), 0);
  5199. }
  5200. bool MD5::operator== (const MD5& other) const
  5201. {
  5202. return memcmp (result, other.result, sizeof (result)) == 0;
  5203. }
  5204. bool MD5::operator!= (const MD5& other) const
  5205. {
  5206. return ! operator== (other);
  5207. }
  5208. END_JUCE_NAMESPACE
  5209. /*** End of inlined file: juce_MD5.cpp ***/
  5210. /*** Start of inlined file: juce_Primes.cpp ***/
  5211. BEGIN_JUCE_NAMESPACE
  5212. namespace PrimesHelpers
  5213. {
  5214. void createSmallSieve (const int numBits, BigInteger& result)
  5215. {
  5216. result.setBit (numBits);
  5217. result.clearBit (numBits); // to enlarge the array
  5218. result.setBit (0);
  5219. int n = 2;
  5220. do
  5221. {
  5222. for (int i = n + n; i < numBits; i += n)
  5223. result.setBit (i);
  5224. n = result.findNextClearBit (n + 1);
  5225. }
  5226. while (n <= (numBits >> 1));
  5227. }
  5228. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5229. const BigInteger& smallSieve, const int smallSieveSize)
  5230. {
  5231. jassert (! base[0]); // must be even!
  5232. result.setBit (numBits);
  5233. result.clearBit (numBits); // to enlarge the array
  5234. int index = smallSieve.findNextClearBit (0);
  5235. do
  5236. {
  5237. const int prime = (index << 1) + 1;
  5238. BigInteger r (base), remainder;
  5239. r.divideBy (prime, remainder);
  5240. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5241. if (r.isZero())
  5242. i += prime;
  5243. if ((i & 1) == 0)
  5244. i += prime;
  5245. i = (i - 1) >> 1;
  5246. while (i < numBits)
  5247. {
  5248. result.setBit (i);
  5249. i += prime;
  5250. }
  5251. index = smallSieve.findNextClearBit (index + 1);
  5252. }
  5253. while (index < smallSieveSize);
  5254. }
  5255. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5256. const int numBits, BigInteger& result, const int certainty)
  5257. {
  5258. for (int i = 0; i < numBits; ++i)
  5259. {
  5260. if (! sieve[i])
  5261. {
  5262. result = base + (unsigned int) ((i << 1) + 1);
  5263. if (Primes::isProbablyPrime (result, certainty))
  5264. return true;
  5265. }
  5266. }
  5267. return false;
  5268. }
  5269. bool passesMillerRabin (const BigInteger& n, int iterations)
  5270. {
  5271. const BigInteger one (1), two (2);
  5272. const BigInteger nMinusOne (n - one);
  5273. BigInteger d (nMinusOne);
  5274. const int s = d.findNextSetBit (0);
  5275. d >>= s;
  5276. BigInteger smallPrimes;
  5277. int numBitsInSmallPrimes = 0;
  5278. for (;;)
  5279. {
  5280. numBitsInSmallPrimes += 256;
  5281. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5282. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5283. if (numPrimesFound > iterations + 1)
  5284. break;
  5285. }
  5286. int smallPrime = 2;
  5287. while (--iterations >= 0)
  5288. {
  5289. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5290. BigInteger r (smallPrime);
  5291. r.exponentModulo (d, n);
  5292. if (r != one && r != nMinusOne)
  5293. {
  5294. for (int j = 0; j < s; ++j)
  5295. {
  5296. r.exponentModulo (two, n);
  5297. if (r == nMinusOne)
  5298. break;
  5299. }
  5300. if (r != nMinusOne)
  5301. return false;
  5302. }
  5303. }
  5304. return true;
  5305. }
  5306. }
  5307. const BigInteger Primes::createProbablePrime (const int bitLength,
  5308. const int certainty,
  5309. const int* randomSeeds,
  5310. int numRandomSeeds)
  5311. {
  5312. using namespace PrimesHelpers;
  5313. int defaultSeeds [16];
  5314. if (numRandomSeeds <= 0)
  5315. {
  5316. randomSeeds = defaultSeeds;
  5317. numRandomSeeds = numElementsInArray (defaultSeeds);
  5318. Random r (0);
  5319. for (int j = 10; --j >= 0;)
  5320. {
  5321. r.setSeedRandomly();
  5322. for (int i = numRandomSeeds; --i >= 0;)
  5323. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5324. }
  5325. }
  5326. BigInteger smallSieve;
  5327. const int smallSieveSize = 15000;
  5328. createSmallSieve (smallSieveSize, smallSieve);
  5329. BigInteger p;
  5330. for (int i = numRandomSeeds; --i >= 0;)
  5331. {
  5332. BigInteger p2;
  5333. Random r (randomSeeds[i]);
  5334. r.fillBitsRandomly (p2, 0, bitLength);
  5335. p ^= p2;
  5336. }
  5337. p.setBit (bitLength - 1);
  5338. p.clearBit (0);
  5339. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5340. while (p.getHighestBit() < bitLength)
  5341. {
  5342. p += 2 * searchLen;
  5343. BigInteger sieve;
  5344. bigSieve (p, searchLen, sieve,
  5345. smallSieve, smallSieveSize);
  5346. BigInteger candidate;
  5347. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5348. return candidate;
  5349. }
  5350. jassertfalse;
  5351. return BigInteger();
  5352. }
  5353. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5354. {
  5355. using namespace PrimesHelpers;
  5356. if (! number[0])
  5357. return false;
  5358. if (number.getHighestBit() <= 10)
  5359. {
  5360. const int num = number.getBitRangeAsInt (0, 10);
  5361. for (int i = num / 2; --i > 1;)
  5362. if (num % i == 0)
  5363. return false;
  5364. return true;
  5365. }
  5366. else
  5367. {
  5368. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5369. return false;
  5370. return passesMillerRabin (number, certainty);
  5371. }
  5372. }
  5373. END_JUCE_NAMESPACE
  5374. /*** End of inlined file: juce_Primes.cpp ***/
  5375. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5376. BEGIN_JUCE_NAMESPACE
  5377. RSAKey::RSAKey()
  5378. {
  5379. }
  5380. RSAKey::RSAKey (const String& s)
  5381. {
  5382. if (s.containsChar (','))
  5383. {
  5384. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5385. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5386. }
  5387. else
  5388. {
  5389. // the string needs to be two hex numbers, comma-separated..
  5390. jassertfalse;
  5391. }
  5392. }
  5393. RSAKey::~RSAKey()
  5394. {
  5395. }
  5396. bool RSAKey::operator== (const RSAKey& other) const throw()
  5397. {
  5398. return part1 == other.part1 && part2 == other.part2;
  5399. }
  5400. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5401. {
  5402. return ! operator== (other);
  5403. }
  5404. const String RSAKey::toString() const
  5405. {
  5406. return part1.toString (16) + "," + part2.toString (16);
  5407. }
  5408. bool RSAKey::applyToValue (BigInteger& value) const
  5409. {
  5410. if (part1.isZero() || part2.isZero() || value <= 0)
  5411. {
  5412. jassertfalse; // using an uninitialised key
  5413. value.clear();
  5414. return false;
  5415. }
  5416. BigInteger result;
  5417. while (! value.isZero())
  5418. {
  5419. result *= part2;
  5420. BigInteger remainder;
  5421. value.divideBy (part2, remainder);
  5422. remainder.exponentModulo (part1, part2);
  5423. result += remainder;
  5424. }
  5425. value.swapWith (result);
  5426. return true;
  5427. }
  5428. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5429. {
  5430. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5431. // are fast to divide + multiply
  5432. for (int i = 2; i <= 65536; i *= 2)
  5433. {
  5434. const BigInteger e (1 + i);
  5435. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5436. return e;
  5437. }
  5438. BigInteger e (4);
  5439. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5440. ++e;
  5441. return e;
  5442. }
  5443. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5444. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5445. {
  5446. jassert (numBits > 16); // not much point using less than this..
  5447. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5448. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5449. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5450. const BigInteger n (p * q);
  5451. const BigInteger m (--p * --q);
  5452. const BigInteger e (findBestCommonDivisor (p, q));
  5453. BigInteger d (e);
  5454. d.inverseModulo (m);
  5455. publicKey.part1 = e;
  5456. publicKey.part2 = n;
  5457. privateKey.part1 = d;
  5458. privateKey.part2 = n;
  5459. }
  5460. END_JUCE_NAMESPACE
  5461. /*** End of inlined file: juce_RSAKey.cpp ***/
  5462. /*** Start of inlined file: juce_InputStream.cpp ***/
  5463. BEGIN_JUCE_NAMESPACE
  5464. char InputStream::readByte()
  5465. {
  5466. char temp = 0;
  5467. read (&temp, 1);
  5468. return temp;
  5469. }
  5470. bool InputStream::readBool()
  5471. {
  5472. return readByte() != 0;
  5473. }
  5474. short InputStream::readShort()
  5475. {
  5476. char temp[2];
  5477. if (read (temp, 2) == 2)
  5478. return (short) ByteOrder::littleEndianShort (temp);
  5479. return 0;
  5480. }
  5481. short InputStream::readShortBigEndian()
  5482. {
  5483. char temp[2];
  5484. if (read (temp, 2) == 2)
  5485. return (short) ByteOrder::bigEndianShort (temp);
  5486. return 0;
  5487. }
  5488. int InputStream::readInt()
  5489. {
  5490. char temp[4];
  5491. if (read (temp, 4) == 4)
  5492. return (int) ByteOrder::littleEndianInt (temp);
  5493. return 0;
  5494. }
  5495. int InputStream::readIntBigEndian()
  5496. {
  5497. char temp[4];
  5498. if (read (temp, 4) == 4)
  5499. return (int) ByteOrder::bigEndianInt (temp);
  5500. return 0;
  5501. }
  5502. int InputStream::readCompressedInt()
  5503. {
  5504. const unsigned char sizeByte = readByte();
  5505. if (sizeByte == 0)
  5506. return 0;
  5507. const int numBytes = (sizeByte & 0x7f);
  5508. if (numBytes > 4)
  5509. {
  5510. jassertfalse; // trying to read corrupt data - this method must only be used
  5511. // to read data that was written by OutputStream::writeCompressedInt()
  5512. return 0;
  5513. }
  5514. char bytes[4] = { 0, 0, 0, 0 };
  5515. if (read (bytes, numBytes) != numBytes)
  5516. return 0;
  5517. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5518. return (sizeByte >> 7) ? -num : num;
  5519. }
  5520. int64 InputStream::readInt64()
  5521. {
  5522. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5523. if (read (n.asBytes, 8) == 8)
  5524. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5525. return 0;
  5526. }
  5527. int64 InputStream::readInt64BigEndian()
  5528. {
  5529. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5530. if (read (n.asBytes, 8) == 8)
  5531. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5532. return 0;
  5533. }
  5534. float InputStream::readFloat()
  5535. {
  5536. // the union below relies on these types being the same size...
  5537. static_jassert (sizeof (int32) == sizeof (float));
  5538. union { int32 asInt; float asFloat; } n;
  5539. n.asInt = (int32) readInt();
  5540. return n.asFloat;
  5541. }
  5542. float InputStream::readFloatBigEndian()
  5543. {
  5544. union { int32 asInt; float asFloat; } n;
  5545. n.asInt = (int32) readIntBigEndian();
  5546. return n.asFloat;
  5547. }
  5548. double InputStream::readDouble()
  5549. {
  5550. union { int64 asInt; double asDouble; } n;
  5551. n.asInt = readInt64();
  5552. return n.asDouble;
  5553. }
  5554. double InputStream::readDoubleBigEndian()
  5555. {
  5556. union { int64 asInt; double asDouble; } n;
  5557. n.asInt = readInt64BigEndian();
  5558. return n.asDouble;
  5559. }
  5560. const String InputStream::readString()
  5561. {
  5562. MemoryBlock buffer (256);
  5563. char* data = static_cast<char*> (buffer.getData());
  5564. size_t i = 0;
  5565. while ((data[i] = readByte()) != 0)
  5566. {
  5567. if (++i >= buffer.getSize())
  5568. {
  5569. buffer.setSize (buffer.getSize() + 512);
  5570. data = static_cast<char*> (buffer.getData());
  5571. }
  5572. }
  5573. return String::fromUTF8 (data, (int) i);
  5574. }
  5575. const String InputStream::readNextLine()
  5576. {
  5577. MemoryBlock buffer (256);
  5578. char* data = static_cast<char*> (buffer.getData());
  5579. size_t i = 0;
  5580. while ((data[i] = readByte()) != 0)
  5581. {
  5582. if (data[i] == '\n')
  5583. break;
  5584. if (data[i] == '\r')
  5585. {
  5586. const int64 lastPos = getPosition();
  5587. if (readByte() != '\n')
  5588. setPosition (lastPos);
  5589. break;
  5590. }
  5591. if (++i >= buffer.getSize())
  5592. {
  5593. buffer.setSize (buffer.getSize() + 512);
  5594. data = static_cast<char*> (buffer.getData());
  5595. }
  5596. }
  5597. return String::fromUTF8 (data, (int) i);
  5598. }
  5599. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5600. {
  5601. MemoryOutputStream mo (block, true);
  5602. return mo.writeFromInputStream (*this, numBytes);
  5603. }
  5604. const String InputStream::readEntireStreamAsString()
  5605. {
  5606. MemoryOutputStream mo;
  5607. mo.writeFromInputStream (*this, -1);
  5608. return mo.toString();
  5609. }
  5610. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5611. {
  5612. if (numBytesToSkip > 0)
  5613. {
  5614. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5615. HeapBlock<char> temp (skipBufferSize);
  5616. while (numBytesToSkip > 0 && ! isExhausted())
  5617. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5618. }
  5619. }
  5620. END_JUCE_NAMESPACE
  5621. /*** End of inlined file: juce_InputStream.cpp ***/
  5622. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5623. BEGIN_JUCE_NAMESPACE
  5624. #if JUCE_DEBUG
  5625. static Array<void*, CriticalSection> activeStreams;
  5626. void juce_CheckForDanglingStreams()
  5627. {
  5628. /*
  5629. It's always a bad idea to leak any object, but if you're leaking output
  5630. streams, then there's a good chance that you're failing to flush a file
  5631. to disk properly, which could result in corrupted data and other similar
  5632. nastiness..
  5633. */
  5634. jassert (activeStreams.size() == 0);
  5635. };
  5636. #endif
  5637. OutputStream::OutputStream()
  5638. : newLineString (NewLine::getDefault())
  5639. {
  5640. #if JUCE_DEBUG
  5641. activeStreams.add (this);
  5642. #endif
  5643. }
  5644. OutputStream::~OutputStream()
  5645. {
  5646. #if JUCE_DEBUG
  5647. activeStreams.removeValue (this);
  5648. #endif
  5649. }
  5650. void OutputStream::writeBool (const bool b)
  5651. {
  5652. writeByte (b ? (char) 1
  5653. : (char) 0);
  5654. }
  5655. void OutputStream::writeByte (char byte)
  5656. {
  5657. write (&byte, 1);
  5658. }
  5659. void OutputStream::writeRepeatedByte (uint8 byte, int numTimesToRepeat)
  5660. {
  5661. while (--numTimesToRepeat >= 0)
  5662. writeByte (byte);
  5663. }
  5664. void OutputStream::writeShort (short value)
  5665. {
  5666. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5667. write (&v, 2);
  5668. }
  5669. void OutputStream::writeShortBigEndian (short value)
  5670. {
  5671. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5672. write (&v, 2);
  5673. }
  5674. void OutputStream::writeInt (int value)
  5675. {
  5676. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5677. write (&v, 4);
  5678. }
  5679. void OutputStream::writeIntBigEndian (int value)
  5680. {
  5681. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5682. write (&v, 4);
  5683. }
  5684. void OutputStream::writeCompressedInt (int value)
  5685. {
  5686. unsigned int un = (value < 0) ? (unsigned int) -value
  5687. : (unsigned int) value;
  5688. uint8 data[5];
  5689. int num = 0;
  5690. while (un > 0)
  5691. {
  5692. data[++num] = (uint8) un;
  5693. un >>= 8;
  5694. }
  5695. data[0] = (uint8) num;
  5696. if (value < 0)
  5697. data[0] |= 0x80;
  5698. write (data, num + 1);
  5699. }
  5700. void OutputStream::writeInt64 (int64 value)
  5701. {
  5702. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5703. write (&v, 8);
  5704. }
  5705. void OutputStream::writeInt64BigEndian (int64 value)
  5706. {
  5707. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5708. write (&v, 8);
  5709. }
  5710. void OutputStream::writeFloat (float value)
  5711. {
  5712. union { int asInt; float asFloat; } n;
  5713. n.asFloat = value;
  5714. writeInt (n.asInt);
  5715. }
  5716. void OutputStream::writeFloatBigEndian (float value)
  5717. {
  5718. union { int asInt; float asFloat; } n;
  5719. n.asFloat = value;
  5720. writeIntBigEndian (n.asInt);
  5721. }
  5722. void OutputStream::writeDouble (double value)
  5723. {
  5724. union { int64 asInt; double asDouble; } n;
  5725. n.asDouble = value;
  5726. writeInt64 (n.asInt);
  5727. }
  5728. void OutputStream::writeDoubleBigEndian (double value)
  5729. {
  5730. union { int64 asInt; double asDouble; } n;
  5731. n.asDouble = value;
  5732. writeInt64BigEndian (n.asInt);
  5733. }
  5734. void OutputStream::writeString (const String& text)
  5735. {
  5736. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5737. // if lots of large, persistent strings were to be written to streams).
  5738. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5739. HeapBlock<char> temp (numBytes);
  5740. text.copyToUTF8 (temp, numBytes);
  5741. write (temp, numBytes);
  5742. }
  5743. void OutputStream::writeText (const String& text, const bool asUTF16,
  5744. const bool writeUTF16ByteOrderMark)
  5745. {
  5746. if (asUTF16)
  5747. {
  5748. if (writeUTF16ByteOrderMark)
  5749. write ("\x0ff\x0fe", 2);
  5750. String::CharPointerType src (text.getCharPointer());
  5751. bool lastCharWasReturn = false;
  5752. for (;;)
  5753. {
  5754. const juce_wchar c = src.getAndAdvance();
  5755. if (c == 0)
  5756. break;
  5757. if (c == '\n' && ! lastCharWasReturn)
  5758. writeShort ((short) '\r');
  5759. lastCharWasReturn = (c == L'\r');
  5760. writeShort ((short) c);
  5761. }
  5762. }
  5763. else
  5764. {
  5765. const char* src = text.toUTF8();
  5766. const char* t = src;
  5767. for (;;)
  5768. {
  5769. if (*t == '\n')
  5770. {
  5771. if (t > src)
  5772. write (src, (int) (t - src));
  5773. write ("\r\n", 2);
  5774. src = t + 1;
  5775. }
  5776. else if (*t == '\r')
  5777. {
  5778. if (t[1] == '\n')
  5779. ++t;
  5780. }
  5781. else if (*t == 0)
  5782. {
  5783. if (t > src)
  5784. write (src, (int) (t - src));
  5785. break;
  5786. }
  5787. ++t;
  5788. }
  5789. }
  5790. }
  5791. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5792. {
  5793. if (numBytesToWrite < 0)
  5794. numBytesToWrite = std::numeric_limits<int64>::max();
  5795. int numWritten = 0;
  5796. while (numBytesToWrite > 0 && ! source.isExhausted())
  5797. {
  5798. char buffer [8192];
  5799. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5800. if (num <= 0)
  5801. break;
  5802. write (buffer, num);
  5803. numBytesToWrite -= num;
  5804. numWritten += num;
  5805. }
  5806. return numWritten;
  5807. }
  5808. void OutputStream::setNewLineString (const String& newLineString_)
  5809. {
  5810. newLineString = newLineString_;
  5811. }
  5812. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5813. {
  5814. return stream << String (number);
  5815. }
  5816. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5817. {
  5818. return stream << String (number);
  5819. }
  5820. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5821. {
  5822. stream.writeByte (character);
  5823. return stream;
  5824. }
  5825. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5826. {
  5827. stream.write (text, (int) strlen (text));
  5828. return stream;
  5829. }
  5830. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5831. {
  5832. stream.write (data.getData(), (int) data.getSize());
  5833. return stream;
  5834. }
  5835. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5836. {
  5837. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5838. if (in != 0)
  5839. stream.writeFromInputStream (*in, -1);
  5840. return stream;
  5841. }
  5842. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5843. {
  5844. return stream << stream.getNewLineString();
  5845. }
  5846. END_JUCE_NAMESPACE
  5847. /*** End of inlined file: juce_OutputStream.cpp ***/
  5848. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5849. BEGIN_JUCE_NAMESPACE
  5850. DirectoryIterator::DirectoryIterator (const File& directory,
  5851. bool isRecursive_,
  5852. const String& wildCard_,
  5853. const int whatToLookFor_)
  5854. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5855. wildCard (wildCard_),
  5856. path (File::addTrailingSeparator (directory.getFullPathName())),
  5857. index (-1),
  5858. totalNumFiles (-1),
  5859. whatToLookFor (whatToLookFor_),
  5860. isRecursive (isRecursive_),
  5861. hasBeenAdvanced (false)
  5862. {
  5863. // you have to specify the type of files you're looking for!
  5864. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5865. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5866. }
  5867. DirectoryIterator::~DirectoryIterator()
  5868. {
  5869. }
  5870. bool DirectoryIterator::next()
  5871. {
  5872. return next (0, 0, 0, 0, 0, 0);
  5873. }
  5874. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5875. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5876. {
  5877. hasBeenAdvanced = true;
  5878. if (subIterator != 0)
  5879. {
  5880. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5881. return true;
  5882. subIterator = 0;
  5883. }
  5884. String filename;
  5885. bool isDirectory, isHidden;
  5886. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5887. {
  5888. ++index;
  5889. if (! filename.containsOnly ("."))
  5890. {
  5891. const File fileFound (path + filename, 0);
  5892. bool matches = false;
  5893. if (isDirectory)
  5894. {
  5895. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5896. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5897. matches = (whatToLookFor & File::findDirectories) != 0;
  5898. }
  5899. else
  5900. {
  5901. matches = (whatToLookFor & File::findFiles) != 0;
  5902. }
  5903. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5904. if (matches && isRecursive)
  5905. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5906. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5907. matches = ! isHidden;
  5908. if (matches)
  5909. {
  5910. currentFile = fileFound;
  5911. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5912. if (isDirResult != 0) *isDirResult = isDirectory;
  5913. return true;
  5914. }
  5915. else if (subIterator != 0)
  5916. {
  5917. return next();
  5918. }
  5919. }
  5920. }
  5921. return false;
  5922. }
  5923. const File DirectoryIterator::getFile() const
  5924. {
  5925. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5926. return subIterator->getFile();
  5927. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5928. jassert (hasBeenAdvanced);
  5929. return currentFile;
  5930. }
  5931. float DirectoryIterator::getEstimatedProgress() const
  5932. {
  5933. if (totalNumFiles < 0)
  5934. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5935. if (totalNumFiles <= 0)
  5936. return 0.0f;
  5937. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5938. : (float) index;
  5939. return detailedIndex / totalNumFiles;
  5940. }
  5941. END_JUCE_NAMESPACE
  5942. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5943. /*** Start of inlined file: juce_File.cpp ***/
  5944. #if ! JUCE_WINDOWS
  5945. #include <pwd.h>
  5946. #endif
  5947. BEGIN_JUCE_NAMESPACE
  5948. File::File (const String& fullPathName)
  5949. : fullPath (parseAbsolutePath (fullPathName))
  5950. {
  5951. }
  5952. File::File (const String& path, int)
  5953. : fullPath (path)
  5954. {
  5955. }
  5956. const File File::createFileWithoutCheckingPath (const String& path)
  5957. {
  5958. return File (path, 0);
  5959. }
  5960. File::File (const File& other)
  5961. : fullPath (other.fullPath)
  5962. {
  5963. }
  5964. File& File::operator= (const String& newPath)
  5965. {
  5966. fullPath = parseAbsolutePath (newPath);
  5967. return *this;
  5968. }
  5969. File& File::operator= (const File& other)
  5970. {
  5971. fullPath = other.fullPath;
  5972. return *this;
  5973. }
  5974. const File File::nonexistent;
  5975. const String File::parseAbsolutePath (const String& p)
  5976. {
  5977. if (p.isEmpty())
  5978. return String::empty;
  5979. #if JUCE_WINDOWS
  5980. // Windows..
  5981. String path (p.replaceCharacter ('/', '\\'));
  5982. if (path.startsWithChar (File::separator))
  5983. {
  5984. if (path[1] != File::separator)
  5985. {
  5986. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5987. If you're trying to parse a string that may be either a relative path or an absolute path,
  5988. you MUST provide a context against which the partial path can be evaluated - you can do
  5989. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5990. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5991. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5992. */
  5993. jassertfalse;
  5994. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5995. }
  5996. }
  5997. else if (! path.containsChar (':'))
  5998. {
  5999. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6000. If you're trying to parse a string that may be either a relative path or an absolute path,
  6001. you MUST provide a context against which the partial path can be evaluated - you can do
  6002. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6003. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6004. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6005. */
  6006. jassertfalse;
  6007. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6008. }
  6009. #else
  6010. // Mac or Linux..
  6011. String path (p.replaceCharacter ('\\', '/'));
  6012. if (path.startsWithChar ('~'))
  6013. {
  6014. if (path[1] == File::separator || path[1] == 0)
  6015. {
  6016. // expand a name of the form "~/abc"
  6017. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  6018. + path.substring (1);
  6019. }
  6020. else
  6021. {
  6022. // expand a name of type "~dave/abc"
  6023. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  6024. struct passwd* const pw = getpwnam (userName.toUTF8());
  6025. if (pw != 0)
  6026. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  6027. }
  6028. }
  6029. else if (! path.startsWithChar (File::separator))
  6030. {
  6031. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6032. If you're trying to parse a string that may be either a relative path or an absolute path,
  6033. you MUST provide a context against which the partial path can be evaluated - you can do
  6034. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6035. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6036. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6037. */
  6038. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  6039. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6040. }
  6041. #endif
  6042. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  6043. path = path.dropLastCharacters (1);
  6044. return path;
  6045. }
  6046. const String File::addTrailingSeparator (const String& path)
  6047. {
  6048. return path.endsWithChar (File::separator) ? path
  6049. : path + File::separator;
  6050. }
  6051. #if JUCE_LINUX
  6052. #define NAMES_ARE_CASE_SENSITIVE 1
  6053. #endif
  6054. bool File::areFileNamesCaseSensitive()
  6055. {
  6056. #if NAMES_ARE_CASE_SENSITIVE
  6057. return true;
  6058. #else
  6059. return false;
  6060. #endif
  6061. }
  6062. bool File::operator== (const File& other) const
  6063. {
  6064. #if NAMES_ARE_CASE_SENSITIVE
  6065. return fullPath == other.fullPath;
  6066. #else
  6067. return fullPath.equalsIgnoreCase (other.fullPath);
  6068. #endif
  6069. }
  6070. bool File::operator!= (const File& other) const
  6071. {
  6072. return ! operator== (other);
  6073. }
  6074. bool File::operator< (const File& other) const
  6075. {
  6076. #if NAMES_ARE_CASE_SENSITIVE
  6077. return fullPath < other.fullPath;
  6078. #else
  6079. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  6080. #endif
  6081. }
  6082. bool File::operator> (const File& other) const
  6083. {
  6084. #if NAMES_ARE_CASE_SENSITIVE
  6085. return fullPath > other.fullPath;
  6086. #else
  6087. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  6088. #endif
  6089. }
  6090. bool File::setReadOnly (const bool shouldBeReadOnly,
  6091. const bool applyRecursively) const
  6092. {
  6093. bool worked = true;
  6094. if (applyRecursively && isDirectory())
  6095. {
  6096. Array <File> subFiles;
  6097. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6098. for (int i = subFiles.size(); --i >= 0;)
  6099. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  6100. }
  6101. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  6102. }
  6103. bool File::deleteRecursively() const
  6104. {
  6105. bool worked = true;
  6106. if (isDirectory())
  6107. {
  6108. Array<File> subFiles;
  6109. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6110. for (int i = subFiles.size(); --i >= 0;)
  6111. worked = subFiles.getReference(i).deleteRecursively() && worked;
  6112. }
  6113. return deleteFile() && worked;
  6114. }
  6115. bool File::moveFileTo (const File& newFile) const
  6116. {
  6117. if (newFile.fullPath == fullPath)
  6118. return true;
  6119. #if ! NAMES_ARE_CASE_SENSITIVE
  6120. if (*this != newFile)
  6121. #endif
  6122. if (! newFile.deleteFile())
  6123. return false;
  6124. return moveInternal (newFile);
  6125. }
  6126. bool File::copyFileTo (const File& newFile) const
  6127. {
  6128. return (*this == newFile)
  6129. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  6130. }
  6131. bool File::copyDirectoryTo (const File& newDirectory) const
  6132. {
  6133. if (isDirectory() && newDirectory.createDirectory())
  6134. {
  6135. Array<File> subFiles;
  6136. findChildFiles (subFiles, File::findFiles, false);
  6137. int i;
  6138. for (i = 0; i < subFiles.size(); ++i)
  6139. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6140. return false;
  6141. subFiles.clear();
  6142. findChildFiles (subFiles, File::findDirectories, false);
  6143. for (i = 0; i < subFiles.size(); ++i)
  6144. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6145. return false;
  6146. return true;
  6147. }
  6148. return false;
  6149. }
  6150. const String File::getPathUpToLastSlash() const
  6151. {
  6152. const int lastSlash = fullPath.lastIndexOfChar (separator);
  6153. if (lastSlash > 0)
  6154. return fullPath.substring (0, lastSlash);
  6155. else if (lastSlash == 0)
  6156. return separatorString;
  6157. else
  6158. return fullPath;
  6159. }
  6160. const File File::getParentDirectory() const
  6161. {
  6162. return File (getPathUpToLastSlash(), (int) 0);
  6163. }
  6164. const String File::getFileName() const
  6165. {
  6166. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  6167. }
  6168. int File::hashCode() const
  6169. {
  6170. return fullPath.hashCode();
  6171. }
  6172. int64 File::hashCode64() const
  6173. {
  6174. return fullPath.hashCode64();
  6175. }
  6176. const String File::getFileNameWithoutExtension() const
  6177. {
  6178. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  6179. const int lastDot = fullPath.lastIndexOfChar ('.');
  6180. if (lastDot > lastSlash)
  6181. return fullPath.substring (lastSlash, lastDot);
  6182. else
  6183. return fullPath.substring (lastSlash);
  6184. }
  6185. bool File::isAChildOf (const File& potentialParent) const
  6186. {
  6187. if (potentialParent == File::nonexistent)
  6188. return false;
  6189. const String ourPath (getPathUpToLastSlash());
  6190. #if NAMES_ARE_CASE_SENSITIVE
  6191. if (potentialParent.fullPath == ourPath)
  6192. #else
  6193. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  6194. #endif
  6195. {
  6196. return true;
  6197. }
  6198. else if (potentialParent.fullPath.length() >= ourPath.length())
  6199. {
  6200. return false;
  6201. }
  6202. else
  6203. {
  6204. return getParentDirectory().isAChildOf (potentialParent);
  6205. }
  6206. }
  6207. bool File::isAbsolutePath (const String& path)
  6208. {
  6209. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  6210. #if JUCE_WINDOWS
  6211. || (path.isNotEmpty() && path[1] == ':');
  6212. #else
  6213. || path.startsWithChar ('~');
  6214. #endif
  6215. }
  6216. const File File::getChildFile (String relativePath) const
  6217. {
  6218. if (isAbsolutePath (relativePath))
  6219. {
  6220. // the path is really absolute..
  6221. return File (relativePath);
  6222. }
  6223. else
  6224. {
  6225. // it's relative, so remove any ../ or ./ bits at the start.
  6226. String path (fullPath);
  6227. if (relativePath[0] == '.')
  6228. {
  6229. #if JUCE_WINDOWS
  6230. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6231. #else
  6232. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6233. #endif
  6234. while (relativePath[0] == '.')
  6235. {
  6236. if (relativePath[1] == '.')
  6237. {
  6238. if (relativePath [2] == 0 || relativePath[2] == separator)
  6239. {
  6240. const int lastSlash = path.lastIndexOfChar (separator);
  6241. if (lastSlash >= 0)
  6242. path = path.substring (0, lastSlash);
  6243. relativePath = relativePath.substring (3);
  6244. }
  6245. else
  6246. {
  6247. break;
  6248. }
  6249. }
  6250. else if (relativePath[1] == separator)
  6251. {
  6252. relativePath = relativePath.substring (2);
  6253. }
  6254. else
  6255. {
  6256. break;
  6257. }
  6258. }
  6259. }
  6260. return File (addTrailingSeparator (path) + relativePath);
  6261. }
  6262. }
  6263. const File File::getSiblingFile (const String& fileName) const
  6264. {
  6265. return getParentDirectory().getChildFile (fileName);
  6266. }
  6267. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6268. {
  6269. if (bytes == 1)
  6270. {
  6271. return "1 byte";
  6272. }
  6273. else if (bytes < 1024)
  6274. {
  6275. return String ((int) bytes) + " bytes";
  6276. }
  6277. else if (bytes < 1024 * 1024)
  6278. {
  6279. return String (bytes / 1024.0, 1) + " KB";
  6280. }
  6281. else if (bytes < 1024 * 1024 * 1024)
  6282. {
  6283. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6284. }
  6285. else
  6286. {
  6287. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6288. }
  6289. }
  6290. bool File::create() const
  6291. {
  6292. if (exists())
  6293. return true;
  6294. {
  6295. const File parentDir (getParentDirectory());
  6296. if (parentDir == *this || ! parentDir.createDirectory())
  6297. return false;
  6298. FileOutputStream fo (*this, 8);
  6299. }
  6300. return exists();
  6301. }
  6302. bool File::createDirectory() const
  6303. {
  6304. if (! isDirectory())
  6305. {
  6306. const File parentDir (getParentDirectory());
  6307. if (parentDir == *this || ! parentDir.createDirectory())
  6308. return false;
  6309. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6310. return isDirectory();
  6311. }
  6312. return true;
  6313. }
  6314. const Time File::getCreationTime() const
  6315. {
  6316. int64 m, a, c;
  6317. getFileTimesInternal (m, a, c);
  6318. return Time (c);
  6319. }
  6320. const Time File::getLastModificationTime() const
  6321. {
  6322. int64 m, a, c;
  6323. getFileTimesInternal (m, a, c);
  6324. return Time (m);
  6325. }
  6326. const Time File::getLastAccessTime() const
  6327. {
  6328. int64 m, a, c;
  6329. getFileTimesInternal (m, a, c);
  6330. return Time (a);
  6331. }
  6332. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6333. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6334. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6335. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6336. {
  6337. if (! existsAsFile())
  6338. return false;
  6339. FileInputStream in (*this);
  6340. return getSize() == in.readIntoMemoryBlock (destBlock);
  6341. }
  6342. const String File::loadFileAsString() const
  6343. {
  6344. if (! existsAsFile())
  6345. return String::empty;
  6346. FileInputStream in (*this);
  6347. return in.readEntireStreamAsString();
  6348. }
  6349. int File::findChildFiles (Array<File>& results,
  6350. const int whatToLookFor,
  6351. const bool searchRecursively,
  6352. const String& wildCardPattern) const
  6353. {
  6354. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6355. int total = 0;
  6356. while (di.next())
  6357. {
  6358. results.add (di.getFile());
  6359. ++total;
  6360. }
  6361. return total;
  6362. }
  6363. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6364. {
  6365. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6366. int total = 0;
  6367. while (di.next())
  6368. ++total;
  6369. return total;
  6370. }
  6371. bool File::containsSubDirectories() const
  6372. {
  6373. if (isDirectory())
  6374. {
  6375. DirectoryIterator di (*this, false, "*", findDirectories);
  6376. return di.next();
  6377. }
  6378. return false;
  6379. }
  6380. const File File::getNonexistentChildFile (const String& prefix_,
  6381. const String& suffix,
  6382. bool putNumbersInBrackets) const
  6383. {
  6384. File f (getChildFile (prefix_ + suffix));
  6385. if (f.exists())
  6386. {
  6387. int num = 2;
  6388. String prefix (prefix_);
  6389. // remove any bracketed numbers that may already be on the end..
  6390. if (prefix.trim().endsWithChar (')'))
  6391. {
  6392. putNumbersInBrackets = true;
  6393. const int openBracks = prefix.lastIndexOfChar ('(');
  6394. const int closeBracks = prefix.lastIndexOfChar (')');
  6395. if (openBracks > 0
  6396. && closeBracks > openBracks
  6397. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6398. {
  6399. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6400. prefix = prefix.substring (0, openBracks);
  6401. }
  6402. }
  6403. // also use brackets if it ends in a digit.
  6404. putNumbersInBrackets = putNumbersInBrackets
  6405. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6406. do
  6407. {
  6408. if (putNumbersInBrackets)
  6409. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6410. else
  6411. f = getChildFile (prefix + String (num++) + suffix);
  6412. } while (f.exists());
  6413. }
  6414. return f;
  6415. }
  6416. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6417. {
  6418. if (exists())
  6419. {
  6420. return getParentDirectory()
  6421. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6422. getFileExtension(),
  6423. putNumbersInBrackets);
  6424. }
  6425. else
  6426. {
  6427. return *this;
  6428. }
  6429. }
  6430. const String File::getFileExtension() const
  6431. {
  6432. String ext;
  6433. if (! isDirectory())
  6434. {
  6435. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6436. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6437. ext = fullPath.substring (indexOfDot);
  6438. }
  6439. return ext;
  6440. }
  6441. bool File::hasFileExtension (const String& possibleSuffix) const
  6442. {
  6443. if (possibleSuffix.isEmpty())
  6444. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6445. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6446. if (semicolon >= 0)
  6447. {
  6448. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6449. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6450. }
  6451. else
  6452. {
  6453. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6454. {
  6455. if (possibleSuffix.startsWithChar ('.'))
  6456. return true;
  6457. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6458. if (dotPos >= 0)
  6459. return fullPath [dotPos] == '.';
  6460. }
  6461. }
  6462. return false;
  6463. }
  6464. const File File::withFileExtension (const String& newExtension) const
  6465. {
  6466. if (fullPath.isEmpty())
  6467. return File::nonexistent;
  6468. String filePart (getFileName());
  6469. int i = filePart.lastIndexOfChar ('.');
  6470. if (i >= 0)
  6471. filePart = filePart.substring (0, i);
  6472. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6473. filePart << '.';
  6474. return getSiblingFile (filePart + newExtension);
  6475. }
  6476. bool File::startAsProcess (const String& parameters) const
  6477. {
  6478. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6479. }
  6480. FileInputStream* File::createInputStream() const
  6481. {
  6482. if (existsAsFile())
  6483. return new FileInputStream (*this);
  6484. return 0;
  6485. }
  6486. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6487. {
  6488. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6489. if (out->failedToOpen())
  6490. return 0;
  6491. return out.release();
  6492. }
  6493. bool File::appendData (const void* const dataToAppend,
  6494. const int numberOfBytes) const
  6495. {
  6496. if (numberOfBytes > 0)
  6497. {
  6498. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6499. if (out == 0)
  6500. return false;
  6501. out->write (dataToAppend, numberOfBytes);
  6502. }
  6503. return true;
  6504. }
  6505. bool File::replaceWithData (const void* const dataToWrite,
  6506. const int numberOfBytes) const
  6507. {
  6508. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6509. if (numberOfBytes <= 0)
  6510. return deleteFile();
  6511. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6512. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6513. return tempFile.overwriteTargetFileWithTemporary();
  6514. }
  6515. bool File::appendText (const String& text,
  6516. const bool asUnicode,
  6517. const bool writeUnicodeHeaderBytes) const
  6518. {
  6519. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6520. if (out != 0)
  6521. {
  6522. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6523. return true;
  6524. }
  6525. return false;
  6526. }
  6527. bool File::replaceWithText (const String& textToWrite,
  6528. const bool asUnicode,
  6529. const bool writeUnicodeHeaderBytes) const
  6530. {
  6531. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6532. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6533. return tempFile.overwriteTargetFileWithTemporary();
  6534. }
  6535. bool File::hasIdenticalContentTo (const File& other) const
  6536. {
  6537. if (other == *this)
  6538. return true;
  6539. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6540. {
  6541. FileInputStream in1 (*this), in2 (other);
  6542. const int bufferSize = 4096;
  6543. HeapBlock <char> buffer1, buffer2;
  6544. buffer1.malloc (bufferSize);
  6545. buffer2.malloc (bufferSize);
  6546. for (;;)
  6547. {
  6548. const int num1 = in1.read (buffer1, bufferSize);
  6549. const int num2 = in2.read (buffer2, bufferSize);
  6550. if (num1 != num2)
  6551. break;
  6552. if (num1 <= 0)
  6553. return true;
  6554. if (memcmp (buffer1, buffer2, num1) != 0)
  6555. break;
  6556. }
  6557. }
  6558. return false;
  6559. }
  6560. const String File::createLegalPathName (const String& original)
  6561. {
  6562. String s (original);
  6563. String start;
  6564. if (s[1] == ':')
  6565. {
  6566. start = s.substring (0, 2);
  6567. s = s.substring (2);
  6568. }
  6569. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6570. .substring (0, 1024);
  6571. }
  6572. const String File::createLegalFileName (const String& original)
  6573. {
  6574. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6575. const int maxLength = 128; // only the length of the filename, not the whole path
  6576. const int len = s.length();
  6577. if (len > maxLength)
  6578. {
  6579. const int lastDot = s.lastIndexOfChar ('.');
  6580. if (lastDot > jmax (0, len - 12))
  6581. {
  6582. s = s.substring (0, maxLength - (len - lastDot))
  6583. + s.substring (lastDot);
  6584. }
  6585. else
  6586. {
  6587. s = s.substring (0, maxLength);
  6588. }
  6589. }
  6590. return s;
  6591. }
  6592. const String File::getRelativePathFrom (const File& dir) const
  6593. {
  6594. String thisPath (fullPath);
  6595. while (thisPath.endsWithChar (separator))
  6596. thisPath = thisPath.dropLastCharacters (1);
  6597. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6598. : dir.fullPath));
  6599. const int len = jmin (thisPath.length(), dirPath.length());
  6600. int commonBitLength = 0;
  6601. for (int i = 0; i < len; ++i)
  6602. {
  6603. #if NAMES_ARE_CASE_SENSITIVE
  6604. if (thisPath[i] != dirPath[i])
  6605. #else
  6606. if (CharacterFunctions::toLowerCase (thisPath[i])
  6607. != CharacterFunctions::toLowerCase (dirPath[i]))
  6608. #endif
  6609. {
  6610. break;
  6611. }
  6612. ++commonBitLength;
  6613. }
  6614. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6615. --commonBitLength;
  6616. // if the only common bit is the root, then just return the full path..
  6617. if (commonBitLength <= 0
  6618. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6619. return fullPath;
  6620. thisPath = thisPath.substring (commonBitLength);
  6621. dirPath = dirPath.substring (commonBitLength);
  6622. while (dirPath.isNotEmpty())
  6623. {
  6624. #if JUCE_WINDOWS
  6625. thisPath = "..\\" + thisPath;
  6626. #else
  6627. thisPath = "../" + thisPath;
  6628. #endif
  6629. const int sep = dirPath.indexOfChar (separator);
  6630. if (sep >= 0)
  6631. dirPath = dirPath.substring (sep + 1);
  6632. else
  6633. dirPath = String::empty;
  6634. }
  6635. return thisPath;
  6636. }
  6637. const File File::createTempFile (const String& fileNameEnding)
  6638. {
  6639. const File tempFile (getSpecialLocation (tempDirectory)
  6640. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6641. .withFileExtension (fileNameEnding));
  6642. if (tempFile.exists())
  6643. return createTempFile (fileNameEnding);
  6644. else
  6645. return tempFile;
  6646. }
  6647. #if JUCE_UNIT_TESTS
  6648. class FileTests : public UnitTest
  6649. {
  6650. public:
  6651. FileTests() : UnitTest ("Files") {}
  6652. void runTest()
  6653. {
  6654. beginTest ("Reading");
  6655. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6656. const File temp (File::getSpecialLocation (File::tempDirectory));
  6657. expect (! File::nonexistent.exists());
  6658. expect (home.isDirectory());
  6659. expect (home.exists());
  6660. expect (! home.existsAsFile());
  6661. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6662. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6663. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6664. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6665. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6666. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6667. expect (home.getBytesFreeOnVolume() > 0);
  6668. expect (! home.isHidden());
  6669. expect (home.isOnHardDisk());
  6670. expect (! home.isOnCDRomDrive());
  6671. expect (File::getCurrentWorkingDirectory().exists());
  6672. expect (home.setAsCurrentWorkingDirectory());
  6673. expect (File::getCurrentWorkingDirectory() == home);
  6674. {
  6675. Array<File> roots;
  6676. File::findFileSystemRoots (roots);
  6677. expect (roots.size() > 0);
  6678. int numRootsExisting = 0;
  6679. for (int i = 0; i < roots.size(); ++i)
  6680. if (roots[i].exists())
  6681. ++numRootsExisting;
  6682. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6683. expect (numRootsExisting > 0);
  6684. }
  6685. beginTest ("Writing");
  6686. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6687. expect (demoFolder.deleteRecursively());
  6688. expect (demoFolder.createDirectory());
  6689. expect (demoFolder.isDirectory());
  6690. expect (demoFolder.getParentDirectory() == temp);
  6691. expect (temp.isDirectory());
  6692. {
  6693. Array<File> files;
  6694. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6695. expect (files.contains (demoFolder));
  6696. }
  6697. {
  6698. Array<File> files;
  6699. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6700. expect (files.contains (demoFolder));
  6701. }
  6702. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6703. expect (tempFile.getFileExtension() == ".txt");
  6704. expect (tempFile.hasFileExtension (".txt"));
  6705. expect (tempFile.hasFileExtension ("txt"));
  6706. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6707. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6708. expect (tempFile.hasWriteAccess());
  6709. {
  6710. FileOutputStream fo (tempFile);
  6711. fo.write ("0123456789", 10);
  6712. }
  6713. expect (tempFile.exists());
  6714. expect (tempFile.getSize() == 10);
  6715. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6716. expect (tempFile.loadFileAsString() == "0123456789");
  6717. expect (! demoFolder.containsSubDirectories());
  6718. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  6719. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  6720. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6721. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6722. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6723. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6724. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6725. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6726. expect (demoFolder.containsSubDirectories());
  6727. expect (tempFile.hasWriteAccess());
  6728. tempFile.setReadOnly (true);
  6729. expect (! tempFile.hasWriteAccess());
  6730. tempFile.setReadOnly (false);
  6731. expect (tempFile.hasWriteAccess());
  6732. Time t (Time::getCurrentTime());
  6733. tempFile.setLastModificationTime (t);
  6734. Time t2 = tempFile.getLastModificationTime();
  6735. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6736. {
  6737. MemoryBlock mb;
  6738. tempFile.loadFileAsData (mb);
  6739. expect (mb.getSize() == 10);
  6740. expect (mb[0] == '0');
  6741. }
  6742. expect (tempFile.appendData ("abcdefghij", 10));
  6743. expect (tempFile.getSize() == 20);
  6744. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6745. expect (tempFile.getSize() == 10);
  6746. File tempFile2 (tempFile.getNonexistentSibling (false));
  6747. expect (tempFile.copyFileTo (tempFile2));
  6748. expect (tempFile2.exists());
  6749. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6750. expect (tempFile.deleteFile());
  6751. expect (! tempFile.exists());
  6752. expect (tempFile2.moveFileTo (tempFile));
  6753. expect (tempFile.exists());
  6754. expect (! tempFile2.exists());
  6755. expect (demoFolder.deleteRecursively());
  6756. expect (! demoFolder.exists());
  6757. }
  6758. };
  6759. static FileTests fileUnitTests;
  6760. #endif
  6761. END_JUCE_NAMESPACE
  6762. /*** End of inlined file: juce_File.cpp ***/
  6763. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6764. BEGIN_JUCE_NAMESPACE
  6765. int64 juce_fileSetPosition (void* handle, int64 pos);
  6766. FileInputStream::FileInputStream (const File& f)
  6767. : file (f),
  6768. fileHandle (0),
  6769. currentPosition (0),
  6770. totalSize (0),
  6771. needToSeek (true)
  6772. {
  6773. openHandle();
  6774. }
  6775. FileInputStream::~FileInputStream()
  6776. {
  6777. closeHandle();
  6778. }
  6779. int64 FileInputStream::getTotalLength()
  6780. {
  6781. return totalSize;
  6782. }
  6783. int FileInputStream::read (void* buffer, int bytesToRead)
  6784. {
  6785. if (needToSeek)
  6786. {
  6787. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6788. return 0;
  6789. needToSeek = false;
  6790. }
  6791. const size_t num = readInternal (buffer, bytesToRead);
  6792. currentPosition += num;
  6793. return (int) num;
  6794. }
  6795. bool FileInputStream::isExhausted()
  6796. {
  6797. return currentPosition >= totalSize;
  6798. }
  6799. int64 FileInputStream::getPosition()
  6800. {
  6801. return currentPosition;
  6802. }
  6803. bool FileInputStream::setPosition (int64 pos)
  6804. {
  6805. pos = jlimit ((int64) 0, totalSize, pos);
  6806. needToSeek |= (currentPosition != pos);
  6807. currentPosition = pos;
  6808. return true;
  6809. }
  6810. END_JUCE_NAMESPACE
  6811. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6812. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6813. BEGIN_JUCE_NAMESPACE
  6814. int64 juce_fileSetPosition (void* handle, int64 pos);
  6815. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6816. : file (f),
  6817. fileHandle (0),
  6818. currentPosition (0),
  6819. bufferSize (bufferSize_),
  6820. bytesInBuffer (0),
  6821. buffer (jmax (bufferSize_, 16))
  6822. {
  6823. openHandle();
  6824. }
  6825. FileOutputStream::~FileOutputStream()
  6826. {
  6827. flush();
  6828. closeHandle();
  6829. }
  6830. int64 FileOutputStream::getPosition()
  6831. {
  6832. return currentPosition;
  6833. }
  6834. bool FileOutputStream::setPosition (int64 newPosition)
  6835. {
  6836. if (newPosition != currentPosition)
  6837. {
  6838. flush();
  6839. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6840. }
  6841. return newPosition == currentPosition;
  6842. }
  6843. void FileOutputStream::flush()
  6844. {
  6845. if (bytesInBuffer > 0)
  6846. {
  6847. writeInternal (buffer, bytesInBuffer);
  6848. bytesInBuffer = 0;
  6849. }
  6850. flushInternal();
  6851. }
  6852. bool FileOutputStream::write (const void* const src, const int numBytes)
  6853. {
  6854. if (bytesInBuffer + numBytes < bufferSize)
  6855. {
  6856. memcpy (buffer + bytesInBuffer, src, numBytes);
  6857. bytesInBuffer += numBytes;
  6858. currentPosition += numBytes;
  6859. }
  6860. else
  6861. {
  6862. if (bytesInBuffer > 0)
  6863. {
  6864. // flush the reservoir
  6865. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6866. bytesInBuffer = 0;
  6867. if (! wroteOk)
  6868. return false;
  6869. }
  6870. if (numBytes < bufferSize)
  6871. {
  6872. memcpy (buffer + bytesInBuffer, src, numBytes);
  6873. bytesInBuffer += numBytes;
  6874. currentPosition += numBytes;
  6875. }
  6876. else
  6877. {
  6878. const int bytesWritten = writeInternal (src, numBytes);
  6879. if (bytesWritten < 0)
  6880. return false;
  6881. currentPosition += bytesWritten;
  6882. return bytesWritten == numBytes;
  6883. }
  6884. }
  6885. return true;
  6886. }
  6887. END_JUCE_NAMESPACE
  6888. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6889. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6890. BEGIN_JUCE_NAMESPACE
  6891. FileSearchPath::FileSearchPath()
  6892. {
  6893. }
  6894. FileSearchPath::FileSearchPath (const String& path)
  6895. {
  6896. init (path);
  6897. }
  6898. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6899. : directories (other.directories)
  6900. {
  6901. }
  6902. FileSearchPath::~FileSearchPath()
  6903. {
  6904. }
  6905. FileSearchPath& FileSearchPath::operator= (const String& path)
  6906. {
  6907. init (path);
  6908. return *this;
  6909. }
  6910. void FileSearchPath::init (const String& path)
  6911. {
  6912. directories.clear();
  6913. directories.addTokens (path, ";", "\"");
  6914. directories.trim();
  6915. directories.removeEmptyStrings();
  6916. for (int i = directories.size(); --i >= 0;)
  6917. directories.set (i, directories[i].unquoted());
  6918. }
  6919. int FileSearchPath::getNumPaths() const
  6920. {
  6921. return directories.size();
  6922. }
  6923. const File FileSearchPath::operator[] (const int index) const
  6924. {
  6925. return File (directories [index]);
  6926. }
  6927. const String FileSearchPath::toString() const
  6928. {
  6929. StringArray directories2 (directories);
  6930. for (int i = directories2.size(); --i >= 0;)
  6931. if (directories2[i].containsChar (';'))
  6932. directories2.set (i, directories2[i].quoted());
  6933. return directories2.joinIntoString (";");
  6934. }
  6935. void FileSearchPath::add (const File& dir, const int insertIndex)
  6936. {
  6937. directories.insert (insertIndex, dir.getFullPathName());
  6938. }
  6939. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6940. {
  6941. for (int i = 0; i < directories.size(); ++i)
  6942. if (File (directories[i]) == dir)
  6943. return;
  6944. add (dir);
  6945. }
  6946. void FileSearchPath::remove (const int index)
  6947. {
  6948. directories.remove (index);
  6949. }
  6950. void FileSearchPath::addPath (const FileSearchPath& other)
  6951. {
  6952. for (int i = 0; i < other.getNumPaths(); ++i)
  6953. addIfNotAlreadyThere (other[i]);
  6954. }
  6955. void FileSearchPath::removeRedundantPaths()
  6956. {
  6957. for (int i = directories.size(); --i >= 0;)
  6958. {
  6959. const File d1 (directories[i]);
  6960. for (int j = directories.size(); --j >= 0;)
  6961. {
  6962. const File d2 (directories[j]);
  6963. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6964. {
  6965. directories.remove (i);
  6966. break;
  6967. }
  6968. }
  6969. }
  6970. }
  6971. void FileSearchPath::removeNonExistentPaths()
  6972. {
  6973. for (int i = directories.size(); --i >= 0;)
  6974. if (! File (directories[i]).isDirectory())
  6975. directories.remove (i);
  6976. }
  6977. int FileSearchPath::findChildFiles (Array<File>& results,
  6978. const int whatToLookFor,
  6979. const bool searchRecursively,
  6980. const String& wildCardPattern) const
  6981. {
  6982. int total = 0;
  6983. for (int i = 0; i < directories.size(); ++i)
  6984. total += operator[] (i).findChildFiles (results,
  6985. whatToLookFor,
  6986. searchRecursively,
  6987. wildCardPattern);
  6988. return total;
  6989. }
  6990. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6991. const bool checkRecursively) const
  6992. {
  6993. for (int i = directories.size(); --i >= 0;)
  6994. {
  6995. const File d (directories[i]);
  6996. if (checkRecursively)
  6997. {
  6998. if (fileToCheck.isAChildOf (d))
  6999. return true;
  7000. }
  7001. else
  7002. {
  7003. if (fileToCheck.getParentDirectory() == d)
  7004. return true;
  7005. }
  7006. }
  7007. return false;
  7008. }
  7009. END_JUCE_NAMESPACE
  7010. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  7011. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  7012. BEGIN_JUCE_NAMESPACE
  7013. NamedPipe::NamedPipe()
  7014. : internal (0)
  7015. {
  7016. }
  7017. NamedPipe::~NamedPipe()
  7018. {
  7019. close();
  7020. }
  7021. bool NamedPipe::openExisting (const String& pipeName)
  7022. {
  7023. currentPipeName = pipeName;
  7024. return openInternal (pipeName, false);
  7025. }
  7026. bool NamedPipe::createNewPipe (const String& pipeName)
  7027. {
  7028. currentPipeName = pipeName;
  7029. return openInternal (pipeName, true);
  7030. }
  7031. bool NamedPipe::isOpen() const
  7032. {
  7033. return internal != 0;
  7034. }
  7035. const String NamedPipe::getName() const
  7036. {
  7037. return currentPipeName;
  7038. }
  7039. // other methods for this class are implemented in the platform-specific files
  7040. END_JUCE_NAMESPACE
  7041. /*** End of inlined file: juce_NamedPipe.cpp ***/
  7042. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  7043. BEGIN_JUCE_NAMESPACE
  7044. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  7045. {
  7046. createTempFile (File::getSpecialLocation (File::tempDirectory),
  7047. "temp_" + String (Random::getSystemRandom().nextInt()),
  7048. suffix,
  7049. optionFlags);
  7050. }
  7051. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  7052. : targetFile (targetFile_)
  7053. {
  7054. // If you use this constructor, you need to give it a valid target file!
  7055. jassert (targetFile != File::nonexistent);
  7056. createTempFile (targetFile.getParentDirectory(),
  7057. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  7058. targetFile.getFileExtension(),
  7059. optionFlags);
  7060. }
  7061. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  7062. const String& suffix, const int optionFlags)
  7063. {
  7064. if ((optionFlags & useHiddenFile) != 0)
  7065. name = "." + name;
  7066. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  7067. }
  7068. TemporaryFile::~TemporaryFile()
  7069. {
  7070. if (! deleteTemporaryFile())
  7071. {
  7072. /* Failed to delete our temporary file! The most likely reason for this would be
  7073. that you've not closed an output stream that was being used to write to file.
  7074. If you find that something beyond your control is changing permissions on
  7075. your temporary files and preventing them from being deleted, you may want to
  7076. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  7077. handle them appropriately.
  7078. */
  7079. jassertfalse;
  7080. }
  7081. }
  7082. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  7083. {
  7084. // This method only works if you created this object with the constructor
  7085. // that takes a target file!
  7086. jassert (targetFile != File::nonexistent);
  7087. if (temporaryFile.exists())
  7088. {
  7089. // Have a few attempts at overwriting the file before giving up..
  7090. for (int i = 5; --i >= 0;)
  7091. {
  7092. if (temporaryFile.moveFileTo (targetFile))
  7093. return true;
  7094. Thread::sleep (100);
  7095. }
  7096. }
  7097. else
  7098. {
  7099. // There's no temporary file to use. If your write failed, you should
  7100. // probably check, and not bother calling this method.
  7101. jassertfalse;
  7102. }
  7103. return false;
  7104. }
  7105. bool TemporaryFile::deleteTemporaryFile() const
  7106. {
  7107. // Have a few attempts at deleting the file before giving up..
  7108. for (int i = 5; --i >= 0;)
  7109. {
  7110. if (temporaryFile.deleteFile())
  7111. return true;
  7112. Thread::sleep (50);
  7113. }
  7114. return false;
  7115. }
  7116. END_JUCE_NAMESPACE
  7117. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  7118. /*** Start of inlined file: juce_Socket.cpp ***/
  7119. #if JUCE_WINDOWS
  7120. #include <winsock2.h>
  7121. #if JUCE_MSVC
  7122. #pragma warning (push)
  7123. #pragma warning (disable : 4127 4389 4018)
  7124. #endif
  7125. #else
  7126. #if JUCE_LINUX || JUCE_ANDROID
  7127. #include <sys/types.h>
  7128. #include <sys/socket.h>
  7129. #include <sys/errno.h>
  7130. #include <unistd.h>
  7131. #include <netinet/in.h>
  7132. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  7133. #include <CoreServices/CoreServices.h>
  7134. #endif
  7135. #include <fcntl.h>
  7136. #include <netdb.h>
  7137. #include <arpa/inet.h>
  7138. #include <netinet/tcp.h>
  7139. #endif
  7140. BEGIN_JUCE_NAMESPACE
  7141. #if JUCE_LINUX || JUCE_MAC || JUCE_IOS || JUCE_ANDROID
  7142. typedef socklen_t juce_socklen_t;
  7143. #else
  7144. typedef int juce_socklen_t;
  7145. #endif
  7146. #if JUCE_WINDOWS
  7147. namespace SocketHelpers
  7148. {
  7149. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  7150. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  7151. void initWin32Sockets()
  7152. {
  7153. static CriticalSection lock;
  7154. const ScopedLock sl (lock);
  7155. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  7156. {
  7157. WSADATA wsaData;
  7158. const WORD wVersionRequested = MAKEWORD (1, 1);
  7159. WSAStartup (wVersionRequested, &wsaData);
  7160. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  7161. }
  7162. }
  7163. }
  7164. void juce_shutdownWin32Sockets()
  7165. {
  7166. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  7167. (*SocketHelpers::juce_CloseWin32SocketLib)();
  7168. }
  7169. #endif
  7170. namespace SocketHelpers
  7171. {
  7172. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  7173. {
  7174. const int sndBufSize = 65536;
  7175. const int rcvBufSize = 65536;
  7176. const int one = 1;
  7177. return handle > 0
  7178. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  7179. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  7180. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  7181. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  7182. }
  7183. bool bindSocketToPort (const int handle, const int port) throw()
  7184. {
  7185. if (handle <= 0 || port <= 0)
  7186. return false;
  7187. struct sockaddr_in servTmpAddr;
  7188. zerostruct (servTmpAddr);
  7189. servTmpAddr.sin_family = PF_INET;
  7190. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7191. servTmpAddr.sin_port = htons ((uint16) port);
  7192. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  7193. }
  7194. int readSocket (const int handle,
  7195. void* const destBuffer, const int maxBytesToRead,
  7196. bool volatile& connected,
  7197. const bool blockUntilSpecifiedAmountHasArrived) throw()
  7198. {
  7199. int bytesRead = 0;
  7200. while (bytesRead < maxBytesToRead)
  7201. {
  7202. int bytesThisTime;
  7203. #if JUCE_WINDOWS
  7204. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  7205. #else
  7206. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  7207. && errno == EINTR
  7208. && connected)
  7209. {
  7210. }
  7211. #endif
  7212. if (bytesThisTime <= 0 || ! connected)
  7213. {
  7214. if (bytesRead == 0)
  7215. bytesRead = -1;
  7216. break;
  7217. }
  7218. bytesRead += bytesThisTime;
  7219. if (! blockUntilSpecifiedAmountHasArrived)
  7220. break;
  7221. }
  7222. return bytesRead;
  7223. }
  7224. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7225. {
  7226. struct timeval timeout;
  7227. struct timeval* timeoutp;
  7228. if (timeoutMsecs >= 0)
  7229. {
  7230. timeout.tv_sec = timeoutMsecs / 1000;
  7231. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7232. timeoutp = &timeout;
  7233. }
  7234. else
  7235. {
  7236. timeoutp = 0;
  7237. }
  7238. fd_set rset, wset;
  7239. FD_ZERO (&rset);
  7240. FD_SET (handle, &rset);
  7241. FD_ZERO (&wset);
  7242. FD_SET (handle, &wset);
  7243. fd_set* const prset = forReading ? &rset : 0;
  7244. fd_set* const pwset = forReading ? 0 : &wset;
  7245. #if JUCE_WINDOWS
  7246. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7247. return -1;
  7248. #else
  7249. {
  7250. int result;
  7251. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7252. && errno == EINTR)
  7253. {
  7254. }
  7255. if (result < 0)
  7256. return -1;
  7257. }
  7258. #endif
  7259. {
  7260. int opt;
  7261. juce_socklen_t len = sizeof (opt);
  7262. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7263. || opt != 0)
  7264. return -1;
  7265. }
  7266. if ((forReading && FD_ISSET (handle, &rset))
  7267. || ((! forReading) && FD_ISSET (handle, &wset)))
  7268. return 1;
  7269. return 0;
  7270. }
  7271. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7272. {
  7273. #if JUCE_WINDOWS
  7274. u_long nonBlocking = shouldBlock ? 0 : 1;
  7275. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7276. return false;
  7277. #else
  7278. int socketFlags = fcntl (handle, F_GETFL, 0);
  7279. if (socketFlags == -1)
  7280. return false;
  7281. if (shouldBlock)
  7282. socketFlags &= ~O_NONBLOCK;
  7283. else
  7284. socketFlags |= O_NONBLOCK;
  7285. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7286. return false;
  7287. #endif
  7288. return true;
  7289. }
  7290. bool connectSocket (int volatile& handle,
  7291. const bool isDatagram,
  7292. void** serverAddress,
  7293. const String& hostName,
  7294. const int portNumber,
  7295. const int timeOutMillisecs) throw()
  7296. {
  7297. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7298. if (hostEnt == 0)
  7299. return false;
  7300. struct in_addr targetAddress;
  7301. memcpy (&targetAddress.s_addr,
  7302. *(hostEnt->h_addr_list),
  7303. sizeof (targetAddress.s_addr));
  7304. struct sockaddr_in servTmpAddr;
  7305. zerostruct (servTmpAddr);
  7306. servTmpAddr.sin_family = PF_INET;
  7307. servTmpAddr.sin_addr = targetAddress;
  7308. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7309. if (handle < 0)
  7310. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7311. if (handle < 0)
  7312. return false;
  7313. if (isDatagram)
  7314. {
  7315. *serverAddress = new struct sockaddr_in();
  7316. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7317. return true;
  7318. }
  7319. setSocketBlockingState (handle, false);
  7320. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7321. if (result < 0)
  7322. {
  7323. #if JUCE_WINDOWS
  7324. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7325. #else
  7326. if (errno == EINPROGRESS)
  7327. #endif
  7328. {
  7329. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7330. {
  7331. setSocketBlockingState (handle, true);
  7332. return false;
  7333. }
  7334. }
  7335. }
  7336. setSocketBlockingState (handle, true);
  7337. resetSocketOptions (handle, false, false);
  7338. return true;
  7339. }
  7340. }
  7341. StreamingSocket::StreamingSocket()
  7342. : portNumber (0),
  7343. handle (-1),
  7344. connected (false),
  7345. isListener (false)
  7346. {
  7347. #if JUCE_WINDOWS
  7348. SocketHelpers::initWin32Sockets();
  7349. #endif
  7350. }
  7351. StreamingSocket::StreamingSocket (const String& hostName_,
  7352. const int portNumber_,
  7353. const int handle_)
  7354. : hostName (hostName_),
  7355. portNumber (portNumber_),
  7356. handle (handle_),
  7357. connected (true),
  7358. isListener (false)
  7359. {
  7360. #if JUCE_WINDOWS
  7361. SocketHelpers::initWin32Sockets();
  7362. #endif
  7363. SocketHelpers::resetSocketOptions (handle_, false, false);
  7364. }
  7365. StreamingSocket::~StreamingSocket()
  7366. {
  7367. close();
  7368. }
  7369. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7370. {
  7371. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7372. : -1;
  7373. }
  7374. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7375. {
  7376. if (isListener || ! connected)
  7377. return -1;
  7378. #if JUCE_WINDOWS
  7379. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7380. #else
  7381. int result;
  7382. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7383. && errno == EINTR)
  7384. {
  7385. }
  7386. return result;
  7387. #endif
  7388. }
  7389. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7390. const int timeoutMsecs) const
  7391. {
  7392. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7393. : -1;
  7394. }
  7395. bool StreamingSocket::bindToPort (const int port)
  7396. {
  7397. return SocketHelpers::bindSocketToPort (handle, port);
  7398. }
  7399. bool StreamingSocket::connect (const String& remoteHostName,
  7400. const int remotePortNumber,
  7401. const int timeOutMillisecs)
  7402. {
  7403. if (isListener)
  7404. {
  7405. jassertfalse; // a listener socket can't connect to another one!
  7406. return false;
  7407. }
  7408. if (connected)
  7409. close();
  7410. hostName = remoteHostName;
  7411. portNumber = remotePortNumber;
  7412. isListener = false;
  7413. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7414. remotePortNumber, timeOutMillisecs);
  7415. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7416. {
  7417. close();
  7418. return false;
  7419. }
  7420. return true;
  7421. }
  7422. void StreamingSocket::close()
  7423. {
  7424. #if JUCE_WINDOWS
  7425. if (handle != SOCKET_ERROR || connected)
  7426. closesocket (handle);
  7427. connected = false;
  7428. #else
  7429. if (connected)
  7430. {
  7431. connected = false;
  7432. if (isListener)
  7433. {
  7434. // need to do this to interrupt the accept() function..
  7435. StreamingSocket temp;
  7436. temp.connect ("localhost", portNumber, 1000);
  7437. }
  7438. }
  7439. if (handle != -1)
  7440. ::close (handle);
  7441. #endif
  7442. hostName = String::empty;
  7443. portNumber = 0;
  7444. handle = -1;
  7445. isListener = false;
  7446. }
  7447. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7448. {
  7449. if (connected)
  7450. close();
  7451. hostName = "listener";
  7452. portNumber = newPortNumber;
  7453. isListener = true;
  7454. struct sockaddr_in servTmpAddr;
  7455. zerostruct (servTmpAddr);
  7456. servTmpAddr.sin_family = PF_INET;
  7457. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7458. if (localHostName.isNotEmpty())
  7459. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7460. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7461. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7462. if (handle < 0)
  7463. return false;
  7464. const int reuse = 1;
  7465. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7466. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7467. || listen (handle, SOMAXCONN) < 0)
  7468. {
  7469. close();
  7470. return false;
  7471. }
  7472. connected = true;
  7473. return true;
  7474. }
  7475. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7476. {
  7477. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7478. // prepare this socket as a listener.
  7479. if (connected && isListener)
  7480. {
  7481. struct sockaddr address;
  7482. juce_socklen_t len = sizeof (sockaddr);
  7483. const int newSocket = (int) accept (handle, &address, &len);
  7484. if (newSocket >= 0 && connected)
  7485. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7486. portNumber, newSocket);
  7487. }
  7488. return 0;
  7489. }
  7490. bool StreamingSocket::isLocal() const throw()
  7491. {
  7492. return hostName == "127.0.0.1";
  7493. }
  7494. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7495. : portNumber (0),
  7496. handle (-1),
  7497. connected (true),
  7498. allowBroadcast (allowBroadcast_),
  7499. serverAddress (0)
  7500. {
  7501. #if JUCE_WINDOWS
  7502. SocketHelpers::initWin32Sockets();
  7503. #endif
  7504. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7505. bindToPort (localPortNumber);
  7506. }
  7507. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7508. const int handle_, const int localPortNumber)
  7509. : hostName (hostName_),
  7510. portNumber (portNumber_),
  7511. handle (handle_),
  7512. connected (true),
  7513. allowBroadcast (false),
  7514. serverAddress (0)
  7515. {
  7516. #if JUCE_WINDOWS
  7517. SocketHelpers::initWin32Sockets();
  7518. #endif
  7519. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7520. bindToPort (localPortNumber);
  7521. }
  7522. DatagramSocket::~DatagramSocket()
  7523. {
  7524. close();
  7525. delete static_cast <struct sockaddr_in*> (serverAddress);
  7526. serverAddress = 0;
  7527. }
  7528. void DatagramSocket::close()
  7529. {
  7530. #if JUCE_WINDOWS
  7531. closesocket (handle);
  7532. connected = false;
  7533. #else
  7534. connected = false;
  7535. ::close (handle);
  7536. #endif
  7537. hostName = String::empty;
  7538. portNumber = 0;
  7539. handle = -1;
  7540. }
  7541. bool DatagramSocket::bindToPort (const int port)
  7542. {
  7543. return SocketHelpers::bindSocketToPort (handle, port);
  7544. }
  7545. bool DatagramSocket::connect (const String& remoteHostName,
  7546. const int remotePortNumber,
  7547. const int timeOutMillisecs)
  7548. {
  7549. if (connected)
  7550. close();
  7551. hostName = remoteHostName;
  7552. portNumber = remotePortNumber;
  7553. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7554. remoteHostName, remotePortNumber,
  7555. timeOutMillisecs);
  7556. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7557. {
  7558. close();
  7559. return false;
  7560. }
  7561. return true;
  7562. }
  7563. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7564. {
  7565. struct sockaddr address;
  7566. juce_socklen_t len = sizeof (sockaddr);
  7567. while (waitUntilReady (true, -1) == 1)
  7568. {
  7569. char buf[1];
  7570. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7571. {
  7572. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7573. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7574. -1, -1);
  7575. }
  7576. }
  7577. return 0;
  7578. }
  7579. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7580. const int timeoutMsecs) const
  7581. {
  7582. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7583. : -1;
  7584. }
  7585. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7586. {
  7587. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7588. : -1;
  7589. }
  7590. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7591. {
  7592. // You need to call connect() first to set the server address..
  7593. jassert (serverAddress != 0 && connected);
  7594. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7595. numBytesToWrite, 0,
  7596. (const struct sockaddr*) serverAddress,
  7597. sizeof (struct sockaddr_in))
  7598. : -1;
  7599. }
  7600. bool DatagramSocket::isLocal() const throw()
  7601. {
  7602. return hostName == "127.0.0.1";
  7603. }
  7604. #if JUCE_MSVC
  7605. #pragma warning (pop)
  7606. #endif
  7607. END_JUCE_NAMESPACE
  7608. /*** End of inlined file: juce_Socket.cpp ***/
  7609. /*** Start of inlined file: juce_URL.cpp ***/
  7610. BEGIN_JUCE_NAMESPACE
  7611. URL::URL()
  7612. {
  7613. }
  7614. URL::URL (const String& url_)
  7615. : url (url_)
  7616. {
  7617. int i = url.indexOfChar ('?');
  7618. if (i >= 0)
  7619. {
  7620. do
  7621. {
  7622. const int nextAmp = url.indexOfChar (i + 1, '&');
  7623. const int equalsPos = url.indexOfChar (i + 1, '=');
  7624. if (equalsPos > i + 1)
  7625. {
  7626. if (nextAmp < 0)
  7627. {
  7628. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7629. removeEscapeChars (url.substring (equalsPos + 1)));
  7630. }
  7631. else if (nextAmp > 0 && equalsPos < nextAmp)
  7632. {
  7633. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7634. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7635. }
  7636. }
  7637. i = nextAmp;
  7638. }
  7639. while (i >= 0);
  7640. url = url.upToFirstOccurrenceOf ("?", false, false);
  7641. }
  7642. }
  7643. URL::URL (const URL& other)
  7644. : url (other.url),
  7645. postData (other.postData),
  7646. parameters (other.parameters),
  7647. filesToUpload (other.filesToUpload),
  7648. mimeTypes (other.mimeTypes)
  7649. {
  7650. }
  7651. URL& URL::operator= (const URL& other)
  7652. {
  7653. url = other.url;
  7654. postData = other.postData;
  7655. parameters = other.parameters;
  7656. filesToUpload = other.filesToUpload;
  7657. mimeTypes = other.mimeTypes;
  7658. return *this;
  7659. }
  7660. URL::~URL()
  7661. {
  7662. }
  7663. namespace URLHelpers
  7664. {
  7665. const String getMangledParameters (const StringPairArray& parameters)
  7666. {
  7667. String p;
  7668. for (int i = 0; i < parameters.size(); ++i)
  7669. {
  7670. if (i > 0)
  7671. p << '&';
  7672. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7673. << '='
  7674. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7675. }
  7676. return p;
  7677. }
  7678. int findStartOfDomain (const String& url)
  7679. {
  7680. int i = 0;
  7681. while (CharacterFunctions::isLetterOrDigit (url[i])
  7682. || url[i] == '+' || url[i] == '-' || url[i] == '.')
  7683. ++i;
  7684. return url[i] == ':' ? i + 1 : 0;
  7685. }
  7686. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7687. {
  7688. MemoryOutputStream data (postData, false);
  7689. if (url.getFilesToUpload().size() > 0)
  7690. {
  7691. // need to upload some files, so do it as multi-part...
  7692. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7693. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7694. data << "--" << boundary;
  7695. int i;
  7696. for (i = 0; i < url.getParameters().size(); ++i)
  7697. {
  7698. data << "\r\nContent-Disposition: form-data; name=\""
  7699. << url.getParameters().getAllKeys() [i]
  7700. << "\"\r\n\r\n"
  7701. << url.getParameters().getAllValues() [i]
  7702. << "\r\n--"
  7703. << boundary;
  7704. }
  7705. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7706. {
  7707. const File file (url.getFilesToUpload().getAllValues() [i]);
  7708. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7709. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7710. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7711. const String mimeType (url.getMimeTypesOfUploadFiles()
  7712. .getValue (paramName, String::empty));
  7713. if (mimeType.isNotEmpty())
  7714. data << "Content-Type: " << mimeType << "\r\n";
  7715. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7716. << file << "\r\n--" << boundary;
  7717. }
  7718. data << "--\r\n";
  7719. data.flush();
  7720. }
  7721. else
  7722. {
  7723. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7724. data.flush();
  7725. // just a short text attachment, so use simple url encoding..
  7726. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7727. << (int) postData.getSize() << "\r\n";
  7728. }
  7729. }
  7730. }
  7731. const String URL::toString (const bool includeGetParameters) const
  7732. {
  7733. if (includeGetParameters && parameters.size() > 0)
  7734. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7735. else
  7736. return url;
  7737. }
  7738. bool URL::isWellFormed() const
  7739. {
  7740. //xxx TODO
  7741. return url.isNotEmpty();
  7742. }
  7743. const String URL::getDomain() const
  7744. {
  7745. int start = URLHelpers::findStartOfDomain (url);
  7746. while (url[start] == '/')
  7747. ++start;
  7748. const int end1 = url.indexOfChar (start, '/');
  7749. const int end2 = url.indexOfChar (start, ':');
  7750. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7751. : jmin (end1, end2);
  7752. return url.substring (start, end);
  7753. }
  7754. const String URL::getSubPath() const
  7755. {
  7756. int start = URLHelpers::findStartOfDomain (url);
  7757. while (url[start] == '/')
  7758. ++start;
  7759. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7760. return startOfPath <= 0 ? String::empty
  7761. : url.substring (startOfPath);
  7762. }
  7763. const String URL::getScheme() const
  7764. {
  7765. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7766. }
  7767. const URL URL::withNewSubPath (const String& newPath) const
  7768. {
  7769. int start = URLHelpers::findStartOfDomain (url);
  7770. while (url[start] == '/')
  7771. ++start;
  7772. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7773. URL u (*this);
  7774. if (startOfPath > 0)
  7775. u.url = url.substring (0, startOfPath);
  7776. if (! u.url.endsWithChar ('/'))
  7777. u.url << '/';
  7778. if (newPath.startsWithChar ('/'))
  7779. u.url << newPath.substring (1);
  7780. else
  7781. u.url << newPath;
  7782. return u;
  7783. }
  7784. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7785. {
  7786. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7787. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7788. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7789. return true;
  7790. if (possibleURL.containsChar ('@')
  7791. || possibleURL.containsChar (' '))
  7792. return false;
  7793. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7794. .fromLastOccurrenceOf (".", false, false));
  7795. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7796. }
  7797. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7798. {
  7799. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7800. return atSign > 0
  7801. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7802. && (! possibleEmailAddress.endsWithChar ('.'));
  7803. }
  7804. InputStream* URL::createInputStream (const bool usePostCommand,
  7805. OpenStreamProgressCallback* const progressCallback,
  7806. void* const progressCallbackContext,
  7807. const String& extraHeaders,
  7808. const int timeOutMs,
  7809. StringPairArray* const responseHeaders) const
  7810. {
  7811. String headers;
  7812. MemoryBlock headersAndPostData;
  7813. if (usePostCommand)
  7814. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7815. headers += extraHeaders;
  7816. if (! headers.endsWithChar ('\n'))
  7817. headers << "\r\n";
  7818. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7819. progressCallback, progressCallbackContext,
  7820. headers, timeOutMs, responseHeaders);
  7821. }
  7822. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7823. const bool usePostCommand) const
  7824. {
  7825. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7826. if (in != 0)
  7827. {
  7828. in->readIntoMemoryBlock (destData);
  7829. return true;
  7830. }
  7831. return false;
  7832. }
  7833. const String URL::readEntireTextStream (const bool usePostCommand) const
  7834. {
  7835. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7836. if (in != 0)
  7837. return in->readEntireStreamAsString();
  7838. return String::empty;
  7839. }
  7840. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7841. {
  7842. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7843. }
  7844. const URL URL::withParameter (const String& parameterName,
  7845. const String& parameterValue) const
  7846. {
  7847. URL u (*this);
  7848. u.parameters.set (parameterName, parameterValue);
  7849. return u;
  7850. }
  7851. const URL URL::withFileToUpload (const String& parameterName,
  7852. const File& fileToUpload,
  7853. const String& mimeType) const
  7854. {
  7855. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7856. URL u (*this);
  7857. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7858. u.mimeTypes.set (parameterName, mimeType);
  7859. return u;
  7860. }
  7861. const URL URL::withPOSTData (const String& postData_) const
  7862. {
  7863. URL u (*this);
  7864. u.postData = postData_;
  7865. return u;
  7866. }
  7867. const StringPairArray& URL::getParameters() const
  7868. {
  7869. return parameters;
  7870. }
  7871. const StringPairArray& URL::getFilesToUpload() const
  7872. {
  7873. return filesToUpload;
  7874. }
  7875. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7876. {
  7877. return mimeTypes;
  7878. }
  7879. const String URL::removeEscapeChars (const String& s)
  7880. {
  7881. String result (s.replaceCharacter ('+', ' '));
  7882. if (! result.containsChar ('%'))
  7883. return result;
  7884. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7885. // after all the replacements have been made, so that multi-byte chars are handled.
  7886. Array<char> utf8 (result.toUTF8().getAddress(), result.getNumBytesAsUTF8());
  7887. for (int i = 0; i < utf8.size(); ++i)
  7888. {
  7889. if (utf8.getUnchecked(i) == '%')
  7890. {
  7891. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7892. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7893. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7894. {
  7895. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7896. utf8.removeRange (i + 1, 2);
  7897. }
  7898. }
  7899. }
  7900. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7901. }
  7902. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7903. {
  7904. const CharPointer_UTF8 legalChars (isParameter ? "_-.*!'()"
  7905. : ",$_-.*!'()");
  7906. Array<char> utf8 (s.toUTF8().getAddress(), s.getNumBytesAsUTF8());
  7907. for (int i = 0; i < utf8.size(); ++i)
  7908. {
  7909. const char c = utf8.getUnchecked(i);
  7910. if (! (CharacterFunctions::isLetterOrDigit (c)
  7911. || legalChars.indexOf ((juce_wchar) c) >= 0))
  7912. {
  7913. if (c == ' ')
  7914. {
  7915. utf8.set (i, '+');
  7916. }
  7917. else
  7918. {
  7919. static const char* const hexDigits = "0123456789abcdef";
  7920. utf8.set (i, '%');
  7921. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7922. utf8.insert (++i, hexDigits [c & 15]);
  7923. }
  7924. }
  7925. }
  7926. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7927. }
  7928. bool URL::launchInDefaultBrowser() const
  7929. {
  7930. String u (toString (true));
  7931. if (u.containsChar ('@') && ! u.containsChar (':'))
  7932. u = "mailto:" + u;
  7933. return PlatformUtilities::openDocument (u, String::empty);
  7934. }
  7935. END_JUCE_NAMESPACE
  7936. /*** End of inlined file: juce_URL.cpp ***/
  7937. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7938. BEGIN_JUCE_NAMESPACE
  7939. MACAddress::MACAddress()
  7940. : asInt64 (0)
  7941. {
  7942. }
  7943. MACAddress::MACAddress (const MACAddress& other)
  7944. : asInt64 (other.asInt64)
  7945. {
  7946. }
  7947. MACAddress& MACAddress::operator= (const MACAddress& other)
  7948. {
  7949. asInt64 = other.asInt64;
  7950. return *this;
  7951. }
  7952. MACAddress::MACAddress (const uint8 bytes[6])
  7953. : asInt64 (0)
  7954. {
  7955. memcpy (asBytes, bytes, sizeof (asBytes));
  7956. }
  7957. const String MACAddress::toString() const
  7958. {
  7959. String s;
  7960. s.preallocateStorage (18);
  7961. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7962. {
  7963. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7964. if (i < numElementsInArray (asBytes) - 1)
  7965. s << '-';
  7966. }
  7967. return s;
  7968. }
  7969. int64 MACAddress::toInt64() const throw()
  7970. {
  7971. int64 n = 0;
  7972. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7973. n = (n << 8) | asBytes[i];
  7974. return n;
  7975. }
  7976. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7977. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7978. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7979. END_JUCE_NAMESPACE
  7980. /*** End of inlined file: juce_MACAddress.cpp ***/
  7981. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7982. BEGIN_JUCE_NAMESPACE
  7983. namespace
  7984. {
  7985. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7986. {
  7987. // You need to supply a real stream when creating a BufferedInputStream
  7988. jassert (source != 0);
  7989. requestedSize = jmax (256, requestedSize);
  7990. const int64 sourceSize = source->getTotalLength();
  7991. if (sourceSize >= 0 && sourceSize < requestedSize)
  7992. requestedSize = jmax (32, (int) sourceSize);
  7993. return requestedSize;
  7994. }
  7995. }
  7996. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7997. const bool deleteSourceWhenDestroyed)
  7998. : source (sourceStream),
  7999. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  8000. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  8001. position (sourceStream->getPosition()),
  8002. lastReadPos (0),
  8003. bufferStart (position),
  8004. bufferOverlap (128)
  8005. {
  8006. buffer.malloc (bufferSize);
  8007. }
  8008. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  8009. : source (&sourceStream),
  8010. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  8011. position (sourceStream.getPosition()),
  8012. lastReadPos (0),
  8013. bufferStart (position),
  8014. bufferOverlap (128)
  8015. {
  8016. buffer.malloc (bufferSize);
  8017. }
  8018. BufferedInputStream::~BufferedInputStream()
  8019. {
  8020. }
  8021. int64 BufferedInputStream::getTotalLength()
  8022. {
  8023. return source->getTotalLength();
  8024. }
  8025. int64 BufferedInputStream::getPosition()
  8026. {
  8027. return position;
  8028. }
  8029. bool BufferedInputStream::setPosition (int64 newPosition)
  8030. {
  8031. position = jmax ((int64) 0, newPosition);
  8032. return true;
  8033. }
  8034. bool BufferedInputStream::isExhausted()
  8035. {
  8036. return (position >= lastReadPos)
  8037. && source->isExhausted();
  8038. }
  8039. void BufferedInputStream::ensureBuffered()
  8040. {
  8041. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  8042. if (position < bufferStart || position >= bufferEndOverlap)
  8043. {
  8044. int bytesRead;
  8045. if (position < lastReadPos
  8046. && position >= bufferEndOverlap
  8047. && position >= bufferStart)
  8048. {
  8049. const int bytesToKeep = (int) (lastReadPos - position);
  8050. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  8051. bufferStart = position;
  8052. bytesRead = source->read (buffer + bytesToKeep,
  8053. bufferSize - bytesToKeep);
  8054. lastReadPos += bytesRead;
  8055. bytesRead += bytesToKeep;
  8056. }
  8057. else
  8058. {
  8059. bufferStart = position;
  8060. source->setPosition (bufferStart);
  8061. bytesRead = source->read (buffer, bufferSize);
  8062. lastReadPos = bufferStart + bytesRead;
  8063. }
  8064. while (bytesRead < bufferSize)
  8065. buffer [bytesRead++] = 0;
  8066. }
  8067. }
  8068. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  8069. {
  8070. if (position >= bufferStart
  8071. && position + maxBytesToRead <= lastReadPos)
  8072. {
  8073. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  8074. position += maxBytesToRead;
  8075. return maxBytesToRead;
  8076. }
  8077. else
  8078. {
  8079. if (position < bufferStart || position >= lastReadPos)
  8080. ensureBuffered();
  8081. int bytesRead = 0;
  8082. while (maxBytesToRead > 0)
  8083. {
  8084. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  8085. if (bytesAvailable > 0)
  8086. {
  8087. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  8088. maxBytesToRead -= bytesAvailable;
  8089. bytesRead += bytesAvailable;
  8090. position += bytesAvailable;
  8091. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  8092. }
  8093. const int64 oldLastReadPos = lastReadPos;
  8094. ensureBuffered();
  8095. if (oldLastReadPos == lastReadPos)
  8096. break; // if ensureBuffered() failed to read any more data, bail out
  8097. if (isExhausted())
  8098. break;
  8099. }
  8100. return bytesRead;
  8101. }
  8102. }
  8103. const String BufferedInputStream::readString()
  8104. {
  8105. if (position >= bufferStart
  8106. && position < lastReadPos)
  8107. {
  8108. const int maxChars = (int) (lastReadPos - position);
  8109. const char* const src = buffer + (int) (position - bufferStart);
  8110. for (int i = 0; i < maxChars; ++i)
  8111. {
  8112. if (src[i] == 0)
  8113. {
  8114. position += i + 1;
  8115. return String::fromUTF8 (src, i);
  8116. }
  8117. }
  8118. }
  8119. return InputStream::readString();
  8120. }
  8121. END_JUCE_NAMESPACE
  8122. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  8123. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8124. BEGIN_JUCE_NAMESPACE
  8125. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  8126. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  8127. {
  8128. }
  8129. FileInputSource::~FileInputSource()
  8130. {
  8131. }
  8132. InputStream* FileInputSource::createInputStream()
  8133. {
  8134. return file.createInputStream();
  8135. }
  8136. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8137. {
  8138. return file.getSiblingFile (relatedItemPath).createInputStream();
  8139. }
  8140. int64 FileInputSource::hashCode() const
  8141. {
  8142. int64 h = file.hashCode();
  8143. if (useFileTimeInHashGeneration)
  8144. h ^= file.getLastModificationTime().toMilliseconds();
  8145. return h;
  8146. }
  8147. END_JUCE_NAMESPACE
  8148. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8149. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8150. BEGIN_JUCE_NAMESPACE
  8151. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8152. const size_t sourceDataSize,
  8153. const bool keepInternalCopy)
  8154. : data (static_cast <const char*> (sourceData)),
  8155. dataSize (sourceDataSize),
  8156. position (0)
  8157. {
  8158. if (keepInternalCopy)
  8159. {
  8160. internalCopy.append (data, sourceDataSize);
  8161. data = static_cast <const char*> (internalCopy.getData());
  8162. }
  8163. }
  8164. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8165. const bool keepInternalCopy)
  8166. : data (static_cast <const char*> (sourceData.getData())),
  8167. dataSize (sourceData.getSize()),
  8168. position (0)
  8169. {
  8170. if (keepInternalCopy)
  8171. {
  8172. internalCopy = sourceData;
  8173. data = static_cast <const char*> (internalCopy.getData());
  8174. }
  8175. }
  8176. MemoryInputStream::~MemoryInputStream()
  8177. {
  8178. }
  8179. int64 MemoryInputStream::getTotalLength()
  8180. {
  8181. return dataSize;
  8182. }
  8183. int MemoryInputStream::read (void* const buffer, const int howMany)
  8184. {
  8185. jassert (howMany >= 0);
  8186. const int num = jmin (howMany, (int) (dataSize - position));
  8187. memcpy (buffer, data + position, num);
  8188. position += num;
  8189. return (int) num;
  8190. }
  8191. bool MemoryInputStream::isExhausted()
  8192. {
  8193. return (position >= dataSize);
  8194. }
  8195. bool MemoryInputStream::setPosition (const int64 pos)
  8196. {
  8197. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8198. return true;
  8199. }
  8200. int64 MemoryInputStream::getPosition()
  8201. {
  8202. return position;
  8203. }
  8204. #if JUCE_UNIT_TESTS
  8205. class MemoryStreamTests : public UnitTest
  8206. {
  8207. public:
  8208. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8209. void runTest()
  8210. {
  8211. beginTest ("Basics");
  8212. int randomInt = Random::getSystemRandom().nextInt();
  8213. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8214. double randomDouble = Random::getSystemRandom().nextDouble();
  8215. String randomString;
  8216. for (int i = 50; --i >= 0;)
  8217. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8218. MemoryOutputStream mo;
  8219. mo.writeInt (randomInt);
  8220. mo.writeIntBigEndian (randomInt);
  8221. mo.writeCompressedInt (randomInt);
  8222. mo.writeString (randomString);
  8223. mo.writeInt64 (randomInt64);
  8224. mo.writeInt64BigEndian (randomInt64);
  8225. mo.writeDouble (randomDouble);
  8226. mo.writeDoubleBigEndian (randomDouble);
  8227. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8228. expect (mi.readInt() == randomInt);
  8229. expect (mi.readIntBigEndian() == randomInt);
  8230. expect (mi.readCompressedInt() == randomInt);
  8231. expect (mi.readString() == randomString);
  8232. expect (mi.readInt64() == randomInt64);
  8233. expect (mi.readInt64BigEndian() == randomInt64);
  8234. expect (mi.readDouble() == randomDouble);
  8235. expect (mi.readDoubleBigEndian() == randomDouble);
  8236. }
  8237. };
  8238. static MemoryStreamTests memoryInputStreamUnitTests;
  8239. #endif
  8240. END_JUCE_NAMESPACE
  8241. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8242. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8243. BEGIN_JUCE_NAMESPACE
  8244. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8245. : data (internalBlock),
  8246. position (0),
  8247. size (0)
  8248. {
  8249. internalBlock.setSize (initialSize, false);
  8250. }
  8251. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8252. const bool appendToExistingBlockContent)
  8253. : data (memoryBlockToWriteTo),
  8254. position (0),
  8255. size (0)
  8256. {
  8257. if (appendToExistingBlockContent)
  8258. position = size = memoryBlockToWriteTo.getSize();
  8259. }
  8260. MemoryOutputStream::~MemoryOutputStream()
  8261. {
  8262. flush();
  8263. }
  8264. void MemoryOutputStream::flush()
  8265. {
  8266. if (&data != &internalBlock)
  8267. data.setSize (size, false);
  8268. }
  8269. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8270. {
  8271. data.ensureSize (bytesToPreallocate + 1);
  8272. }
  8273. void MemoryOutputStream::reset() throw()
  8274. {
  8275. position = 0;
  8276. size = 0;
  8277. }
  8278. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8279. {
  8280. if (howMany > 0)
  8281. {
  8282. const size_t storageNeeded = position + howMany;
  8283. if (storageNeeded >= data.getSize())
  8284. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8285. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8286. position += howMany;
  8287. size = jmax (size, position);
  8288. }
  8289. return true;
  8290. }
  8291. const void* MemoryOutputStream::getData() const throw()
  8292. {
  8293. void* const d = data.getData();
  8294. if (data.getSize() > size)
  8295. static_cast <char*> (d) [size] = 0;
  8296. return d;
  8297. }
  8298. bool MemoryOutputStream::setPosition (int64 newPosition)
  8299. {
  8300. if (newPosition <= (int64) size)
  8301. {
  8302. // ok to seek backwards
  8303. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8304. return true;
  8305. }
  8306. else
  8307. {
  8308. // trying to make it bigger isn't a good thing to do..
  8309. return false;
  8310. }
  8311. }
  8312. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8313. {
  8314. // before writing from an input, see if we can preallocate to make it more efficient..
  8315. int64 availableData = source.getTotalLength() - source.getPosition();
  8316. if (availableData > 0)
  8317. {
  8318. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8319. availableData = maxNumBytesToWrite;
  8320. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8321. }
  8322. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8323. }
  8324. const String MemoryOutputStream::toUTF8() const
  8325. {
  8326. return String::fromUTF8 (static_cast <const char*> (getData()), getDataSize());
  8327. }
  8328. const String MemoryOutputStream::toString() const
  8329. {
  8330. return String::createStringFromData (getData(), (int) getDataSize());
  8331. }
  8332. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8333. {
  8334. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8335. return stream;
  8336. }
  8337. END_JUCE_NAMESPACE
  8338. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8339. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8340. BEGIN_JUCE_NAMESPACE
  8341. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8342. const int64 startPositionInSourceStream_,
  8343. const int64 lengthOfSourceStream_,
  8344. const bool deleteSourceWhenDestroyed)
  8345. : source (sourceStream),
  8346. startPositionInSourceStream (startPositionInSourceStream_),
  8347. lengthOfSourceStream (lengthOfSourceStream_)
  8348. {
  8349. if (deleteSourceWhenDestroyed)
  8350. sourceToDelete = source;
  8351. setPosition (0);
  8352. }
  8353. SubregionStream::~SubregionStream()
  8354. {
  8355. }
  8356. int64 SubregionStream::getTotalLength()
  8357. {
  8358. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8359. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8360. : srcLen;
  8361. }
  8362. int64 SubregionStream::getPosition()
  8363. {
  8364. return source->getPosition() - startPositionInSourceStream;
  8365. }
  8366. bool SubregionStream::setPosition (int64 newPosition)
  8367. {
  8368. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8369. }
  8370. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8371. {
  8372. if (lengthOfSourceStream < 0)
  8373. {
  8374. return source->read (destBuffer, maxBytesToRead);
  8375. }
  8376. else
  8377. {
  8378. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8379. if (maxBytesToRead <= 0)
  8380. return 0;
  8381. return source->read (destBuffer, maxBytesToRead);
  8382. }
  8383. }
  8384. bool SubregionStream::isExhausted()
  8385. {
  8386. if (lengthOfSourceStream >= 0)
  8387. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8388. else
  8389. return source->isExhausted();
  8390. }
  8391. END_JUCE_NAMESPACE
  8392. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8393. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8394. BEGIN_JUCE_NAMESPACE
  8395. PerformanceCounter::PerformanceCounter (const String& name_,
  8396. int runsPerPrintout,
  8397. const File& loggingFile)
  8398. : name (name_),
  8399. numRuns (0),
  8400. runsPerPrint (runsPerPrintout),
  8401. totalTime (0),
  8402. outputFile (loggingFile)
  8403. {
  8404. if (outputFile != File::nonexistent)
  8405. {
  8406. String s ("**** Counter for \"");
  8407. s << name_ << "\" started at: "
  8408. << Time::getCurrentTime().toString (true, true)
  8409. << newLine;
  8410. outputFile.appendText (s, false, false);
  8411. }
  8412. }
  8413. PerformanceCounter::~PerformanceCounter()
  8414. {
  8415. printStatistics();
  8416. }
  8417. void PerformanceCounter::start()
  8418. {
  8419. started = Time::getHighResolutionTicks();
  8420. }
  8421. void PerformanceCounter::stop()
  8422. {
  8423. const int64 now = Time::getHighResolutionTicks();
  8424. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8425. if (++numRuns == runsPerPrint)
  8426. printStatistics();
  8427. }
  8428. void PerformanceCounter::printStatistics()
  8429. {
  8430. if (numRuns > 0)
  8431. {
  8432. String s ("Performance count for \"");
  8433. s << name << "\" - average over " << numRuns << " run(s) = ";
  8434. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8435. if (micros > 10000)
  8436. s << (micros/1000) << " millisecs";
  8437. else
  8438. s << micros << " microsecs";
  8439. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8440. Logger::outputDebugString (s);
  8441. s << newLine;
  8442. if (outputFile != File::nonexistent)
  8443. outputFile.appendText (s, false, false);
  8444. numRuns = 0;
  8445. totalTime = 0;
  8446. }
  8447. }
  8448. END_JUCE_NAMESPACE
  8449. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8450. /*** Start of inlined file: juce_Uuid.cpp ***/
  8451. BEGIN_JUCE_NAMESPACE
  8452. Uuid::Uuid()
  8453. {
  8454. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8455. // to make it very very unlikely that two UUIDs will ever be the same..
  8456. static int64 macAddresses[2];
  8457. static bool hasCheckedMacAddresses = false;
  8458. if (! hasCheckedMacAddresses)
  8459. {
  8460. hasCheckedMacAddresses = true;
  8461. Array<MACAddress> result;
  8462. MACAddress::findAllAddresses (result);
  8463. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8464. macAddresses[i] = result[i].toInt64();
  8465. }
  8466. value.asInt64[0] = macAddresses[0];
  8467. value.asInt64[1] = macAddresses[1];
  8468. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8469. // whose seed will carry over between calls to this method.
  8470. Random r (macAddresses[0] ^ macAddresses[1]
  8471. ^ Random::getSystemRandom().nextInt64());
  8472. for (int i = 4; --i >= 0;)
  8473. {
  8474. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8475. value.asInt[i] ^= r.nextInt();
  8476. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8477. }
  8478. }
  8479. Uuid::~Uuid() throw()
  8480. {
  8481. }
  8482. Uuid::Uuid (const Uuid& other)
  8483. : value (other.value)
  8484. {
  8485. }
  8486. Uuid& Uuid::operator= (const Uuid& other)
  8487. {
  8488. value = other.value;
  8489. return *this;
  8490. }
  8491. bool Uuid::operator== (const Uuid& other) const
  8492. {
  8493. return value.asInt64[0] == other.value.asInt64[0]
  8494. && value.asInt64[1] == other.value.asInt64[1];
  8495. }
  8496. bool Uuid::operator!= (const Uuid& other) const
  8497. {
  8498. return ! operator== (other);
  8499. }
  8500. bool Uuid::isNull() const throw()
  8501. {
  8502. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8503. }
  8504. const String Uuid::toString() const
  8505. {
  8506. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8507. }
  8508. Uuid::Uuid (const String& uuidString)
  8509. {
  8510. operator= (uuidString);
  8511. }
  8512. Uuid& Uuid::operator= (const String& uuidString)
  8513. {
  8514. MemoryBlock mb;
  8515. mb.loadFromHexString (uuidString);
  8516. mb.ensureSize (sizeof (value.asBytes), true);
  8517. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8518. return *this;
  8519. }
  8520. Uuid::Uuid (const uint8* const rawData)
  8521. {
  8522. operator= (rawData);
  8523. }
  8524. Uuid& Uuid::operator= (const uint8* const rawData)
  8525. {
  8526. if (rawData != 0)
  8527. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8528. else
  8529. zeromem (value.asBytes, sizeof (value.asBytes));
  8530. return *this;
  8531. }
  8532. END_JUCE_NAMESPACE
  8533. /*** End of inlined file: juce_Uuid.cpp ***/
  8534. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8535. BEGIN_JUCE_NAMESPACE
  8536. class ZipFile::ZipEntryInfo
  8537. {
  8538. public:
  8539. ZipFile::ZipEntry entry;
  8540. int streamOffset;
  8541. int compressedSize;
  8542. bool compressed;
  8543. };
  8544. class ZipFile::ZipInputStream : public InputStream
  8545. {
  8546. public:
  8547. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8548. : file (file_),
  8549. zipEntryInfo (zei),
  8550. pos (0),
  8551. headerSize (0),
  8552. inputStream (0)
  8553. {
  8554. inputStream = file_.inputStream;
  8555. if (file_.inputSource != 0)
  8556. {
  8557. inputStream = streamToDelete = file.inputSource->createInputStream();
  8558. }
  8559. else
  8560. {
  8561. #if JUCE_DEBUG
  8562. file_.numOpenStreams++;
  8563. #endif
  8564. }
  8565. char buffer [30];
  8566. if (inputStream != 0
  8567. && inputStream->setPosition (zei.streamOffset)
  8568. && inputStream->read (buffer, 30) == 30
  8569. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8570. {
  8571. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8572. + ByteOrder::littleEndianShort (buffer + 28);
  8573. }
  8574. }
  8575. ~ZipInputStream()
  8576. {
  8577. #if JUCE_DEBUG
  8578. if (inputStream != 0 && inputStream == file.inputStream)
  8579. file.numOpenStreams--;
  8580. #endif
  8581. }
  8582. int64 getTotalLength()
  8583. {
  8584. return zipEntryInfo.compressedSize;
  8585. }
  8586. int read (void* buffer, int howMany)
  8587. {
  8588. if (headerSize <= 0)
  8589. return 0;
  8590. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8591. if (inputStream == 0)
  8592. return 0;
  8593. int num;
  8594. if (inputStream == file.inputStream)
  8595. {
  8596. const ScopedLock sl (file.lock);
  8597. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8598. num = inputStream->read (buffer, howMany);
  8599. }
  8600. else
  8601. {
  8602. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8603. num = inputStream->read (buffer, howMany);
  8604. }
  8605. pos += num;
  8606. return num;
  8607. }
  8608. bool isExhausted()
  8609. {
  8610. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8611. }
  8612. int64 getPosition()
  8613. {
  8614. return pos;
  8615. }
  8616. bool setPosition (int64 newPos)
  8617. {
  8618. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8619. return true;
  8620. }
  8621. private:
  8622. ZipFile& file;
  8623. ZipEntryInfo zipEntryInfo;
  8624. int64 pos;
  8625. int headerSize;
  8626. InputStream* inputStream;
  8627. ScopedPointer<InputStream> streamToDelete;
  8628. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8629. };
  8630. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8631. : inputStream (source_)
  8632. #if JUCE_DEBUG
  8633. , numOpenStreams (0)
  8634. #endif
  8635. {
  8636. if (deleteStreamWhenDestroyed)
  8637. streamToDelete = inputStream;
  8638. init();
  8639. }
  8640. ZipFile::ZipFile (const File& file)
  8641. : inputStream (0)
  8642. #if JUCE_DEBUG
  8643. , numOpenStreams (0)
  8644. #endif
  8645. {
  8646. inputSource = new FileInputSource (file);
  8647. init();
  8648. }
  8649. ZipFile::ZipFile (InputSource* const inputSource_)
  8650. : inputStream (0),
  8651. inputSource (inputSource_)
  8652. #if JUCE_DEBUG
  8653. , numOpenStreams (0)
  8654. #endif
  8655. {
  8656. init();
  8657. }
  8658. ZipFile::~ZipFile()
  8659. {
  8660. #if JUCE_DEBUG
  8661. entries.clear();
  8662. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8663. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8664. Streams can't be kept open after the file is deleted because they need to share the input
  8665. stream that the file uses to read itself.
  8666. */
  8667. jassert (numOpenStreams == 0);
  8668. #endif
  8669. }
  8670. int ZipFile::getNumEntries() const throw()
  8671. {
  8672. return entries.size();
  8673. }
  8674. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8675. {
  8676. ZipEntryInfo* const zei = entries [index];
  8677. return zei != 0 ? &(zei->entry) : 0;
  8678. }
  8679. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8680. {
  8681. for (int i = 0; i < entries.size(); ++i)
  8682. if (entries.getUnchecked (i)->entry.filename == fileName)
  8683. return i;
  8684. return -1;
  8685. }
  8686. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8687. {
  8688. return getEntry (getIndexOfFileName (fileName));
  8689. }
  8690. InputStream* ZipFile::createStreamForEntry (const int index)
  8691. {
  8692. ZipEntryInfo* const zei = entries[index];
  8693. InputStream* stream = 0;
  8694. if (zei != 0)
  8695. {
  8696. stream = new ZipInputStream (*this, *zei);
  8697. if (zei->compressed)
  8698. {
  8699. stream = new GZIPDecompressorInputStream (stream, true, true,
  8700. zei->entry.uncompressedSize);
  8701. // (much faster to unzip in big blocks using a buffer..)
  8702. stream = new BufferedInputStream (stream, 32768, true);
  8703. }
  8704. }
  8705. return stream;
  8706. }
  8707. class ZipFile::ZipFilenameComparator
  8708. {
  8709. public:
  8710. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8711. {
  8712. return first->entry.filename.compare (second->entry.filename);
  8713. }
  8714. };
  8715. void ZipFile::sortEntriesByFilename()
  8716. {
  8717. ZipFilenameComparator sorter;
  8718. entries.sort (sorter);
  8719. }
  8720. void ZipFile::init()
  8721. {
  8722. ScopedPointer <InputStream> toDelete;
  8723. InputStream* in = inputStream;
  8724. if (inputSource != 0)
  8725. {
  8726. in = inputSource->createInputStream();
  8727. toDelete = in;
  8728. }
  8729. if (in != 0)
  8730. {
  8731. int numEntries = 0;
  8732. int pos = findEndOfZipEntryTable (*in, numEntries);
  8733. if (pos >= 0 && pos < in->getTotalLength())
  8734. {
  8735. const int size = (int) (in->getTotalLength() - pos);
  8736. in->setPosition (pos);
  8737. MemoryBlock headerData;
  8738. if (in->readIntoMemoryBlock (headerData, size) == size)
  8739. {
  8740. pos = 0;
  8741. for (int i = 0; i < numEntries; ++i)
  8742. {
  8743. if (pos + 46 > size)
  8744. break;
  8745. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8746. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8747. if (pos + 46 + fileNameLen > size)
  8748. break;
  8749. ZipEntryInfo* const zei = new ZipEntryInfo();
  8750. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8751. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8752. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8753. const int year = 1980 + (date >> 9);
  8754. const int month = ((date >> 5) & 15) - 1;
  8755. const int day = date & 31;
  8756. const int hours = time >> 11;
  8757. const int minutes = (time >> 5) & 63;
  8758. const int seconds = (time & 31) << 1;
  8759. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8760. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8761. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8762. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8763. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8764. entries.add (zei);
  8765. pos += 46 + fileNameLen
  8766. + ByteOrder::littleEndianShort (buffer + 30)
  8767. + ByteOrder::littleEndianShort (buffer + 32);
  8768. }
  8769. }
  8770. }
  8771. }
  8772. }
  8773. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8774. {
  8775. BufferedInputStream in (input, 8192);
  8776. in.setPosition (in.getTotalLength());
  8777. int64 pos = in.getPosition();
  8778. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8779. char buffer [32];
  8780. zeromem (buffer, sizeof (buffer));
  8781. while (pos > lowestPos)
  8782. {
  8783. in.setPosition (pos - 22);
  8784. pos = in.getPosition();
  8785. memcpy (buffer + 22, buffer, 4);
  8786. if (in.read (buffer, 22) != 22)
  8787. return 0;
  8788. for (int i = 0; i < 22; ++i)
  8789. {
  8790. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8791. {
  8792. in.setPosition (pos + i);
  8793. in.read (buffer, 22);
  8794. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8795. return ByteOrder::littleEndianInt (buffer + 16);
  8796. }
  8797. }
  8798. }
  8799. return 0;
  8800. }
  8801. bool ZipFile::uncompressTo (const File& targetDirectory,
  8802. const bool shouldOverwriteFiles)
  8803. {
  8804. for (int i = 0; i < entries.size(); ++i)
  8805. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8806. return false;
  8807. return true;
  8808. }
  8809. bool ZipFile::uncompressEntry (const int index,
  8810. const File& targetDirectory,
  8811. bool shouldOverwriteFiles)
  8812. {
  8813. const ZipEntryInfo* zei = entries [index];
  8814. if (zei != 0)
  8815. {
  8816. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8817. if (zei->entry.filename.endsWithChar ('/'))
  8818. {
  8819. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8820. }
  8821. else
  8822. {
  8823. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8824. if (in != 0)
  8825. {
  8826. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8827. return false;
  8828. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8829. {
  8830. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8831. if (out != 0)
  8832. {
  8833. out->writeFromInputStream (*in, -1);
  8834. out = 0;
  8835. targetFile.setCreationTime (zei->entry.fileTime);
  8836. targetFile.setLastModificationTime (zei->entry.fileTime);
  8837. targetFile.setLastAccessTime (zei->entry.fileTime);
  8838. return true;
  8839. }
  8840. }
  8841. }
  8842. }
  8843. }
  8844. return false;
  8845. }
  8846. END_JUCE_NAMESPACE
  8847. /*** End of inlined file: juce_ZipFile.cpp ***/
  8848. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8849. #if JUCE_MSVC
  8850. #pragma warning (push)
  8851. #pragma warning (disable: 4514 4996)
  8852. #endif
  8853. #if ! JUCE_ANDROID
  8854. #include <cwctype>
  8855. #endif
  8856. #include <cctype>
  8857. #include <ctime>
  8858. BEGIN_JUCE_NAMESPACE
  8859. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8860. {
  8861. return towupper ((wchar_t) character);
  8862. }
  8863. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8864. {
  8865. return towlower ((wchar_t) character);
  8866. }
  8867. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8868. {
  8869. #if JUCE_WINDOWS
  8870. return iswupper ((wchar_t) character) != 0;
  8871. #else
  8872. return toLowerCase (character) != character;
  8873. #endif
  8874. }
  8875. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8876. {
  8877. #if JUCE_WINDOWS
  8878. return iswlower ((wchar_t) character) != 0;
  8879. #else
  8880. return toUpperCase (character) != character;
  8881. #endif
  8882. }
  8883. bool CharacterFunctions::isWhitespace (const char character) throw()
  8884. {
  8885. return character == ' ' || (character <= 13 && character >= 9);
  8886. }
  8887. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8888. {
  8889. return iswspace ((wchar_t) character) != 0;
  8890. }
  8891. bool CharacterFunctions::isDigit (const char character) throw()
  8892. {
  8893. return (character >= '0' && character <= '9');
  8894. }
  8895. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8896. {
  8897. return iswdigit ((wchar_t) character) != 0;
  8898. }
  8899. bool CharacterFunctions::isLetter (const char character) throw()
  8900. {
  8901. return (character >= 'a' && character <= 'z')
  8902. || (character >= 'A' && character <= 'Z');
  8903. }
  8904. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8905. {
  8906. return iswalpha ((wchar_t) character) != 0;
  8907. }
  8908. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8909. {
  8910. return (character >= 'a' && character <= 'z')
  8911. || (character >= 'A' && character <= 'Z')
  8912. || (character >= '0' && character <= '9');
  8913. }
  8914. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8915. {
  8916. return iswalnum ((wchar_t) character) != 0;
  8917. }
  8918. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8919. {
  8920. unsigned int d = digit - '0';
  8921. if (d < (unsigned int) 10)
  8922. return (int) d;
  8923. d += (unsigned int) ('0' - 'a');
  8924. if (d < (unsigned int) 6)
  8925. return (int) d + 10;
  8926. d += (unsigned int) ('a' - 'A');
  8927. if (d < (unsigned int) 6)
  8928. return (int) d + 10;
  8929. return -1;
  8930. }
  8931. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8932. {
  8933. return (int) strftime (dest, maxChars, format, tm);
  8934. }
  8935. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8936. {
  8937. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  8938. HeapBlock <char> tempDest;
  8939. tempDest.calloc (maxChars + 2);
  8940. int result = ftime (tempDest.getData(), maxChars, String (format).toUTF8(), tm);
  8941. CharPointer_UTF32 (dest).writeAll (CharPointer_UTF8 (tempDest.getData()));
  8942. return result;
  8943. #else
  8944. return (int) wcsftime (dest, maxChars, format, tm);
  8945. #endif
  8946. }
  8947. #if JUCE_MSVC
  8948. #pragma warning (pop)
  8949. #endif
  8950. double CharacterFunctions::mulexp10 (const double value, int exponent) throw()
  8951. {
  8952. if (exponent == 0)
  8953. return value;
  8954. if (value == 0)
  8955. return 0;
  8956. const bool negative = (exponent < 0);
  8957. if (negative)
  8958. exponent = -exponent;
  8959. double result = 1.0, power = 10.0;
  8960. for (int bit = 1; exponent != 0; bit <<= 1)
  8961. {
  8962. if ((exponent & bit) != 0)
  8963. {
  8964. exponent ^= bit;
  8965. result *= power;
  8966. if (exponent == 0)
  8967. break;
  8968. }
  8969. power *= power;
  8970. }
  8971. return negative ? (value / result) : (value * result);
  8972. }
  8973. END_JUCE_NAMESPACE
  8974. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8975. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8976. BEGIN_JUCE_NAMESPACE
  8977. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8978. {
  8979. loadFromText (fileContents);
  8980. }
  8981. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8982. {
  8983. loadFromText (fileToLoad.loadFileAsString());
  8984. }
  8985. LocalisedStrings::~LocalisedStrings()
  8986. {
  8987. }
  8988. const String LocalisedStrings::translate (const String& text) const
  8989. {
  8990. return translations.getValue (text, text);
  8991. }
  8992. namespace
  8993. {
  8994. CriticalSection currentMappingsLock;
  8995. LocalisedStrings* currentMappings = 0;
  8996. int findCloseQuote (const String& text, int startPos)
  8997. {
  8998. juce_wchar lastChar = 0;
  8999. for (;;)
  9000. {
  9001. const juce_wchar c = text [startPos];
  9002. if (c == 0 || (c == '"' && lastChar != '\\'))
  9003. break;
  9004. lastChar = c;
  9005. ++startPos;
  9006. }
  9007. return startPos;
  9008. }
  9009. const String unescapeString (const String& s)
  9010. {
  9011. return s.replace ("\\\"", "\"")
  9012. .replace ("\\\'", "\'")
  9013. .replace ("\\t", "\t")
  9014. .replace ("\\r", "\r")
  9015. .replace ("\\n", "\n");
  9016. }
  9017. }
  9018. void LocalisedStrings::loadFromText (const String& fileContents)
  9019. {
  9020. StringArray lines;
  9021. lines.addLines (fileContents);
  9022. for (int i = 0; i < lines.size(); ++i)
  9023. {
  9024. String line (lines[i].trim());
  9025. if (line.startsWithChar ('"'))
  9026. {
  9027. int closeQuote = findCloseQuote (line, 1);
  9028. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9029. if (originalText.isNotEmpty())
  9030. {
  9031. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9032. closeQuote = findCloseQuote (line, openingQuote + 1);
  9033. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9034. if (newText.isNotEmpty())
  9035. translations.set (originalText, newText);
  9036. }
  9037. }
  9038. else if (line.startsWithIgnoreCase ("language:"))
  9039. {
  9040. languageName = line.substring (9).trim();
  9041. }
  9042. else if (line.startsWithIgnoreCase ("countries:"))
  9043. {
  9044. countryCodes.addTokens (line.substring (10).trim(), true);
  9045. countryCodes.trim();
  9046. countryCodes.removeEmptyStrings();
  9047. }
  9048. }
  9049. }
  9050. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9051. {
  9052. translations.setIgnoresCase (shouldIgnoreCase);
  9053. }
  9054. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9055. {
  9056. const ScopedLock sl (currentMappingsLock);
  9057. delete currentMappings;
  9058. currentMappings = newTranslations;
  9059. }
  9060. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9061. {
  9062. return currentMappings;
  9063. }
  9064. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9065. {
  9066. const ScopedLock sl (currentMappingsLock);
  9067. if (currentMappings != 0)
  9068. return currentMappings->translate (text);
  9069. return text;
  9070. }
  9071. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9072. {
  9073. return translateWithCurrentMappings (String (text));
  9074. }
  9075. END_JUCE_NAMESPACE
  9076. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9077. /*** Start of inlined file: juce_String.cpp ***/
  9078. #if JUCE_MSVC
  9079. #pragma warning (push)
  9080. #pragma warning (disable: 4514 4996)
  9081. #endif
  9082. #include <locale>
  9083. BEGIN_JUCE_NAMESPACE
  9084. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9085. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9086. #endif
  9087. NewLine newLine;
  9088. class StringHolder
  9089. {
  9090. public:
  9091. StringHolder()
  9092. : refCount (0x3fffffff), allocatedNumChars (0)
  9093. {
  9094. text[0] = 0;
  9095. }
  9096. typedef String::CharPointerType CharPointerType;
  9097. static const CharPointerType createUninitialised (const size_t numChars)
  9098. {
  9099. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9100. s->refCount.value = 0;
  9101. s->allocatedNumChars = numChars;
  9102. return CharPointerType (&(s->text[0]));
  9103. }
  9104. template <class CharPointer>
  9105. static const CharPointerType createFromCharPointer (const CharPointer& text)
  9106. {
  9107. if (text.getAddress() == 0 || text.isEmpty())
  9108. return getEmpty();
  9109. const size_t numChars = text.length();
  9110. const CharPointerType dest (createUninitialised (numChars));
  9111. CharPointerType (dest).writeAll (text);
  9112. return dest;
  9113. }
  9114. template <class CharPointer>
  9115. static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars)
  9116. {
  9117. if (text.getAddress() == 0 || text.isEmpty())
  9118. return getEmpty();
  9119. size_t numChars = text.lengthUpTo (maxChars);
  9120. if (numChars == 0)
  9121. return getEmpty();
  9122. const CharPointerType dest (createUninitialised (numChars));
  9123. CharPointerType (dest).writeWithCharLimit (text, (int) (numChars + 1));
  9124. return dest;
  9125. }
  9126. static CharPointerType createFromFixedLength (const juce_wchar* const src, const size_t numChars)
  9127. {
  9128. CharPointerType dest (createUninitialised (numChars));
  9129. copyChars (dest, CharPointerType (src), (int) numChars);
  9130. return dest;
  9131. }
  9132. static const CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  9133. {
  9134. const CharPointerType dest (createUninitialised (numChars));
  9135. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  9136. return dest;
  9137. }
  9138. static inline const CharPointerType getEmpty() throw()
  9139. {
  9140. return CharPointerType (&(empty.text[0]));
  9141. }
  9142. static void retain (const CharPointerType& text) throw()
  9143. {
  9144. ++(bufferFromText (text)->refCount);
  9145. }
  9146. static inline void release (StringHolder* const b) throw()
  9147. {
  9148. if (--(b->refCount) == -1 && b != &empty)
  9149. delete[] reinterpret_cast <char*> (b);
  9150. }
  9151. static void release (const CharPointerType& text) throw()
  9152. {
  9153. release (bufferFromText (text));
  9154. }
  9155. static CharPointerType makeUnique (const CharPointerType& text)
  9156. {
  9157. StringHolder* const b = bufferFromText (text);
  9158. if (b->refCount.get() <= 0)
  9159. return text;
  9160. CharPointerType newText (createFromFixedLength (text, b->allocatedNumChars));
  9161. release (b);
  9162. return newText;
  9163. }
  9164. static CharPointerType makeUniqueWithSize (const CharPointerType& text, size_t numChars)
  9165. {
  9166. StringHolder* const b = bufferFromText (text);
  9167. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9168. return text;
  9169. CharPointerType newText (createUninitialised (jmax (b->allocatedNumChars, numChars)));
  9170. copyChars (newText, text, b->allocatedNumChars);
  9171. release (b);
  9172. return newText;
  9173. }
  9174. static size_t getAllocatedNumChars (const CharPointerType& text) throw()
  9175. {
  9176. return bufferFromText (text)->allocatedNumChars;
  9177. }
  9178. static void copyChars (CharPointerType dest, const CharPointerType& src, const size_t numChars) throw()
  9179. {
  9180. jassert (src.getAddress() != 0 && dest.getAddress() != 0);
  9181. memcpy (dest.getAddress(), src.getAddress(), numChars * sizeof (juce_wchar));
  9182. CharPointerType (dest + (int) numChars).writeNull();
  9183. }
  9184. Atomic<int> refCount;
  9185. size_t allocatedNumChars;
  9186. juce_wchar text[1];
  9187. static StringHolder empty;
  9188. private:
  9189. static inline StringHolder* bufferFromText (const CharPointerType& text) throw()
  9190. {
  9191. // (Can't use offsetof() here because of warnings about this not being a POD)
  9192. return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress())
  9193. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9194. }
  9195. };
  9196. StringHolder StringHolder::empty;
  9197. const String String::empty;
  9198. void String::appendFixedLength (const juce_wchar* const newText, const int numExtraChars)
  9199. {
  9200. if (numExtraChars > 0)
  9201. {
  9202. const int oldLen = length();
  9203. const int newTotalLen = oldLen + numExtraChars;
  9204. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9205. StringHolder::copyChars (text + oldLen, CharPointer_UTF32 (newText), numExtraChars);
  9206. }
  9207. }
  9208. void String::preallocateStorage (const size_t numChars)
  9209. {
  9210. text = StringHolder::makeUniqueWithSize (text, numChars);
  9211. }
  9212. String::String() throw()
  9213. : text (StringHolder::getEmpty())
  9214. {
  9215. }
  9216. String::~String() throw()
  9217. {
  9218. StringHolder::release (text);
  9219. }
  9220. String::String (const String& other) throw()
  9221. : text (other.text)
  9222. {
  9223. StringHolder::retain (text);
  9224. }
  9225. void String::swapWith (String& other) throw()
  9226. {
  9227. swapVariables (text, other.text);
  9228. }
  9229. String& String::operator= (const String& other) throw()
  9230. {
  9231. StringHolder::retain (other.text);
  9232. StringHolder::release (text.atomicSwap (other.text));
  9233. return *this;
  9234. }
  9235. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9236. String::String (const Preallocation& preallocationSize)
  9237. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9238. {
  9239. }
  9240. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9241. : text (0)
  9242. {
  9243. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9244. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9245. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9246. }
  9247. String::String (const char* const t)
  9248. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t)))
  9249. {
  9250. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9251. that contains values greater than 127. These can NOT be correctly converted to unicode
  9252. because there's no way for the String class to know what encoding was used to
  9253. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9254. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9255. string to the String class - so for example if your source data is actually UTF-8,
  9256. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9257. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9258. you use UTF-8 with escape characters in your source code to represent extended characters,
  9259. because there's no other way to represent these strings in a way that isn't dependent on
  9260. the compiler, source code editor and platform.
  9261. */
  9262. jassert (CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  9263. }
  9264. String::String (const char* const t, const size_t maxChars)
  9265. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars))
  9266. {
  9267. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9268. that contains values greater than 127. These can NOT be correctly converted to unicode
  9269. because there's no way for the String class to know what encoding was used to
  9270. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9271. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9272. string to the String class - so for example if your source data is actually UTF-8,
  9273. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9274. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9275. you use UTF-8 with escape characters in your source code to represent extended characters,
  9276. because there's no other way to represent these strings in a way that isn't dependent on
  9277. the compiler, source code editor and platform.
  9278. */
  9279. jassert (CharPointer_ASCII::isValidString (t, (int) maxChars));
  9280. }
  9281. String::String (const juce_wchar* const t)
  9282. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t)))
  9283. {
  9284. }
  9285. String::String (const juce_wchar* const t, const size_t maxChars)
  9286. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t), maxChars))
  9287. {
  9288. }
  9289. String::String (const CharPointer_UTF8& t)
  9290. : text (StringHolder::createFromCharPointer (t))
  9291. {
  9292. }
  9293. String::String (const CharPointer_UTF16& t)
  9294. : text (StringHolder::createFromCharPointer (t))
  9295. {
  9296. }
  9297. String::String (const CharPointer_UTF32& t)
  9298. : text (StringHolder::createFromCharPointer (t))
  9299. {
  9300. }
  9301. String::String (const CharPointer_UTF32& t, const size_t maxChars)
  9302. : text (StringHolder::createFromCharPointer (t, maxChars))
  9303. {
  9304. }
  9305. String::String (const CharPointer_ASCII& t)
  9306. : text (StringHolder::createFromCharPointer (t))
  9307. {
  9308. }
  9309. #if JUCE_WINDOWS
  9310. String::String (const wchar_t* const t)
  9311. : text (StringHolder::createFromCharPointer (CharPointer_UTF16 (t)))
  9312. {
  9313. }
  9314. String::String (const wchar_t* const t, size_t maxChars)
  9315. : text (StringHolder::createFromCharPointer (CharPointer_UTF16 (t), maxChars))
  9316. {
  9317. }
  9318. #endif
  9319. const String String::charToString (const juce_wchar character)
  9320. {
  9321. String result (Preallocation (1));
  9322. result.text[0] = character;
  9323. result.text[1] = 0;
  9324. return result;
  9325. }
  9326. namespace NumberToStringConverters
  9327. {
  9328. // pass in a pointer to the END of a buffer..
  9329. juce_wchar* numberToString (juce_wchar* t, const int64 n) throw()
  9330. {
  9331. *--t = 0;
  9332. int64 v = (n >= 0) ? n : -n;
  9333. do
  9334. {
  9335. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9336. v /= 10;
  9337. } while (v > 0);
  9338. if (n < 0)
  9339. *--t = '-';
  9340. return t;
  9341. }
  9342. juce_wchar* numberToString (juce_wchar* t, uint64 v) throw()
  9343. {
  9344. *--t = 0;
  9345. do
  9346. {
  9347. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9348. v /= 10;
  9349. } while (v > 0);
  9350. return t;
  9351. }
  9352. juce_wchar* numberToString (juce_wchar* t, const int n) throw()
  9353. {
  9354. if (n == (int) 0x80000000) // (would cause an overflow)
  9355. return numberToString (t, (int64) n);
  9356. *--t = 0;
  9357. int v = abs (n);
  9358. do
  9359. {
  9360. *--t = (juce_wchar) ('0' + (v % 10));
  9361. v /= 10;
  9362. } while (v > 0);
  9363. if (n < 0)
  9364. *--t = '-';
  9365. return t;
  9366. }
  9367. juce_wchar* numberToString (juce_wchar* t, unsigned int v) throw()
  9368. {
  9369. *--t = 0;
  9370. do
  9371. {
  9372. *--t = (juce_wchar) ('0' + (v % 10));
  9373. v /= 10;
  9374. } while (v > 0);
  9375. return t;
  9376. }
  9377. juce_wchar getDecimalPoint()
  9378. {
  9379. #if JUCE_VC7_OR_EARLIER
  9380. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9381. #else
  9382. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9383. #endif
  9384. return dp;
  9385. }
  9386. char* doubleToString (char* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9387. {
  9388. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9389. {
  9390. char* const end = buffer + numChars;
  9391. char* t = end;
  9392. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9393. *--t = (char) 0;
  9394. while (numDecPlaces >= 0 || v > 0)
  9395. {
  9396. if (numDecPlaces == 0)
  9397. *--t = (char) getDecimalPoint();
  9398. *--t = (char) ('0' + (v % 10));
  9399. v /= 10;
  9400. --numDecPlaces;
  9401. }
  9402. if (n < 0)
  9403. *--t = '-';
  9404. len = end - t - 1;
  9405. return t;
  9406. }
  9407. else
  9408. {
  9409. len = sprintf (buffer, "%.9g", n);
  9410. return buffer;
  9411. }
  9412. }
  9413. template <typename IntegerType>
  9414. const String::CharPointerType createFromInteger (const IntegerType number)
  9415. {
  9416. juce_wchar buffer [32];
  9417. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9418. juce_wchar* const start = numberToString (end, number);
  9419. return StringHolder::createFromFixedLength (start, end - start - 1);
  9420. }
  9421. const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  9422. {
  9423. char buffer [48];
  9424. size_t len;
  9425. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9426. return StringHolder::createFromFixedLength (start, len);
  9427. }
  9428. }
  9429. String::String (const int number)
  9430. : text (NumberToStringConverters::createFromInteger (number))
  9431. {
  9432. }
  9433. String::String (const unsigned int number)
  9434. : text (NumberToStringConverters::createFromInteger (number))
  9435. {
  9436. }
  9437. String::String (const short number)
  9438. : text (NumberToStringConverters::createFromInteger ((int) number))
  9439. {
  9440. }
  9441. String::String (const unsigned short number)
  9442. : text (NumberToStringConverters::createFromInteger ((unsigned int) number))
  9443. {
  9444. }
  9445. String::String (const int64 number)
  9446. : text (NumberToStringConverters::createFromInteger (number))
  9447. {
  9448. }
  9449. String::String (const uint64 number)
  9450. : text (NumberToStringConverters::createFromInteger (number))
  9451. {
  9452. }
  9453. String::String (const float number, const int numberOfDecimalPlaces)
  9454. : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces))
  9455. {
  9456. }
  9457. String::String (const double number, const int numberOfDecimalPlaces)
  9458. : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces))
  9459. {
  9460. }
  9461. int String::length() const throw()
  9462. {
  9463. return (int) text.length();
  9464. }
  9465. const juce_wchar String::operator[] (int index) const throw()
  9466. {
  9467. jassert (index == 0 || isPositiveAndNotGreaterThan (index, length()));
  9468. return text [index];
  9469. }
  9470. int String::hashCode() const throw()
  9471. {
  9472. const juce_wchar* t = text;
  9473. int result = 0;
  9474. while (*t != (juce_wchar) 0)
  9475. result = 31 * result + *t++;
  9476. return result;
  9477. }
  9478. int64 String::hashCode64() const throw()
  9479. {
  9480. const juce_wchar* t = text;
  9481. int64 result = 0;
  9482. while (*t != (juce_wchar) 0)
  9483. result = 101 * result + *t++;
  9484. return result;
  9485. }
  9486. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9487. {
  9488. return string1.compare (string2) == 0;
  9489. }
  9490. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9491. {
  9492. return string1.compare (string2) == 0;
  9493. }
  9494. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9495. {
  9496. return string1.compare (string2) == 0;
  9497. }
  9498. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw()
  9499. {
  9500. return string1.getCharPointer().compare (string2) == 0;
  9501. }
  9502. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw()
  9503. {
  9504. return string1.getCharPointer().compare (string2) == 0;
  9505. }
  9506. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw()
  9507. {
  9508. return string1.getCharPointer().compare (string2) == 0;
  9509. }
  9510. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9511. {
  9512. return string1.compare (string2) != 0;
  9513. }
  9514. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9515. {
  9516. return string1.compare (string2) != 0;
  9517. }
  9518. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9519. {
  9520. return string1.compare (string2) != 0;
  9521. }
  9522. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw()
  9523. {
  9524. return string1.getCharPointer().compare (string2) != 0;
  9525. }
  9526. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw()
  9527. {
  9528. return string1.getCharPointer().compare (string2) != 0;
  9529. }
  9530. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw()
  9531. {
  9532. return string1.getCharPointer().compare (string2) != 0;
  9533. }
  9534. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9535. {
  9536. return string1.compare (string2) > 0;
  9537. }
  9538. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9539. {
  9540. return string1.compare (string2) < 0;
  9541. }
  9542. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9543. {
  9544. return string1.compare (string2) >= 0;
  9545. }
  9546. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9547. {
  9548. return string1.compare (string2) <= 0;
  9549. }
  9550. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9551. {
  9552. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF32 (t)) == 0
  9553. : isEmpty();
  9554. }
  9555. bool String::equalsIgnoreCase (const char* t) const throw()
  9556. {
  9557. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  9558. : isEmpty();
  9559. }
  9560. bool String::equalsIgnoreCase (const String& other) const throw()
  9561. {
  9562. return text == other.text
  9563. || text.compareIgnoreCase (other.text) == 0;
  9564. }
  9565. int String::compare (const String& other) const throw()
  9566. {
  9567. return (text == other.text) ? 0 : text.compare (other.text);
  9568. }
  9569. int String::compare (const char* other) const throw()
  9570. {
  9571. return text.compare (CharPointer_UTF8 (other));
  9572. }
  9573. int String::compare (const juce_wchar* other) const throw()
  9574. {
  9575. return text.compare (CharPointer_UTF32 (other));
  9576. }
  9577. int String::compareIgnoreCase (const String& other) const throw()
  9578. {
  9579. return (text == other.text) ? 0 : text.compareIgnoreCase (other.text);
  9580. }
  9581. int String::compareLexicographically (const String& other) const throw()
  9582. {
  9583. CharPointerType s1 (text);
  9584. while (! (s1.isEmpty() || s1.isLetterOrDigit()))
  9585. ++s1;
  9586. CharPointerType s2 (other.text);
  9587. while (! (s2.isEmpty() || s2.isLetterOrDigit()))
  9588. ++s2;
  9589. return s1.compareIgnoreCase (s2);
  9590. }
  9591. void String::append (const String& textToAppend, size_t maxCharsToTake)
  9592. {
  9593. appendCharPointer (textToAppend.text, maxCharsToTake);
  9594. }
  9595. String& String::operator+= (const juce_wchar* const t)
  9596. {
  9597. appendCharPointer (CharPointer_UTF32 (t));
  9598. return *this;
  9599. }
  9600. String& String::operator+= (const String& other)
  9601. {
  9602. if (isEmpty())
  9603. return operator= (other);
  9604. appendCharPointer (other.text);
  9605. return *this;
  9606. }
  9607. String& String::operator+= (const char ch)
  9608. {
  9609. return operator+= ((juce_wchar) ch);
  9610. }
  9611. String& String::operator+= (const juce_wchar ch)
  9612. {
  9613. const juce_wchar asString[] = { ch, 0 };
  9614. return operator+= (static_cast <const juce_wchar*> (asString));
  9615. }
  9616. #if JUCE_WINDOWS
  9617. String& String::operator+= (const wchar_t ch)
  9618. {
  9619. return operator+= ((juce_wchar) ch);
  9620. }
  9621. String& String::operator+= (const wchar_t* t)
  9622. {
  9623. return operator+= (String (t));
  9624. }
  9625. #endif
  9626. String& String::operator+= (const int number)
  9627. {
  9628. juce_wchar buffer [16];
  9629. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9630. juce_wchar* const start = NumberToStringConverters::numberToString (end, number);
  9631. appendFixedLength (start, (int) (end - start));
  9632. return *this;
  9633. }
  9634. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9635. {
  9636. String s (string1);
  9637. return s += string2;
  9638. }
  9639. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9640. {
  9641. String s (string1);
  9642. return s += string2;
  9643. }
  9644. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9645. {
  9646. return String::charToString (string1) + string2;
  9647. }
  9648. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9649. {
  9650. return String::charToString (string1) + string2;
  9651. }
  9652. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9653. {
  9654. return string1 += string2;
  9655. }
  9656. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9657. {
  9658. return string1 += string2;
  9659. }
  9660. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9661. {
  9662. return string1 += string2;
  9663. }
  9664. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9665. {
  9666. return string1 += string2;
  9667. }
  9668. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9669. {
  9670. return string1 += string2;
  9671. }
  9672. #if JUCE_WINDOWS
  9673. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t string2)
  9674. {
  9675. return string1 += string2;
  9676. }
  9677. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2)
  9678. {
  9679. string1.appendCharPointer (CharPointer_UTF16 (string2));
  9680. return string1;
  9681. }
  9682. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2)
  9683. {
  9684. String s (string1);
  9685. return s += string2;
  9686. }
  9687. #endif
  9688. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9689. {
  9690. return string1 += characterToAppend;
  9691. }
  9692. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9693. {
  9694. return string1 += characterToAppend;
  9695. }
  9696. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9697. {
  9698. return string1 += string2;
  9699. }
  9700. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9701. {
  9702. return string1 += string2;
  9703. }
  9704. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9705. {
  9706. return string1 += string2;
  9707. }
  9708. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9709. {
  9710. return string1 += (int) number;
  9711. }
  9712. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9713. {
  9714. return string1 += number;
  9715. }
  9716. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9717. {
  9718. return string1 += (int) number;
  9719. }
  9720. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9721. {
  9722. return string1 += String (number);
  9723. }
  9724. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9725. {
  9726. return string1 += String (number);
  9727. }
  9728. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9729. {
  9730. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9731. // if lots of large, persistent strings were to be written to streams).
  9732. const int numBytes = text.getNumBytesAsUTF8();
  9733. HeapBlock<char> temp (numBytes + 1);
  9734. text.copyToUTF8 (temp, numBytes + 1);
  9735. stream.write (temp, numBytes);
  9736. return stream;
  9737. }
  9738. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9739. {
  9740. return string1 += NewLine::getDefault();
  9741. }
  9742. int String::indexOfChar (const juce_wchar character) const throw()
  9743. {
  9744. const juce_wchar* t = text;
  9745. for (;;)
  9746. {
  9747. if (*t == character)
  9748. return (int) (t - text);
  9749. if (*t++ == 0)
  9750. return -1;
  9751. }
  9752. }
  9753. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9754. {
  9755. for (int i = length(); --i >= 0;)
  9756. if (text[i] == character)
  9757. return i;
  9758. return -1;
  9759. }
  9760. int String::indexOf (const String& t) const throw()
  9761. {
  9762. return t.isEmpty() ? 0 : text.indexOf (t.text);
  9763. }
  9764. int String::indexOfChar (const int startIndex,
  9765. const juce_wchar character) const throw()
  9766. {
  9767. if (startIndex > 0 && startIndex >= length())
  9768. return -1;
  9769. const juce_wchar* t = text + jmax (0, startIndex);
  9770. for (;;)
  9771. {
  9772. if (*t == character)
  9773. return (int) (t - text);
  9774. if (*t == 0)
  9775. return -1;
  9776. ++t;
  9777. }
  9778. }
  9779. int String::indexOfAnyOf (const String& charactersToLookFor,
  9780. const int startIndex,
  9781. const bool ignoreCase) const throw()
  9782. {
  9783. if (startIndex > 0 && startIndex >= length())
  9784. return -1;
  9785. CharPointerType t (text);
  9786. int i = jmax (0, startIndex);
  9787. t += i;
  9788. while (! t.isEmpty())
  9789. {
  9790. if (charactersToLookFor.text.indexOf (*t, ignoreCase) >= 0)
  9791. return i;
  9792. ++i;
  9793. ++t;
  9794. }
  9795. return -1;
  9796. }
  9797. int String::indexOf (const int startIndex, const String& other) const throw()
  9798. {
  9799. if (startIndex > 0 && startIndex >= length())
  9800. return -1;
  9801. int i = CharPointerType (text + jmax (0, startIndex)).indexOf (other.text);
  9802. return i >= 0 ? i + startIndex : -1;
  9803. }
  9804. int String::indexOfIgnoreCase (const String& other) const throw()
  9805. {
  9806. if (other.isEmpty())
  9807. return 0;
  9808. const int len = other.length();
  9809. const int end = length() - len;
  9810. for (int i = 0; i <= end; ++i)
  9811. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9812. return i;
  9813. return -1;
  9814. }
  9815. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9816. {
  9817. if (other.isNotEmpty())
  9818. {
  9819. const int len = other.length();
  9820. const int end = length() - len;
  9821. for (int i = jmax (0, startIndex); i <= end; ++i)
  9822. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9823. return i;
  9824. }
  9825. return -1;
  9826. }
  9827. int String::lastIndexOf (const String& other) const throw()
  9828. {
  9829. if (other.isNotEmpty())
  9830. {
  9831. const int len = other.length();
  9832. int i = length() - len;
  9833. if (i >= 0)
  9834. {
  9835. CharPointerType n (text + i);
  9836. while (i >= 0)
  9837. {
  9838. if (n.compareUpTo (other.text, len) == 0)
  9839. return i;
  9840. --n;
  9841. --i;
  9842. }
  9843. }
  9844. }
  9845. return -1;
  9846. }
  9847. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9848. {
  9849. if (other.isNotEmpty())
  9850. {
  9851. const int len = other.length();
  9852. int i = length() - len;
  9853. if (i >= 0)
  9854. {
  9855. CharPointerType n (text + i);
  9856. while (i >= 0)
  9857. {
  9858. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  9859. return i;
  9860. --n;
  9861. --i;
  9862. }
  9863. }
  9864. }
  9865. return -1;
  9866. }
  9867. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9868. {
  9869. for (int i = length(); --i >= 0;)
  9870. if (charactersToLookFor.text.indexOf (text[i], ignoreCase) >= 0)
  9871. return i;
  9872. return -1;
  9873. }
  9874. bool String::contains (const String& other) const throw()
  9875. {
  9876. return indexOf (other) >= 0;
  9877. }
  9878. bool String::containsChar (const juce_wchar character) const throw()
  9879. {
  9880. const juce_wchar* t = text;
  9881. for (;;)
  9882. {
  9883. if (*t == 0)
  9884. return false;
  9885. if (*t == character)
  9886. return true;
  9887. ++t;
  9888. }
  9889. }
  9890. bool String::containsIgnoreCase (const String& t) const throw()
  9891. {
  9892. return indexOfIgnoreCase (t) >= 0;
  9893. }
  9894. int String::indexOfWholeWord (const String& word) const throw()
  9895. {
  9896. if (word.isNotEmpty())
  9897. {
  9898. CharPointerType t (text);
  9899. const int wordLen = word.length();
  9900. const int end = (int) t.length() - wordLen;
  9901. for (int i = 0; i <= end; ++i)
  9902. {
  9903. if (t.compareUpTo (word.text, wordLen) == 0
  9904. && (i == 0 || ! (t - 1).isLetterOrDigit())
  9905. && ! (t + wordLen).isLetterOrDigit())
  9906. return i;
  9907. ++t;
  9908. }
  9909. }
  9910. return -1;
  9911. }
  9912. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9913. {
  9914. if (word.isNotEmpty())
  9915. {
  9916. CharPointerType t (text);
  9917. const int wordLen = word.length();
  9918. const int end = (int) t.length() - wordLen;
  9919. for (int i = 0; i <= end; ++i)
  9920. {
  9921. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  9922. && (i == 0 || ! (t + -1).isLetterOrDigit())
  9923. && ! (t + wordLen).isLetterOrDigit())
  9924. return i;
  9925. ++t;
  9926. }
  9927. }
  9928. return -1;
  9929. }
  9930. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9931. {
  9932. return indexOfWholeWord (wordToLookFor) >= 0;
  9933. }
  9934. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9935. {
  9936. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9937. }
  9938. namespace WildCardHelpers
  9939. {
  9940. int indexOfMatch (const String::CharPointerType& wildcard,
  9941. String::CharPointerType test,
  9942. const bool ignoreCase) throw()
  9943. {
  9944. int start = 0;
  9945. while (! test.isEmpty())
  9946. {
  9947. String::CharPointerType t (test);
  9948. String::CharPointerType w (wildcard);
  9949. for (;;)
  9950. {
  9951. const juce_wchar wc = *w;
  9952. const juce_wchar tc = *t;
  9953. if (wc == tc
  9954. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  9955. || (wc == '?' && tc != 0))
  9956. {
  9957. if (wc == 0)
  9958. return start;
  9959. ++t;
  9960. ++w;
  9961. }
  9962. else
  9963. {
  9964. if (wc == '*' && (w[1] == 0 || indexOfMatch (w + 1, t, ignoreCase) >= 0))
  9965. return start;
  9966. break;
  9967. }
  9968. }
  9969. ++start;
  9970. ++test;
  9971. }
  9972. return -1;
  9973. }
  9974. }
  9975. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9976. {
  9977. CharPointerType w (wildcard.text);
  9978. CharPointerType t (text);
  9979. for (;;)
  9980. {
  9981. const juce_wchar wc = *w;
  9982. const juce_wchar tc = *t;
  9983. if (wc == tc
  9984. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  9985. || (wc == '?' && tc != 0))
  9986. {
  9987. if (wc == 0)
  9988. return true;
  9989. ++w;
  9990. ++t;
  9991. }
  9992. else
  9993. {
  9994. return wc == '*' && (w[1] == 0 || WildCardHelpers::indexOfMatch (w + 1, t, ignoreCase) >= 0);
  9995. }
  9996. }
  9997. }
  9998. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9999. {
  10000. if (numberOfTimesToRepeat <= 0)
  10001. return String::empty;
  10002. const int len = stringToRepeat.length();
  10003. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10004. CharPointerType n (result.text);
  10005. while (--numberOfTimesToRepeat >= 0)
  10006. {
  10007. StringHolder::copyChars (n, stringToRepeat.text, len);
  10008. n += len;
  10009. }
  10010. return result;
  10011. }
  10012. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10013. {
  10014. jassert (padCharacter != 0);
  10015. const int len = length();
  10016. if (len >= minimumLength || padCharacter == 0)
  10017. return *this;
  10018. String result (Preallocation (minimumLength + 1));
  10019. CharPointerType n (result.text);
  10020. minimumLength -= len;
  10021. while (--minimumLength >= 0)
  10022. n.write (padCharacter);
  10023. StringHolder::copyChars (n, text, len);
  10024. return result;
  10025. }
  10026. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10027. {
  10028. jassert (padCharacter != 0);
  10029. const int len = length();
  10030. if (len >= minimumLength || padCharacter == 0)
  10031. return *this;
  10032. String result (*this, (size_t) minimumLength);
  10033. CharPointerType n (result.text + len);
  10034. minimumLength -= len;
  10035. while (--minimumLength >= 0)
  10036. n.write (padCharacter);
  10037. n.writeNull();
  10038. return result;
  10039. }
  10040. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10041. {
  10042. if (index < 0)
  10043. {
  10044. // a negative index to replace from?
  10045. jassertfalse;
  10046. index = 0;
  10047. }
  10048. if (numCharsToReplace < 0)
  10049. {
  10050. // replacing a negative number of characters?
  10051. numCharsToReplace = 0;
  10052. jassertfalse;
  10053. }
  10054. const int len = length();
  10055. if (index + numCharsToReplace > len)
  10056. {
  10057. if (index > len)
  10058. {
  10059. // replacing beyond the end of the string?
  10060. index = len;
  10061. jassertfalse;
  10062. }
  10063. numCharsToReplace = len - index;
  10064. }
  10065. const int newStringLen = stringToInsert.length();
  10066. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10067. if (newTotalLen <= 0)
  10068. return String::empty;
  10069. String result (Preallocation ((size_t) newTotalLen));
  10070. StringHolder::copyChars (result.text, text, index);
  10071. if (newStringLen > 0)
  10072. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10073. const int endStringLen = newTotalLen - (index + newStringLen);
  10074. if (endStringLen > 0)
  10075. StringHolder::copyChars (result.text + (index + newStringLen),
  10076. text + (index + numCharsToReplace),
  10077. endStringLen);
  10078. return result;
  10079. }
  10080. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10081. {
  10082. const int stringToReplaceLen = stringToReplace.length();
  10083. const int stringToInsertLen = stringToInsert.length();
  10084. int i = 0;
  10085. String result (*this);
  10086. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10087. : result.indexOf (i, stringToReplace))) >= 0)
  10088. {
  10089. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10090. i += stringToInsertLen;
  10091. }
  10092. return result;
  10093. }
  10094. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10095. {
  10096. const int index = indexOfChar (charToReplace);
  10097. if (index < 0)
  10098. return *this;
  10099. String result (*this, size_t());
  10100. CharPointerType t (result.text + index);
  10101. while (! t.isEmpty())
  10102. {
  10103. if (*t == charToReplace)
  10104. t.replaceChar (charToInsert);
  10105. ++t;
  10106. }
  10107. return result;
  10108. }
  10109. const String String::replaceCharacters (const String& charactersToReplace,
  10110. const String& charactersToInsertInstead) const
  10111. {
  10112. String result (*this, size_t());
  10113. CharPointerType t (result.text);
  10114. const int len2 = charactersToInsertInstead.length();
  10115. // the two strings passed in are supposed to be the same length!
  10116. jassert (len2 == charactersToReplace.length());
  10117. while (! t.isEmpty())
  10118. {
  10119. const int index = charactersToReplace.indexOfChar (*t);
  10120. if (isPositiveAndBelow (index, len2))
  10121. t.replaceChar (charactersToInsertInstead [index]);
  10122. ++t;
  10123. }
  10124. return result;
  10125. }
  10126. bool String::startsWith (const String& other) const throw()
  10127. {
  10128. return text.compareUpTo (other.text, other.length()) == 0;
  10129. }
  10130. bool String::startsWithIgnoreCase (const String& other) const throw()
  10131. {
  10132. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  10133. }
  10134. bool String::startsWithChar (const juce_wchar character) const throw()
  10135. {
  10136. jassert (character != 0); // strings can't contain a null character!
  10137. return text[0] == character;
  10138. }
  10139. bool String::endsWithChar (const juce_wchar character) const throw()
  10140. {
  10141. jassert (character != 0); // strings can't contain a null character!
  10142. return text[0] != 0
  10143. && text [length() - 1] == character;
  10144. }
  10145. bool String::endsWith (const String& other) const throw()
  10146. {
  10147. const int thisLen = length();
  10148. const int otherLen = other.length();
  10149. return thisLen >= otherLen
  10150. && CharPointerType (text + thisLen - otherLen).compare (other.text) == 0;
  10151. }
  10152. bool String::endsWithIgnoreCase (const String& other) const throw()
  10153. {
  10154. const int thisLen = length();
  10155. const int otherLen = other.length();
  10156. return thisLen >= otherLen
  10157. && CharPointerType (text + thisLen - otherLen).compareIgnoreCase (other.text) == 0;
  10158. }
  10159. const String String::toUpperCase() const
  10160. {
  10161. String result (Preallocation (this->length()));
  10162. CharPointerType dest (result.text);
  10163. CharPointerType src (text);
  10164. for (;;)
  10165. {
  10166. const juce_wchar c = src.toUpperCase();
  10167. dest.write (c);
  10168. if (c == 0)
  10169. break;
  10170. ++src;
  10171. }
  10172. return result;
  10173. }
  10174. const String String::toLowerCase() const
  10175. {
  10176. String result (Preallocation (this->length()));
  10177. CharPointerType dest (result.text);
  10178. CharPointerType src (text);
  10179. for (;;)
  10180. {
  10181. const juce_wchar c = src.toLowerCase();
  10182. dest.write (c);
  10183. if (c == 0)
  10184. break;
  10185. ++src;
  10186. }
  10187. return result;
  10188. }
  10189. juce_wchar String::getLastCharacter() const throw()
  10190. {
  10191. return isEmpty() ? juce_wchar() : text [length() - 1];
  10192. }
  10193. const String String::substring (int start, int end) const
  10194. {
  10195. if (start < 0)
  10196. start = 0;
  10197. else if (end <= start)
  10198. return empty;
  10199. int len = 0;
  10200. while (len <= end && text [len] != 0)
  10201. ++len;
  10202. if (end >= len)
  10203. {
  10204. if (start == 0)
  10205. return *this;
  10206. end = len;
  10207. }
  10208. return String (text + start, end - start);
  10209. }
  10210. const String String::substring (const int start) const
  10211. {
  10212. if (start <= 0)
  10213. return *this;
  10214. const int len = length();
  10215. if (start >= len)
  10216. return empty;
  10217. return String (text + start, len - start);
  10218. }
  10219. const String String::dropLastCharacters (const int numberToDrop) const
  10220. {
  10221. return String (text, jmax (0, length() - numberToDrop));
  10222. }
  10223. const String String::getLastCharacters (const int numCharacters) const
  10224. {
  10225. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10226. }
  10227. const String String::fromFirstOccurrenceOf (const String& sub,
  10228. const bool includeSubString,
  10229. const bool ignoreCase) const
  10230. {
  10231. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10232. : indexOf (sub);
  10233. if (i < 0)
  10234. return empty;
  10235. return substring (includeSubString ? i : i + sub.length());
  10236. }
  10237. const String String::fromLastOccurrenceOf (const String& sub,
  10238. const bool includeSubString,
  10239. const bool ignoreCase) const
  10240. {
  10241. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10242. : lastIndexOf (sub);
  10243. if (i < 0)
  10244. return *this;
  10245. return substring (includeSubString ? i : i + sub.length());
  10246. }
  10247. const String String::upToFirstOccurrenceOf (const String& sub,
  10248. const bool includeSubString,
  10249. const bool ignoreCase) const
  10250. {
  10251. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10252. : indexOf (sub);
  10253. if (i < 0)
  10254. return *this;
  10255. return substring (0, includeSubString ? i + sub.length() : i);
  10256. }
  10257. const String String::upToLastOccurrenceOf (const String& sub,
  10258. const bool includeSubString,
  10259. const bool ignoreCase) const
  10260. {
  10261. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10262. : lastIndexOf (sub);
  10263. if (i < 0)
  10264. return *this;
  10265. return substring (0, includeSubString ? i + sub.length() : i);
  10266. }
  10267. bool String::isQuotedString() const
  10268. {
  10269. const String trimmed (trimStart());
  10270. return trimmed[0] == '"'
  10271. || trimmed[0] == '\'';
  10272. }
  10273. const String String::unquoted() const
  10274. {
  10275. const int len = length();
  10276. if (len == 0)
  10277. return empty;
  10278. const juce_wchar lastChar = text [len - 1];
  10279. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  10280. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  10281. return substring (dropAtStart, len - dropAtEnd);
  10282. }
  10283. const String String::quoted (const juce_wchar quoteCharacter) const
  10284. {
  10285. if (isEmpty())
  10286. return charToString (quoteCharacter) + quoteCharacter;
  10287. String t (*this);
  10288. if (! t.startsWithChar (quoteCharacter))
  10289. t = charToString (quoteCharacter) + t;
  10290. if (! t.endsWithChar (quoteCharacter))
  10291. t += quoteCharacter;
  10292. return t;
  10293. }
  10294. const String String::trim() const
  10295. {
  10296. if (isEmpty())
  10297. return empty;
  10298. int start = 0;
  10299. while ((text + start).isWhitespace())
  10300. ++start;
  10301. const int len = length();
  10302. int end = len - 1;
  10303. while ((end >= start) && (text + end).isWhitespace())
  10304. --end;
  10305. ++end;
  10306. if (end <= start)
  10307. return empty;
  10308. else if (start > 0 || end < len)
  10309. return String (text + start, end - start);
  10310. return *this;
  10311. }
  10312. const String String::trimStart() const
  10313. {
  10314. if (isEmpty())
  10315. return empty;
  10316. CharPointerType t (text.findEndOfWhitespace());
  10317. if (t == text)
  10318. return *this;
  10319. return String (t);
  10320. }
  10321. const String String::trimEnd() const
  10322. {
  10323. if (isEmpty())
  10324. return empty;
  10325. CharPointerType endT (text);
  10326. endT = endT.findTerminatingNull() - 1;
  10327. while ((endT.getAddress() >= text) && endT.isWhitespace())
  10328. --endT;
  10329. return String (text, 1 + (int) (endT.getAddress() - text));
  10330. }
  10331. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10332. {
  10333. CharPointerType t (text);
  10334. while (charactersToTrim.containsChar (*t))
  10335. ++t;
  10336. return t == text ? *this : String (t);
  10337. }
  10338. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10339. {
  10340. if (isEmpty())
  10341. return empty;
  10342. const int len = length();
  10343. const juce_wchar* endT = text + (len - 1);
  10344. int numToRemove = 0;
  10345. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10346. {
  10347. ++numToRemove;
  10348. --endT;
  10349. }
  10350. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10351. }
  10352. const String String::retainCharacters (const String& charactersToRetain) const
  10353. {
  10354. if (isEmpty())
  10355. return empty;
  10356. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10357. CharPointerType dst (result.text);
  10358. CharPointerType src (text);
  10359. for (;;)
  10360. {
  10361. const juce_wchar c = src.getAndAdvance();
  10362. if (c == 0)
  10363. break;
  10364. if (charactersToRetain.containsChar (c))
  10365. dst.write (c);
  10366. }
  10367. dst.writeNull();
  10368. return result;
  10369. }
  10370. const String String::removeCharacters (const String& charactersToRemove) const
  10371. {
  10372. if (isEmpty())
  10373. return empty;
  10374. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10375. CharPointerType dst (result.text);
  10376. CharPointerType src (text);
  10377. for (;;)
  10378. {
  10379. const juce_wchar c = src.getAndAdvance();
  10380. if (c == 0)
  10381. break;
  10382. if (! charactersToRemove.containsChar (c))
  10383. dst.write (c);
  10384. }
  10385. dst.writeNull();
  10386. return result;
  10387. }
  10388. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10389. {
  10390. int i = 0;
  10391. for (;;)
  10392. {
  10393. if (! permittedCharacters.containsChar (text[i]))
  10394. break;
  10395. ++i;
  10396. }
  10397. return substring (0, i);
  10398. }
  10399. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10400. {
  10401. const juce_wchar* const t = text;
  10402. int i = 0;
  10403. while (t[i] != 0)
  10404. {
  10405. if (charactersToStopAt.containsChar (t[i]))
  10406. return String (text, i);
  10407. ++i;
  10408. }
  10409. return empty;
  10410. }
  10411. bool String::containsOnly (const String& chars) const throw()
  10412. {
  10413. CharPointerType t (text);
  10414. while (! t.isEmpty())
  10415. if (! chars.containsChar (t.getAndAdvance()))
  10416. return false;
  10417. return true;
  10418. }
  10419. bool String::containsAnyOf (const String& chars) const throw()
  10420. {
  10421. const juce_wchar* t = text;
  10422. while (*t != 0)
  10423. if (chars.containsChar (*t++))
  10424. return true;
  10425. return false;
  10426. }
  10427. bool String::containsNonWhitespaceChars() const throw()
  10428. {
  10429. CharPointerType t (text);
  10430. while (! t.isEmpty())
  10431. {
  10432. if (! t.isWhitespace())
  10433. return true;
  10434. ++t;
  10435. }
  10436. return false;
  10437. }
  10438. const String String::formatted (const juce_wchar* const pf, ... )
  10439. {
  10440. jassert (pf != 0);
  10441. va_list args;
  10442. va_start (args, pf);
  10443. size_t bufferSize = 256;
  10444. String result (Preallocation ((size_t) bufferSize));
  10445. result.text[0] = 0;
  10446. for (;;)
  10447. {
  10448. #if JUCE_LINUX && JUCE_64BIT
  10449. va_list tempArgs;
  10450. va_copy (tempArgs, args);
  10451. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, tempArgs);
  10452. va_end (tempArgs);
  10453. #elif JUCE_WINDOWS
  10454. HeapBlock <wchar_t> temp (bufferSize);
  10455. const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, String (pf).toUTF16(), args);
  10456. if (num > 0)
  10457. CharPointerType (result.text).writeAll (CharPointer_UTF16 (temp.getData()));
  10458. #elif JUCE_ANDROID
  10459. HeapBlock <char> temp (bufferSize);
  10460. const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, String (pf).toUTF8(), args);
  10461. if (num > 0)
  10462. CharPointerType (result.text).writeAll (CharPointer_UTF8 (temp.getData()));
  10463. #else
  10464. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, args);
  10465. #endif
  10466. if (num > 0)
  10467. return result;
  10468. bufferSize += 256;
  10469. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10470. break; // returns -1 because of an error rather than because it needs more space.
  10471. result.preallocateStorage (bufferSize);
  10472. }
  10473. return empty;
  10474. }
  10475. int String::getIntValue() const throw()
  10476. {
  10477. return text.getIntValue32();
  10478. }
  10479. int String::getTrailingIntValue() const throw()
  10480. {
  10481. int n = 0;
  10482. int mult = 1;
  10483. CharPointerType t (text.findTerminatingNull());
  10484. while ((--t).getAddress() >= text)
  10485. {
  10486. if (! t.isDigit())
  10487. {
  10488. if (*t == '-')
  10489. n = -n;
  10490. break;
  10491. }
  10492. n += mult * (*t - '0');
  10493. mult *= 10;
  10494. }
  10495. return n;
  10496. }
  10497. int64 String::getLargeIntValue() const throw()
  10498. {
  10499. return text.getIntValue64();
  10500. }
  10501. float String::getFloatValue() const throw()
  10502. {
  10503. return (float) getDoubleValue();
  10504. }
  10505. double String::getDoubleValue() const throw()
  10506. {
  10507. return text.getDoubleValue();
  10508. }
  10509. static const char* const hexDigits = "0123456789abcdef";
  10510. const String String::toHexString (const int number)
  10511. {
  10512. juce_wchar buffer[32];
  10513. juce_wchar* const end = buffer + 32;
  10514. juce_wchar* t = end;
  10515. *--t = 0;
  10516. unsigned int v = (unsigned int) number;
  10517. do
  10518. {
  10519. *--t = (juce_wchar) hexDigits [v & 15];
  10520. v >>= 4;
  10521. } while (v != 0);
  10522. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10523. }
  10524. const String String::toHexString (const int64 number)
  10525. {
  10526. juce_wchar buffer[32];
  10527. juce_wchar* const end = buffer + 32;
  10528. juce_wchar* t = end;
  10529. *--t = 0;
  10530. uint64 v = (uint64) number;
  10531. do
  10532. {
  10533. *--t = (juce_wchar) hexDigits [(int) (v & 15)];
  10534. v >>= 4;
  10535. } while (v != 0);
  10536. return String (t, (int) (((char*) end) - (char*) t));
  10537. }
  10538. const String String::toHexString (const short number)
  10539. {
  10540. return toHexString ((int) (unsigned short) number);
  10541. }
  10542. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10543. {
  10544. if (size <= 0)
  10545. return empty;
  10546. int numChars = (size * 2) + 2;
  10547. if (groupSize > 0)
  10548. numChars += size / groupSize;
  10549. String s (Preallocation ((size_t) numChars));
  10550. CharPointerType dest (s.text);
  10551. for (int i = 0; i < size; ++i)
  10552. {
  10553. dest.write ((juce_wchar) hexDigits [(*data) >> 4]);
  10554. dest.write ((juce_wchar) hexDigits [(*data) & 0xf]);
  10555. ++data;
  10556. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10557. dest.write ((juce_wchar) ' ');
  10558. }
  10559. dest.writeNull();
  10560. return s;
  10561. }
  10562. int String::getHexValue32() const throw()
  10563. {
  10564. int result = 0;
  10565. CharPointerType t (text);
  10566. while (! t.isEmpty())
  10567. {
  10568. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10569. if (hexValue >= 0)
  10570. result = (result << 4) | hexValue;
  10571. }
  10572. return result;
  10573. }
  10574. int64 String::getHexValue64() const throw()
  10575. {
  10576. int64 result = 0;
  10577. CharPointerType t (text);
  10578. while (! t.isEmpty())
  10579. {
  10580. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10581. if (hexValue >= 0)
  10582. result = (result << 4) | hexValue;
  10583. }
  10584. return result;
  10585. }
  10586. const String String::createStringFromData (const void* const data_, const int size)
  10587. {
  10588. const uint8* const data = static_cast <const uint8*> (data_);
  10589. if (size <= 0 || data == 0)
  10590. {
  10591. return empty;
  10592. }
  10593. else if (size == 1)
  10594. {
  10595. return charToString ((char) data[0]);
  10596. }
  10597. else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2)
  10598. || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE1))
  10599. {
  10600. const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1);
  10601. const int numChars = size / 2 - 1;
  10602. String result;
  10603. result.preallocateStorage (numChars + 2);
  10604. const uint16* const src = (const uint16*) (data + 2);
  10605. CharPointerType dst (result.getCharPointer());
  10606. if (bigEndian)
  10607. {
  10608. for (int i = 0; i < numChars; ++i)
  10609. dst.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  10610. }
  10611. else
  10612. {
  10613. for (int i = 0; i < numChars; ++i)
  10614. dst.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  10615. }
  10616. dst.writeNull();
  10617. return result;
  10618. }
  10619. else
  10620. {
  10621. if (size >= 3
  10622. && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1
  10623. && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2
  10624. && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3)
  10625. return String::fromUTF8 ((const char*) data + 3, size - 3);
  10626. return String::fromUTF8 ((const char*) data, size);
  10627. }
  10628. }
  10629. void* String::createSpaceAtEndOfBuffer (const size_t numExtraBytes) const
  10630. {
  10631. const int currentLen = length() + 1;
  10632. String& mutableThis = const_cast <String&> (*this);
  10633. mutableThis.preallocateStorage (currentLen + 1 + numExtraBytes / sizeof (juce_wchar));
  10634. return (mutableThis.text + currentLen).getAddress();
  10635. }
  10636. const CharPointer_UTF8 String::toUTF8() const
  10637. {
  10638. if (isEmpty())
  10639. return CharPointer_UTF8 (reinterpret_cast <const CharPointer_UTF8::CharType*> (text.getAddress()));
  10640. const size_t extraBytesNeeded = CharPointer_UTF8::getBytesRequiredFor (text);
  10641. CharPointer_UTF8 extraSpace (static_cast <CharPointer_UTF8::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10642. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10643. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10644. #endif
  10645. CharPointer_UTF8 (extraSpace).writeAll (text);
  10646. return extraSpace;
  10647. }
  10648. CharPointer_UTF16 String::toUTF16() const
  10649. {
  10650. if (isEmpty())
  10651. return CharPointer_UTF16 (reinterpret_cast <const CharPointer_UTF16::CharType*> (text.getAddress()));
  10652. const size_t extraBytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text);
  10653. CharPointer_UTF16 extraSpace (static_cast <CharPointer_UTF16::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10654. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10655. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10656. #endif
  10657. CharPointer_UTF16 (extraSpace).writeAll (text);
  10658. return extraSpace;
  10659. }
  10660. int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const throw()
  10661. {
  10662. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10663. if (buffer == 0)
  10664. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10665. return CharPointer_UTF8 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10666. }
  10667. int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const throw()
  10668. {
  10669. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10670. if (buffer == 0)
  10671. return (int) CharPointer_UTF16::getBytesRequiredFor (text);
  10672. return CharPointer_UTF16 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10673. }
  10674. int String::getNumBytesAsUTF8() const throw()
  10675. {
  10676. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10677. }
  10678. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10679. {
  10680. if (buffer == 0)
  10681. return empty;
  10682. const int len = (int) (bufferSizeBytes >= 0 ? CharPointer_UTF8 (buffer).lengthUpTo (bufferSizeBytes)
  10683. : CharPointer_UTF8 (buffer).length());
  10684. String result (Preallocation (len + 1));
  10685. CharPointerType (result.text).writeWithCharLimit (CharPointer_UTF8 (buffer), len + 1);
  10686. return result;
  10687. }
  10688. const char* String::toCString() const
  10689. {
  10690. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10691. return toUTF8();
  10692. #else
  10693. if (isEmpty())
  10694. return reinterpret_cast <const char*> (text.getAddress());
  10695. const int len = getNumBytesAsCString();
  10696. char* const extraSpace = static_cast <char*> (createSpaceAtEndOfBuffer (len + 1));
  10697. wcstombs (extraSpace, text, len);
  10698. extraSpace [len] = 0;
  10699. return extraSpace;
  10700. #endif
  10701. }
  10702. int String::getNumBytesAsCString() const throw()
  10703. {
  10704. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10705. return getNumBytesAsUTF8();
  10706. #else
  10707. return (int) wcstombs (0, text, 0);
  10708. #endif
  10709. }
  10710. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10711. {
  10712. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10713. return copyToUTF8 (destBuffer, maxBufferSizeBytes);
  10714. #else
  10715. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10716. if (destBuffer != 0 && numBytes >= 0)
  10717. destBuffer [numBytes] = 0;
  10718. return numBytes;
  10719. #endif
  10720. }
  10721. #if JUCE_MSVC
  10722. #pragma warning (pop)
  10723. #endif
  10724. String::Concatenator::Concatenator (String& stringToAppendTo)
  10725. : result (stringToAppendTo),
  10726. nextIndex (stringToAppendTo.length())
  10727. {
  10728. }
  10729. String::Concatenator::~Concatenator()
  10730. {
  10731. }
  10732. void String::Concatenator::append (const String& s)
  10733. {
  10734. const int len = s.length();
  10735. if (len > 0)
  10736. {
  10737. result.preallocateStorage (nextIndex + len);
  10738. CharPointerType (result.text + nextIndex).writeAll (s.text);
  10739. nextIndex += len;
  10740. }
  10741. }
  10742. #if JUCE_UNIT_TESTS
  10743. class StringTests : public UnitTest
  10744. {
  10745. public:
  10746. StringTests() : UnitTest ("String class") {}
  10747. template <class CharPointerType>
  10748. struct TestUTFConversion
  10749. {
  10750. static void test (UnitTest& test)
  10751. {
  10752. String s (createRandomWideCharString());
  10753. typename CharPointerType::CharType buffer [300];
  10754. memset (buffer, 0xff, sizeof (buffer));
  10755. CharPointerType (buffer).writeAll (s.toUTF32());
  10756. test.expectEquals (String (CharPointerType (buffer)), s);
  10757. memset (buffer, 0xff, sizeof (buffer));
  10758. CharPointerType (buffer).writeAll (s.toUTF16());
  10759. test.expectEquals (String (CharPointerType (buffer)), s);
  10760. memset (buffer, 0xff, sizeof (buffer));
  10761. CharPointerType (buffer).writeAll (s.toUTF8());
  10762. test.expectEquals (String (CharPointerType (buffer)), s);
  10763. }
  10764. };
  10765. static const String createRandomWideCharString()
  10766. {
  10767. juce_wchar buffer [50];
  10768. zerostruct (buffer);
  10769. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  10770. {
  10771. if (Random::getSystemRandom().nextBool())
  10772. {
  10773. do
  10774. {
  10775. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  10776. }
  10777. while (buffer[i] >= 0xd800 && buffer[i] <= 0xdfff); // (these code-points are illegal in UTF-16)
  10778. }
  10779. else
  10780. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  10781. }
  10782. return buffer;
  10783. }
  10784. void runTest()
  10785. {
  10786. {
  10787. beginTest ("Basics");
  10788. expect (String().length() == 0);
  10789. expect (String() == String::empty);
  10790. String s1, s2 ("abcd");
  10791. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10792. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10793. expect (s2.length() == 4);
  10794. s1 = "abcd";
  10795. expect (s2 == s1 && s1 == s2);
  10796. expect (s1 == "abcd" && s1 == L"abcd");
  10797. expect (String ("abcd") == String (L"abcd"));
  10798. expect (String ("abcdefg", 4) == L"abcd");
  10799. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10800. expect (String::charToString ('x') == "x");
  10801. expect (String::charToString (0) == String::empty);
  10802. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10803. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10804. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10805. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10806. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10807. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10808. expect (s1.indexOf (String::empty) == 0);
  10809. expect (s1.indexOfIgnoreCase (String::empty) == 0);
  10810. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10811. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10812. expect (s1.containsChar ('a'));
  10813. expect (! s1.containsChar ('x'));
  10814. expect (! s1.containsChar (0));
  10815. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10816. }
  10817. {
  10818. beginTest ("Operations");
  10819. String s ("012345678");
  10820. expect (s.hashCode() != 0);
  10821. expect (s.hashCode64() != 0);
  10822. expect (s.hashCode() != (s + s).hashCode());
  10823. expect (s.hashCode64() != (s + s).hashCode64());
  10824. expect (s.compare (String ("012345678")) == 0);
  10825. expect (s.compare (String ("012345679")) < 0);
  10826. expect (s.compare (String ("012345676")) > 0);
  10827. expect (s.substring (2, 3) == String::charToString (s[2]));
  10828. expect (s.substring (0, 1) == String::charToString (s[0]));
  10829. expect (s.getLastCharacter() == s [s.length() - 1]);
  10830. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10831. expect (s.substring (0, 3) == L"012");
  10832. expect (s.substring (0, 100) == s);
  10833. expect (s.substring (-1, 100) == s);
  10834. expect (s.substring (3) == "345678");
  10835. expect (s.indexOf (L"45") == 4);
  10836. expect (String ("444445").indexOf ("45") == 4);
  10837. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10838. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10839. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10840. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10841. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  10842. expect (s.indexOfChar (L'4') == 4);
  10843. expect (s + s == "012345678012345678");
  10844. expect (s.startsWith (s));
  10845. expect (s.startsWith (s.substring (0, 4)));
  10846. expect (s.startsWith (s.dropLastCharacters (4)));
  10847. expect (s.endsWith (s.substring (5)));
  10848. expect (s.endsWith (s));
  10849. expect (s.contains (s.substring (3, 6)));
  10850. expect (s.contains (s.substring (3)));
  10851. expect (s.startsWithChar (s[0]));
  10852. expect (s.endsWithChar (s.getLastCharacter()));
  10853. expect (s [s.length()] == 0);
  10854. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  10855. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  10856. String s2 ("123");
  10857. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  10858. s2 += "xyz";
  10859. expect (s2 == "1234567890xyz");
  10860. beginTest ("Numeric conversions");
  10861. expect (String::empty.getIntValue() == 0);
  10862. expect (String::empty.getDoubleValue() == 0.0);
  10863. expect (String::empty.getFloatValue() == 0.0f);
  10864. expect (s.getIntValue() == 12345678);
  10865. expect (s.getLargeIntValue() == (int64) 12345678);
  10866. expect (s.getDoubleValue() == 12345678.0);
  10867. expect (s.getFloatValue() == 12345678.0f);
  10868. expect (String (-1234).getIntValue() == -1234);
  10869. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  10870. expect (String (-1234.56).getDoubleValue() == -1234.56);
  10871. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  10872. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  10873. expect (s.getHexValue32() == 0x12345678);
  10874. expect (s.getHexValue64() == (int64) 0x12345678);
  10875. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10876. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10877. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  10878. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  10879. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  10880. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  10881. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  10882. beginTest ("Subsections");
  10883. String s3;
  10884. s3 = "abcdeFGHIJ";
  10885. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  10886. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  10887. expect (s3.containsIgnoreCase (s3.substring (3)));
  10888. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  10889. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  10890. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  10891. expect (s3.containsAnyOf (L"zzzFs"));
  10892. expect (s3.startsWith ("abcd"));
  10893. expect (s3.startsWithIgnoreCase (L"abCD"));
  10894. expect (s3.startsWith (String::empty));
  10895. expect (s3.startsWithChar ('a'));
  10896. expect (s3.endsWith (String ("HIJ")));
  10897. expect (s3.endsWithIgnoreCase (L"Hij"));
  10898. expect (s3.endsWith (String::empty));
  10899. expect (s3.endsWithChar (L'J'));
  10900. expect (s3.indexOf ("HIJ") == 7);
  10901. expect (s3.indexOf (L"HIJK") == -1);
  10902. expect (s3.indexOfIgnoreCase ("hij") == 7);
  10903. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  10904. String s4 (s3);
  10905. s4.append (String ("xyz123"), 3);
  10906. expect (s4 == s3 + "xyz");
  10907. expect (String (1234) < String (1235));
  10908. expect (String (1235) > String (1234));
  10909. expect (String (1234) >= String (1234));
  10910. expect (String (1234) <= String (1234));
  10911. expect (String (1235) >= String (1234));
  10912. expect (String (1234) <= String (1235));
  10913. String s5 ("word word2 word3");
  10914. expect (s5.containsWholeWord (String ("word2")));
  10915. expect (s5.indexOfWholeWord ("word2") == 5);
  10916. expect (s5.containsWholeWord (L"word"));
  10917. expect (s5.containsWholeWord ("word3"));
  10918. expect (s5.containsWholeWord (s5));
  10919. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  10920. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  10921. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  10922. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  10923. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  10924. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  10925. expect (s5.containsNonWhitespaceChars());
  10926. expect (s5.containsOnly ("ordw23 "));
  10927. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  10928. expect (s5.matchesWildcard (L"wor*", false));
  10929. expect (s5.matchesWildcard ("wOr*", true));
  10930. expect (s5.matchesWildcard (L"*word3", true));
  10931. expect (s5.matchesWildcard ("*word?", true));
  10932. expect (s5.matchesWildcard (L"Word*3", true));
  10933. expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5);
  10934. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  10935. expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5));
  10936. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  10937. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  10938. expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6));
  10939. expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5);
  10940. expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5);
  10941. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  10942. expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5));
  10943. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  10944. expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1));
  10945. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  10946. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  10947. expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10));
  10948. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  10949. expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5));
  10950. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  10951. expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5);
  10952. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  10953. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10954. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10955. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  10956. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  10957. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  10958. expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3"));
  10959. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  10960. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  10961. expect (s5.replace ("Word", "", true) == " 2 3");
  10962. expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3"));
  10963. expect (s5.replaceCharacter (L'w', 'x') != s5);
  10964. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  10965. expect (s5.replaceCharacters ("wo", "xy") != s5);
  10966. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5);
  10967. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  10968. expect (s5.retainCharacters (String::empty).isEmpty());
  10969. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  10970. expectEquals (s5.removeCharacters (String::empty), s5);
  10971. expect (s5.initialSectionContainingOnly ("word") == L"word");
  10972. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  10973. expect (! s5.isQuotedString());
  10974. expect (s5.quoted().isQuotedString());
  10975. expect (! s5.quoted().unquoted().isQuotedString());
  10976. expect (! String ("x'").isQuotedString());
  10977. expect (String ("'x").isQuotedString());
  10978. String s6 (" \t xyz \t\r\n");
  10979. expectEquals (s6.trim(), String ("xyz"));
  10980. expect (s6.trim().trim() == "xyz");
  10981. expectEquals (s5.trim(), s5);
  10982. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  10983. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  10984. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  10985. expect (s6.trimStart() != s6.trimEnd());
  10986. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  10987. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  10988. }
  10989. {
  10990. beginTest ("UTF conversions");
  10991. TestUTFConversion <CharPointer_UTF32>::test (*this);
  10992. TestUTFConversion <CharPointer_UTF8>::test (*this);
  10993. TestUTFConversion <CharPointer_UTF16>::test (*this);
  10994. }
  10995. {
  10996. beginTest ("StringArray");
  10997. StringArray s;
  10998. for (int i = 5; --i >= 0;)
  10999. s.add (String (i));
  11000. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  11001. s.remove (2);
  11002. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  11003. expectEquals (s.joinIntoString (String::empty), String ("4310"));
  11004. s.clear();
  11005. expectEquals (s.joinIntoString ("x"), String::empty);
  11006. }
  11007. }
  11008. };
  11009. static StringTests stringUnitTests;
  11010. #endif
  11011. END_JUCE_NAMESPACE
  11012. /*** End of inlined file: juce_String.cpp ***/
  11013. /*** Start of inlined file: juce_StringArray.cpp ***/
  11014. BEGIN_JUCE_NAMESPACE
  11015. StringArray::StringArray() throw()
  11016. {
  11017. }
  11018. StringArray::StringArray (const StringArray& other)
  11019. : strings (other.strings)
  11020. {
  11021. }
  11022. StringArray::StringArray (const String& firstValue)
  11023. {
  11024. strings.add (firstValue);
  11025. }
  11026. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11027. const int numberOfStrings)
  11028. {
  11029. for (int i = 0; i < numberOfStrings; ++i)
  11030. strings.add (initialStrings [i]);
  11031. }
  11032. StringArray::StringArray (const char* const* const initialStrings,
  11033. const int numberOfStrings)
  11034. {
  11035. for (int i = 0; i < numberOfStrings; ++i)
  11036. strings.add (initialStrings [i]);
  11037. }
  11038. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11039. {
  11040. int i = 0;
  11041. while (initialStrings[i] != 0)
  11042. strings.add (initialStrings [i++]);
  11043. }
  11044. StringArray::StringArray (const char* const* const initialStrings)
  11045. {
  11046. int i = 0;
  11047. while (initialStrings[i] != 0)
  11048. strings.add (initialStrings [i++]);
  11049. }
  11050. StringArray& StringArray::operator= (const StringArray& other)
  11051. {
  11052. strings = other.strings;
  11053. return *this;
  11054. }
  11055. StringArray::~StringArray()
  11056. {
  11057. }
  11058. bool StringArray::operator== (const StringArray& other) const throw()
  11059. {
  11060. if (other.size() != size())
  11061. return false;
  11062. for (int i = size(); --i >= 0;)
  11063. if (other.strings.getReference(i) != strings.getReference(i))
  11064. return false;
  11065. return true;
  11066. }
  11067. bool StringArray::operator!= (const StringArray& other) const throw()
  11068. {
  11069. return ! operator== (other);
  11070. }
  11071. void StringArray::clear()
  11072. {
  11073. strings.clear();
  11074. }
  11075. const String& StringArray::operator[] (const int index) const throw()
  11076. {
  11077. if (isPositiveAndBelow (index, strings.size()))
  11078. return strings.getReference (index);
  11079. return String::empty;
  11080. }
  11081. String& StringArray::getReference (const int index) throw()
  11082. {
  11083. jassert (isPositiveAndBelow (index, strings.size()));
  11084. return strings.getReference (index);
  11085. }
  11086. void StringArray::add (const String& newString)
  11087. {
  11088. strings.add (newString);
  11089. }
  11090. void StringArray::insert (const int index, const String& newString)
  11091. {
  11092. strings.insert (index, newString);
  11093. }
  11094. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11095. {
  11096. if (! contains (newString, ignoreCase))
  11097. add (newString);
  11098. }
  11099. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11100. {
  11101. if (startIndex < 0)
  11102. {
  11103. jassertfalse;
  11104. startIndex = 0;
  11105. }
  11106. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11107. numElementsToAdd = otherArray.size() - startIndex;
  11108. while (--numElementsToAdd >= 0)
  11109. strings.add (otherArray.strings.getReference (startIndex++));
  11110. }
  11111. void StringArray::set (const int index, const String& newString)
  11112. {
  11113. strings.set (index, newString);
  11114. }
  11115. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11116. {
  11117. if (ignoreCase)
  11118. {
  11119. for (int i = size(); --i >= 0;)
  11120. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11121. return true;
  11122. }
  11123. else
  11124. {
  11125. for (int i = size(); --i >= 0;)
  11126. if (stringToLookFor == strings.getReference(i))
  11127. return true;
  11128. }
  11129. return false;
  11130. }
  11131. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11132. {
  11133. if (i < 0)
  11134. i = 0;
  11135. const int numElements = size();
  11136. if (ignoreCase)
  11137. {
  11138. while (i < numElements)
  11139. {
  11140. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11141. return i;
  11142. ++i;
  11143. }
  11144. }
  11145. else
  11146. {
  11147. while (i < numElements)
  11148. {
  11149. if (stringToLookFor == strings.getReference (i))
  11150. return i;
  11151. ++i;
  11152. }
  11153. }
  11154. return -1;
  11155. }
  11156. void StringArray::remove (const int index)
  11157. {
  11158. strings.remove (index);
  11159. }
  11160. void StringArray::removeString (const String& stringToRemove,
  11161. const bool ignoreCase)
  11162. {
  11163. if (ignoreCase)
  11164. {
  11165. for (int i = size(); --i >= 0;)
  11166. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11167. strings.remove (i);
  11168. }
  11169. else
  11170. {
  11171. for (int i = size(); --i >= 0;)
  11172. if (stringToRemove == strings.getReference (i))
  11173. strings.remove (i);
  11174. }
  11175. }
  11176. void StringArray::removeRange (int startIndex, int numberToRemove)
  11177. {
  11178. strings.removeRange (startIndex, numberToRemove);
  11179. }
  11180. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11181. {
  11182. if (removeWhitespaceStrings)
  11183. {
  11184. for (int i = size(); --i >= 0;)
  11185. if (! strings.getReference(i).containsNonWhitespaceChars())
  11186. strings.remove (i);
  11187. }
  11188. else
  11189. {
  11190. for (int i = size(); --i >= 0;)
  11191. if (strings.getReference(i).isEmpty())
  11192. strings.remove (i);
  11193. }
  11194. }
  11195. void StringArray::trim()
  11196. {
  11197. for (int i = size(); --i >= 0;)
  11198. {
  11199. String& s = strings.getReference(i);
  11200. s = s.trim();
  11201. }
  11202. }
  11203. class InternalStringArrayComparator_CaseSensitive
  11204. {
  11205. public:
  11206. static int compareElements (String& first, String& second) { return first.compare (second); }
  11207. };
  11208. class InternalStringArrayComparator_CaseInsensitive
  11209. {
  11210. public:
  11211. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11212. };
  11213. void StringArray::sort (const bool ignoreCase)
  11214. {
  11215. if (ignoreCase)
  11216. {
  11217. InternalStringArrayComparator_CaseInsensitive comp;
  11218. strings.sort (comp);
  11219. }
  11220. else
  11221. {
  11222. InternalStringArrayComparator_CaseSensitive comp;
  11223. strings.sort (comp);
  11224. }
  11225. }
  11226. void StringArray::move (const int currentIndex, int newIndex) throw()
  11227. {
  11228. strings.move (currentIndex, newIndex);
  11229. }
  11230. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11231. {
  11232. const int last = (numberToJoin < 0) ? size()
  11233. : jmin (size(), start + numberToJoin);
  11234. if (start < 0)
  11235. start = 0;
  11236. if (start >= last)
  11237. return String::empty;
  11238. if (start == last - 1)
  11239. return strings.getReference (start);
  11240. const int separatorLen = separator.length();
  11241. int charsNeeded = separatorLen * (last - start - 1);
  11242. for (int i = start; i < last; ++i)
  11243. charsNeeded += strings.getReference(i).length();
  11244. String result;
  11245. result.preallocateStorage (charsNeeded);
  11246. String::CharPointerType dest (result.getCharPointer());
  11247. while (start < last)
  11248. {
  11249. const String& s = strings.getReference (start);
  11250. if (! s.isEmpty())
  11251. dest.writeAll (s.getCharPointer());
  11252. if (++start < last && separatorLen > 0)
  11253. dest.writeAll (separator.getCharPointer());
  11254. }
  11255. dest.writeNull();
  11256. return result;
  11257. }
  11258. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11259. {
  11260. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11261. }
  11262. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11263. {
  11264. int num = 0;
  11265. if (text.isNotEmpty())
  11266. {
  11267. bool insideQuotes = false;
  11268. juce_wchar currentQuoteChar = 0;
  11269. String::CharPointerType t (text.getCharPointer());
  11270. String::CharPointerType tokenStart (t);
  11271. int numChars = 0;
  11272. for (;;)
  11273. {
  11274. const juce_wchar c = t.getAndAdvance();
  11275. ++numChars;
  11276. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11277. if (! isBreak)
  11278. {
  11279. if (quoteCharacters.containsChar (c))
  11280. {
  11281. if (insideQuotes)
  11282. {
  11283. // only break out of quotes-mode if we find a matching quote to the
  11284. // one that we opened with..
  11285. if (currentQuoteChar == c)
  11286. insideQuotes = false;
  11287. }
  11288. else
  11289. {
  11290. insideQuotes = true;
  11291. currentQuoteChar = c;
  11292. }
  11293. }
  11294. }
  11295. else
  11296. {
  11297. add (String (tokenStart, numChars - 1));
  11298. ++num;
  11299. tokenStart = t;
  11300. numChars = 0;
  11301. }
  11302. if (c == 0)
  11303. break;
  11304. }
  11305. }
  11306. return num;
  11307. }
  11308. int StringArray::addLines (const String& sourceText)
  11309. {
  11310. int numLines = 0;
  11311. String::CharPointerType text (sourceText.getCharPointer());
  11312. bool finished = text.isEmpty();
  11313. while (! finished)
  11314. {
  11315. String::CharPointerType startOfLine (text);
  11316. int numChars = 0;
  11317. for (;;)
  11318. {
  11319. const juce_wchar c = text.getAndAdvance();
  11320. if (c == 0)
  11321. {
  11322. finished = true;
  11323. break;
  11324. }
  11325. if (c == '\n')
  11326. break;
  11327. if (c == '\r')
  11328. {
  11329. if (*text == '\n')
  11330. ++text;
  11331. break;
  11332. }
  11333. ++numChars;
  11334. }
  11335. add (String (startOfLine, numChars));
  11336. ++numLines;
  11337. }
  11338. return numLines;
  11339. }
  11340. void StringArray::removeDuplicates (const bool ignoreCase)
  11341. {
  11342. for (int i = 0; i < size() - 1; ++i)
  11343. {
  11344. const String s (strings.getReference(i));
  11345. int nextIndex = i + 1;
  11346. for (;;)
  11347. {
  11348. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11349. if (nextIndex < 0)
  11350. break;
  11351. strings.remove (nextIndex);
  11352. }
  11353. }
  11354. }
  11355. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11356. const bool appendNumberToFirstInstance,
  11357. CharPointer_UTF8 preNumberString,
  11358. CharPointer_UTF8 postNumberString)
  11359. {
  11360. CharPointer_UTF8 defaultPre (" ("), defaultPost (")");
  11361. if (preNumberString.getAddress() == 0)
  11362. preNumberString = defaultPre;
  11363. if (postNumberString.getAddress() == 0)
  11364. postNumberString = defaultPost;
  11365. for (int i = 0; i < size() - 1; ++i)
  11366. {
  11367. String& s = strings.getReference(i);
  11368. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11369. if (nextIndex >= 0)
  11370. {
  11371. const String original (s);
  11372. int number = 0;
  11373. if (appendNumberToFirstInstance)
  11374. s = original + String (preNumberString) + String (++number) + String (postNumberString);
  11375. else
  11376. ++number;
  11377. while (nextIndex >= 0)
  11378. {
  11379. set (nextIndex, (*this)[nextIndex] + String (preNumberString) + String (++number) + String (postNumberString));
  11380. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11381. }
  11382. }
  11383. }
  11384. }
  11385. void StringArray::minimiseStorageOverheads()
  11386. {
  11387. strings.minimiseStorageOverheads();
  11388. }
  11389. END_JUCE_NAMESPACE
  11390. /*** End of inlined file: juce_StringArray.cpp ***/
  11391. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11392. BEGIN_JUCE_NAMESPACE
  11393. StringPairArray::StringPairArray (const bool ignoreCase_)
  11394. : ignoreCase (ignoreCase_)
  11395. {
  11396. }
  11397. StringPairArray::StringPairArray (const StringPairArray& other)
  11398. : keys (other.keys),
  11399. values (other.values),
  11400. ignoreCase (other.ignoreCase)
  11401. {
  11402. }
  11403. StringPairArray::~StringPairArray()
  11404. {
  11405. }
  11406. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11407. {
  11408. keys = other.keys;
  11409. values = other.values;
  11410. return *this;
  11411. }
  11412. bool StringPairArray::operator== (const StringPairArray& other) const
  11413. {
  11414. for (int i = keys.size(); --i >= 0;)
  11415. if (other [keys[i]] != values[i])
  11416. return false;
  11417. return true;
  11418. }
  11419. bool StringPairArray::operator!= (const StringPairArray& other) const
  11420. {
  11421. return ! operator== (other);
  11422. }
  11423. const String& StringPairArray::operator[] (const String& key) const
  11424. {
  11425. return values [keys.indexOf (key, ignoreCase)];
  11426. }
  11427. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11428. {
  11429. const int i = keys.indexOf (key, ignoreCase);
  11430. if (i >= 0)
  11431. return values[i];
  11432. return defaultReturnValue;
  11433. }
  11434. void StringPairArray::set (const String& key, const String& value)
  11435. {
  11436. const int i = keys.indexOf (key, ignoreCase);
  11437. if (i >= 0)
  11438. {
  11439. values.set (i, value);
  11440. }
  11441. else
  11442. {
  11443. keys.add (key);
  11444. values.add (value);
  11445. }
  11446. }
  11447. void StringPairArray::addArray (const StringPairArray& other)
  11448. {
  11449. for (int i = 0; i < other.size(); ++i)
  11450. set (other.keys[i], other.values[i]);
  11451. }
  11452. void StringPairArray::clear()
  11453. {
  11454. keys.clear();
  11455. values.clear();
  11456. }
  11457. void StringPairArray::remove (const String& key)
  11458. {
  11459. remove (keys.indexOf (key, ignoreCase));
  11460. }
  11461. void StringPairArray::remove (const int index)
  11462. {
  11463. keys.remove (index);
  11464. values.remove (index);
  11465. }
  11466. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11467. {
  11468. ignoreCase = shouldIgnoreCase;
  11469. }
  11470. const String StringPairArray::getDescription() const
  11471. {
  11472. String s;
  11473. for (int i = 0; i < keys.size(); ++i)
  11474. {
  11475. s << keys[i] << " = " << values[i];
  11476. if (i < keys.size())
  11477. s << ", ";
  11478. }
  11479. return s;
  11480. }
  11481. void StringPairArray::minimiseStorageOverheads()
  11482. {
  11483. keys.minimiseStorageOverheads();
  11484. values.minimiseStorageOverheads();
  11485. }
  11486. END_JUCE_NAMESPACE
  11487. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11488. /*** Start of inlined file: juce_StringPool.cpp ***/
  11489. BEGIN_JUCE_NAMESPACE
  11490. StringPool::StringPool() throw() {}
  11491. StringPool::~StringPool() {}
  11492. namespace StringPoolHelpers
  11493. {
  11494. template <class StringType>
  11495. const String::CharPointerType getPooledStringFromArray (Array<String>& strings, StringType newString)
  11496. {
  11497. int start = 0;
  11498. int end = strings.size();
  11499. for (;;)
  11500. {
  11501. if (start >= end)
  11502. {
  11503. jassert (start <= end);
  11504. strings.insert (start, newString);
  11505. return strings.getReference (start).getCharPointer();
  11506. }
  11507. else
  11508. {
  11509. const String& startString = strings.getReference (start);
  11510. if (startString == newString)
  11511. return startString.getCharPointer();
  11512. const int halfway = (start + end) >> 1;
  11513. if (halfway == start)
  11514. {
  11515. if (startString.compare (newString) < 0)
  11516. ++start;
  11517. strings.insert (start, newString);
  11518. return strings.getReference (start).getCharPointer();
  11519. }
  11520. const int comp = strings.getReference (halfway).compare (newString);
  11521. if (comp == 0)
  11522. return strings.getReference (halfway).getCharPointer();
  11523. else if (comp < 0)
  11524. start = halfway;
  11525. else
  11526. end = halfway;
  11527. }
  11528. }
  11529. }
  11530. }
  11531. const String::CharPointerType StringPool::getPooledString (const String& s)
  11532. {
  11533. if (s.isEmpty())
  11534. return String::empty.getCharPointer();
  11535. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11536. }
  11537. const String::CharPointerType StringPool::getPooledString (const char* const s)
  11538. {
  11539. if (s == 0 || *s == 0)
  11540. return String::empty.getCharPointer();
  11541. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11542. }
  11543. const String::CharPointerType StringPool::getPooledString (const juce_wchar* const s)
  11544. {
  11545. if (s == 0 || *s == 0)
  11546. return String::empty.getCharPointer();
  11547. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11548. }
  11549. int StringPool::size() const throw()
  11550. {
  11551. return strings.size();
  11552. }
  11553. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11554. {
  11555. return strings [index].getCharPointer();
  11556. }
  11557. END_JUCE_NAMESPACE
  11558. /*** End of inlined file: juce_StringPool.cpp ***/
  11559. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11560. BEGIN_JUCE_NAMESPACE
  11561. XmlDocument::XmlDocument (const String& documentText)
  11562. : originalText (documentText),
  11563. input (0),
  11564. ignoreEmptyTextElements (true)
  11565. {
  11566. }
  11567. XmlDocument::XmlDocument (const File& file)
  11568. : input (0),
  11569. ignoreEmptyTextElements (true),
  11570. inputSource (new FileInputSource (file))
  11571. {
  11572. }
  11573. XmlDocument::~XmlDocument()
  11574. {
  11575. }
  11576. XmlElement* XmlDocument::parse (const File& file)
  11577. {
  11578. XmlDocument doc (file);
  11579. return doc.getDocumentElement();
  11580. }
  11581. XmlElement* XmlDocument::parse (const String& xmlData)
  11582. {
  11583. XmlDocument doc (xmlData);
  11584. return doc.getDocumentElement();
  11585. }
  11586. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11587. {
  11588. inputSource = newSource;
  11589. }
  11590. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11591. {
  11592. ignoreEmptyTextElements = shouldBeIgnored;
  11593. }
  11594. namespace XmlIdentifierChars
  11595. {
  11596. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11597. {
  11598. return CharacterFunctions::isLetterOrDigit (c)
  11599. || c == '_' || c == '-' || c == ':' || c == '.';
  11600. }
  11601. bool isIdentifierChar (const juce_wchar c) throw()
  11602. {
  11603. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11604. return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11605. : isIdentifierCharSlow (c);
  11606. }
  11607. /*static void generateIdentifierCharConstants()
  11608. {
  11609. uint32 n[8];
  11610. zerostruct (n);
  11611. for (int i = 0; i < 256; ++i)
  11612. if (isIdentifierCharSlow (i))
  11613. n[i >> 5] |= (1 << (i & 31));
  11614. String s;
  11615. for (int i = 0; i < 8; ++i)
  11616. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11617. DBG (s);
  11618. }*/
  11619. }
  11620. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11621. {
  11622. String textToParse (originalText);
  11623. if (textToParse.isEmpty() && inputSource != 0)
  11624. {
  11625. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11626. if (in != 0)
  11627. {
  11628. MemoryOutputStream data;
  11629. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11630. textToParse = data.toString();
  11631. if (! onlyReadOuterDocumentElement)
  11632. originalText = textToParse;
  11633. }
  11634. }
  11635. input = textToParse.getCharPointer();
  11636. lastError = String::empty;
  11637. errorOccurred = false;
  11638. outOfData = false;
  11639. needToLoadDTD = true;
  11640. if (textToParse.isEmpty())
  11641. {
  11642. lastError = "not enough input";
  11643. }
  11644. else
  11645. {
  11646. skipHeader();
  11647. if (input.getAddress() != 0)
  11648. {
  11649. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11650. if (! errorOccurred)
  11651. return result.release();
  11652. }
  11653. else
  11654. {
  11655. lastError = "incorrect xml header";
  11656. }
  11657. }
  11658. return 0;
  11659. }
  11660. const String& XmlDocument::getLastParseError() const throw()
  11661. {
  11662. return lastError;
  11663. }
  11664. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11665. {
  11666. lastError = desc;
  11667. errorOccurred = ! carryOn;
  11668. }
  11669. const String XmlDocument::getFileContents (const String& filename) const
  11670. {
  11671. if (inputSource != 0)
  11672. {
  11673. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11674. if (in != 0)
  11675. return in->readEntireStreamAsString();
  11676. }
  11677. return String::empty;
  11678. }
  11679. juce_wchar XmlDocument::readNextChar() throw()
  11680. {
  11681. if (*input != 0)
  11682. return *input++;
  11683. outOfData = true;
  11684. return 0;
  11685. }
  11686. int XmlDocument::findNextTokenLength() throw()
  11687. {
  11688. int len = 0;
  11689. juce_wchar c = *input;
  11690. while (XmlIdentifierChars::isIdentifierChar (c))
  11691. c = input [++len];
  11692. return len;
  11693. }
  11694. void XmlDocument::skipHeader()
  11695. {
  11696. const int headerStart = input.indexOf (CharPointer_UTF8 ("<?xml"));
  11697. if (headerStart >= 0)
  11698. {
  11699. const int headerEnd = (input + headerStart).indexOf (CharPointer_UTF8 ("?>"));
  11700. if (headerEnd < 0)
  11701. return;
  11702. #if JUCE_DEBUG
  11703. const String header ((input + headerStart).getAddress(), headerEnd - headerStart);
  11704. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11705. .fromFirstOccurrenceOf ("=", false, false)
  11706. .fromFirstOccurrenceOf ("\"", false, false)
  11707. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11708. /* If you load an XML document with a non-UTF encoding type, it may have been
  11709. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11710. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11711. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11712. read, use your own code to convert them to a unicode String, and pass that to the
  11713. XML parser.
  11714. */
  11715. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11716. #endif
  11717. input += headerEnd + 2;
  11718. }
  11719. skipNextWhiteSpace();
  11720. const int docTypeIndex = input.indexOf (CharPointer_UTF8 ("<!DOCTYPE"));
  11721. if (docTypeIndex < 0)
  11722. return;
  11723. input += docTypeIndex + 9;
  11724. const String::CharPointerType docType (input);
  11725. int n = 1;
  11726. while (n > 0)
  11727. {
  11728. const juce_wchar c = readNextChar();
  11729. if (outOfData)
  11730. return;
  11731. if (c == '<')
  11732. ++n;
  11733. else if (c == '>')
  11734. --n;
  11735. }
  11736. dtdText = String (docType.getAddress(), (int) (input.getAddress() - (docType.getAddress() + 1))).trim();
  11737. }
  11738. void XmlDocument::skipNextWhiteSpace()
  11739. {
  11740. for (;;)
  11741. {
  11742. juce_wchar c = *input;
  11743. while (CharacterFunctions::isWhitespace (c))
  11744. c = *++input;
  11745. if (c == 0)
  11746. {
  11747. outOfData = true;
  11748. break;
  11749. }
  11750. else if (c == '<')
  11751. {
  11752. if (input[1] == '!'
  11753. && input[2] == '-'
  11754. && input[3] == '-')
  11755. {
  11756. const int closeComment = input.indexOf (CharPointer_UTF8 ("-->"));
  11757. if (closeComment < 0)
  11758. {
  11759. outOfData = true;
  11760. break;
  11761. }
  11762. input += closeComment + 3;
  11763. continue;
  11764. }
  11765. else if (input[1] == '?')
  11766. {
  11767. const int closeBracket = input.indexOf (CharPointer_UTF8 ("?>"));
  11768. if (closeBracket < 0)
  11769. {
  11770. outOfData = true;
  11771. break;
  11772. }
  11773. input += closeBracket + 2;
  11774. continue;
  11775. }
  11776. }
  11777. break;
  11778. }
  11779. }
  11780. void XmlDocument::readQuotedString (String& result)
  11781. {
  11782. const juce_wchar quote = readNextChar();
  11783. while (! outOfData)
  11784. {
  11785. const juce_wchar c = readNextChar();
  11786. if (c == quote)
  11787. break;
  11788. if (c == '&')
  11789. {
  11790. --input;
  11791. readEntity (result);
  11792. }
  11793. else
  11794. {
  11795. --input;
  11796. const String::CharPointerType start (input);
  11797. for (;;)
  11798. {
  11799. const juce_wchar character = *input;
  11800. if (character == quote)
  11801. {
  11802. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11803. ++input;
  11804. return;
  11805. }
  11806. else if (character == '&')
  11807. {
  11808. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11809. break;
  11810. }
  11811. else if (character == 0)
  11812. {
  11813. outOfData = true;
  11814. setLastError ("unmatched quotes", false);
  11815. break;
  11816. }
  11817. ++input;
  11818. }
  11819. }
  11820. }
  11821. }
  11822. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11823. {
  11824. XmlElement* node = 0;
  11825. skipNextWhiteSpace();
  11826. if (outOfData)
  11827. return 0;
  11828. const int openBracket = input.indexOf ((juce_wchar) '<');
  11829. if (openBracket >= 0)
  11830. {
  11831. input += openBracket + 1;
  11832. int tagLen = findNextTokenLength();
  11833. if (tagLen == 0)
  11834. {
  11835. // no tag name - but allow for a gap after the '<' before giving an error
  11836. skipNextWhiteSpace();
  11837. tagLen = findNextTokenLength();
  11838. if (tagLen == 0)
  11839. {
  11840. setLastError ("tag name missing", false);
  11841. return node;
  11842. }
  11843. }
  11844. node = new XmlElement (String (input.getAddress(), tagLen));
  11845. input += tagLen;
  11846. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  11847. // look for attributes
  11848. for (;;)
  11849. {
  11850. skipNextWhiteSpace();
  11851. const juce_wchar c = *input;
  11852. // empty tag..
  11853. if (c == '/' && input[1] == '>')
  11854. {
  11855. input += 2;
  11856. break;
  11857. }
  11858. // parse the guts of the element..
  11859. if (c == '>')
  11860. {
  11861. ++input;
  11862. if (alsoParseSubElements)
  11863. readChildElements (node);
  11864. break;
  11865. }
  11866. // get an attribute..
  11867. if (XmlIdentifierChars::isIdentifierChar (c))
  11868. {
  11869. const int attNameLen = findNextTokenLength();
  11870. if (attNameLen > 0)
  11871. {
  11872. const String::CharPointerType attNameStart (input);
  11873. input += attNameLen;
  11874. skipNextWhiteSpace();
  11875. if (readNextChar() == '=')
  11876. {
  11877. skipNextWhiteSpace();
  11878. const juce_wchar nextChar = *input;
  11879. if (nextChar == '"' || nextChar == '\'')
  11880. {
  11881. XmlElement::XmlAttributeNode* const newAtt
  11882. = new XmlElement::XmlAttributeNode (String (attNameStart.getAddress(), attNameLen),
  11883. String::empty);
  11884. readQuotedString (newAtt->value);
  11885. attributeAppender.append (newAtt);
  11886. continue;
  11887. }
  11888. }
  11889. }
  11890. }
  11891. else
  11892. {
  11893. if (! outOfData)
  11894. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11895. }
  11896. break;
  11897. }
  11898. }
  11899. return node;
  11900. }
  11901. void XmlDocument::readChildElements (XmlElement* parent)
  11902. {
  11903. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  11904. for (;;)
  11905. {
  11906. const String::CharPointerType preWhitespaceInput (input);
  11907. skipNextWhiteSpace();
  11908. if (outOfData)
  11909. {
  11910. setLastError ("unmatched tags", false);
  11911. break;
  11912. }
  11913. if (*input == '<')
  11914. {
  11915. if (input[1] == '/')
  11916. {
  11917. // our close tag..
  11918. const int closeTag = input.indexOf ((juce_wchar) '>');
  11919. if (closeTag >= 0)
  11920. input += closeTag + 1;
  11921. break;
  11922. }
  11923. else if (input[1] == '!'
  11924. && input[2] == '['
  11925. && input[3] == 'C'
  11926. && input[4] == 'D'
  11927. && input[5] == 'A'
  11928. && input[6] == 'T'
  11929. && input[7] == 'A'
  11930. && input[8] == '[')
  11931. {
  11932. input += 9;
  11933. const String::CharPointerType inputStart (input);
  11934. int len = 0;
  11935. for (;;)
  11936. {
  11937. if (*input == 0)
  11938. {
  11939. setLastError ("unterminated CDATA section", false);
  11940. outOfData = true;
  11941. break;
  11942. }
  11943. else if (input[0] == ']'
  11944. && input[1] == ']'
  11945. && input[2] == '>')
  11946. {
  11947. input += 3;
  11948. break;
  11949. }
  11950. ++input;
  11951. ++len;
  11952. }
  11953. childAppender.append (XmlElement::createTextElement (String (inputStart.getAddress(), len)));
  11954. }
  11955. else
  11956. {
  11957. // this is some other element, so parse and add it..
  11958. XmlElement* const n = readNextElement (true);
  11959. if (n != 0)
  11960. childAppender.append (n);
  11961. else
  11962. return;
  11963. }
  11964. }
  11965. else // must be a character block
  11966. {
  11967. input = preWhitespaceInput; // roll back to include the leading whitespace
  11968. String textElementContent;
  11969. for (;;)
  11970. {
  11971. const juce_wchar c = *input;
  11972. if (c == '<')
  11973. break;
  11974. if (c == 0)
  11975. {
  11976. setLastError ("unmatched tags", false);
  11977. outOfData = true;
  11978. return;
  11979. }
  11980. if (c == '&')
  11981. {
  11982. String entity;
  11983. readEntity (entity);
  11984. if (entity.startsWithChar ('<') && entity [1] != 0)
  11985. {
  11986. const String::CharPointerType oldInput (input);
  11987. const bool oldOutOfData = outOfData;
  11988. input = entity.getCharPointer();
  11989. outOfData = false;
  11990. for (;;)
  11991. {
  11992. XmlElement* const n = readNextElement (true);
  11993. if (n == 0)
  11994. break;
  11995. childAppender.append (n);
  11996. }
  11997. input = oldInput;
  11998. outOfData = oldOutOfData;
  11999. }
  12000. else
  12001. {
  12002. textElementContent += entity;
  12003. }
  12004. }
  12005. else
  12006. {
  12007. const String::CharPointerType start (input);
  12008. int len = 0;
  12009. for (;;)
  12010. {
  12011. const juce_wchar nextChar = *input;
  12012. if (nextChar == '<' || nextChar == '&')
  12013. {
  12014. break;
  12015. }
  12016. else if (nextChar == 0)
  12017. {
  12018. setLastError ("unmatched tags", false);
  12019. outOfData = true;
  12020. return;
  12021. }
  12022. ++input;
  12023. ++len;
  12024. }
  12025. textElementContent.append (start.getAddress(), len);
  12026. }
  12027. }
  12028. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12029. {
  12030. childAppender.append (XmlElement::createTextElement (textElementContent));
  12031. }
  12032. }
  12033. }
  12034. }
  12035. void XmlDocument::readEntity (String& result)
  12036. {
  12037. // skip over the ampersand
  12038. ++input;
  12039. if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("amp;"), 4) == 0)
  12040. {
  12041. input += 4;
  12042. result += '&';
  12043. }
  12044. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("quot;"), 5) == 0)
  12045. {
  12046. input += 5;
  12047. result += '"';
  12048. }
  12049. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("apos;"), 5) == 0)
  12050. {
  12051. input += 5;
  12052. result += '\'';
  12053. }
  12054. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("lt;"), 3) == 0)
  12055. {
  12056. input += 3;
  12057. result += '<';
  12058. }
  12059. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("gt;"), 3) == 0)
  12060. {
  12061. input += 3;
  12062. result += '>';
  12063. }
  12064. else if (*input == '#')
  12065. {
  12066. int charCode = 0;
  12067. ++input;
  12068. if (*input == 'x' || *input == 'X')
  12069. {
  12070. ++input;
  12071. int numChars = 0;
  12072. while (input[0] != ';')
  12073. {
  12074. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12075. if (hexValue < 0 || ++numChars > 8)
  12076. {
  12077. setLastError ("illegal escape sequence", true);
  12078. break;
  12079. }
  12080. charCode = (charCode << 4) | hexValue;
  12081. ++input;
  12082. }
  12083. ++input;
  12084. }
  12085. else if (input[0] >= '0' && input[0] <= '9')
  12086. {
  12087. int numChars = 0;
  12088. while (input[0] != ';')
  12089. {
  12090. if (++numChars > 12)
  12091. {
  12092. setLastError ("illegal escape sequence", true);
  12093. break;
  12094. }
  12095. charCode = charCode * 10 + (input[0] - '0');
  12096. ++input;
  12097. }
  12098. ++input;
  12099. }
  12100. else
  12101. {
  12102. setLastError ("illegal escape sequence", true);
  12103. result += '&';
  12104. return;
  12105. }
  12106. result << (juce_wchar) charCode;
  12107. }
  12108. else
  12109. {
  12110. const String::CharPointerType entityNameStart (input);
  12111. const int closingSemiColon = input.indexOf ((juce_wchar) ';');
  12112. if (closingSemiColon < 0)
  12113. {
  12114. outOfData = true;
  12115. result += '&';
  12116. }
  12117. else
  12118. {
  12119. input += closingSemiColon + 1;
  12120. result += expandExternalEntity (String (entityNameStart.getAddress(), closingSemiColon));
  12121. }
  12122. }
  12123. }
  12124. const String XmlDocument::expandEntity (const String& ent)
  12125. {
  12126. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12127. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12128. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12129. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12130. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12131. if (ent[0] == '#')
  12132. {
  12133. if (ent[1] == 'x' || ent[1] == 'X')
  12134. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12135. if (ent[1] >= '0' && ent[1] <= '9')
  12136. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12137. setLastError ("illegal escape sequence", false);
  12138. return String::charToString ('&');
  12139. }
  12140. return expandExternalEntity (ent);
  12141. }
  12142. const String XmlDocument::expandExternalEntity (const String& entity)
  12143. {
  12144. if (needToLoadDTD)
  12145. {
  12146. if (dtdText.isNotEmpty())
  12147. {
  12148. dtdText = dtdText.trimCharactersAtEnd (">");
  12149. tokenisedDTD.addTokens (dtdText, true);
  12150. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12151. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12152. {
  12153. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12154. tokenisedDTD.clear();
  12155. tokenisedDTD.addTokens (getFileContents (fn), true);
  12156. }
  12157. else
  12158. {
  12159. tokenisedDTD.clear();
  12160. const int openBracket = dtdText.indexOfChar ('[');
  12161. if (openBracket > 0)
  12162. {
  12163. const int closeBracket = dtdText.lastIndexOfChar (']');
  12164. if (closeBracket > openBracket)
  12165. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12166. closeBracket), true);
  12167. }
  12168. }
  12169. for (int i = tokenisedDTD.size(); --i >= 0;)
  12170. {
  12171. if (tokenisedDTD[i].startsWithChar ('%')
  12172. && tokenisedDTD[i].endsWithChar (';'))
  12173. {
  12174. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12175. StringArray newToks;
  12176. newToks.addTokens (parsed, true);
  12177. tokenisedDTD.remove (i);
  12178. for (int j = newToks.size(); --j >= 0;)
  12179. tokenisedDTD.insert (i, newToks[j]);
  12180. }
  12181. }
  12182. }
  12183. needToLoadDTD = false;
  12184. }
  12185. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12186. {
  12187. if (tokenisedDTD[i] == entity)
  12188. {
  12189. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12190. {
  12191. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12192. // check for sub-entities..
  12193. int ampersand = ent.indexOfChar ('&');
  12194. while (ampersand >= 0)
  12195. {
  12196. const int semiColon = ent.indexOf (i + 1, ";");
  12197. if (semiColon < 0)
  12198. {
  12199. setLastError ("entity without terminating semi-colon", false);
  12200. break;
  12201. }
  12202. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12203. ent = ent.substring (0, ampersand)
  12204. + resolved
  12205. + ent.substring (semiColon + 1);
  12206. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12207. }
  12208. return ent;
  12209. }
  12210. }
  12211. }
  12212. setLastError ("unknown entity", true);
  12213. return entity;
  12214. }
  12215. const String XmlDocument::getParameterEntity (const String& entity)
  12216. {
  12217. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12218. {
  12219. if (tokenisedDTD[i] == entity
  12220. && tokenisedDTD [i - 1] == "%"
  12221. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12222. {
  12223. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12224. if (ent.equalsIgnoreCase ("system"))
  12225. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12226. else
  12227. return ent.trim().unquoted();
  12228. }
  12229. }
  12230. return entity;
  12231. }
  12232. END_JUCE_NAMESPACE
  12233. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12234. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12235. BEGIN_JUCE_NAMESPACE
  12236. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12237. : name (other.name),
  12238. value (other.value)
  12239. {
  12240. }
  12241. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12242. : name (name_),
  12243. value (value_)
  12244. {
  12245. #if JUCE_DEBUG
  12246. // this checks whether the attribute name string contains any illegal characters..
  12247. for (String::CharPointerType t (name.getCharPointer()); ! t.isEmpty(); ++t)
  12248. jassert (t.isLetterOrDigit() || *t == '_' || *t == '-' || *t == ':');
  12249. #endif
  12250. }
  12251. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12252. {
  12253. return name.equalsIgnoreCase (nameToMatch);
  12254. }
  12255. XmlElement::XmlElement (const String& tagName_) throw()
  12256. : tagName (tagName_)
  12257. {
  12258. // the tag name mustn't be empty, or it'll look like a text element!
  12259. jassert (tagName_.containsNonWhitespaceChars())
  12260. // The tag can't contain spaces or other characters that would create invalid XML!
  12261. jassert (! tagName_.containsAnyOf (" <>/&"));
  12262. }
  12263. XmlElement::XmlElement (int /*dummy*/) throw()
  12264. {
  12265. }
  12266. XmlElement::XmlElement (const XmlElement& other)
  12267. : tagName (other.tagName)
  12268. {
  12269. copyChildrenAndAttributesFrom (other);
  12270. }
  12271. XmlElement& XmlElement::operator= (const XmlElement& other)
  12272. {
  12273. if (this != &other)
  12274. {
  12275. removeAllAttributes();
  12276. deleteAllChildElements();
  12277. tagName = other.tagName;
  12278. copyChildrenAndAttributesFrom (other);
  12279. }
  12280. return *this;
  12281. }
  12282. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12283. {
  12284. jassert (firstChildElement.get() == 0);
  12285. firstChildElement.addCopyOfList (other.firstChildElement);
  12286. jassert (attributes.get() == 0);
  12287. attributes.addCopyOfList (other.attributes);
  12288. }
  12289. XmlElement::~XmlElement() throw()
  12290. {
  12291. firstChildElement.deleteAll();
  12292. attributes.deleteAll();
  12293. }
  12294. namespace XmlOutputFunctions
  12295. {
  12296. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12297. {
  12298. if ((character >= 'a' && character <= 'z')
  12299. || (character >= 'A' && character <= 'Z')
  12300. || (character >= '0' && character <= '9'))
  12301. return true;
  12302. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12303. do
  12304. {
  12305. if (((juce_wchar) (uint8) *t) == character)
  12306. return true;
  12307. }
  12308. while (*++t != 0);
  12309. return false;
  12310. }
  12311. void generateLegalCharConstants()
  12312. {
  12313. uint8 n[32];
  12314. zerostruct (n);
  12315. for (int i = 0; i < 256; ++i)
  12316. if (isLegalXmlCharSlow (i))
  12317. n[i >> 3] |= (1 << (i & 7));
  12318. String s;
  12319. for (int i = 0; i < 32; ++i)
  12320. s << (int) n[i] << ", ";
  12321. DBG (s);
  12322. }*/
  12323. bool isLegalXmlChar (const uint32 c) throw()
  12324. {
  12325. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12326. return c < sizeof (legalChars) * 8
  12327. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12328. }
  12329. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12330. {
  12331. String::CharPointerType t (text.getCharPointer());
  12332. for (;;)
  12333. {
  12334. const uint32 character = (uint32) t.getAndAdvance();
  12335. if (character == 0)
  12336. break;
  12337. if (isLegalXmlChar (character))
  12338. {
  12339. outputStream << (char) character;
  12340. }
  12341. else
  12342. {
  12343. switch (character)
  12344. {
  12345. case '&': outputStream << "&amp;"; break;
  12346. case '"': outputStream << "&quot;"; break;
  12347. case '>': outputStream << "&gt;"; break;
  12348. case '<': outputStream << "&lt;"; break;
  12349. case '\n':
  12350. case '\r':
  12351. if (! changeNewLines)
  12352. {
  12353. outputStream << (char) character;
  12354. break;
  12355. }
  12356. // Note: deliberate fall-through here!
  12357. default:
  12358. outputStream << "&#" << ((int) character) << ';';
  12359. break;
  12360. }
  12361. }
  12362. }
  12363. }
  12364. void writeSpaces (OutputStream& out, int numSpaces)
  12365. {
  12366. if (numSpaces > 0)
  12367. {
  12368. const char blanks[] = " ";
  12369. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12370. while (numSpaces > blankSize)
  12371. {
  12372. out.write (blanks, blankSize);
  12373. numSpaces -= blankSize;
  12374. }
  12375. out.write (blanks, numSpaces);
  12376. }
  12377. }
  12378. }
  12379. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12380. const int indentationLevel,
  12381. const int lineWrapLength) const
  12382. {
  12383. using namespace XmlOutputFunctions;
  12384. writeSpaces (outputStream, indentationLevel);
  12385. if (! isTextElement())
  12386. {
  12387. outputStream.writeByte ('<');
  12388. outputStream << tagName;
  12389. {
  12390. const int attIndent = indentationLevel + tagName.length() + 1;
  12391. int lineLen = 0;
  12392. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12393. {
  12394. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12395. {
  12396. outputStream << newLine;
  12397. writeSpaces (outputStream, attIndent);
  12398. lineLen = 0;
  12399. }
  12400. const int64 startPos = outputStream.getPosition();
  12401. outputStream.writeByte (' ');
  12402. outputStream << att->name;
  12403. outputStream.write ("=\"", 2);
  12404. escapeIllegalXmlChars (outputStream, att->value, true);
  12405. outputStream.writeByte ('"');
  12406. lineLen += (int) (outputStream.getPosition() - startPos);
  12407. }
  12408. }
  12409. if (firstChildElement != 0)
  12410. {
  12411. outputStream.writeByte ('>');
  12412. XmlElement* child = firstChildElement;
  12413. bool lastWasTextNode = false;
  12414. while (child != 0)
  12415. {
  12416. if (child->isTextElement())
  12417. {
  12418. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12419. lastWasTextNode = true;
  12420. }
  12421. else
  12422. {
  12423. if (indentationLevel >= 0 && ! lastWasTextNode)
  12424. outputStream << newLine;
  12425. child->writeElementAsText (outputStream,
  12426. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12427. lastWasTextNode = false;
  12428. }
  12429. child = child->getNextElement();
  12430. }
  12431. if (indentationLevel >= 0 && ! lastWasTextNode)
  12432. {
  12433. outputStream << newLine;
  12434. writeSpaces (outputStream, indentationLevel);
  12435. }
  12436. outputStream.write ("</", 2);
  12437. outputStream << tagName;
  12438. outputStream.writeByte ('>');
  12439. }
  12440. else
  12441. {
  12442. outputStream.write ("/>", 2);
  12443. }
  12444. }
  12445. else
  12446. {
  12447. escapeIllegalXmlChars (outputStream, getText(), false);
  12448. }
  12449. }
  12450. const String XmlElement::createDocument (const String& dtdToUse,
  12451. const bool allOnOneLine,
  12452. const bool includeXmlHeader,
  12453. const String& encodingType,
  12454. const int lineWrapLength) const
  12455. {
  12456. MemoryOutputStream mem (2048);
  12457. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12458. return mem.toUTF8();
  12459. }
  12460. void XmlElement::writeToStream (OutputStream& output,
  12461. const String& dtdToUse,
  12462. const bool allOnOneLine,
  12463. const bool includeXmlHeader,
  12464. const String& encodingType,
  12465. const int lineWrapLength) const
  12466. {
  12467. using namespace XmlOutputFunctions;
  12468. if (includeXmlHeader)
  12469. {
  12470. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12471. if (allOnOneLine)
  12472. output.writeByte (' ');
  12473. else
  12474. output << newLine << newLine;
  12475. }
  12476. if (dtdToUse.isNotEmpty())
  12477. {
  12478. output << dtdToUse;
  12479. if (allOnOneLine)
  12480. output.writeByte (' ');
  12481. else
  12482. output << newLine;
  12483. }
  12484. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12485. if (! allOnOneLine)
  12486. output << newLine;
  12487. }
  12488. bool XmlElement::writeToFile (const File& file,
  12489. const String& dtdToUse,
  12490. const String& encodingType,
  12491. const int lineWrapLength) const
  12492. {
  12493. if (file.hasWriteAccess())
  12494. {
  12495. TemporaryFile tempFile (file);
  12496. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12497. if (out != 0)
  12498. {
  12499. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12500. out = 0;
  12501. return tempFile.overwriteTargetFileWithTemporary();
  12502. }
  12503. }
  12504. return false;
  12505. }
  12506. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12507. {
  12508. #if JUCE_DEBUG
  12509. // if debugging, check that the case is actually the same, because
  12510. // valid xml is case-sensitive, and although this lets it pass, it's
  12511. // better not to..
  12512. if (tagName.equalsIgnoreCase (tagNameWanted))
  12513. {
  12514. jassert (tagName == tagNameWanted);
  12515. return true;
  12516. }
  12517. else
  12518. {
  12519. return false;
  12520. }
  12521. #else
  12522. return tagName.equalsIgnoreCase (tagNameWanted);
  12523. #endif
  12524. }
  12525. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12526. {
  12527. XmlElement* e = nextListItem;
  12528. while (e != 0 && ! e->hasTagName (requiredTagName))
  12529. e = e->nextListItem;
  12530. return e;
  12531. }
  12532. int XmlElement::getNumAttributes() const throw()
  12533. {
  12534. return attributes.size();
  12535. }
  12536. const String& XmlElement::getAttributeName (const int index) const throw()
  12537. {
  12538. const XmlAttributeNode* const att = attributes [index];
  12539. return att != 0 ? att->name : String::empty;
  12540. }
  12541. const String& XmlElement::getAttributeValue (const int index) const throw()
  12542. {
  12543. const XmlAttributeNode* const att = attributes [index];
  12544. return att != 0 ? att->value : String::empty;
  12545. }
  12546. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12547. {
  12548. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12549. if (att->hasName (attributeName))
  12550. return true;
  12551. return false;
  12552. }
  12553. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12554. {
  12555. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12556. if (att->hasName (attributeName))
  12557. return att->value;
  12558. return String::empty;
  12559. }
  12560. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12561. {
  12562. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12563. if (att->hasName (attributeName))
  12564. return att->value;
  12565. return defaultReturnValue;
  12566. }
  12567. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12568. {
  12569. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12570. if (att->hasName (attributeName))
  12571. return att->value.getIntValue();
  12572. return defaultReturnValue;
  12573. }
  12574. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12575. {
  12576. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12577. if (att->hasName (attributeName))
  12578. return att->value.getDoubleValue();
  12579. return defaultReturnValue;
  12580. }
  12581. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12582. {
  12583. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12584. {
  12585. if (att->hasName (attributeName))
  12586. {
  12587. juce_wchar firstChar = att->value[0];
  12588. if (CharacterFunctions::isWhitespace (firstChar))
  12589. firstChar = att->value.trimStart() [0];
  12590. return firstChar == '1'
  12591. || firstChar == 't'
  12592. || firstChar == 'y'
  12593. || firstChar == 'T'
  12594. || firstChar == 'Y';
  12595. }
  12596. }
  12597. return defaultReturnValue;
  12598. }
  12599. bool XmlElement::compareAttribute (const String& attributeName,
  12600. const String& stringToCompareAgainst,
  12601. const bool ignoreCase) const throw()
  12602. {
  12603. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12604. if (att->hasName (attributeName))
  12605. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12606. : att->value == stringToCompareAgainst;
  12607. return false;
  12608. }
  12609. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12610. {
  12611. if (attributes == 0)
  12612. {
  12613. attributes = new XmlAttributeNode (attributeName, value);
  12614. }
  12615. else
  12616. {
  12617. XmlAttributeNode* att = attributes;
  12618. for (;;)
  12619. {
  12620. if (att->hasName (attributeName))
  12621. {
  12622. att->value = value;
  12623. break;
  12624. }
  12625. else if (att->nextListItem == 0)
  12626. {
  12627. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12628. break;
  12629. }
  12630. att = att->nextListItem;
  12631. }
  12632. }
  12633. }
  12634. void XmlElement::setAttribute (const String& attributeName, const int number)
  12635. {
  12636. setAttribute (attributeName, String (number));
  12637. }
  12638. void XmlElement::setAttribute (const String& attributeName, const double number)
  12639. {
  12640. setAttribute (attributeName, String (number));
  12641. }
  12642. void XmlElement::removeAttribute (const String& attributeName) throw()
  12643. {
  12644. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12645. while (att->get() != 0)
  12646. {
  12647. if (att->get()->hasName (attributeName))
  12648. {
  12649. delete att->removeNext();
  12650. break;
  12651. }
  12652. att = &(att->get()->nextListItem);
  12653. }
  12654. }
  12655. void XmlElement::removeAllAttributes() throw()
  12656. {
  12657. attributes.deleteAll();
  12658. }
  12659. int XmlElement::getNumChildElements() const throw()
  12660. {
  12661. return firstChildElement.size();
  12662. }
  12663. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12664. {
  12665. return firstChildElement [index].get();
  12666. }
  12667. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12668. {
  12669. XmlElement* child = firstChildElement;
  12670. while (child != 0)
  12671. {
  12672. if (child->hasTagName (childName))
  12673. break;
  12674. child = child->nextListItem;
  12675. }
  12676. return child;
  12677. }
  12678. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12679. {
  12680. if (newNode != 0)
  12681. firstChildElement.append (newNode);
  12682. }
  12683. void XmlElement::insertChildElement (XmlElement* const newNode,
  12684. int indexToInsertAt) throw()
  12685. {
  12686. if (newNode != 0)
  12687. {
  12688. removeChildElement (newNode, false);
  12689. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12690. }
  12691. }
  12692. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12693. {
  12694. XmlElement* const newElement = new XmlElement (childTagName);
  12695. addChildElement (newElement);
  12696. return newElement;
  12697. }
  12698. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12699. XmlElement* const newNode) throw()
  12700. {
  12701. if (newNode != 0)
  12702. {
  12703. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12704. if (p != 0)
  12705. {
  12706. if (currentChildElement != newNode)
  12707. delete p->replaceNext (newNode);
  12708. return true;
  12709. }
  12710. }
  12711. return false;
  12712. }
  12713. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12714. const bool shouldDeleteTheChild) throw()
  12715. {
  12716. if (childToRemove != 0)
  12717. {
  12718. firstChildElement.remove (childToRemove);
  12719. if (shouldDeleteTheChild)
  12720. delete childToRemove;
  12721. }
  12722. }
  12723. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12724. const bool ignoreOrderOfAttributes) const throw()
  12725. {
  12726. if (this != other)
  12727. {
  12728. if (other == 0 || tagName != other->tagName)
  12729. return false;
  12730. if (ignoreOrderOfAttributes)
  12731. {
  12732. int totalAtts = 0;
  12733. const XmlAttributeNode* att = attributes;
  12734. while (att != 0)
  12735. {
  12736. if (! other->compareAttribute (att->name, att->value))
  12737. return false;
  12738. att = att->nextListItem;
  12739. ++totalAtts;
  12740. }
  12741. if (totalAtts != other->getNumAttributes())
  12742. return false;
  12743. }
  12744. else
  12745. {
  12746. const XmlAttributeNode* thisAtt = attributes;
  12747. const XmlAttributeNode* otherAtt = other->attributes;
  12748. for (;;)
  12749. {
  12750. if (thisAtt == 0 || otherAtt == 0)
  12751. {
  12752. if (thisAtt == otherAtt) // both 0, so it's a match
  12753. break;
  12754. return false;
  12755. }
  12756. if (thisAtt->name != otherAtt->name
  12757. || thisAtt->value != otherAtt->value)
  12758. {
  12759. return false;
  12760. }
  12761. thisAtt = thisAtt->nextListItem;
  12762. otherAtt = otherAtt->nextListItem;
  12763. }
  12764. }
  12765. const XmlElement* thisChild = firstChildElement;
  12766. const XmlElement* otherChild = other->firstChildElement;
  12767. for (;;)
  12768. {
  12769. if (thisChild == 0 || otherChild == 0)
  12770. {
  12771. if (thisChild == otherChild) // both 0, so it's a match
  12772. break;
  12773. return false;
  12774. }
  12775. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12776. return false;
  12777. thisChild = thisChild->nextListItem;
  12778. otherChild = otherChild->nextListItem;
  12779. }
  12780. }
  12781. return true;
  12782. }
  12783. void XmlElement::deleteAllChildElements() throw()
  12784. {
  12785. firstChildElement.deleteAll();
  12786. }
  12787. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12788. {
  12789. XmlElement* child = firstChildElement;
  12790. while (child != 0)
  12791. {
  12792. XmlElement* const nextChild = child->nextListItem;
  12793. if (child->hasTagName (name))
  12794. removeChildElement (child, true);
  12795. child = nextChild;
  12796. }
  12797. }
  12798. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12799. {
  12800. return firstChildElement.contains (possibleChild);
  12801. }
  12802. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12803. {
  12804. if (this == elementToLookFor || elementToLookFor == 0)
  12805. return 0;
  12806. XmlElement* child = firstChildElement;
  12807. while (child != 0)
  12808. {
  12809. if (elementToLookFor == child)
  12810. return this;
  12811. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12812. if (found != 0)
  12813. return found;
  12814. child = child->nextListItem;
  12815. }
  12816. return 0;
  12817. }
  12818. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12819. {
  12820. firstChildElement.copyToArray (elems);
  12821. }
  12822. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12823. {
  12824. XmlElement* e = firstChildElement = elems[0];
  12825. for (int i = 1; i < num; ++i)
  12826. {
  12827. e->nextListItem = elems[i];
  12828. e = e->nextListItem;
  12829. }
  12830. e->nextListItem = 0;
  12831. }
  12832. bool XmlElement::isTextElement() const throw()
  12833. {
  12834. return tagName.isEmpty();
  12835. }
  12836. static const String juce_xmltextContentAttributeName ("text");
  12837. const String& XmlElement::getText() const throw()
  12838. {
  12839. jassert (isTextElement()); // you're trying to get the text from an element that
  12840. // isn't actually a text element.. If this contains text sub-nodes, you
  12841. // probably want to use getAllSubText instead.
  12842. return getStringAttribute (juce_xmltextContentAttributeName);
  12843. }
  12844. void XmlElement::setText (const String& newText)
  12845. {
  12846. if (isTextElement())
  12847. setAttribute (juce_xmltextContentAttributeName, newText);
  12848. else
  12849. jassertfalse; // you can only change the text in a text element, not a normal one.
  12850. }
  12851. const String XmlElement::getAllSubText() const
  12852. {
  12853. if (isTextElement())
  12854. return getText();
  12855. String result;
  12856. String::Concatenator concatenator (result);
  12857. const XmlElement* child = firstChildElement;
  12858. while (child != 0)
  12859. {
  12860. concatenator.append (child->getAllSubText());
  12861. child = child->nextListItem;
  12862. }
  12863. return result;
  12864. }
  12865. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12866. const String& defaultReturnValue) const
  12867. {
  12868. const XmlElement* const child = getChildByName (childTagName);
  12869. if (child != 0)
  12870. return child->getAllSubText();
  12871. return defaultReturnValue;
  12872. }
  12873. XmlElement* XmlElement::createTextElement (const String& text)
  12874. {
  12875. XmlElement* const e = new XmlElement ((int) 0);
  12876. e->setAttribute (juce_xmltextContentAttributeName, text);
  12877. return e;
  12878. }
  12879. void XmlElement::addTextElement (const String& text)
  12880. {
  12881. addChildElement (createTextElement (text));
  12882. }
  12883. void XmlElement::deleteAllTextElements() throw()
  12884. {
  12885. XmlElement* child = firstChildElement;
  12886. while (child != 0)
  12887. {
  12888. XmlElement* const next = child->nextListItem;
  12889. if (child->isTextElement())
  12890. removeChildElement (child, true);
  12891. child = next;
  12892. }
  12893. }
  12894. END_JUCE_NAMESPACE
  12895. /*** End of inlined file: juce_XmlElement.cpp ***/
  12896. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12897. BEGIN_JUCE_NAMESPACE
  12898. ReadWriteLock::ReadWriteLock() throw()
  12899. : numWaitingWriters (0),
  12900. numWriters (0),
  12901. writerThreadId (0)
  12902. {
  12903. }
  12904. ReadWriteLock::~ReadWriteLock() throw()
  12905. {
  12906. jassert (readerThreads.size() == 0);
  12907. jassert (numWriters == 0);
  12908. }
  12909. void ReadWriteLock::enterRead() const throw()
  12910. {
  12911. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12912. const ScopedLock sl (accessLock);
  12913. for (;;)
  12914. {
  12915. jassert (readerThreads.size() % 2 == 0);
  12916. int i;
  12917. for (i = 0; i < readerThreads.size(); i += 2)
  12918. if (readerThreads.getUnchecked(i) == threadId)
  12919. break;
  12920. if (i < readerThreads.size()
  12921. || numWriters + numWaitingWriters == 0
  12922. || (threadId == writerThreadId && numWriters > 0))
  12923. {
  12924. if (i < readerThreads.size())
  12925. {
  12926. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12927. }
  12928. else
  12929. {
  12930. readerThreads.add (threadId);
  12931. readerThreads.add ((Thread::ThreadID) 1);
  12932. }
  12933. return;
  12934. }
  12935. const ScopedUnlock ul (accessLock);
  12936. waitEvent.wait (100);
  12937. }
  12938. }
  12939. void ReadWriteLock::exitRead() const throw()
  12940. {
  12941. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12942. const ScopedLock sl (accessLock);
  12943. for (int i = 0; i < readerThreads.size(); i += 2)
  12944. {
  12945. if (readerThreads.getUnchecked(i) == threadId)
  12946. {
  12947. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12948. if (newCount == 0)
  12949. {
  12950. readerThreads.removeRange (i, 2);
  12951. waitEvent.signal();
  12952. }
  12953. else
  12954. {
  12955. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12956. }
  12957. return;
  12958. }
  12959. }
  12960. jassertfalse; // unlocking a lock that wasn't locked..
  12961. }
  12962. void ReadWriteLock::enterWrite() const throw()
  12963. {
  12964. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12965. const ScopedLock sl (accessLock);
  12966. for (;;)
  12967. {
  12968. if (readerThreads.size() + numWriters == 0
  12969. || threadId == writerThreadId
  12970. || (readerThreads.size() == 2
  12971. && readerThreads.getUnchecked(0) == threadId))
  12972. {
  12973. writerThreadId = threadId;
  12974. ++numWriters;
  12975. break;
  12976. }
  12977. ++numWaitingWriters;
  12978. accessLock.exit();
  12979. waitEvent.wait (100);
  12980. accessLock.enter();
  12981. --numWaitingWriters;
  12982. }
  12983. }
  12984. bool ReadWriteLock::tryEnterWrite() const throw()
  12985. {
  12986. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12987. const ScopedLock sl (accessLock);
  12988. if (readerThreads.size() + numWriters == 0
  12989. || threadId == writerThreadId
  12990. || (readerThreads.size() == 2
  12991. && readerThreads.getUnchecked(0) == threadId))
  12992. {
  12993. writerThreadId = threadId;
  12994. ++numWriters;
  12995. return true;
  12996. }
  12997. return false;
  12998. }
  12999. void ReadWriteLock::exitWrite() const throw()
  13000. {
  13001. const ScopedLock sl (accessLock);
  13002. // check this thread actually had the lock..
  13003. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13004. if (--numWriters == 0)
  13005. {
  13006. writerThreadId = 0;
  13007. waitEvent.signal();
  13008. }
  13009. }
  13010. END_JUCE_NAMESPACE
  13011. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13012. /*** Start of inlined file: juce_Thread.cpp ***/
  13013. BEGIN_JUCE_NAMESPACE
  13014. class RunningThreadsList
  13015. {
  13016. public:
  13017. RunningThreadsList()
  13018. {
  13019. }
  13020. void add (Thread* const thread)
  13021. {
  13022. const ScopedLock sl (lock);
  13023. jassert (! threads.contains (thread));
  13024. threads.add (thread);
  13025. }
  13026. void remove (Thread* const thread)
  13027. {
  13028. const ScopedLock sl (lock);
  13029. jassert (threads.contains (thread));
  13030. threads.removeValue (thread);
  13031. }
  13032. int size() const throw()
  13033. {
  13034. return threads.size();
  13035. }
  13036. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13037. {
  13038. const ScopedLock sl (lock);
  13039. for (int i = threads.size(); --i >= 0;)
  13040. {
  13041. Thread* const t = threads.getUnchecked(i);
  13042. if (t->getThreadId() == targetID)
  13043. return t;
  13044. }
  13045. return 0;
  13046. }
  13047. void stopAll (const int timeOutMilliseconds)
  13048. {
  13049. signalAllThreadsToStop();
  13050. for (;;)
  13051. {
  13052. Thread* firstThread = getFirstThread();
  13053. if (firstThread != 0)
  13054. firstThread->stopThread (timeOutMilliseconds);
  13055. else
  13056. break;
  13057. }
  13058. }
  13059. static RunningThreadsList& getInstance()
  13060. {
  13061. static RunningThreadsList runningThreads;
  13062. return runningThreads;
  13063. }
  13064. private:
  13065. Array<Thread*> threads;
  13066. CriticalSection lock;
  13067. void signalAllThreadsToStop()
  13068. {
  13069. const ScopedLock sl (lock);
  13070. for (int i = threads.size(); --i >= 0;)
  13071. threads.getUnchecked(i)->signalThreadShouldExit();
  13072. }
  13073. Thread* getFirstThread() const
  13074. {
  13075. const ScopedLock sl (lock);
  13076. return threads.getFirst();
  13077. }
  13078. };
  13079. void Thread::threadEntryPoint()
  13080. {
  13081. RunningThreadsList::getInstance().add (this);
  13082. JUCE_TRY
  13083. {
  13084. if (threadName_.isNotEmpty())
  13085. setCurrentThreadName (threadName_);
  13086. if (startSuspensionEvent_.wait (10000))
  13087. {
  13088. jassert (getCurrentThreadId() == threadId_);
  13089. if (affinityMask_ != 0)
  13090. setCurrentThreadAffinityMask (affinityMask_);
  13091. run();
  13092. }
  13093. }
  13094. JUCE_CATCH_ALL_ASSERT
  13095. RunningThreadsList::getInstance().remove (this);
  13096. closeThreadHandle();
  13097. }
  13098. // used to wrap the incoming call from the platform-specific code
  13099. void JUCE_API juce_threadEntryPoint (void* userData)
  13100. {
  13101. static_cast <Thread*> (userData)->threadEntryPoint();
  13102. }
  13103. Thread::Thread (const String& threadName)
  13104. : threadName_ (threadName),
  13105. threadHandle_ (0),
  13106. threadId_ (0),
  13107. threadPriority_ (5),
  13108. affinityMask_ (0),
  13109. threadShouldExit_ (false)
  13110. {
  13111. }
  13112. Thread::~Thread()
  13113. {
  13114. /* If your thread class's destructor has been called without first stopping the thread, that
  13115. means that this partially destructed object is still performing some work - and that's
  13116. probably a Bad Thing!
  13117. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13118. your subclass's destructor.
  13119. */
  13120. jassert (! isThreadRunning());
  13121. stopThread (100);
  13122. }
  13123. void Thread::startThread()
  13124. {
  13125. const ScopedLock sl (startStopLock);
  13126. threadShouldExit_ = false;
  13127. if (threadHandle_ == 0)
  13128. {
  13129. launchThread();
  13130. setThreadPriority (threadHandle_, threadPriority_);
  13131. startSuspensionEvent_.signal();
  13132. }
  13133. }
  13134. void Thread::startThread (const int priority)
  13135. {
  13136. const ScopedLock sl (startStopLock);
  13137. if (threadHandle_ == 0)
  13138. {
  13139. threadPriority_ = priority;
  13140. startThread();
  13141. }
  13142. else
  13143. {
  13144. setPriority (priority);
  13145. }
  13146. }
  13147. bool Thread::isThreadRunning() const
  13148. {
  13149. return threadHandle_ != 0;
  13150. }
  13151. void Thread::signalThreadShouldExit()
  13152. {
  13153. threadShouldExit_ = true;
  13154. }
  13155. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13156. {
  13157. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13158. jassert (getThreadId() != getCurrentThreadId());
  13159. const int sleepMsPerIteration = 5;
  13160. int count = timeOutMilliseconds / sleepMsPerIteration;
  13161. while (isThreadRunning())
  13162. {
  13163. if (timeOutMilliseconds > 0 && --count < 0)
  13164. return false;
  13165. sleep (sleepMsPerIteration);
  13166. }
  13167. return true;
  13168. }
  13169. void Thread::stopThread (const int timeOutMilliseconds)
  13170. {
  13171. // agh! You can't stop the thread that's calling this method! How on earth
  13172. // would that work??
  13173. jassert (getCurrentThreadId() != getThreadId());
  13174. const ScopedLock sl (startStopLock);
  13175. if (isThreadRunning())
  13176. {
  13177. signalThreadShouldExit();
  13178. notify();
  13179. if (timeOutMilliseconds != 0)
  13180. waitForThreadToExit (timeOutMilliseconds);
  13181. if (isThreadRunning())
  13182. {
  13183. // very bad karma if this point is reached, as there are bound to be
  13184. // locks and events left in silly states when a thread is killed by force..
  13185. jassertfalse;
  13186. Logger::writeToLog ("!! killing thread by force !!");
  13187. killThread();
  13188. RunningThreadsList::getInstance().remove (this);
  13189. threadHandle_ = 0;
  13190. threadId_ = 0;
  13191. }
  13192. }
  13193. }
  13194. bool Thread::setPriority (const int priority)
  13195. {
  13196. const ScopedLock sl (startStopLock);
  13197. if (setThreadPriority (threadHandle_, priority))
  13198. {
  13199. threadPriority_ = priority;
  13200. return true;
  13201. }
  13202. return false;
  13203. }
  13204. bool Thread::setCurrentThreadPriority (const int priority)
  13205. {
  13206. return setThreadPriority (0, priority);
  13207. }
  13208. void Thread::setAffinityMask (const uint32 affinityMask)
  13209. {
  13210. affinityMask_ = affinityMask;
  13211. }
  13212. bool Thread::wait (const int timeOutMilliseconds) const
  13213. {
  13214. return defaultEvent_.wait (timeOutMilliseconds);
  13215. }
  13216. void Thread::notify() const
  13217. {
  13218. defaultEvent_.signal();
  13219. }
  13220. int Thread::getNumRunningThreads()
  13221. {
  13222. return RunningThreadsList::getInstance().size();
  13223. }
  13224. Thread* Thread::getCurrentThread()
  13225. {
  13226. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13227. }
  13228. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13229. {
  13230. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13231. }
  13232. END_JUCE_NAMESPACE
  13233. /*** End of inlined file: juce_Thread.cpp ***/
  13234. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13235. BEGIN_JUCE_NAMESPACE
  13236. ThreadPoolJob::ThreadPoolJob (const String& name)
  13237. : jobName (name),
  13238. pool (0),
  13239. shouldStop (false),
  13240. isActive (false),
  13241. shouldBeDeleted (false)
  13242. {
  13243. }
  13244. ThreadPoolJob::~ThreadPoolJob()
  13245. {
  13246. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13247. // to remove it first!
  13248. jassert (pool == 0 || ! pool->contains (this));
  13249. }
  13250. const String ThreadPoolJob::getJobName() const
  13251. {
  13252. return jobName;
  13253. }
  13254. void ThreadPoolJob::setJobName (const String& newName)
  13255. {
  13256. jobName = newName;
  13257. }
  13258. void ThreadPoolJob::signalJobShouldExit()
  13259. {
  13260. shouldStop = true;
  13261. }
  13262. class ThreadPool::ThreadPoolThread : public Thread
  13263. {
  13264. public:
  13265. ThreadPoolThread (ThreadPool& pool_)
  13266. : Thread ("Pool"),
  13267. pool (pool_),
  13268. busy (false)
  13269. {
  13270. }
  13271. void run()
  13272. {
  13273. while (! threadShouldExit())
  13274. {
  13275. if (! pool.runNextJob())
  13276. wait (500);
  13277. }
  13278. }
  13279. private:
  13280. ThreadPool& pool;
  13281. bool volatile busy;
  13282. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13283. };
  13284. ThreadPool::ThreadPool (const int numThreads,
  13285. const bool startThreadsOnlyWhenNeeded,
  13286. const int stopThreadsWhenNotUsedTimeoutMs)
  13287. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13288. priority (5)
  13289. {
  13290. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13291. for (int i = jmax (1, numThreads); --i >= 0;)
  13292. threads.add (new ThreadPoolThread (*this));
  13293. if (! startThreadsOnlyWhenNeeded)
  13294. for (int i = threads.size(); --i >= 0;)
  13295. threads.getUnchecked(i)->startThread (priority);
  13296. }
  13297. ThreadPool::~ThreadPool()
  13298. {
  13299. removeAllJobs (true, 4000);
  13300. int i;
  13301. for (i = threads.size(); --i >= 0;)
  13302. threads.getUnchecked(i)->signalThreadShouldExit();
  13303. for (i = threads.size(); --i >= 0;)
  13304. threads.getUnchecked(i)->stopThread (500);
  13305. }
  13306. void ThreadPool::addJob (ThreadPoolJob* const job)
  13307. {
  13308. jassert (job != 0);
  13309. jassert (job->pool == 0);
  13310. if (job->pool == 0)
  13311. {
  13312. job->pool = this;
  13313. job->shouldStop = false;
  13314. job->isActive = false;
  13315. {
  13316. const ScopedLock sl (lock);
  13317. jobs.add (job);
  13318. int numRunning = 0;
  13319. for (int i = threads.size(); --i >= 0;)
  13320. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13321. ++numRunning;
  13322. if (numRunning < threads.size())
  13323. {
  13324. bool startedOne = false;
  13325. int n = 1000;
  13326. while (--n >= 0 && ! startedOne)
  13327. {
  13328. for (int i = threads.size(); --i >= 0;)
  13329. {
  13330. if (! threads.getUnchecked(i)->isThreadRunning())
  13331. {
  13332. threads.getUnchecked(i)->startThread (priority);
  13333. startedOne = true;
  13334. break;
  13335. }
  13336. }
  13337. if (! startedOne)
  13338. Thread::sleep (2);
  13339. }
  13340. }
  13341. }
  13342. for (int i = threads.size(); --i >= 0;)
  13343. threads.getUnchecked(i)->notify();
  13344. }
  13345. }
  13346. int ThreadPool::getNumJobs() const
  13347. {
  13348. return jobs.size();
  13349. }
  13350. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13351. {
  13352. const ScopedLock sl (lock);
  13353. return jobs [index];
  13354. }
  13355. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13356. {
  13357. const ScopedLock sl (lock);
  13358. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13359. }
  13360. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13361. {
  13362. const ScopedLock sl (lock);
  13363. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13364. }
  13365. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13366. const int timeOutMs) const
  13367. {
  13368. if (job != 0)
  13369. {
  13370. const uint32 start = Time::getMillisecondCounter();
  13371. while (contains (job))
  13372. {
  13373. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13374. return false;
  13375. jobFinishedSignal.wait (2);
  13376. }
  13377. }
  13378. return true;
  13379. }
  13380. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13381. const bool interruptIfRunning,
  13382. const int timeOutMs)
  13383. {
  13384. bool dontWait = true;
  13385. if (job != 0)
  13386. {
  13387. const ScopedLock sl (lock);
  13388. if (jobs.contains (job))
  13389. {
  13390. if (job->isActive)
  13391. {
  13392. if (interruptIfRunning)
  13393. job->signalJobShouldExit();
  13394. dontWait = false;
  13395. }
  13396. else
  13397. {
  13398. jobs.removeValue (job);
  13399. job->pool = 0;
  13400. }
  13401. }
  13402. }
  13403. return dontWait || waitForJobToFinish (job, timeOutMs);
  13404. }
  13405. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13406. const int timeOutMs,
  13407. const bool deleteInactiveJobs,
  13408. ThreadPool::JobSelector* selectedJobsToRemove)
  13409. {
  13410. Array <ThreadPoolJob*> jobsToWaitFor;
  13411. {
  13412. const ScopedLock sl (lock);
  13413. for (int i = jobs.size(); --i >= 0;)
  13414. {
  13415. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13416. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13417. {
  13418. if (job->isActive)
  13419. {
  13420. jobsToWaitFor.add (job);
  13421. if (interruptRunningJobs)
  13422. job->signalJobShouldExit();
  13423. }
  13424. else
  13425. {
  13426. jobs.remove (i);
  13427. if (deleteInactiveJobs)
  13428. delete job;
  13429. else
  13430. job->pool = 0;
  13431. }
  13432. }
  13433. }
  13434. }
  13435. const uint32 start = Time::getMillisecondCounter();
  13436. for (;;)
  13437. {
  13438. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13439. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13440. jobsToWaitFor.remove (i);
  13441. if (jobsToWaitFor.size() == 0)
  13442. break;
  13443. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13444. return false;
  13445. jobFinishedSignal.wait (20);
  13446. }
  13447. return true;
  13448. }
  13449. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13450. {
  13451. StringArray s;
  13452. const ScopedLock sl (lock);
  13453. for (int i = 0; i < jobs.size(); ++i)
  13454. {
  13455. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13456. if (job->isActive || ! onlyReturnActiveJobs)
  13457. s.add (job->getJobName());
  13458. }
  13459. return s;
  13460. }
  13461. bool ThreadPool::setThreadPriorities (const int newPriority)
  13462. {
  13463. bool ok = true;
  13464. if (priority != newPriority)
  13465. {
  13466. priority = newPriority;
  13467. for (int i = threads.size(); --i >= 0;)
  13468. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13469. ok = false;
  13470. }
  13471. return ok;
  13472. }
  13473. bool ThreadPool::runNextJob()
  13474. {
  13475. ThreadPoolJob* job = 0;
  13476. {
  13477. const ScopedLock sl (lock);
  13478. for (int i = 0; i < jobs.size(); ++i)
  13479. {
  13480. job = jobs[i];
  13481. if (job != 0 && ! (job->isActive || job->shouldStop))
  13482. break;
  13483. job = 0;
  13484. }
  13485. if (job != 0)
  13486. job->isActive = true;
  13487. }
  13488. if (job != 0)
  13489. {
  13490. JUCE_TRY
  13491. {
  13492. ThreadPoolJob::JobStatus result = job->runJob();
  13493. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13494. const ScopedLock sl (lock);
  13495. if (jobs.contains (job))
  13496. {
  13497. job->isActive = false;
  13498. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13499. {
  13500. job->pool = 0;
  13501. job->shouldStop = true;
  13502. jobs.removeValue (job);
  13503. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13504. delete job;
  13505. jobFinishedSignal.signal();
  13506. }
  13507. else
  13508. {
  13509. // move the job to the end of the queue if it wants another go
  13510. jobs.move (jobs.indexOf (job), -1);
  13511. }
  13512. }
  13513. }
  13514. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13515. catch (...)
  13516. {
  13517. const ScopedLock sl (lock);
  13518. jobs.removeValue (job);
  13519. }
  13520. #endif
  13521. }
  13522. else
  13523. {
  13524. if (threadStopTimeout > 0
  13525. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13526. {
  13527. const ScopedLock sl (lock);
  13528. if (jobs.size() == 0)
  13529. for (int i = threads.size(); --i >= 0;)
  13530. threads.getUnchecked(i)->signalThreadShouldExit();
  13531. }
  13532. else
  13533. {
  13534. return false;
  13535. }
  13536. }
  13537. return true;
  13538. }
  13539. END_JUCE_NAMESPACE
  13540. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13541. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13542. BEGIN_JUCE_NAMESPACE
  13543. TimeSliceThread::TimeSliceThread (const String& threadName)
  13544. : Thread (threadName),
  13545. clientBeingCalled (0)
  13546. {
  13547. }
  13548. TimeSliceThread::~TimeSliceThread()
  13549. {
  13550. stopThread (2000);
  13551. }
  13552. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client, int millisecondsBeforeStarting)
  13553. {
  13554. if (client != 0)
  13555. {
  13556. const ScopedLock sl (listLock);
  13557. client->nextCallTime = Time::getCurrentTime() + RelativeTime::milliseconds (millisecondsBeforeStarting);
  13558. clients.addIfNotAlreadyThere (client);
  13559. notify();
  13560. }
  13561. }
  13562. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13563. {
  13564. const ScopedLock sl1 (listLock);
  13565. // if there's a chance we're in the middle of calling this client, we need to
  13566. // also lock the outer lock..
  13567. if (clientBeingCalled == client)
  13568. {
  13569. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13570. const ScopedLock sl2 (callbackLock);
  13571. const ScopedLock sl3 (listLock);
  13572. clients.removeValue (client);
  13573. }
  13574. else
  13575. {
  13576. clients.removeValue (client);
  13577. }
  13578. }
  13579. int TimeSliceThread::getNumClients() const
  13580. {
  13581. return clients.size();
  13582. }
  13583. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13584. {
  13585. const ScopedLock sl (listLock);
  13586. return clients [i];
  13587. }
  13588. TimeSliceClient* TimeSliceThread::getNextClient (int index) const
  13589. {
  13590. Time soonest;
  13591. TimeSliceClient* client = 0;
  13592. for (int i = clients.size(); --i >= 0;)
  13593. {
  13594. TimeSliceClient* const c = clients.getUnchecked ((i + index) % clients.size());
  13595. if (client == 0 || c->nextCallTime < soonest)
  13596. {
  13597. client = c;
  13598. soonest = c->nextCallTime;
  13599. }
  13600. }
  13601. return client;
  13602. }
  13603. void TimeSliceThread::run()
  13604. {
  13605. int index = 0;
  13606. while (! threadShouldExit())
  13607. {
  13608. int timeToWait = 500;
  13609. {
  13610. Time nextClientTime;
  13611. {
  13612. const ScopedLock sl2 (listLock);
  13613. index = clients.size() > 0 ? ((index + 1) % clients.size()) : 0;
  13614. TimeSliceClient* const firstClient = getNextClient (index);
  13615. if (firstClient != 0)
  13616. nextClientTime = firstClient->nextCallTime;
  13617. }
  13618. const Time now (Time::getCurrentTime());
  13619. if (nextClientTime > now)
  13620. {
  13621. timeToWait = (int) jmin ((int64) 500, (nextClientTime - now).inMilliseconds());
  13622. }
  13623. else
  13624. {
  13625. timeToWait = index == 0 ? 1 : 0;
  13626. const ScopedLock sl (callbackLock);
  13627. {
  13628. const ScopedLock sl2 (listLock);
  13629. clientBeingCalled = getNextClient (index);
  13630. }
  13631. if (clientBeingCalled != 0)
  13632. {
  13633. const int msUntilNextCall = clientBeingCalled->useTimeSlice();
  13634. const ScopedLock sl2 (listLock);
  13635. if (msUntilNextCall >= 0)
  13636. clientBeingCalled->nextCallTime += RelativeTime::milliseconds (msUntilNextCall);
  13637. else
  13638. clients.removeValue (clientBeingCalled);
  13639. clientBeingCalled = 0;
  13640. }
  13641. }
  13642. }
  13643. if (timeToWait > 0)
  13644. wait (timeToWait);
  13645. }
  13646. }
  13647. END_JUCE_NAMESPACE
  13648. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13649. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13650. BEGIN_JUCE_NAMESPACE
  13651. DeletedAtShutdown::DeletedAtShutdown()
  13652. {
  13653. const ScopedLock sl (getLock());
  13654. getObjects().add (this);
  13655. }
  13656. DeletedAtShutdown::~DeletedAtShutdown()
  13657. {
  13658. const ScopedLock sl (getLock());
  13659. getObjects().removeValue (this);
  13660. }
  13661. void DeletedAtShutdown::deleteAll()
  13662. {
  13663. // make a local copy of the array, so it can't get into a loop if something
  13664. // creates another DeletedAtShutdown object during its destructor.
  13665. Array <DeletedAtShutdown*> localCopy;
  13666. {
  13667. const ScopedLock sl (getLock());
  13668. localCopy = getObjects();
  13669. }
  13670. for (int i = localCopy.size(); --i >= 0;)
  13671. {
  13672. JUCE_TRY
  13673. {
  13674. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13675. // double-check that it's not already been deleted during another object's destructor.
  13676. {
  13677. const ScopedLock sl (getLock());
  13678. if (! getObjects().contains (deletee))
  13679. deletee = 0;
  13680. }
  13681. delete deletee;
  13682. }
  13683. JUCE_CATCH_EXCEPTION
  13684. }
  13685. // if no objects got re-created during shutdown, this should have been emptied by their
  13686. // destructors
  13687. jassert (getObjects().size() == 0);
  13688. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13689. }
  13690. CriticalSection& DeletedAtShutdown::getLock()
  13691. {
  13692. static CriticalSection lock;
  13693. return lock;
  13694. }
  13695. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13696. {
  13697. static Array <DeletedAtShutdown*> objects;
  13698. return objects;
  13699. }
  13700. END_JUCE_NAMESPACE
  13701. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13702. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13703. BEGIN_JUCE_NAMESPACE
  13704. UnitTest::UnitTest (const String& name_)
  13705. : name (name_), runner (0)
  13706. {
  13707. getAllTests().add (this);
  13708. }
  13709. UnitTest::~UnitTest()
  13710. {
  13711. getAllTests().removeValue (this);
  13712. }
  13713. Array<UnitTest*>& UnitTest::getAllTests()
  13714. {
  13715. static Array<UnitTest*> tests;
  13716. return tests;
  13717. }
  13718. void UnitTest::initialise() {}
  13719. void UnitTest::shutdown() {}
  13720. void UnitTest::performTest (UnitTestRunner* const runner_)
  13721. {
  13722. jassert (runner_ != 0);
  13723. runner = runner_;
  13724. initialise();
  13725. runTest();
  13726. shutdown();
  13727. }
  13728. void UnitTest::logMessage (const String& message)
  13729. {
  13730. runner->logMessage (message);
  13731. }
  13732. void UnitTest::beginTest (const String& testName)
  13733. {
  13734. runner->beginNewTest (this, testName);
  13735. }
  13736. void UnitTest::expect (const bool result, const String& failureMessage)
  13737. {
  13738. if (result)
  13739. runner->addPass();
  13740. else
  13741. runner->addFail (failureMessage);
  13742. }
  13743. UnitTestRunner::UnitTestRunner()
  13744. : currentTest (0), assertOnFailure (false)
  13745. {
  13746. }
  13747. UnitTestRunner::~UnitTestRunner()
  13748. {
  13749. }
  13750. int UnitTestRunner::getNumResults() const throw()
  13751. {
  13752. return results.size();
  13753. }
  13754. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  13755. {
  13756. return results [index];
  13757. }
  13758. void UnitTestRunner::resultsUpdated()
  13759. {
  13760. }
  13761. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  13762. {
  13763. results.clear();
  13764. assertOnFailure = assertOnFailure_;
  13765. resultsUpdated();
  13766. for (int i = 0; i < tests.size(); ++i)
  13767. {
  13768. try
  13769. {
  13770. tests.getUnchecked(i)->performTest (this);
  13771. }
  13772. catch (...)
  13773. {
  13774. addFail ("An unhandled exception was thrown!");
  13775. }
  13776. }
  13777. endTest();
  13778. }
  13779. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  13780. {
  13781. runTests (UnitTest::getAllTests(), assertOnFailure_);
  13782. }
  13783. void UnitTestRunner::logMessage (const String& message)
  13784. {
  13785. Logger::writeToLog (message);
  13786. }
  13787. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  13788. {
  13789. endTest();
  13790. currentTest = test;
  13791. TestResult* const r = new TestResult();
  13792. r->unitTestName = test->getName();
  13793. r->subcategoryName = subCategory;
  13794. r->passes = 0;
  13795. r->failures = 0;
  13796. results.add (r);
  13797. logMessage ("-----------------------------------------------------------------");
  13798. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  13799. resultsUpdated();
  13800. }
  13801. void UnitTestRunner::endTest()
  13802. {
  13803. if (results.size() > 0)
  13804. {
  13805. TestResult* const r = results.getLast();
  13806. if (r->failures > 0)
  13807. {
  13808. String m ("FAILED!!");
  13809. m << r->failures << (r->failures == 1 ? "test" : "tests")
  13810. << " failed, out of a total of " << (r->passes + r->failures);
  13811. logMessage (String::empty);
  13812. logMessage (m);
  13813. logMessage (String::empty);
  13814. }
  13815. else
  13816. {
  13817. logMessage ("All tests completed successfully");
  13818. }
  13819. }
  13820. }
  13821. void UnitTestRunner::addPass()
  13822. {
  13823. {
  13824. const ScopedLock sl (results.getLock());
  13825. TestResult* const r = results.getLast();
  13826. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13827. r->passes++;
  13828. String message ("Test ");
  13829. message << (r->failures + r->passes) << " passed";
  13830. logMessage (message);
  13831. }
  13832. resultsUpdated();
  13833. }
  13834. void UnitTestRunner::addFail (const String& failureMessage)
  13835. {
  13836. {
  13837. const ScopedLock sl (results.getLock());
  13838. TestResult* const r = results.getLast();
  13839. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13840. r->failures++;
  13841. String message ("!!! Test ");
  13842. message << (r->failures + r->passes) << " failed";
  13843. if (failureMessage.isNotEmpty())
  13844. message << ": " << failureMessage;
  13845. r->messages.add (message);
  13846. logMessage (message);
  13847. }
  13848. resultsUpdated();
  13849. if (assertOnFailure) { jassertfalse }
  13850. }
  13851. END_JUCE_NAMESPACE
  13852. /*** End of inlined file: juce_UnitTest.cpp ***/
  13853. #endif
  13854. #if JUCE_BUILD_MISC
  13855. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13856. BEGIN_JUCE_NAMESPACE
  13857. class ValueTree::SetPropertyAction : public UndoableAction
  13858. {
  13859. public:
  13860. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13861. const var& newValue_, const var& oldValue_,
  13862. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13863. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13864. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13865. {
  13866. }
  13867. bool perform()
  13868. {
  13869. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13870. if (isDeletingProperty)
  13871. target->removeProperty (name, 0);
  13872. else
  13873. target->setProperty (name, newValue, 0);
  13874. return true;
  13875. }
  13876. bool undo()
  13877. {
  13878. if (isAddingNewProperty)
  13879. target->removeProperty (name, 0);
  13880. else
  13881. target->setProperty (name, oldValue, 0);
  13882. return true;
  13883. }
  13884. int getSizeInUnits()
  13885. {
  13886. return (int) sizeof (*this); //xxx should be more accurate
  13887. }
  13888. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13889. {
  13890. if (! (isAddingNewProperty || isDeletingProperty))
  13891. {
  13892. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13893. if (next != 0 && next->target == target && next->name == name
  13894. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13895. {
  13896. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13897. }
  13898. }
  13899. return 0;
  13900. }
  13901. private:
  13902. const SharedObjectPtr target;
  13903. const Identifier name;
  13904. const var newValue;
  13905. var oldValue;
  13906. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13907. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  13908. };
  13909. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13910. {
  13911. public:
  13912. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13913. const SharedObjectPtr& newChild_)
  13914. : target (target_),
  13915. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13916. childIndex (childIndex_),
  13917. isDeleting (newChild_ == 0)
  13918. {
  13919. jassert (child != 0);
  13920. }
  13921. bool perform()
  13922. {
  13923. if (isDeleting)
  13924. target->removeChild (childIndex, 0);
  13925. else
  13926. target->addChild (child, childIndex, 0);
  13927. return true;
  13928. }
  13929. bool undo()
  13930. {
  13931. if (isDeleting)
  13932. {
  13933. target->addChild (child, childIndex, 0);
  13934. }
  13935. else
  13936. {
  13937. // If you hit this, it seems that your object's state is getting confused - probably
  13938. // because you've interleaved some undoable and non-undoable operations?
  13939. jassert (childIndex < target->children.size());
  13940. target->removeChild (childIndex, 0);
  13941. }
  13942. return true;
  13943. }
  13944. int getSizeInUnits()
  13945. {
  13946. return (int) sizeof (*this); //xxx should be more accurate
  13947. }
  13948. private:
  13949. const SharedObjectPtr target, child;
  13950. const int childIndex;
  13951. const bool isDeleting;
  13952. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  13953. };
  13954. class ValueTree::MoveChildAction : public UndoableAction
  13955. {
  13956. public:
  13957. MoveChildAction (const SharedObjectPtr& parent_,
  13958. const int startIndex_, const int endIndex_)
  13959. : parent (parent_),
  13960. startIndex (startIndex_),
  13961. endIndex (endIndex_)
  13962. {
  13963. }
  13964. bool perform()
  13965. {
  13966. parent->moveChild (startIndex, endIndex, 0);
  13967. return true;
  13968. }
  13969. bool undo()
  13970. {
  13971. parent->moveChild (endIndex, startIndex, 0);
  13972. return true;
  13973. }
  13974. int getSizeInUnits()
  13975. {
  13976. return (int) sizeof (*this); //xxx should be more accurate
  13977. }
  13978. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13979. {
  13980. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13981. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13982. return new MoveChildAction (parent, startIndex, next->endIndex);
  13983. return 0;
  13984. }
  13985. private:
  13986. const SharedObjectPtr parent;
  13987. const int startIndex, endIndex;
  13988. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  13989. };
  13990. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13991. : type (type_), parent (0)
  13992. {
  13993. }
  13994. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13995. : type (other.type), properties (other.properties), parent (0)
  13996. {
  13997. for (int i = 0; i < other.children.size(); ++i)
  13998. {
  13999. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14000. child->parent = this;
  14001. children.add (child);
  14002. }
  14003. }
  14004. ValueTree::SharedObject::~SharedObject()
  14005. {
  14006. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14007. for (int i = children.size(); --i >= 0;)
  14008. {
  14009. const SharedObjectPtr c (children.getUnchecked(i));
  14010. c->parent = 0;
  14011. children.remove (i);
  14012. c->sendParentChangeMessage();
  14013. }
  14014. }
  14015. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14016. {
  14017. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14018. {
  14019. ValueTree* const v = valueTreesWithListeners[i];
  14020. if (v != 0)
  14021. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14022. }
  14023. }
  14024. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14025. {
  14026. ValueTree tree (this);
  14027. ValueTree::SharedObject* t = this;
  14028. while (t != 0)
  14029. {
  14030. t->sendPropertyChangeMessage (tree, property);
  14031. t = t->parent;
  14032. }
  14033. }
  14034. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree& tree, ValueTree& child)
  14035. {
  14036. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14037. {
  14038. ValueTree* const v = valueTreesWithListeners[i];
  14039. if (v != 0)
  14040. v->listeners.call (&ValueTree::Listener::valueTreeChildAdded, tree, child);
  14041. }
  14042. }
  14043. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree child)
  14044. {
  14045. ValueTree tree (this);
  14046. ValueTree::SharedObject* t = this;
  14047. while (t != 0)
  14048. {
  14049. t->sendChildAddedMessage (tree, child);
  14050. t = t->parent;
  14051. }
  14052. }
  14053. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree& tree, ValueTree& child)
  14054. {
  14055. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14056. {
  14057. ValueTree* const v = valueTreesWithListeners[i];
  14058. if (v != 0)
  14059. v->listeners.call (&ValueTree::Listener::valueTreeChildRemoved, tree, child);
  14060. }
  14061. }
  14062. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree child)
  14063. {
  14064. ValueTree tree (this);
  14065. ValueTree::SharedObject* t = this;
  14066. while (t != 0)
  14067. {
  14068. t->sendChildRemovedMessage (tree, child);
  14069. t = t->parent;
  14070. }
  14071. }
  14072. void ValueTree::SharedObject::sendChildOrderChangedMessage (ValueTree& tree)
  14073. {
  14074. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14075. {
  14076. ValueTree* const v = valueTreesWithListeners[i];
  14077. if (v != 0)
  14078. v->listeners.call (&ValueTree::Listener::valueTreeChildOrderChanged, tree);
  14079. }
  14080. }
  14081. void ValueTree::SharedObject::sendChildOrderChangedMessage()
  14082. {
  14083. ValueTree tree (this);
  14084. ValueTree::SharedObject* t = this;
  14085. while (t != 0)
  14086. {
  14087. t->sendChildOrderChangedMessage (tree);
  14088. t = t->parent;
  14089. }
  14090. }
  14091. void ValueTree::SharedObject::sendParentChangeMessage()
  14092. {
  14093. ValueTree tree (this);
  14094. int i;
  14095. for (i = children.size(); --i >= 0;)
  14096. {
  14097. SharedObject* const t = children[i];
  14098. if (t != 0)
  14099. t->sendParentChangeMessage();
  14100. }
  14101. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14102. {
  14103. ValueTree* const v = valueTreesWithListeners[i];
  14104. if (v != 0)
  14105. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14106. }
  14107. }
  14108. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14109. {
  14110. return properties [name];
  14111. }
  14112. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14113. {
  14114. return properties.getWithDefault (name, defaultReturnValue);
  14115. }
  14116. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14117. {
  14118. if (undoManager == 0)
  14119. {
  14120. if (properties.set (name, newValue))
  14121. sendPropertyChangeMessage (name);
  14122. }
  14123. else
  14124. {
  14125. var* const existingValue = properties.getVarPointer (name);
  14126. if (existingValue != 0)
  14127. {
  14128. if (*existingValue != newValue)
  14129. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14130. }
  14131. else
  14132. {
  14133. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14134. }
  14135. }
  14136. }
  14137. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14138. {
  14139. return properties.contains (name);
  14140. }
  14141. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14142. {
  14143. if (undoManager == 0)
  14144. {
  14145. if (properties.remove (name))
  14146. sendPropertyChangeMessage (name);
  14147. }
  14148. else
  14149. {
  14150. if (properties.contains (name))
  14151. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14152. }
  14153. }
  14154. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14155. {
  14156. if (undoManager == 0)
  14157. {
  14158. while (properties.size() > 0)
  14159. {
  14160. const Identifier name (properties.getName (properties.size() - 1));
  14161. properties.remove (name);
  14162. sendPropertyChangeMessage (name);
  14163. }
  14164. }
  14165. else
  14166. {
  14167. for (int i = properties.size(); --i >= 0;)
  14168. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14169. }
  14170. }
  14171. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14172. {
  14173. for (int i = 0; i < children.size(); ++i)
  14174. if (children.getUnchecked(i)->type == typeToMatch)
  14175. return ValueTree (children.getUnchecked(i).getObject());
  14176. return ValueTree::invalid;
  14177. }
  14178. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14179. {
  14180. for (int i = 0; i < children.size(); ++i)
  14181. if (children.getUnchecked(i)->type == typeToMatch)
  14182. return ValueTree (children.getUnchecked(i).getObject());
  14183. SharedObject* const newObject = new SharedObject (typeToMatch);
  14184. addChild (newObject, -1, undoManager);
  14185. return ValueTree (newObject);
  14186. }
  14187. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14188. {
  14189. for (int i = 0; i < children.size(); ++i)
  14190. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14191. return ValueTree (children.getUnchecked(i).getObject());
  14192. return ValueTree::invalid;
  14193. }
  14194. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14195. {
  14196. const SharedObject* p = parent;
  14197. while (p != 0)
  14198. {
  14199. if (p == possibleParent)
  14200. return true;
  14201. p = p->parent;
  14202. }
  14203. return false;
  14204. }
  14205. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14206. {
  14207. return children.indexOf (child.object);
  14208. }
  14209. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14210. {
  14211. if (child != 0 && child->parent != this)
  14212. {
  14213. if (child != this && ! isAChildOf (child))
  14214. {
  14215. // You should always make sure that a child is removed from its previous parent before
  14216. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14217. // undomanager should be used when removing it from its current parent..
  14218. jassert (child->parent == 0);
  14219. if (child->parent != 0)
  14220. {
  14221. jassert (child->parent->children.indexOf (child) >= 0);
  14222. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14223. }
  14224. if (undoManager == 0)
  14225. {
  14226. children.insert (index, child);
  14227. child->parent = this;
  14228. sendChildAddedMessage (ValueTree (child));
  14229. child->sendParentChangeMessage();
  14230. }
  14231. else
  14232. {
  14233. if (index < 0)
  14234. index = children.size();
  14235. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14236. }
  14237. }
  14238. else
  14239. {
  14240. // You're attempting to create a recursive loop! A node
  14241. // can't be a child of one of its own children!
  14242. jassertfalse;
  14243. }
  14244. }
  14245. }
  14246. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14247. {
  14248. const SharedObjectPtr child (children [childIndex]);
  14249. if (child != 0)
  14250. {
  14251. if (undoManager == 0)
  14252. {
  14253. children.remove (childIndex);
  14254. child->parent = 0;
  14255. sendChildRemovedMessage (ValueTree (child));
  14256. child->sendParentChangeMessage();
  14257. }
  14258. else
  14259. {
  14260. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14261. }
  14262. }
  14263. }
  14264. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14265. {
  14266. while (children.size() > 0)
  14267. removeChild (children.size() - 1, undoManager);
  14268. }
  14269. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14270. {
  14271. // The source index must be a valid index!
  14272. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14273. if (currentIndex != newIndex
  14274. && isPositiveAndBelow (currentIndex, children.size()))
  14275. {
  14276. if (undoManager == 0)
  14277. {
  14278. children.move (currentIndex, newIndex);
  14279. sendChildOrderChangedMessage();
  14280. }
  14281. else
  14282. {
  14283. if (! isPositiveAndBelow (newIndex, children.size()))
  14284. newIndex = children.size() - 1;
  14285. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14286. }
  14287. }
  14288. }
  14289. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14290. {
  14291. jassert (newOrder.size() == children.size());
  14292. if (undoManager == 0)
  14293. {
  14294. children = newOrder;
  14295. sendChildOrderChangedMessage();
  14296. }
  14297. else
  14298. {
  14299. for (int i = 0; i < children.size(); ++i)
  14300. {
  14301. const SharedObjectPtr child (newOrder.getUnchecked(i));
  14302. if (children.getUnchecked(i) != child)
  14303. {
  14304. const int oldIndex = children.indexOf (child);
  14305. jassert (oldIndex >= 0);
  14306. moveChild (oldIndex, i, undoManager);
  14307. }
  14308. }
  14309. }
  14310. }
  14311. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14312. {
  14313. if (type != other.type
  14314. || properties.size() != other.properties.size()
  14315. || children.size() != other.children.size()
  14316. || properties != other.properties)
  14317. return false;
  14318. for (int i = 0; i < children.size(); ++i)
  14319. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14320. return false;
  14321. return true;
  14322. }
  14323. ValueTree::ValueTree() throw()
  14324. : object (0)
  14325. {
  14326. }
  14327. const ValueTree ValueTree::invalid;
  14328. ValueTree::ValueTree (const Identifier& type_)
  14329. : object (new ValueTree::SharedObject (type_))
  14330. {
  14331. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14332. }
  14333. ValueTree::ValueTree (SharedObject* const object_)
  14334. : object (object_)
  14335. {
  14336. }
  14337. ValueTree::ValueTree (const ValueTree& other)
  14338. : object (other.object)
  14339. {
  14340. }
  14341. ValueTree& ValueTree::operator= (const ValueTree& other)
  14342. {
  14343. if (listeners.size() > 0)
  14344. {
  14345. if (object != 0)
  14346. object->valueTreesWithListeners.removeValue (this);
  14347. if (other.object != 0)
  14348. other.object->valueTreesWithListeners.add (this);
  14349. }
  14350. object = other.object;
  14351. return *this;
  14352. }
  14353. ValueTree::~ValueTree()
  14354. {
  14355. if (listeners.size() > 0 && object != 0)
  14356. object->valueTreesWithListeners.removeValue (this);
  14357. }
  14358. bool ValueTree::operator== (const ValueTree& other) const throw()
  14359. {
  14360. return object == other.object;
  14361. }
  14362. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14363. {
  14364. return object != other.object;
  14365. }
  14366. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14367. {
  14368. return object == other.object
  14369. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14370. }
  14371. ValueTree ValueTree::createCopy() const
  14372. {
  14373. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14374. }
  14375. bool ValueTree::hasType (const Identifier& typeName) const
  14376. {
  14377. return object != 0 && object->type == typeName;
  14378. }
  14379. const Identifier ValueTree::getType() const
  14380. {
  14381. return object != 0 ? object->type : Identifier();
  14382. }
  14383. ValueTree ValueTree::getParent() const
  14384. {
  14385. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14386. }
  14387. ValueTree ValueTree::getSibling (const int delta) const
  14388. {
  14389. if (object == 0 || object->parent == 0)
  14390. return invalid;
  14391. const int index = object->parent->indexOf (*this) + delta;
  14392. return ValueTree (object->parent->children [index].getObject());
  14393. }
  14394. const var& ValueTree::operator[] (const Identifier& name) const
  14395. {
  14396. return object == 0 ? var::null : object->getProperty (name);
  14397. }
  14398. const var& ValueTree::getProperty (const Identifier& name) const
  14399. {
  14400. return object == 0 ? var::null : object->getProperty (name);
  14401. }
  14402. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14403. {
  14404. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14405. }
  14406. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14407. {
  14408. jassert (name.toString().isNotEmpty());
  14409. if (object != 0 && name.toString().isNotEmpty())
  14410. object->setProperty (name, newValue, undoManager);
  14411. }
  14412. bool ValueTree::hasProperty (const Identifier& name) const
  14413. {
  14414. return object != 0 && object->hasProperty (name);
  14415. }
  14416. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14417. {
  14418. if (object != 0)
  14419. object->removeProperty (name, undoManager);
  14420. }
  14421. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14422. {
  14423. if (object != 0)
  14424. object->removeAllProperties (undoManager);
  14425. }
  14426. int ValueTree::getNumProperties() const
  14427. {
  14428. return object == 0 ? 0 : object->properties.size();
  14429. }
  14430. const Identifier ValueTree::getPropertyName (const int index) const
  14431. {
  14432. return object == 0 ? Identifier()
  14433. : object->properties.getName (index);
  14434. }
  14435. class ValueTreePropertyValueSource : public Value::ValueSource,
  14436. public ValueTree::Listener
  14437. {
  14438. public:
  14439. ValueTreePropertyValueSource (const ValueTree& tree_,
  14440. const Identifier& property_,
  14441. UndoManager* const undoManager_)
  14442. : tree (tree_),
  14443. property (property_),
  14444. undoManager (undoManager_)
  14445. {
  14446. tree.addListener (this);
  14447. }
  14448. ~ValueTreePropertyValueSource()
  14449. {
  14450. tree.removeListener (this);
  14451. }
  14452. const var getValue() const
  14453. {
  14454. return tree [property];
  14455. }
  14456. void setValue (const var& newValue)
  14457. {
  14458. tree.setProperty (property, newValue, undoManager);
  14459. }
  14460. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14461. {
  14462. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14463. sendChangeMessage (false);
  14464. }
  14465. void valueTreeChildAdded (ValueTree&, ValueTree&) {}
  14466. void valueTreeChildRemoved (ValueTree&, ValueTree&) {}
  14467. void valueTreeChildOrderChanged (ValueTree&) {}
  14468. void valueTreeParentChanged (ValueTree&) {}
  14469. private:
  14470. ValueTree tree;
  14471. const Identifier property;
  14472. UndoManager* const undoManager;
  14473. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14474. };
  14475. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14476. {
  14477. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14478. }
  14479. int ValueTree::getNumChildren() const
  14480. {
  14481. return object == 0 ? 0 : object->children.size();
  14482. }
  14483. ValueTree ValueTree::getChild (int index) const
  14484. {
  14485. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14486. }
  14487. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14488. {
  14489. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14490. }
  14491. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14492. {
  14493. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14494. }
  14495. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14496. {
  14497. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14498. }
  14499. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14500. {
  14501. return object != 0 && object->isAChildOf (possibleParent.object);
  14502. }
  14503. int ValueTree::indexOf (const ValueTree& child) const
  14504. {
  14505. return object != 0 ? object->indexOf (child) : -1;
  14506. }
  14507. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14508. {
  14509. if (object != 0)
  14510. object->addChild (child.object, index, undoManager);
  14511. }
  14512. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14513. {
  14514. if (object != 0)
  14515. object->removeChild (childIndex, undoManager);
  14516. }
  14517. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14518. {
  14519. if (object != 0)
  14520. object->removeChild (object->children.indexOf (child.object), undoManager);
  14521. }
  14522. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14523. {
  14524. if (object != 0)
  14525. object->removeAllChildren (undoManager);
  14526. }
  14527. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14528. {
  14529. if (object != 0)
  14530. object->moveChild (currentIndex, newIndex, undoManager);
  14531. }
  14532. void ValueTree::addListener (Listener* listener)
  14533. {
  14534. if (listener != 0)
  14535. {
  14536. if (listeners.size() == 0 && object != 0)
  14537. object->valueTreesWithListeners.add (this);
  14538. listeners.add (listener);
  14539. }
  14540. }
  14541. void ValueTree::removeListener (Listener* listener)
  14542. {
  14543. listeners.remove (listener);
  14544. if (listeners.size() == 0 && object != 0)
  14545. object->valueTreesWithListeners.removeValue (this);
  14546. }
  14547. XmlElement* ValueTree::SharedObject::createXml() const
  14548. {
  14549. XmlElement* const xml = new XmlElement (type.toString());
  14550. properties.copyToXmlAttributes (*xml);
  14551. for (int i = 0; i < children.size(); ++i)
  14552. xml->addChildElement (children.getUnchecked(i)->createXml());
  14553. return xml;
  14554. }
  14555. XmlElement* ValueTree::createXml() const
  14556. {
  14557. return object != 0 ? object->createXml() : 0;
  14558. }
  14559. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14560. {
  14561. ValueTree v (xml.getTagName());
  14562. v.object->properties.setFromXmlAttributes (xml);
  14563. forEachXmlChildElement (xml, e)
  14564. v.addChild (fromXml (*e), -1, 0);
  14565. return v;
  14566. }
  14567. void ValueTree::writeToStream (OutputStream& output)
  14568. {
  14569. output.writeString (getType().toString());
  14570. const int numProps = getNumProperties();
  14571. output.writeCompressedInt (numProps);
  14572. int i;
  14573. for (i = 0; i < numProps; ++i)
  14574. {
  14575. const Identifier name (getPropertyName(i));
  14576. output.writeString (name.toString());
  14577. getProperty(name).writeToStream (output);
  14578. }
  14579. const int numChildren = getNumChildren();
  14580. output.writeCompressedInt (numChildren);
  14581. for (i = 0; i < numChildren; ++i)
  14582. getChild (i).writeToStream (output);
  14583. }
  14584. ValueTree ValueTree::readFromStream (InputStream& input)
  14585. {
  14586. const String type (input.readString());
  14587. if (type.isEmpty())
  14588. return ValueTree::invalid;
  14589. ValueTree v (type);
  14590. const int numProps = input.readCompressedInt();
  14591. if (numProps < 0)
  14592. {
  14593. jassertfalse; // trying to read corrupted data!
  14594. return v;
  14595. }
  14596. int i;
  14597. for (i = 0; i < numProps; ++i)
  14598. {
  14599. const String name (input.readString());
  14600. jassert (name.isNotEmpty());
  14601. const var value (var::readFromStream (input));
  14602. v.object->properties.set (name, value);
  14603. }
  14604. const int numChildren = input.readCompressedInt();
  14605. for (i = 0; i < numChildren; ++i)
  14606. {
  14607. ValueTree child (readFromStream (input));
  14608. v.object->children.add (child.object);
  14609. child.object->parent = v.object;
  14610. }
  14611. return v;
  14612. }
  14613. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14614. {
  14615. MemoryInputStream in (data, numBytes, false);
  14616. return readFromStream (in);
  14617. }
  14618. END_JUCE_NAMESPACE
  14619. /*** End of inlined file: juce_ValueTree.cpp ***/
  14620. /*** Start of inlined file: juce_Value.cpp ***/
  14621. BEGIN_JUCE_NAMESPACE
  14622. Value::ValueSource::ValueSource()
  14623. {
  14624. }
  14625. Value::ValueSource::~ValueSource()
  14626. {
  14627. }
  14628. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14629. {
  14630. if (synchronous)
  14631. {
  14632. for (int i = valuesWithListeners.size(); --i >= 0;)
  14633. {
  14634. Value* const v = valuesWithListeners[i];
  14635. if (v != 0)
  14636. v->callListeners();
  14637. }
  14638. }
  14639. else
  14640. {
  14641. triggerAsyncUpdate();
  14642. }
  14643. }
  14644. void Value::ValueSource::handleAsyncUpdate()
  14645. {
  14646. sendChangeMessage (true);
  14647. }
  14648. class SimpleValueSource : public Value::ValueSource
  14649. {
  14650. public:
  14651. SimpleValueSource()
  14652. {
  14653. }
  14654. SimpleValueSource (const var& initialValue)
  14655. : value (initialValue)
  14656. {
  14657. }
  14658. const var getValue() const
  14659. {
  14660. return value;
  14661. }
  14662. void setValue (const var& newValue)
  14663. {
  14664. if (! newValue.equalsWithSameType (value))
  14665. {
  14666. value = newValue;
  14667. sendChangeMessage (false);
  14668. }
  14669. }
  14670. private:
  14671. var value;
  14672. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14673. };
  14674. Value::Value()
  14675. : value (new SimpleValueSource())
  14676. {
  14677. }
  14678. Value::Value (ValueSource* const value_)
  14679. : value (value_)
  14680. {
  14681. jassert (value_ != 0);
  14682. }
  14683. Value::Value (const var& initialValue)
  14684. : value (new SimpleValueSource (initialValue))
  14685. {
  14686. }
  14687. Value::Value (const Value& other)
  14688. : value (other.value)
  14689. {
  14690. }
  14691. Value& Value::operator= (const Value& other)
  14692. {
  14693. value = other.value;
  14694. return *this;
  14695. }
  14696. Value::~Value()
  14697. {
  14698. if (listeners.size() > 0)
  14699. value->valuesWithListeners.removeValue (this);
  14700. }
  14701. const var Value::getValue() const
  14702. {
  14703. return value->getValue();
  14704. }
  14705. Value::operator const var() const
  14706. {
  14707. return getValue();
  14708. }
  14709. void Value::setValue (const var& newValue)
  14710. {
  14711. value->setValue (newValue);
  14712. }
  14713. const String Value::toString() const
  14714. {
  14715. return value->getValue().toString();
  14716. }
  14717. Value& Value::operator= (const var& newValue)
  14718. {
  14719. value->setValue (newValue);
  14720. return *this;
  14721. }
  14722. void Value::referTo (const Value& valueToReferTo)
  14723. {
  14724. if (valueToReferTo.value != value)
  14725. {
  14726. if (listeners.size() > 0)
  14727. {
  14728. value->valuesWithListeners.removeValue (this);
  14729. valueToReferTo.value->valuesWithListeners.add (this);
  14730. }
  14731. value = valueToReferTo.value;
  14732. callListeners();
  14733. }
  14734. }
  14735. bool Value::refersToSameSourceAs (const Value& other) const
  14736. {
  14737. return value == other.value;
  14738. }
  14739. bool Value::operator== (const Value& other) const
  14740. {
  14741. return value == other.value || value->getValue() == other.getValue();
  14742. }
  14743. bool Value::operator!= (const Value& other) const
  14744. {
  14745. return value != other.value && value->getValue() != other.getValue();
  14746. }
  14747. void Value::addListener (ValueListener* const listener)
  14748. {
  14749. if (listener != 0)
  14750. {
  14751. if (listeners.size() == 0)
  14752. value->valuesWithListeners.add (this);
  14753. listeners.add (listener);
  14754. }
  14755. }
  14756. void Value::removeListener (ValueListener* const listener)
  14757. {
  14758. listeners.remove (listener);
  14759. if (listeners.size() == 0)
  14760. value->valuesWithListeners.removeValue (this);
  14761. }
  14762. void Value::callListeners()
  14763. {
  14764. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14765. listeners.call (&ValueListener::valueChanged, v);
  14766. }
  14767. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14768. {
  14769. return stream << value.toString();
  14770. }
  14771. END_JUCE_NAMESPACE
  14772. /*** End of inlined file: juce_Value.cpp ***/
  14773. /*** Start of inlined file: juce_Application.cpp ***/
  14774. BEGIN_JUCE_NAMESPACE
  14775. #if JUCE_MAC
  14776. extern void juce_initialiseMacMainMenu();
  14777. #endif
  14778. JUCEApplication::JUCEApplication()
  14779. : appReturnValue (0),
  14780. stillInitialising (true)
  14781. {
  14782. jassert (isStandaloneApp() && appInstance == 0);
  14783. appInstance = this;
  14784. }
  14785. JUCEApplication::~JUCEApplication()
  14786. {
  14787. if (appLock != 0)
  14788. {
  14789. appLock->exit();
  14790. appLock = 0;
  14791. }
  14792. jassert (appInstance == this);
  14793. appInstance = 0;
  14794. }
  14795. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14796. JUCEApplication* JUCEApplication::appInstance = 0;
  14797. bool JUCEApplication::moreThanOneInstanceAllowed()
  14798. {
  14799. return true;
  14800. }
  14801. void JUCEApplication::anotherInstanceStarted (const String&)
  14802. {
  14803. }
  14804. void JUCEApplication::systemRequestedQuit()
  14805. {
  14806. quit();
  14807. }
  14808. void JUCEApplication::quit()
  14809. {
  14810. MessageManager::getInstance()->stopDispatchLoop();
  14811. }
  14812. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14813. {
  14814. appReturnValue = newReturnValue;
  14815. }
  14816. void JUCEApplication::actionListenerCallback (const String& message)
  14817. {
  14818. if (message.startsWith (getApplicationName() + "/"))
  14819. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14820. }
  14821. void JUCEApplication::unhandledException (const std::exception*,
  14822. const String&,
  14823. const int)
  14824. {
  14825. jassertfalse;
  14826. }
  14827. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14828. const char* const sourceFile,
  14829. const int lineNumber)
  14830. {
  14831. if (appInstance != 0)
  14832. appInstance->unhandledException (e, sourceFile, lineNumber);
  14833. }
  14834. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14835. {
  14836. return 0;
  14837. }
  14838. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14839. {
  14840. commands.add (StandardApplicationCommandIDs::quit);
  14841. }
  14842. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14843. {
  14844. if (commandID == StandardApplicationCommandIDs::quit)
  14845. {
  14846. result.setInfo (TRANS("Quit"),
  14847. TRANS("Quits the application"),
  14848. "Application",
  14849. 0);
  14850. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14851. }
  14852. }
  14853. bool JUCEApplication::perform (const InvocationInfo& info)
  14854. {
  14855. if (info.commandID == StandardApplicationCommandIDs::quit)
  14856. {
  14857. systemRequestedQuit();
  14858. return true;
  14859. }
  14860. return false;
  14861. }
  14862. bool JUCEApplication::initialiseApp (const String& commandLine)
  14863. {
  14864. commandLineParameters = commandLine.trim();
  14865. #if ! JUCE_IOS
  14866. jassert (appLock == 0); // initialiseApp must only be called once!
  14867. if (! moreThanOneInstanceAllowed())
  14868. {
  14869. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14870. if (! appLock->enter(0))
  14871. {
  14872. appLock = 0;
  14873. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14874. DBG ("Another instance is running - quitting...");
  14875. return false;
  14876. }
  14877. }
  14878. #endif
  14879. // let the app do its setting-up..
  14880. initialise (commandLineParameters);
  14881. #if JUCE_MAC
  14882. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14883. #endif
  14884. // register for broadcast new app messages
  14885. MessageManager::getInstance()->registerBroadcastListener (this);
  14886. stillInitialising = false;
  14887. return true;
  14888. }
  14889. int JUCEApplication::shutdownApp()
  14890. {
  14891. jassert (appInstance == this);
  14892. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14893. JUCE_TRY
  14894. {
  14895. // give the app a chance to clean up..
  14896. shutdown();
  14897. }
  14898. JUCE_CATCH_EXCEPTION
  14899. return getApplicationReturnValue();
  14900. }
  14901. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  14902. void JUCEApplication::appWillTerminateByForce()
  14903. {
  14904. {
  14905. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  14906. if (app != 0)
  14907. app->shutdownApp();
  14908. }
  14909. shutdownJuce_GUI();
  14910. }
  14911. int JUCEApplication::main (const String& commandLine)
  14912. {
  14913. ScopedJuceInitialiser_GUI libraryInitialiser;
  14914. jassert (createInstance != 0);
  14915. int returnCode = 0;
  14916. {
  14917. const ScopedPointer<JUCEApplication> app (createInstance());
  14918. if (! app->initialiseApp (commandLine))
  14919. return 0;
  14920. JUCE_TRY
  14921. {
  14922. // loop until a quit message is received..
  14923. MessageManager::getInstance()->runDispatchLoop();
  14924. }
  14925. JUCE_CATCH_EXCEPTION
  14926. returnCode = app->shutdownApp();
  14927. }
  14928. return returnCode;
  14929. }
  14930. #if JUCE_IOS
  14931. extern int juce_iOSMain (int argc, const char* argv[]);
  14932. #endif
  14933. #if ! JUCE_WINDOWS
  14934. extern const char* juce_Argv0;
  14935. #endif
  14936. int JUCEApplication::main (int argc, const char* argv[])
  14937. {
  14938. JUCE_AUTORELEASEPOOL
  14939. #if ! JUCE_WINDOWS
  14940. jassert (createInstance != 0);
  14941. juce_Argv0 = argv[0];
  14942. #endif
  14943. #if JUCE_IOS
  14944. return juce_iOSMain (argc, argv);
  14945. #else
  14946. String cmd;
  14947. for (int i = 1; i < argc; ++i)
  14948. cmd << argv[i] << ' ';
  14949. return JUCEApplication::main (cmd);
  14950. #endif
  14951. }
  14952. END_JUCE_NAMESPACE
  14953. /*** End of inlined file: juce_Application.cpp ***/
  14954. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14955. BEGIN_JUCE_NAMESPACE
  14956. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14957. : commandID (commandID_),
  14958. flags (0)
  14959. {
  14960. }
  14961. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14962. const String& description_,
  14963. const String& categoryName_,
  14964. const int flags_) throw()
  14965. {
  14966. shortName = shortName_;
  14967. description = description_;
  14968. categoryName = categoryName_;
  14969. flags = flags_;
  14970. }
  14971. void ApplicationCommandInfo::setActive (const bool b) throw()
  14972. {
  14973. if (b)
  14974. flags &= ~isDisabled;
  14975. else
  14976. flags |= isDisabled;
  14977. }
  14978. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14979. {
  14980. if (b)
  14981. flags |= isTicked;
  14982. else
  14983. flags &= ~isTicked;
  14984. }
  14985. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14986. {
  14987. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14988. }
  14989. END_JUCE_NAMESPACE
  14990. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14991. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14992. BEGIN_JUCE_NAMESPACE
  14993. ApplicationCommandManager::ApplicationCommandManager()
  14994. : firstTarget (0)
  14995. {
  14996. keyMappings = new KeyPressMappingSet (this);
  14997. Desktop::getInstance().addFocusChangeListener (this);
  14998. }
  14999. ApplicationCommandManager::~ApplicationCommandManager()
  15000. {
  15001. Desktop::getInstance().removeFocusChangeListener (this);
  15002. keyMappings = 0;
  15003. }
  15004. void ApplicationCommandManager::clearCommands()
  15005. {
  15006. commands.clear();
  15007. keyMappings->clearAllKeyPresses();
  15008. triggerAsyncUpdate();
  15009. }
  15010. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15011. {
  15012. // zero isn't a valid command ID!
  15013. jassert (newCommand.commandID != 0);
  15014. // the name isn't optional!
  15015. jassert (newCommand.shortName.isNotEmpty());
  15016. if (getCommandForID (newCommand.commandID) == 0)
  15017. {
  15018. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15019. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15020. commands.add (newInfo);
  15021. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15022. triggerAsyncUpdate();
  15023. }
  15024. else
  15025. {
  15026. // trying to re-register the same command with different parameters?
  15027. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15028. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15029. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15030. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15031. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15032. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15033. }
  15034. }
  15035. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15036. {
  15037. if (target != 0)
  15038. {
  15039. Array <CommandID> commandIDs;
  15040. target->getAllCommands (commandIDs);
  15041. for (int i = 0; i < commandIDs.size(); ++i)
  15042. {
  15043. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15044. target->getCommandInfo (info.commandID, info);
  15045. registerCommand (info);
  15046. }
  15047. }
  15048. }
  15049. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15050. {
  15051. for (int i = commands.size(); --i >= 0;)
  15052. {
  15053. if (commands.getUnchecked (i)->commandID == commandID)
  15054. {
  15055. commands.remove (i);
  15056. triggerAsyncUpdate();
  15057. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15058. for (int j = keys.size(); --j >= 0;)
  15059. keyMappings->removeKeyPress (keys.getReference (j));
  15060. }
  15061. }
  15062. }
  15063. void ApplicationCommandManager::commandStatusChanged()
  15064. {
  15065. triggerAsyncUpdate();
  15066. }
  15067. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15068. {
  15069. for (int i = commands.size(); --i >= 0;)
  15070. if (commands.getUnchecked(i)->commandID == commandID)
  15071. return commands.getUnchecked(i);
  15072. return 0;
  15073. }
  15074. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15075. {
  15076. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15077. return (ci != 0) ? ci->shortName : String::empty;
  15078. }
  15079. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15080. {
  15081. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15082. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15083. : String::empty;
  15084. }
  15085. const StringArray ApplicationCommandManager::getCommandCategories() const
  15086. {
  15087. StringArray s;
  15088. for (int i = 0; i < commands.size(); ++i)
  15089. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15090. return s;
  15091. }
  15092. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15093. {
  15094. Array <CommandID> results;
  15095. for (int i = 0; i < commands.size(); ++i)
  15096. if (commands.getUnchecked(i)->categoryName == categoryName)
  15097. results.add (commands.getUnchecked(i)->commandID);
  15098. return results;
  15099. }
  15100. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15101. {
  15102. ApplicationCommandTarget::InvocationInfo info (commandID);
  15103. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15104. return invoke (info, asynchronously);
  15105. }
  15106. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15107. {
  15108. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15109. // manager first..
  15110. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15111. ApplicationCommandInfo commandInfo (0);
  15112. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15113. if (target == 0)
  15114. return false;
  15115. ApplicationCommandTarget::InvocationInfo info (info_);
  15116. info.commandFlags = commandInfo.flags;
  15117. sendListenerInvokeCallback (info);
  15118. const bool ok = target->invoke (info, asynchronously);
  15119. commandStatusChanged();
  15120. return ok;
  15121. }
  15122. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15123. {
  15124. return firstTarget != 0 ? firstTarget
  15125. : findDefaultComponentTarget();
  15126. }
  15127. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15128. {
  15129. firstTarget = newTarget;
  15130. }
  15131. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15132. ApplicationCommandInfo& upToDateInfo)
  15133. {
  15134. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15135. if (target == 0)
  15136. target = JUCEApplication::getInstance();
  15137. if (target != 0)
  15138. target = target->getTargetForCommand (commandID);
  15139. if (target != 0)
  15140. target->getCommandInfo (commandID, upToDateInfo);
  15141. return target;
  15142. }
  15143. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15144. {
  15145. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15146. if (target == 0 && c != 0)
  15147. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15148. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15149. return target;
  15150. }
  15151. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15152. {
  15153. Component* c = Component::getCurrentlyFocusedComponent();
  15154. if (c == 0)
  15155. {
  15156. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15157. if (activeWindow != 0)
  15158. {
  15159. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15160. if (c == 0)
  15161. c = activeWindow;
  15162. }
  15163. }
  15164. if (c == 0 && Process::isForegroundProcess())
  15165. {
  15166. // getting a bit desperate now - try all desktop comps..
  15167. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15168. {
  15169. ApplicationCommandTarget* const target
  15170. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15171. ->getPeer()->getLastFocusedSubcomponent());
  15172. if (target != 0)
  15173. return target;
  15174. }
  15175. }
  15176. if (c != 0)
  15177. {
  15178. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15179. // if we're focused on a ResizableWindow, chances are that it's the content
  15180. // component that really should get the event. And if not, the event will
  15181. // still be passed up to the top level window anyway, so let's send it to the
  15182. // content comp.
  15183. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15184. c = resizableWindow->getContentComponent();
  15185. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15186. if (target != 0)
  15187. return target;
  15188. }
  15189. return JUCEApplication::getInstance();
  15190. }
  15191. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15192. {
  15193. listeners.add (listener);
  15194. }
  15195. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15196. {
  15197. listeners.remove (listener);
  15198. }
  15199. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15200. {
  15201. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15202. }
  15203. void ApplicationCommandManager::handleAsyncUpdate()
  15204. {
  15205. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15206. }
  15207. void ApplicationCommandManager::globalFocusChanged (Component*)
  15208. {
  15209. commandStatusChanged();
  15210. }
  15211. END_JUCE_NAMESPACE
  15212. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15213. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15214. BEGIN_JUCE_NAMESPACE
  15215. ApplicationCommandTarget::ApplicationCommandTarget()
  15216. {
  15217. }
  15218. ApplicationCommandTarget::~ApplicationCommandTarget()
  15219. {
  15220. messageInvoker = 0;
  15221. }
  15222. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15223. {
  15224. if (isCommandActive (info.commandID))
  15225. {
  15226. if (async)
  15227. {
  15228. if (messageInvoker == 0)
  15229. messageInvoker = new CommandTargetMessageInvoker (this);
  15230. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15231. return true;
  15232. }
  15233. else
  15234. {
  15235. const bool success = perform (info);
  15236. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15237. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15238. // returns the command's info.
  15239. return success;
  15240. }
  15241. }
  15242. return false;
  15243. }
  15244. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15245. {
  15246. Component* c = dynamic_cast <Component*> (this);
  15247. if (c != 0)
  15248. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15249. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15250. return 0;
  15251. }
  15252. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15253. {
  15254. ApplicationCommandTarget* target = this;
  15255. int depth = 0;
  15256. while (target != 0)
  15257. {
  15258. Array <CommandID> commandIDs;
  15259. target->getAllCommands (commandIDs);
  15260. if (commandIDs.contains (commandID))
  15261. return target;
  15262. target = target->getNextCommandTarget();
  15263. ++depth;
  15264. jassert (depth < 100); // could be a recursive command chain??
  15265. jassert (target != this); // definitely a recursive command chain!
  15266. if (depth > 100 || target == this)
  15267. break;
  15268. }
  15269. if (target == 0)
  15270. {
  15271. target = JUCEApplication::getInstance();
  15272. if (target != 0)
  15273. {
  15274. Array <CommandID> commandIDs;
  15275. target->getAllCommands (commandIDs);
  15276. if (commandIDs.contains (commandID))
  15277. return target;
  15278. }
  15279. }
  15280. return 0;
  15281. }
  15282. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15283. {
  15284. ApplicationCommandInfo info (commandID);
  15285. info.flags = ApplicationCommandInfo::isDisabled;
  15286. getCommandInfo (commandID, info);
  15287. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15288. }
  15289. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15290. {
  15291. ApplicationCommandTarget* target = this;
  15292. int depth = 0;
  15293. while (target != 0)
  15294. {
  15295. if (target->tryToInvoke (info, async))
  15296. return true;
  15297. target = target->getNextCommandTarget();
  15298. ++depth;
  15299. jassert (depth < 100); // could be a recursive command chain??
  15300. jassert (target != this); // definitely a recursive command chain!
  15301. if (depth > 100 || target == this)
  15302. break;
  15303. }
  15304. if (target == 0)
  15305. {
  15306. target = JUCEApplication::getInstance();
  15307. if (target != 0)
  15308. return target->tryToInvoke (info, async);
  15309. }
  15310. return false;
  15311. }
  15312. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15313. {
  15314. ApplicationCommandTarget::InvocationInfo info (commandID);
  15315. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15316. return invoke (info, asynchronously);
  15317. }
  15318. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15319. : commandID (commandID_),
  15320. commandFlags (0),
  15321. invocationMethod (direct),
  15322. originatingComponent (0),
  15323. isKeyDown (false),
  15324. millisecsSinceKeyPressed (0)
  15325. {
  15326. }
  15327. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15328. : owner (owner_)
  15329. {
  15330. }
  15331. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15332. {
  15333. }
  15334. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15335. {
  15336. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15337. owner->tryToInvoke (*info, false);
  15338. }
  15339. END_JUCE_NAMESPACE
  15340. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15341. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15342. BEGIN_JUCE_NAMESPACE
  15343. juce_ImplementSingleton (ApplicationProperties)
  15344. ApplicationProperties::ApplicationProperties()
  15345. : msBeforeSaving (3000),
  15346. options (PropertiesFile::storeAsBinary),
  15347. commonSettingsAreReadOnly (0),
  15348. processLock (0)
  15349. {
  15350. }
  15351. ApplicationProperties::~ApplicationProperties()
  15352. {
  15353. closeFiles();
  15354. clearSingletonInstance();
  15355. }
  15356. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15357. const String& fileNameSuffix,
  15358. const String& folderName_,
  15359. const int millisecondsBeforeSaving,
  15360. const int propertiesFileOptions,
  15361. InterProcessLock* processLock_)
  15362. {
  15363. appName = applicationName;
  15364. fileSuffix = fileNameSuffix;
  15365. folderName = folderName_;
  15366. msBeforeSaving = millisecondsBeforeSaving;
  15367. options = propertiesFileOptions;
  15368. processLock = processLock_;
  15369. }
  15370. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15371. const bool testCommonSettings,
  15372. const bool showWarningDialogOnFailure)
  15373. {
  15374. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15375. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15376. if (! (userOk && commonOk))
  15377. {
  15378. if (showWarningDialogOnFailure)
  15379. {
  15380. String filenames;
  15381. if (userProps != 0 && ! userOk)
  15382. filenames << '\n' << userProps->getFile().getFullPathName();
  15383. if (commonProps != 0 && ! commonOk)
  15384. filenames << '\n' << commonProps->getFile().getFullPathName();
  15385. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15386. appName + TRANS(" - Unable to save settings"),
  15387. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15388. + appName + TRANS(" needs to be able to write to the following files:\n")
  15389. + filenames
  15390. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15391. }
  15392. return false;
  15393. }
  15394. return true;
  15395. }
  15396. void ApplicationProperties::openFiles()
  15397. {
  15398. // You need to call setStorageParameters() before trying to get hold of the
  15399. // properties!
  15400. jassert (appName.isNotEmpty());
  15401. if (appName.isNotEmpty())
  15402. {
  15403. if (userProps == 0)
  15404. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15405. false, msBeforeSaving, options, processLock);
  15406. if (commonProps == 0)
  15407. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15408. true, msBeforeSaving, options, processLock);
  15409. userProps->setFallbackPropertySet (commonProps);
  15410. }
  15411. }
  15412. PropertiesFile* ApplicationProperties::getUserSettings()
  15413. {
  15414. if (userProps == 0)
  15415. openFiles();
  15416. return userProps;
  15417. }
  15418. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15419. {
  15420. if (commonProps == 0)
  15421. openFiles();
  15422. if (returnUserPropsIfReadOnly)
  15423. {
  15424. if (commonSettingsAreReadOnly == 0)
  15425. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15426. if (commonSettingsAreReadOnly > 0)
  15427. return userProps;
  15428. }
  15429. return commonProps;
  15430. }
  15431. bool ApplicationProperties::saveIfNeeded()
  15432. {
  15433. return (userProps == 0 || userProps->saveIfNeeded())
  15434. && (commonProps == 0 || commonProps->saveIfNeeded());
  15435. }
  15436. void ApplicationProperties::closeFiles()
  15437. {
  15438. userProps = 0;
  15439. commonProps = 0;
  15440. }
  15441. END_JUCE_NAMESPACE
  15442. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15443. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15444. BEGIN_JUCE_NAMESPACE
  15445. namespace PropertyFileConstants
  15446. {
  15447. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15448. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15449. static const char* const fileTag = "PROPERTIES";
  15450. static const char* const valueTag = "VALUE";
  15451. static const char* const nameAttribute = "name";
  15452. static const char* const valueAttribute = "val";
  15453. }
  15454. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15455. const int options_, InterProcessLock* const processLock_)
  15456. : PropertySet (ignoreCaseOfKeyNames),
  15457. file (f),
  15458. timerInterval (millisecondsBeforeSaving),
  15459. options (options_),
  15460. loadedOk (false),
  15461. needsWriting (false),
  15462. processLock (processLock_)
  15463. {
  15464. // You need to correctly specify just one storage format for the file
  15465. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15466. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15467. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15468. ProcessScopedLock pl (createProcessLock());
  15469. if (pl != 0 && ! pl->isLocked())
  15470. return; // locking failure..
  15471. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15472. if (fileStream != 0)
  15473. {
  15474. int magicNumber = fileStream->readInt();
  15475. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15476. {
  15477. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15478. magicNumber = PropertyFileConstants::magicNumber;
  15479. }
  15480. if (magicNumber == PropertyFileConstants::magicNumber)
  15481. {
  15482. loadedOk = true;
  15483. BufferedInputStream in (fileStream.release(), 2048, true);
  15484. int numValues = in.readInt();
  15485. while (--numValues >= 0 && ! in.isExhausted())
  15486. {
  15487. const String key (in.readString());
  15488. const String value (in.readString());
  15489. jassert (key.isNotEmpty());
  15490. if (key.isNotEmpty())
  15491. getAllProperties().set (key, value);
  15492. }
  15493. }
  15494. else
  15495. {
  15496. // Not a binary props file - let's see if it's XML..
  15497. fileStream = 0;
  15498. XmlDocument parser (f);
  15499. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15500. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15501. {
  15502. doc = parser.getDocumentElement();
  15503. if (doc != 0)
  15504. {
  15505. loadedOk = true;
  15506. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15507. {
  15508. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15509. if (name.isNotEmpty())
  15510. {
  15511. getAllProperties().set (name,
  15512. e->getFirstChildElement() != 0
  15513. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15514. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15515. }
  15516. }
  15517. }
  15518. else
  15519. {
  15520. // must be a pretty broken XML file we're trying to parse here,
  15521. // or a sign that this object needs an InterProcessLock,
  15522. // or just a failure reading the file. This last reason is why
  15523. // we don't jassertfalse here.
  15524. }
  15525. }
  15526. }
  15527. }
  15528. else
  15529. {
  15530. loadedOk = ! f.exists();
  15531. }
  15532. }
  15533. PropertiesFile::~PropertiesFile()
  15534. {
  15535. if (! saveIfNeeded())
  15536. jassertfalse;
  15537. }
  15538. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15539. {
  15540. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15541. }
  15542. bool PropertiesFile::saveIfNeeded()
  15543. {
  15544. const ScopedLock sl (getLock());
  15545. return (! needsWriting) || save();
  15546. }
  15547. bool PropertiesFile::needsToBeSaved() const
  15548. {
  15549. const ScopedLock sl (getLock());
  15550. return needsWriting;
  15551. }
  15552. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15553. {
  15554. const ScopedLock sl (getLock());
  15555. needsWriting = needsToBeSaved_;
  15556. }
  15557. bool PropertiesFile::save()
  15558. {
  15559. const ScopedLock sl (getLock());
  15560. stopTimer();
  15561. if (file == File::nonexistent
  15562. || file.isDirectory()
  15563. || ! file.getParentDirectory().createDirectory())
  15564. return false;
  15565. if ((options & storeAsXML) != 0)
  15566. {
  15567. XmlElement doc (PropertyFileConstants::fileTag);
  15568. for (int i = 0; i < getAllProperties().size(); ++i)
  15569. {
  15570. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15571. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15572. // if the value seems to contain xml, store it as such..
  15573. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15574. if (childElement != 0)
  15575. e->addChildElement (childElement);
  15576. else
  15577. e->setAttribute (PropertyFileConstants::valueAttribute,
  15578. getAllProperties().getAllValues() [i]);
  15579. }
  15580. ProcessScopedLock pl (createProcessLock());
  15581. if (pl != 0 && ! pl->isLocked())
  15582. return false; // locking failure..
  15583. if (doc.writeToFile (file, String::empty))
  15584. {
  15585. needsWriting = false;
  15586. return true;
  15587. }
  15588. }
  15589. else
  15590. {
  15591. ProcessScopedLock pl (createProcessLock());
  15592. if (pl != 0 && ! pl->isLocked())
  15593. return false; // locking failure..
  15594. TemporaryFile tempFile (file);
  15595. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15596. if (out != 0)
  15597. {
  15598. if ((options & storeAsCompressedBinary) != 0)
  15599. {
  15600. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15601. out->flush();
  15602. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15603. }
  15604. else
  15605. {
  15606. // have you set up the storage option flags correctly?
  15607. jassert ((options & storeAsBinary) != 0);
  15608. out->writeInt (PropertyFileConstants::magicNumber);
  15609. }
  15610. const int numProperties = getAllProperties().size();
  15611. out->writeInt (numProperties);
  15612. for (int i = 0; i < numProperties; ++i)
  15613. {
  15614. out->writeString (getAllProperties().getAllKeys() [i]);
  15615. out->writeString (getAllProperties().getAllValues() [i]);
  15616. }
  15617. out = 0;
  15618. if (tempFile.overwriteTargetFileWithTemporary())
  15619. {
  15620. needsWriting = false;
  15621. return true;
  15622. }
  15623. }
  15624. }
  15625. return false;
  15626. }
  15627. void PropertiesFile::timerCallback()
  15628. {
  15629. saveIfNeeded();
  15630. }
  15631. void PropertiesFile::propertyChanged()
  15632. {
  15633. sendChangeMessage();
  15634. needsWriting = true;
  15635. if (timerInterval > 0)
  15636. startTimer (timerInterval);
  15637. else if (timerInterval == 0)
  15638. saveIfNeeded();
  15639. }
  15640. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15641. const String& fileNameSuffix,
  15642. const String& folderName,
  15643. const bool commonToAllUsers)
  15644. {
  15645. // mustn't have illegal characters in this name..
  15646. jassert (applicationName == File::createLegalFileName (applicationName));
  15647. #if JUCE_MAC || JUCE_IOS
  15648. File dir (commonToAllUsers ? "/Library/Preferences"
  15649. : "~/Library/Preferences");
  15650. if (folderName.isNotEmpty())
  15651. dir = dir.getChildFile (folderName);
  15652. #elif JUCE_LINUX || JUCE_ANDROID
  15653. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15654. + (folderName.isNotEmpty() ? folderName
  15655. : ("." + applicationName)));
  15656. #elif JUCE_WINDOWS
  15657. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15658. : File::userApplicationDataDirectory));
  15659. if (dir == File::nonexistent)
  15660. return File::nonexistent;
  15661. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15662. : applicationName);
  15663. #endif
  15664. return dir.getChildFile (applicationName)
  15665. .withFileExtension (fileNameSuffix);
  15666. }
  15667. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15668. const String& fileNameSuffix,
  15669. const String& folderName,
  15670. const bool commonToAllUsers,
  15671. const int millisecondsBeforeSaving,
  15672. const int propertiesFileOptions,
  15673. InterProcessLock* processLock_)
  15674. {
  15675. const File file (getDefaultAppSettingsFile (applicationName,
  15676. fileNameSuffix,
  15677. folderName,
  15678. commonToAllUsers));
  15679. jassert (file != File::nonexistent);
  15680. if (file == File::nonexistent)
  15681. return 0;
  15682. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15683. }
  15684. END_JUCE_NAMESPACE
  15685. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15686. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15687. BEGIN_JUCE_NAMESPACE
  15688. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15689. const String& fileWildcard_,
  15690. const String& openFileDialogTitle_,
  15691. const String& saveFileDialogTitle_)
  15692. : changedSinceSave (false),
  15693. fileExtension (fileExtension_),
  15694. fileWildcard (fileWildcard_),
  15695. openFileDialogTitle (openFileDialogTitle_),
  15696. saveFileDialogTitle (saveFileDialogTitle_)
  15697. {
  15698. }
  15699. FileBasedDocument::~FileBasedDocument()
  15700. {
  15701. }
  15702. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15703. {
  15704. if (changedSinceSave != hasChanged)
  15705. {
  15706. changedSinceSave = hasChanged;
  15707. sendChangeMessage();
  15708. }
  15709. }
  15710. void FileBasedDocument::changed()
  15711. {
  15712. changedSinceSave = true;
  15713. sendChangeMessage();
  15714. }
  15715. void FileBasedDocument::setFile (const File& newFile)
  15716. {
  15717. if (documentFile != newFile)
  15718. {
  15719. documentFile = newFile;
  15720. changed();
  15721. }
  15722. }
  15723. bool FileBasedDocument::loadFrom (const File& newFile,
  15724. const bool showMessageOnFailure)
  15725. {
  15726. MouseCursor::showWaitCursor();
  15727. const File oldFile (documentFile);
  15728. documentFile = newFile;
  15729. String error;
  15730. if (newFile.existsAsFile())
  15731. {
  15732. error = loadDocument (newFile);
  15733. if (error.isEmpty())
  15734. {
  15735. setChangedFlag (false);
  15736. MouseCursor::hideWaitCursor();
  15737. setLastDocumentOpened (newFile);
  15738. return true;
  15739. }
  15740. }
  15741. else
  15742. {
  15743. error = "The file doesn't exist";
  15744. }
  15745. documentFile = oldFile;
  15746. MouseCursor::hideWaitCursor();
  15747. if (showMessageOnFailure)
  15748. {
  15749. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15750. TRANS("Failed to open file..."),
  15751. TRANS("There was an error while trying to load the file:\n\n")
  15752. + newFile.getFullPathName()
  15753. + "\n\n"
  15754. + error);
  15755. }
  15756. return false;
  15757. }
  15758. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15759. {
  15760. FileChooser fc (openFileDialogTitle,
  15761. getLastDocumentOpened(),
  15762. fileWildcard);
  15763. if (fc.browseForFileToOpen())
  15764. return loadFrom (fc.getResult(), showMessageOnFailure);
  15765. return false;
  15766. }
  15767. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15768. const bool showMessageOnFailure)
  15769. {
  15770. return saveAs (documentFile,
  15771. false,
  15772. askUserForFileIfNotSpecified,
  15773. showMessageOnFailure);
  15774. }
  15775. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15776. const bool warnAboutOverwritingExistingFiles,
  15777. const bool askUserForFileIfNotSpecified,
  15778. const bool showMessageOnFailure)
  15779. {
  15780. if (newFile == File::nonexistent)
  15781. {
  15782. if (askUserForFileIfNotSpecified)
  15783. {
  15784. return saveAsInteractive (true);
  15785. }
  15786. else
  15787. {
  15788. // can't save to an unspecified file
  15789. jassertfalse;
  15790. return failedToWriteToFile;
  15791. }
  15792. }
  15793. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15794. {
  15795. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15796. TRANS("File already exists"),
  15797. TRANS("There's already a file called:\n\n")
  15798. + newFile.getFullPathName()
  15799. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15800. TRANS("overwrite"),
  15801. TRANS("cancel")))
  15802. {
  15803. return userCancelledSave;
  15804. }
  15805. }
  15806. MouseCursor::showWaitCursor();
  15807. const File oldFile (documentFile);
  15808. documentFile = newFile;
  15809. String error (saveDocument (newFile));
  15810. if (error.isEmpty())
  15811. {
  15812. setChangedFlag (false);
  15813. MouseCursor::hideWaitCursor();
  15814. return savedOk;
  15815. }
  15816. documentFile = oldFile;
  15817. MouseCursor::hideWaitCursor();
  15818. if (showMessageOnFailure)
  15819. {
  15820. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15821. TRANS("Error writing to file..."),
  15822. TRANS("An error occurred while trying to save \"")
  15823. + getDocumentTitle()
  15824. + TRANS("\" to the file:\n\n")
  15825. + newFile.getFullPathName()
  15826. + "\n\n"
  15827. + error);
  15828. }
  15829. return failedToWriteToFile;
  15830. }
  15831. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15832. {
  15833. if (! hasChangedSinceSaved())
  15834. return savedOk;
  15835. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15836. TRANS("Closing document..."),
  15837. TRANS("Do you want to save the changes to \"")
  15838. + getDocumentTitle() + "\"?",
  15839. TRANS("save"),
  15840. TRANS("discard changes"),
  15841. TRANS("cancel"));
  15842. if (r == 1)
  15843. {
  15844. // save changes
  15845. return save (true, true);
  15846. }
  15847. else if (r == 2)
  15848. {
  15849. // discard changes
  15850. return savedOk;
  15851. }
  15852. return userCancelledSave;
  15853. }
  15854. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15855. {
  15856. File f;
  15857. if (documentFile.existsAsFile())
  15858. f = documentFile;
  15859. else
  15860. f = getLastDocumentOpened();
  15861. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15862. if (legalFilename.isEmpty())
  15863. legalFilename = "unnamed";
  15864. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15865. f = f.getSiblingFile (legalFilename);
  15866. else
  15867. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15868. f = f.withFileExtension (fileExtension)
  15869. .getNonexistentSibling (true);
  15870. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15871. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15872. {
  15873. File chosen (fc.getResult());
  15874. if (chosen.getFileExtension().isEmpty())
  15875. {
  15876. chosen = chosen.withFileExtension (fileExtension);
  15877. if (chosen.exists())
  15878. {
  15879. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15880. TRANS("File already exists"),
  15881. TRANS("There's already a file called:")
  15882. + "\n\n" + chosen.getFullPathName()
  15883. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15884. TRANS("overwrite"),
  15885. TRANS("cancel")))
  15886. {
  15887. return userCancelledSave;
  15888. }
  15889. }
  15890. }
  15891. setLastDocumentOpened (chosen);
  15892. return saveAs (chosen, false, false, true);
  15893. }
  15894. return userCancelledSave;
  15895. }
  15896. END_JUCE_NAMESPACE
  15897. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15898. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15899. BEGIN_JUCE_NAMESPACE
  15900. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15901. : maxNumberOfItems (10)
  15902. {
  15903. }
  15904. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15905. {
  15906. }
  15907. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15908. {
  15909. maxNumberOfItems = jmax (1, newMaxNumber);
  15910. while (getNumFiles() > maxNumberOfItems)
  15911. files.remove (getNumFiles() - 1);
  15912. }
  15913. int RecentlyOpenedFilesList::getNumFiles() const
  15914. {
  15915. return files.size();
  15916. }
  15917. const File RecentlyOpenedFilesList::getFile (const int index) const
  15918. {
  15919. return File (files [index]);
  15920. }
  15921. void RecentlyOpenedFilesList::clear()
  15922. {
  15923. files.clear();
  15924. }
  15925. void RecentlyOpenedFilesList::addFile (const File& file)
  15926. {
  15927. const String path (file.getFullPathName());
  15928. files.removeString (path, true);
  15929. files.insert (0, path);
  15930. setMaxNumberOfItems (maxNumberOfItems);
  15931. }
  15932. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15933. {
  15934. for (int i = getNumFiles(); --i >= 0;)
  15935. if (! getFile(i).exists())
  15936. files.remove (i);
  15937. }
  15938. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15939. const int baseItemId,
  15940. const bool showFullPaths,
  15941. const bool dontAddNonExistentFiles,
  15942. const File** filesToAvoid)
  15943. {
  15944. int num = 0;
  15945. for (int i = 0; i < getNumFiles(); ++i)
  15946. {
  15947. const File f (getFile(i));
  15948. if ((! dontAddNonExistentFiles) || f.exists())
  15949. {
  15950. bool needsAvoiding = false;
  15951. if (filesToAvoid != 0)
  15952. {
  15953. const File** avoid = filesToAvoid;
  15954. while (*avoid != 0)
  15955. {
  15956. if (f == **avoid)
  15957. {
  15958. needsAvoiding = true;
  15959. break;
  15960. }
  15961. ++avoid;
  15962. }
  15963. }
  15964. if (! needsAvoiding)
  15965. {
  15966. menuToAddTo.addItem (baseItemId + i,
  15967. showFullPaths ? f.getFullPathName()
  15968. : f.getFileName());
  15969. ++num;
  15970. }
  15971. }
  15972. }
  15973. return num;
  15974. }
  15975. const String RecentlyOpenedFilesList::toString() const
  15976. {
  15977. return files.joinIntoString ("\n");
  15978. }
  15979. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15980. {
  15981. clear();
  15982. files.addLines (stringifiedVersion);
  15983. setMaxNumberOfItems (maxNumberOfItems);
  15984. }
  15985. END_JUCE_NAMESPACE
  15986. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15987. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15988. BEGIN_JUCE_NAMESPACE
  15989. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15990. const int minimumTransactions)
  15991. : totalUnitsStored (0),
  15992. nextIndex (0),
  15993. newTransaction (true),
  15994. reentrancyCheck (false)
  15995. {
  15996. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15997. minimumTransactions);
  15998. }
  15999. UndoManager::~UndoManager()
  16000. {
  16001. clearUndoHistory();
  16002. }
  16003. void UndoManager::clearUndoHistory()
  16004. {
  16005. transactions.clear();
  16006. transactionNames.clear();
  16007. totalUnitsStored = 0;
  16008. nextIndex = 0;
  16009. sendChangeMessage();
  16010. }
  16011. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16012. {
  16013. return totalUnitsStored;
  16014. }
  16015. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16016. const int minimumTransactions)
  16017. {
  16018. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16019. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16020. }
  16021. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16022. {
  16023. if (command_ != 0)
  16024. {
  16025. ScopedPointer<UndoableAction> command (command_);
  16026. if (actionName.isNotEmpty())
  16027. currentTransactionName = actionName;
  16028. if (reentrancyCheck)
  16029. {
  16030. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16031. // undo() methods, or else these actions won't actually get done.
  16032. return false;
  16033. }
  16034. else if (command->perform())
  16035. {
  16036. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16037. if (commandSet != 0 && ! newTransaction)
  16038. {
  16039. UndoableAction* lastAction = commandSet->getLast();
  16040. if (lastAction != 0)
  16041. {
  16042. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16043. if (coalescedAction != 0)
  16044. {
  16045. command = coalescedAction;
  16046. totalUnitsStored -= lastAction->getSizeInUnits();
  16047. commandSet->removeLast();
  16048. }
  16049. }
  16050. }
  16051. else
  16052. {
  16053. commandSet = new OwnedArray<UndoableAction>();
  16054. transactions.insert (nextIndex, commandSet);
  16055. transactionNames.insert (nextIndex, currentTransactionName);
  16056. ++nextIndex;
  16057. }
  16058. totalUnitsStored += command->getSizeInUnits();
  16059. commandSet->add (command.release());
  16060. newTransaction = false;
  16061. while (nextIndex < transactions.size())
  16062. {
  16063. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16064. for (int i = lastSet->size(); --i >= 0;)
  16065. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16066. transactions.removeLast();
  16067. transactionNames.remove (transactionNames.size() - 1);
  16068. }
  16069. while (nextIndex > 0
  16070. && totalUnitsStored > maxNumUnitsToKeep
  16071. && transactions.size() > minimumTransactionsToKeep)
  16072. {
  16073. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16074. for (int i = firstSet->size(); --i >= 0;)
  16075. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16076. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16077. transactions.remove (0);
  16078. transactionNames.remove (0);
  16079. --nextIndex;
  16080. }
  16081. sendChangeMessage();
  16082. return true;
  16083. }
  16084. }
  16085. return false;
  16086. }
  16087. void UndoManager::beginNewTransaction (const String& actionName)
  16088. {
  16089. newTransaction = true;
  16090. currentTransactionName = actionName;
  16091. }
  16092. void UndoManager::setCurrentTransactionName (const String& newName)
  16093. {
  16094. currentTransactionName = newName;
  16095. }
  16096. bool UndoManager::canUndo() const
  16097. {
  16098. return nextIndex > 0;
  16099. }
  16100. bool UndoManager::canRedo() const
  16101. {
  16102. return nextIndex < transactions.size();
  16103. }
  16104. const String UndoManager::getUndoDescription() const
  16105. {
  16106. return transactionNames [nextIndex - 1];
  16107. }
  16108. const String UndoManager::getRedoDescription() const
  16109. {
  16110. return transactionNames [nextIndex];
  16111. }
  16112. bool UndoManager::undo()
  16113. {
  16114. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16115. if (commandSet == 0)
  16116. return false;
  16117. bool failed = false;
  16118. {
  16119. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16120. for (int i = commandSet->size(); --i >= 0;)
  16121. {
  16122. if (! commandSet->getUnchecked(i)->undo())
  16123. {
  16124. jassertfalse;
  16125. failed = true;
  16126. break;
  16127. }
  16128. }
  16129. }
  16130. if (failed)
  16131. clearUndoHistory();
  16132. else
  16133. --nextIndex;
  16134. beginNewTransaction();
  16135. sendChangeMessage();
  16136. return true;
  16137. }
  16138. bool UndoManager::redo()
  16139. {
  16140. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16141. if (commandSet == 0)
  16142. return false;
  16143. bool failed = false;
  16144. {
  16145. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16146. for (int i = 0; i < commandSet->size(); ++i)
  16147. {
  16148. if (! commandSet->getUnchecked(i)->perform())
  16149. {
  16150. jassertfalse;
  16151. failed = true;
  16152. break;
  16153. }
  16154. }
  16155. }
  16156. if (failed)
  16157. clearUndoHistory();
  16158. else
  16159. ++nextIndex;
  16160. beginNewTransaction();
  16161. sendChangeMessage();
  16162. return true;
  16163. }
  16164. bool UndoManager::undoCurrentTransactionOnly()
  16165. {
  16166. return newTransaction ? false : undo();
  16167. }
  16168. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16169. {
  16170. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16171. if (commandSet != 0 && ! newTransaction)
  16172. {
  16173. for (int i = 0; i < commandSet->size(); ++i)
  16174. actionsFound.add (commandSet->getUnchecked(i));
  16175. }
  16176. }
  16177. int UndoManager::getNumActionsInCurrentTransaction() const
  16178. {
  16179. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16180. if (commandSet != 0 && ! newTransaction)
  16181. return commandSet->size();
  16182. return 0;
  16183. }
  16184. END_JUCE_NAMESPACE
  16185. /*** End of inlined file: juce_UndoManager.cpp ***/
  16186. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16187. BEGIN_JUCE_NAMESPACE
  16188. static const char* const aiffFormatName = "AIFF file";
  16189. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16190. class AiffAudioFormatReader : public AudioFormatReader
  16191. {
  16192. public:
  16193. int bytesPerFrame;
  16194. int64 dataChunkStart;
  16195. bool littleEndian;
  16196. AiffAudioFormatReader (InputStream* in)
  16197. : AudioFormatReader (in, TRANS (aiffFormatName))
  16198. {
  16199. if (input->readInt() == chunkName ("FORM"))
  16200. {
  16201. const int len = input->readIntBigEndian();
  16202. const int64 end = input->getPosition() + len;
  16203. const int nextType = input->readInt();
  16204. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16205. {
  16206. bool hasGotVer = false;
  16207. bool hasGotData = false;
  16208. bool hasGotType = false;
  16209. while (input->getPosition() < end)
  16210. {
  16211. const int type = input->readInt();
  16212. const uint32 length = (uint32) input->readIntBigEndian();
  16213. const int64 chunkEnd = input->getPosition() + length;
  16214. if (type == chunkName ("FVER"))
  16215. {
  16216. hasGotVer = true;
  16217. const int ver = input->readIntBigEndian();
  16218. if (ver != 0 && ver != (int) 0xa2805140)
  16219. break;
  16220. }
  16221. else if (type == chunkName ("COMM"))
  16222. {
  16223. hasGotType = true;
  16224. numChannels = (unsigned int) input->readShortBigEndian();
  16225. lengthInSamples = input->readIntBigEndian();
  16226. bitsPerSample = input->readShortBigEndian();
  16227. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16228. unsigned char sampleRateBytes[10];
  16229. input->read (sampleRateBytes, 10);
  16230. const int byte0 = sampleRateBytes[0];
  16231. if ((byte0 & 0x80) != 0
  16232. || byte0 <= 0x3F || byte0 > 0x40
  16233. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16234. break;
  16235. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16236. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16237. sampleRate = (int) sampRate;
  16238. if (length <= 18)
  16239. {
  16240. // some types don't have a chunk large enough to include a compression
  16241. // type, so assume it's just big-endian pcm
  16242. littleEndian = false;
  16243. }
  16244. else
  16245. {
  16246. const int compType = input->readInt();
  16247. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16248. {
  16249. littleEndian = false;
  16250. }
  16251. else if (compType == chunkName ("sowt"))
  16252. {
  16253. littleEndian = true;
  16254. }
  16255. else
  16256. {
  16257. sampleRate = 0;
  16258. break;
  16259. }
  16260. }
  16261. }
  16262. else if (type == chunkName ("SSND"))
  16263. {
  16264. hasGotData = true;
  16265. const int offset = input->readIntBigEndian();
  16266. dataChunkStart = input->getPosition() + 4 + offset;
  16267. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16268. }
  16269. else if ((hasGotVer && hasGotData && hasGotType)
  16270. || chunkEnd < input->getPosition()
  16271. || input->isExhausted())
  16272. {
  16273. break;
  16274. }
  16275. input->setPosition (chunkEnd);
  16276. }
  16277. }
  16278. }
  16279. }
  16280. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16281. int64 startSampleInFile, int numSamples)
  16282. {
  16283. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16284. if (samplesAvailable < numSamples)
  16285. {
  16286. for (int i = numDestChannels; --i >= 0;)
  16287. if (destSamples[i] != 0)
  16288. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16289. numSamples = (int) samplesAvailable;
  16290. }
  16291. if (numSamples <= 0)
  16292. return true;
  16293. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16294. while (numSamples > 0)
  16295. {
  16296. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16297. char tempBuffer [tempBufSize];
  16298. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16299. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16300. if (bytesRead < numThisTime * bytesPerFrame)
  16301. {
  16302. jassert (bytesRead >= 0);
  16303. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16304. }
  16305. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16306. if (littleEndian)
  16307. {
  16308. switch (bitsPerSample)
  16309. {
  16310. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16311. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16312. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16313. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16314. default: jassertfalse; break;
  16315. }
  16316. }
  16317. else
  16318. {
  16319. switch (bitsPerSample)
  16320. {
  16321. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16322. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16323. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16324. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16325. default: jassertfalse; break;
  16326. }
  16327. }
  16328. startOffsetInDestBuffer += numThisTime;
  16329. numSamples -= numThisTime;
  16330. }
  16331. return true;
  16332. }
  16333. private:
  16334. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16335. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16336. };
  16337. class AiffAudioFormatWriter : public AudioFormatWriter
  16338. {
  16339. public:
  16340. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16341. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16342. lengthInSamples (0),
  16343. bytesWritten (0),
  16344. writeFailed (false)
  16345. {
  16346. headerPosition = out->getPosition();
  16347. writeHeader();
  16348. }
  16349. ~AiffAudioFormatWriter()
  16350. {
  16351. if ((bytesWritten & 1) != 0)
  16352. output->writeByte (0);
  16353. writeHeader();
  16354. }
  16355. bool write (const int** data, int numSamples)
  16356. {
  16357. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16358. if (writeFailed)
  16359. return false;
  16360. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16361. tempBlock.ensureSize (bytes, false);
  16362. switch (bitsPerSample)
  16363. {
  16364. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16365. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16366. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16367. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16368. default: jassertfalse; break;
  16369. }
  16370. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16371. || ! output->write (tempBlock.getData(), bytes))
  16372. {
  16373. // failed to write to disk, so let's try writing the header.
  16374. // If it's just run out of disk space, then if it does manage
  16375. // to write the header, we'll still have a useable file..
  16376. writeHeader();
  16377. writeFailed = true;
  16378. return false;
  16379. }
  16380. else
  16381. {
  16382. bytesWritten += bytes;
  16383. lengthInSamples += numSamples;
  16384. return true;
  16385. }
  16386. }
  16387. private:
  16388. MemoryBlock tempBlock;
  16389. uint32 lengthInSamples, bytesWritten;
  16390. int64 headerPosition;
  16391. bool writeFailed;
  16392. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16393. void writeHeader()
  16394. {
  16395. const bool couldSeekOk = output->setPosition (headerPosition);
  16396. (void) couldSeekOk;
  16397. // if this fails, you've given it an output stream that can't seek! It needs
  16398. // to be able to seek back to write the header
  16399. jassert (couldSeekOk);
  16400. const int headerLen = 54;
  16401. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16402. audioBytes += (audioBytes & 1);
  16403. output->writeInt (chunkName ("FORM"));
  16404. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16405. output->writeInt (chunkName ("AIFF"));
  16406. output->writeInt (chunkName ("COMM"));
  16407. output->writeIntBigEndian (18);
  16408. output->writeShortBigEndian ((short) numChannels);
  16409. output->writeIntBigEndian (lengthInSamples);
  16410. output->writeShortBigEndian ((short) bitsPerSample);
  16411. uint8 sampleRateBytes[10];
  16412. zeromem (sampleRateBytes, 10);
  16413. if (sampleRate <= 1)
  16414. {
  16415. sampleRateBytes[0] = 0x3f;
  16416. sampleRateBytes[1] = 0xff;
  16417. sampleRateBytes[2] = 0x80;
  16418. }
  16419. else
  16420. {
  16421. int mask = 0x40000000;
  16422. sampleRateBytes[0] = 0x40;
  16423. if (sampleRate >= mask)
  16424. {
  16425. jassertfalse;
  16426. sampleRateBytes[1] = 0x1d;
  16427. }
  16428. else
  16429. {
  16430. int n = (int) sampleRate;
  16431. int i;
  16432. for (i = 0; i <= 32 ; ++i)
  16433. {
  16434. if ((n & mask) != 0)
  16435. break;
  16436. mask >>= 1;
  16437. }
  16438. n = n << (i + 1);
  16439. sampleRateBytes[1] = (uint8) (29 - i);
  16440. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16441. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16442. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16443. sampleRateBytes[5] = (uint8) (n & 0xff);
  16444. }
  16445. }
  16446. output->write (sampleRateBytes, 10);
  16447. output->writeInt (chunkName ("SSND"));
  16448. output->writeIntBigEndian (audioBytes + 8);
  16449. output->writeInt (0);
  16450. output->writeInt (0);
  16451. jassert (output->getPosition() == headerLen);
  16452. }
  16453. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16454. };
  16455. AiffAudioFormat::AiffAudioFormat()
  16456. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16457. {
  16458. }
  16459. AiffAudioFormat::~AiffAudioFormat()
  16460. {
  16461. }
  16462. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16463. {
  16464. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16465. return Array <int> (rates);
  16466. }
  16467. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16468. {
  16469. const int depths[] = { 8, 16, 24, 0 };
  16470. return Array <int> (depths);
  16471. }
  16472. bool AiffAudioFormat::canDoStereo() { return true; }
  16473. bool AiffAudioFormat::canDoMono() { return true; }
  16474. #if JUCE_MAC
  16475. bool AiffAudioFormat::canHandleFile (const File& f)
  16476. {
  16477. if (AudioFormat::canHandleFile (f))
  16478. return true;
  16479. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16480. return type == 'AIFF' || type == 'AIFC'
  16481. || type == 'aiff' || type == 'aifc';
  16482. }
  16483. #endif
  16484. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16485. {
  16486. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16487. if (w->sampleRate != 0)
  16488. return w.release();
  16489. if (! deleteStreamIfOpeningFails)
  16490. w->input = 0;
  16491. return 0;
  16492. }
  16493. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16494. double sampleRate,
  16495. unsigned int numberOfChannels,
  16496. int bitsPerSample,
  16497. const StringPairArray& /*metadataValues*/,
  16498. int /*qualityOptionIndex*/)
  16499. {
  16500. if (getPossibleBitDepths().contains (bitsPerSample))
  16501. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16502. return 0;
  16503. }
  16504. END_JUCE_NAMESPACE
  16505. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16506. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16507. BEGIN_JUCE_NAMESPACE
  16508. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16509. : formatName (name),
  16510. fileExtensions (extensions)
  16511. {
  16512. }
  16513. AudioFormat::~AudioFormat()
  16514. {
  16515. }
  16516. bool AudioFormat::canHandleFile (const File& f)
  16517. {
  16518. for (int i = 0; i < fileExtensions.size(); ++i)
  16519. if (f.hasFileExtension (fileExtensions[i]))
  16520. return true;
  16521. return false;
  16522. }
  16523. const String& AudioFormat::getFormatName() const { return formatName; }
  16524. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16525. bool AudioFormat::isCompressed() { return false; }
  16526. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16527. END_JUCE_NAMESPACE
  16528. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16529. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16530. BEGIN_JUCE_NAMESPACE
  16531. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16532. const String& formatName_)
  16533. : sampleRate (0),
  16534. bitsPerSample (0),
  16535. lengthInSamples (0),
  16536. numChannels (0),
  16537. usesFloatingPointData (false),
  16538. input (in),
  16539. formatName (formatName_)
  16540. {
  16541. }
  16542. AudioFormatReader::~AudioFormatReader()
  16543. {
  16544. delete input;
  16545. }
  16546. bool AudioFormatReader::read (int* const* destSamples,
  16547. int numDestChannels,
  16548. int64 startSampleInSource,
  16549. int numSamplesToRead,
  16550. const bool fillLeftoverChannelsWithCopies)
  16551. {
  16552. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16553. int startOffsetInDestBuffer = 0;
  16554. if (startSampleInSource < 0)
  16555. {
  16556. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16557. for (int i = numDestChannels; --i >= 0;)
  16558. if (destSamples[i] != 0)
  16559. zeromem (destSamples[i], sizeof (int) * silence);
  16560. startOffsetInDestBuffer += silence;
  16561. numSamplesToRead -= silence;
  16562. startSampleInSource = 0;
  16563. }
  16564. if (numSamplesToRead <= 0)
  16565. return true;
  16566. if (! readSamples (const_cast<int**> (destSamples),
  16567. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16568. startSampleInSource, numSamplesToRead))
  16569. return false;
  16570. if (numDestChannels > (int) numChannels)
  16571. {
  16572. if (fillLeftoverChannelsWithCopies)
  16573. {
  16574. int* lastFullChannel = destSamples[0];
  16575. for (int i = (int) numChannels; --i > 0;)
  16576. {
  16577. if (destSamples[i] != 0)
  16578. {
  16579. lastFullChannel = destSamples[i];
  16580. break;
  16581. }
  16582. }
  16583. if (lastFullChannel != 0)
  16584. for (int i = numChannels; i < numDestChannels; ++i)
  16585. if (destSamples[i] != 0)
  16586. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16587. }
  16588. else
  16589. {
  16590. for (int i = numChannels; i < numDestChannels; ++i)
  16591. if (destSamples[i] != 0)
  16592. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16593. }
  16594. }
  16595. return true;
  16596. }
  16597. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16598. int64 numSamples,
  16599. float& lowestLeft, float& highestLeft,
  16600. float& lowestRight, float& highestRight)
  16601. {
  16602. if (numSamples <= 0)
  16603. {
  16604. lowestLeft = 0;
  16605. lowestRight = 0;
  16606. highestLeft = 0;
  16607. highestRight = 0;
  16608. return;
  16609. }
  16610. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16611. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16612. int* tempBuffer[3];
  16613. tempBuffer[0] = tempSpace.getData();
  16614. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16615. tempBuffer[2] = 0;
  16616. if (usesFloatingPointData)
  16617. {
  16618. float lmin = 1.0e6f;
  16619. float lmax = -lmin;
  16620. float rmin = lmin;
  16621. float rmax = lmax;
  16622. while (numSamples > 0)
  16623. {
  16624. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16625. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16626. numSamples -= numToDo;
  16627. startSampleInFile += numToDo;
  16628. float bufMin, bufMax;
  16629. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16630. lmin = jmin (lmin, bufMin);
  16631. lmax = jmax (lmax, bufMax);
  16632. if (numChannels > 1)
  16633. {
  16634. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16635. rmin = jmin (rmin, bufMin);
  16636. rmax = jmax (rmax, bufMax);
  16637. }
  16638. }
  16639. if (numChannels <= 1)
  16640. {
  16641. rmax = lmax;
  16642. rmin = lmin;
  16643. }
  16644. lowestLeft = lmin;
  16645. highestLeft = lmax;
  16646. lowestRight = rmin;
  16647. highestRight = rmax;
  16648. }
  16649. else
  16650. {
  16651. int lmax = std::numeric_limits<int>::min();
  16652. int lmin = std::numeric_limits<int>::max();
  16653. int rmax = std::numeric_limits<int>::min();
  16654. int rmin = std::numeric_limits<int>::max();
  16655. while (numSamples > 0)
  16656. {
  16657. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16658. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16659. break;
  16660. numSamples -= numToDo;
  16661. startSampleInFile += numToDo;
  16662. for (int j = numChannels; --j >= 0;)
  16663. {
  16664. int bufMin, bufMax;
  16665. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16666. if (j == 0)
  16667. {
  16668. lmax = jmax (lmax, bufMax);
  16669. lmin = jmin (lmin, bufMin);
  16670. }
  16671. else
  16672. {
  16673. rmax = jmax (rmax, bufMax);
  16674. rmin = jmin (rmin, bufMin);
  16675. }
  16676. }
  16677. }
  16678. if (numChannels <= 1)
  16679. {
  16680. rmax = lmax;
  16681. rmin = lmin;
  16682. }
  16683. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16684. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16685. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16686. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16687. }
  16688. }
  16689. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16690. int64 numSamplesToSearch,
  16691. const double magnitudeRangeMinimum,
  16692. const double magnitudeRangeMaximum,
  16693. const int minimumConsecutiveSamples)
  16694. {
  16695. if (numSamplesToSearch == 0)
  16696. return -1;
  16697. const int bufferSize = 4096;
  16698. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16699. int* tempBuffer[3];
  16700. tempBuffer[0] = tempSpace.getData();
  16701. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16702. tempBuffer[2] = 0;
  16703. int consecutive = 0;
  16704. int64 firstMatchPos = -1;
  16705. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16706. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16707. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16708. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16709. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16710. while (numSamplesToSearch != 0)
  16711. {
  16712. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16713. int64 bufferStart = startSample;
  16714. if (numSamplesToSearch < 0)
  16715. bufferStart -= numThisTime;
  16716. if (bufferStart >= (int) lengthInSamples)
  16717. break;
  16718. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16719. int num = numThisTime;
  16720. while (--num >= 0)
  16721. {
  16722. if (numSamplesToSearch < 0)
  16723. --startSample;
  16724. bool matches = false;
  16725. const int index = (int) (startSample - bufferStart);
  16726. if (usesFloatingPointData)
  16727. {
  16728. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16729. if (sample1 >= magnitudeRangeMinimum
  16730. && sample1 <= magnitudeRangeMaximum)
  16731. {
  16732. matches = true;
  16733. }
  16734. else if (numChannels > 1)
  16735. {
  16736. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16737. matches = (sample2 >= magnitudeRangeMinimum
  16738. && sample2 <= magnitudeRangeMaximum);
  16739. }
  16740. }
  16741. else
  16742. {
  16743. const int sample1 = abs (tempBuffer[0] [index]);
  16744. if (sample1 >= intMagnitudeRangeMinimum
  16745. && sample1 <= intMagnitudeRangeMaximum)
  16746. {
  16747. matches = true;
  16748. }
  16749. else if (numChannels > 1)
  16750. {
  16751. const int sample2 = abs (tempBuffer[1][index]);
  16752. matches = (sample2 >= intMagnitudeRangeMinimum
  16753. && sample2 <= intMagnitudeRangeMaximum);
  16754. }
  16755. }
  16756. if (matches)
  16757. {
  16758. if (firstMatchPos < 0)
  16759. firstMatchPos = startSample;
  16760. if (++consecutive >= minimumConsecutiveSamples)
  16761. {
  16762. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16763. return -1;
  16764. return firstMatchPos;
  16765. }
  16766. }
  16767. else
  16768. {
  16769. consecutive = 0;
  16770. firstMatchPos = -1;
  16771. }
  16772. if (numSamplesToSearch > 0)
  16773. ++startSample;
  16774. }
  16775. if (numSamplesToSearch > 0)
  16776. numSamplesToSearch -= numThisTime;
  16777. else
  16778. numSamplesToSearch += numThisTime;
  16779. }
  16780. return -1;
  16781. }
  16782. END_JUCE_NAMESPACE
  16783. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  16784. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  16785. BEGIN_JUCE_NAMESPACE
  16786. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16787. const String& formatName_,
  16788. const double rate,
  16789. const unsigned int numChannels_,
  16790. const unsigned int bitsPerSample_)
  16791. : sampleRate (rate),
  16792. numChannels (numChannels_),
  16793. bitsPerSample (bitsPerSample_),
  16794. usesFloatingPointData (false),
  16795. output (out),
  16796. formatName (formatName_)
  16797. {
  16798. }
  16799. AudioFormatWriter::~AudioFormatWriter()
  16800. {
  16801. delete output;
  16802. }
  16803. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16804. int64 startSample,
  16805. int64 numSamplesToRead)
  16806. {
  16807. const int bufferSize = 16384;
  16808. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16809. int* buffers [128];
  16810. zerostruct (buffers);
  16811. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16812. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  16813. if (numSamplesToRead < 0)
  16814. numSamplesToRead = reader.lengthInSamples;
  16815. while (numSamplesToRead > 0)
  16816. {
  16817. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16818. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16819. return false;
  16820. if (reader.usesFloatingPointData != isFloatingPoint())
  16821. {
  16822. int** bufferChan = buffers;
  16823. while (*bufferChan != 0)
  16824. {
  16825. int* b = *bufferChan++;
  16826. if (isFloatingPoint())
  16827. {
  16828. // int -> float
  16829. const double factor = 1.0 / std::numeric_limits<int>::max();
  16830. for (int i = 0; i < numToDo; ++i)
  16831. ((float*) b)[i] = (float) (factor * b[i]);
  16832. }
  16833. else
  16834. {
  16835. // float -> int
  16836. for (int i = 0; i < numToDo; ++i)
  16837. {
  16838. const double samp = *(const float*) b;
  16839. if (samp <= -1.0)
  16840. *b++ = std::numeric_limits<int>::min();
  16841. else if (samp >= 1.0)
  16842. *b++ = std::numeric_limits<int>::max();
  16843. else
  16844. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16845. }
  16846. }
  16847. }
  16848. }
  16849. if (! write (const_cast<const int**> (buffers), numToDo))
  16850. return false;
  16851. numSamplesToRead -= numToDo;
  16852. startSample += numToDo;
  16853. }
  16854. return true;
  16855. }
  16856. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  16857. {
  16858. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16859. while (numSamplesToRead > 0)
  16860. {
  16861. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16862. AudioSourceChannelInfo info;
  16863. info.buffer = &tempBuffer;
  16864. info.startSample = 0;
  16865. info.numSamples = numToDo;
  16866. info.clearActiveBufferRegion();
  16867. source.getNextAudioBlock (info);
  16868. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  16869. return false;
  16870. numSamplesToRead -= numToDo;
  16871. }
  16872. return true;
  16873. }
  16874. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  16875. {
  16876. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  16877. if (numSamples <= 0)
  16878. return true;
  16879. HeapBlock<int> tempBuffer;
  16880. HeapBlock<int*> chans (numChannels + 1);
  16881. chans [numChannels] = 0;
  16882. if (isFloatingPoint())
  16883. {
  16884. for (int i = numChannels; --i >= 0;)
  16885. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  16886. }
  16887. else
  16888. {
  16889. tempBuffer.malloc (numSamples * numChannels);
  16890. for (unsigned int i = 0; i < numChannels; ++i)
  16891. {
  16892. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  16893. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  16894. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  16895. SourceSampleType sourceData (source.getSampleData (i, startSample));
  16896. destData.convertSamples (sourceData, numSamples);
  16897. }
  16898. }
  16899. return write ((const int**) chans.getData(), numSamples);
  16900. }
  16901. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  16902. public AbstractFifo
  16903. {
  16904. public:
  16905. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  16906. : AbstractFifo (bufferSize_),
  16907. buffer (numChannels, bufferSize_),
  16908. timeSliceThread (timeSliceThread_),
  16909. writer (writer_),
  16910. thumbnailToUpdate (0),
  16911. samplesWritten (0),
  16912. isRunning (true)
  16913. {
  16914. timeSliceThread.addTimeSliceClient (this);
  16915. }
  16916. ~Buffer()
  16917. {
  16918. isRunning = false;
  16919. timeSliceThread.removeTimeSliceClient (this);
  16920. while (useTimeSlice() == 0)
  16921. {}
  16922. }
  16923. bool write (const float** data, int numSamples)
  16924. {
  16925. if (numSamples <= 0 || ! isRunning)
  16926. return true;
  16927. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  16928. int start1, size1, start2, size2;
  16929. prepareToWrite (numSamples, start1, size1, start2, size2);
  16930. if (size1 + size2 < numSamples)
  16931. return false;
  16932. for (int i = buffer.getNumChannels(); --i >= 0;)
  16933. {
  16934. buffer.copyFrom (i, start1, data[i], size1);
  16935. buffer.copyFrom (i, start2, data[i] + size1, size2);
  16936. }
  16937. finishedWrite (size1 + size2);
  16938. timeSliceThread.notify();
  16939. return true;
  16940. }
  16941. int useTimeSlice()
  16942. {
  16943. const int numToDo = getTotalSize() / 4;
  16944. int start1, size1, start2, size2;
  16945. prepareToRead (numToDo, start1, size1, start2, size2);
  16946. if (size1 <= 0)
  16947. return 10;
  16948. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  16949. const ScopedLock sl (thumbnailLock);
  16950. if (thumbnailToUpdate != 0)
  16951. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  16952. samplesWritten += size1;
  16953. if (size2 > 0)
  16954. {
  16955. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  16956. if (thumbnailToUpdate != 0)
  16957. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  16958. samplesWritten += size2;
  16959. }
  16960. finishedRead (size1 + size2);
  16961. return 0;
  16962. }
  16963. void setThumbnail (AudioThumbnail* thumb)
  16964. {
  16965. if (thumb != 0)
  16966. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  16967. const ScopedLock sl (thumbnailLock);
  16968. thumbnailToUpdate = thumb;
  16969. samplesWritten = 0;
  16970. }
  16971. private:
  16972. AudioSampleBuffer buffer;
  16973. TimeSliceThread& timeSliceThread;
  16974. ScopedPointer<AudioFormatWriter> writer;
  16975. CriticalSection thumbnailLock;
  16976. AudioThumbnail* thumbnailToUpdate;
  16977. int64 samplesWritten;
  16978. volatile bool isRunning;
  16979. JUCE_DECLARE_NON_COPYABLE (Buffer);
  16980. };
  16981. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  16982. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  16983. {
  16984. }
  16985. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  16986. {
  16987. }
  16988. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  16989. {
  16990. return buffer->write (data, numSamples);
  16991. }
  16992. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  16993. {
  16994. buffer->setThumbnail (thumb);
  16995. }
  16996. END_JUCE_NAMESPACE
  16997. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  16998. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16999. BEGIN_JUCE_NAMESPACE
  17000. AudioFormatManager::AudioFormatManager()
  17001. : defaultFormatIndex (0)
  17002. {
  17003. }
  17004. AudioFormatManager::~AudioFormatManager()
  17005. {
  17006. }
  17007. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17008. {
  17009. jassert (newFormat != 0);
  17010. if (newFormat != 0)
  17011. {
  17012. #if JUCE_DEBUG
  17013. for (int i = getNumKnownFormats(); --i >= 0;)
  17014. {
  17015. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17016. {
  17017. jassertfalse; // trying to add the same format twice!
  17018. }
  17019. }
  17020. #endif
  17021. if (makeThisTheDefaultFormat)
  17022. defaultFormatIndex = getNumKnownFormats();
  17023. knownFormats.add (newFormat);
  17024. }
  17025. }
  17026. void AudioFormatManager::registerBasicFormats()
  17027. {
  17028. #if JUCE_MAC
  17029. registerFormat (new AiffAudioFormat(), true);
  17030. registerFormat (new WavAudioFormat(), false);
  17031. #else
  17032. registerFormat (new WavAudioFormat(), true);
  17033. registerFormat (new AiffAudioFormat(), false);
  17034. #endif
  17035. #if JUCE_USE_FLAC
  17036. registerFormat (new FlacAudioFormat(), false);
  17037. #endif
  17038. #if JUCE_USE_OGGVORBIS
  17039. registerFormat (new OggVorbisAudioFormat(), false);
  17040. #endif
  17041. }
  17042. void AudioFormatManager::clearFormats()
  17043. {
  17044. knownFormats.clear();
  17045. defaultFormatIndex = 0;
  17046. }
  17047. int AudioFormatManager::getNumKnownFormats() const
  17048. {
  17049. return knownFormats.size();
  17050. }
  17051. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17052. {
  17053. return knownFormats [index];
  17054. }
  17055. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17056. {
  17057. return getKnownFormat (defaultFormatIndex);
  17058. }
  17059. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17060. {
  17061. String e (fileExtension);
  17062. if (! e.startsWithChar ('.'))
  17063. e = "." + e;
  17064. for (int i = 0; i < getNumKnownFormats(); ++i)
  17065. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17066. return getKnownFormat(i);
  17067. return 0;
  17068. }
  17069. const String AudioFormatManager::getWildcardForAllFormats() const
  17070. {
  17071. StringArray allExtensions;
  17072. int i;
  17073. for (i = 0; i < getNumKnownFormats(); ++i)
  17074. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17075. allExtensions.trim();
  17076. allExtensions.removeEmptyStrings();
  17077. String s;
  17078. for (i = 0; i < allExtensions.size(); ++i)
  17079. {
  17080. s << '*';
  17081. if (! allExtensions[i].startsWithChar ('.'))
  17082. s << '.';
  17083. s << allExtensions[i];
  17084. if (i < allExtensions.size() - 1)
  17085. s << ';';
  17086. }
  17087. return s;
  17088. }
  17089. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17090. {
  17091. // you need to actually register some formats before the manager can
  17092. // use them to open a file!
  17093. jassert (getNumKnownFormats() > 0);
  17094. for (int i = 0; i < getNumKnownFormats(); ++i)
  17095. {
  17096. AudioFormat* const af = getKnownFormat(i);
  17097. if (af->canHandleFile (file))
  17098. {
  17099. InputStream* const in = file.createInputStream();
  17100. if (in != 0)
  17101. {
  17102. AudioFormatReader* const r = af->createReaderFor (in, true);
  17103. if (r != 0)
  17104. return r;
  17105. }
  17106. }
  17107. }
  17108. return 0;
  17109. }
  17110. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17111. {
  17112. // you need to actually register some formats before the manager can
  17113. // use them to open a file!
  17114. jassert (getNumKnownFormats() > 0);
  17115. ScopedPointer <InputStream> in (audioFileStream);
  17116. if (in != 0)
  17117. {
  17118. const int64 originalStreamPos = in->getPosition();
  17119. for (int i = 0; i < getNumKnownFormats(); ++i)
  17120. {
  17121. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17122. if (r != 0)
  17123. {
  17124. in.release();
  17125. return r;
  17126. }
  17127. in->setPosition (originalStreamPos);
  17128. // the stream that is passed-in must be capable of being repositioned so
  17129. // that all the formats can have a go at opening it.
  17130. jassert (in->getPosition() == originalStreamPos);
  17131. }
  17132. }
  17133. return 0;
  17134. }
  17135. END_JUCE_NAMESPACE
  17136. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17137. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17138. BEGIN_JUCE_NAMESPACE
  17139. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17140. const int64 startSample_,
  17141. const int64 length_,
  17142. const bool deleteSourceWhenDeleted_)
  17143. : AudioFormatReader (0, source_->getFormatName()),
  17144. source (source_),
  17145. startSample (startSample_),
  17146. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17147. {
  17148. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17149. sampleRate = source->sampleRate;
  17150. bitsPerSample = source->bitsPerSample;
  17151. lengthInSamples = length;
  17152. numChannels = source->numChannels;
  17153. usesFloatingPointData = source->usesFloatingPointData;
  17154. }
  17155. AudioSubsectionReader::~AudioSubsectionReader()
  17156. {
  17157. if (deleteSourceWhenDeleted)
  17158. delete source;
  17159. }
  17160. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17161. int64 startSampleInFile, int numSamples)
  17162. {
  17163. if (startSampleInFile + numSamples > length)
  17164. {
  17165. for (int i = numDestChannels; --i >= 0;)
  17166. if (destSamples[i] != 0)
  17167. zeromem (destSamples[i], sizeof (int) * numSamples);
  17168. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17169. if (numSamples <= 0)
  17170. return true;
  17171. }
  17172. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17173. startSampleInFile + startSample, numSamples);
  17174. }
  17175. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17176. int64 numSamples,
  17177. float& lowestLeft,
  17178. float& highestLeft,
  17179. float& lowestRight,
  17180. float& highestRight)
  17181. {
  17182. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17183. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17184. source->readMaxLevels (startSampleInFile + startSample,
  17185. numSamples,
  17186. lowestLeft,
  17187. highestLeft,
  17188. lowestRight,
  17189. highestRight);
  17190. }
  17191. END_JUCE_NAMESPACE
  17192. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17193. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17194. BEGIN_JUCE_NAMESPACE
  17195. struct AudioThumbnail::MinMaxValue
  17196. {
  17197. char minValue;
  17198. char maxValue;
  17199. MinMaxValue() : minValue (0), maxValue (0)
  17200. {
  17201. }
  17202. inline void set (const char newMin, const char newMax) throw()
  17203. {
  17204. minValue = newMin;
  17205. maxValue = newMax;
  17206. }
  17207. inline void setFloat (const float newMin, const float newMax) throw()
  17208. {
  17209. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17210. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17211. if (maxValue == minValue)
  17212. maxValue = (char) jmin (127, maxValue + 1);
  17213. }
  17214. inline bool isNonZero() const throw()
  17215. {
  17216. return maxValue > minValue;
  17217. }
  17218. inline int getPeak() const throw()
  17219. {
  17220. return jmax (std::abs ((int) minValue),
  17221. std::abs ((int) maxValue));
  17222. }
  17223. inline void read (InputStream& input)
  17224. {
  17225. minValue = input.readByte();
  17226. maxValue = input.readByte();
  17227. }
  17228. inline void write (OutputStream& output)
  17229. {
  17230. output.writeByte (minValue);
  17231. output.writeByte (maxValue);
  17232. }
  17233. };
  17234. class AudioThumbnail::LevelDataSource : public TimeSliceClient
  17235. {
  17236. public:
  17237. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17238. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17239. hashCode (hash), owner (owner_), reader (newReader)
  17240. {
  17241. }
  17242. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17243. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17244. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17245. {
  17246. }
  17247. ~LevelDataSource()
  17248. {
  17249. owner.cache.removeTimeSliceClient (this);
  17250. }
  17251. enum { timeBeforeDeletingReader = 1000 };
  17252. void initialise (int64 numSamplesFinished_)
  17253. {
  17254. const ScopedLock sl (readerLock);
  17255. numSamplesFinished = numSamplesFinished_;
  17256. createReader();
  17257. if (reader != 0)
  17258. {
  17259. lengthInSamples = reader->lengthInSamples;
  17260. numChannels = reader->numChannels;
  17261. sampleRate = reader->sampleRate;
  17262. if (lengthInSamples <= 0 || isFullyLoaded())
  17263. reader = 0;
  17264. else
  17265. owner.cache.addTimeSliceClient (this);
  17266. }
  17267. }
  17268. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17269. {
  17270. const ScopedLock sl (readerLock);
  17271. if (reader == 0)
  17272. {
  17273. createReader();
  17274. if (reader != 0)
  17275. owner.cache.addTimeSliceClient (this);
  17276. }
  17277. if (reader != 0)
  17278. {
  17279. float l[4] = { 0 };
  17280. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17281. levels.clearQuick();
  17282. levels.addArray ((const float*) l, 4);
  17283. }
  17284. }
  17285. void releaseResources()
  17286. {
  17287. const ScopedLock sl (readerLock);
  17288. reader = 0;
  17289. }
  17290. int useTimeSlice()
  17291. {
  17292. if (isFullyLoaded())
  17293. {
  17294. if (reader != 0 && source != 0)
  17295. releaseResources();
  17296. return -1;
  17297. }
  17298. bool justFinished = false;
  17299. {
  17300. const ScopedLock sl (readerLock);
  17301. createReader();
  17302. if (reader != 0)
  17303. {
  17304. if (! readNextBlock())
  17305. return 0;
  17306. justFinished = true;
  17307. }
  17308. }
  17309. if (justFinished)
  17310. owner.cache.storeThumb (owner, hashCode);
  17311. return timeBeforeDeletingReader;
  17312. }
  17313. bool isFullyLoaded() const throw()
  17314. {
  17315. return numSamplesFinished >= lengthInSamples;
  17316. }
  17317. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17318. {
  17319. return (int) (originalSample / owner.samplesPerThumbSample);
  17320. }
  17321. int64 lengthInSamples, numSamplesFinished;
  17322. double sampleRate;
  17323. int numChannels;
  17324. int64 hashCode;
  17325. private:
  17326. AudioThumbnail& owner;
  17327. ScopedPointer <InputSource> source;
  17328. ScopedPointer <AudioFormatReader> reader;
  17329. CriticalSection readerLock;
  17330. void createReader()
  17331. {
  17332. if (reader == 0 && source != 0)
  17333. {
  17334. InputStream* audioFileStream = source->createInputStream();
  17335. if (audioFileStream != 0)
  17336. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17337. }
  17338. }
  17339. bool readNextBlock()
  17340. {
  17341. jassert (reader != 0);
  17342. if (! isFullyLoaded())
  17343. {
  17344. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17345. if (numToDo > 0)
  17346. {
  17347. int64 startSample = numSamplesFinished;
  17348. const int firstThumbIndex = sampleToThumbSample (startSample);
  17349. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17350. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17351. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17352. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17353. for (int i = 0; i < numThumbSamps; ++i)
  17354. {
  17355. float lowestLeft, highestLeft, lowestRight, highestRight;
  17356. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17357. lowestLeft, highestLeft, lowestRight, highestRight);
  17358. levels[0][i].setFloat (lowestLeft, highestLeft);
  17359. levels[1][i].setFloat (lowestRight, highestRight);
  17360. }
  17361. {
  17362. const ScopedUnlock su (readerLock);
  17363. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17364. }
  17365. numSamplesFinished += numToDo;
  17366. }
  17367. }
  17368. return isFullyLoaded();
  17369. }
  17370. };
  17371. class AudioThumbnail::ThumbData
  17372. {
  17373. public:
  17374. ThumbData (const int numThumbSamples)
  17375. : peakLevel (-1)
  17376. {
  17377. ensureSize (numThumbSamples);
  17378. }
  17379. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17380. {
  17381. jassert (thumbSampleIndex < data.size());
  17382. return data.getRawDataPointer() + thumbSampleIndex;
  17383. }
  17384. int getSize() const throw()
  17385. {
  17386. return data.size();
  17387. }
  17388. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17389. {
  17390. if (startSample >= 0)
  17391. {
  17392. endSample = jmin (endSample, data.size() - 1);
  17393. char mx = -128;
  17394. char mn = 127;
  17395. while (startSample <= endSample)
  17396. {
  17397. const MinMaxValue& v = data.getReference (startSample);
  17398. if (v.minValue < mn) mn = v.minValue;
  17399. if (v.maxValue > mx) mx = v.maxValue;
  17400. ++startSample;
  17401. }
  17402. if (mn <= mx)
  17403. {
  17404. result.set (mn, mx);
  17405. return;
  17406. }
  17407. }
  17408. result.set (1, 0);
  17409. }
  17410. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17411. {
  17412. resetPeak();
  17413. if (startIndex + numValues > data.size())
  17414. ensureSize (startIndex + numValues);
  17415. MinMaxValue* const dest = getData (startIndex);
  17416. for (int i = 0; i < numValues; ++i)
  17417. dest[i] = source[i];
  17418. }
  17419. void resetPeak()
  17420. {
  17421. peakLevel = -1;
  17422. }
  17423. int getPeak()
  17424. {
  17425. if (peakLevel < 0)
  17426. {
  17427. for (int i = 0; i < data.size(); ++i)
  17428. {
  17429. const int peak = data[i].getPeak();
  17430. if (peak > peakLevel)
  17431. peakLevel = peak;
  17432. }
  17433. }
  17434. return peakLevel;
  17435. }
  17436. private:
  17437. Array <MinMaxValue> data;
  17438. int peakLevel;
  17439. void ensureSize (const int thumbSamples)
  17440. {
  17441. const int extraNeeded = thumbSamples - data.size();
  17442. if (extraNeeded > 0)
  17443. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17444. }
  17445. };
  17446. class AudioThumbnail::CachedWindow
  17447. {
  17448. public:
  17449. CachedWindow()
  17450. : cachedStart (0), cachedTimePerPixel (0),
  17451. numChannelsCached (0), numSamplesCached (0),
  17452. cacheNeedsRefilling (true)
  17453. {
  17454. }
  17455. void invalidate()
  17456. {
  17457. cacheNeedsRefilling = true;
  17458. }
  17459. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17460. const double startTime, const double endTime,
  17461. const int channelNum, const float verticalZoomFactor,
  17462. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17463. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17464. {
  17465. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17466. numChannels, samplesPerThumbSample, levelData, channels);
  17467. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17468. {
  17469. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17470. if (! clip.isEmpty())
  17471. {
  17472. const float topY = (float) area.getY();
  17473. const float bottomY = (float) area.getBottom();
  17474. const float midY = (topY + bottomY) * 0.5f;
  17475. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17476. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17477. int x = clip.getX();
  17478. for (int w = clip.getWidth(); --w >= 0;)
  17479. {
  17480. if (cacheData->isNonZero())
  17481. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17482. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17483. ++x;
  17484. ++cacheData;
  17485. }
  17486. }
  17487. }
  17488. }
  17489. private:
  17490. Array <MinMaxValue> data;
  17491. double cachedStart, cachedTimePerPixel;
  17492. int numChannelsCached, numSamplesCached;
  17493. bool cacheNeedsRefilling;
  17494. void refillCache (const int numSamples, double startTime, const double endTime,
  17495. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17496. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17497. {
  17498. const double timePerPixel = (endTime - startTime) / numSamples;
  17499. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17500. {
  17501. invalidate();
  17502. return;
  17503. }
  17504. if (numSamples == numSamplesCached
  17505. && numChannelsCached == numChannels
  17506. && startTime == cachedStart
  17507. && timePerPixel == cachedTimePerPixel
  17508. && ! cacheNeedsRefilling)
  17509. {
  17510. return;
  17511. }
  17512. numSamplesCached = numSamples;
  17513. numChannelsCached = numChannels;
  17514. cachedStart = startTime;
  17515. cachedTimePerPixel = timePerPixel;
  17516. cacheNeedsRefilling = false;
  17517. ensureSize (numSamples);
  17518. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17519. {
  17520. int sample = roundToInt (startTime * sampleRate);
  17521. Array<float> levels;
  17522. int i;
  17523. for (i = 0; i < numSamples; ++i)
  17524. {
  17525. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17526. if (sample >= 0)
  17527. {
  17528. if (sample >= levelData->lengthInSamples)
  17529. break;
  17530. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17531. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17532. for (int chan = 0; chan < numChans; ++chan)
  17533. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17534. levels.getUnchecked (chan * 2 + 1));
  17535. }
  17536. startTime += timePerPixel;
  17537. sample = nextSample;
  17538. }
  17539. numSamplesCached = i;
  17540. }
  17541. else
  17542. {
  17543. jassert (channels.size() == numChannelsCached);
  17544. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17545. {
  17546. ThumbData* channelData = channels.getUnchecked (channelNum);
  17547. MinMaxValue* cacheData = getData (channelNum, 0);
  17548. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17549. startTime = cachedStart;
  17550. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17551. for (int i = numSamples; --i >= 0;)
  17552. {
  17553. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17554. channelData->getMinMax (sample, nextSample, *cacheData);
  17555. ++cacheData;
  17556. startTime += timePerPixel;
  17557. sample = nextSample;
  17558. }
  17559. }
  17560. }
  17561. }
  17562. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17563. {
  17564. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17565. return data.getRawDataPointer() + channelNum * numSamplesCached
  17566. + cacheIndex;
  17567. }
  17568. void ensureSize (const int numSamples)
  17569. {
  17570. const int itemsRequired = numSamples * numChannelsCached;
  17571. if (data.size() < itemsRequired)
  17572. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17573. }
  17574. };
  17575. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17576. AudioFormatManager& formatManagerToUse_,
  17577. AudioThumbnailCache& cacheToUse)
  17578. : formatManagerToUse (formatManagerToUse_),
  17579. cache (cacheToUse),
  17580. window (new CachedWindow()),
  17581. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17582. totalSamples (0),
  17583. numChannels (0),
  17584. sampleRate (0)
  17585. {
  17586. }
  17587. AudioThumbnail::~AudioThumbnail()
  17588. {
  17589. clear();
  17590. }
  17591. void AudioThumbnail::clear()
  17592. {
  17593. source = 0;
  17594. const ScopedLock sl (lock);
  17595. window->invalidate();
  17596. channels.clear();
  17597. totalSamples = numSamplesFinished = 0;
  17598. numChannels = 0;
  17599. sampleRate = 0;
  17600. sendChangeMessage();
  17601. }
  17602. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17603. {
  17604. clear();
  17605. numChannels = newNumChannels;
  17606. sampleRate = newSampleRate;
  17607. totalSamples = totalSamplesInSource;
  17608. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17609. }
  17610. void AudioThumbnail::createChannels (const int length)
  17611. {
  17612. while (channels.size() < numChannels)
  17613. channels.add (new ThumbData (length));
  17614. }
  17615. void AudioThumbnail::loadFrom (InputStream& input)
  17616. {
  17617. clear();
  17618. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17619. return;
  17620. samplesPerThumbSample = input.readInt();
  17621. totalSamples = input.readInt64(); // Total number of source samples.
  17622. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17623. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17624. numChannels = input.readInt(); // Number of audio channels.
  17625. sampleRate = input.readInt(); // Source sample rate.
  17626. input.skipNextBytes (16); // reserved area
  17627. createChannels (numThumbnailSamples);
  17628. for (int i = 0; i < numThumbnailSamples; ++i)
  17629. for (int chan = 0; chan < numChannels; ++chan)
  17630. channels.getUnchecked(chan)->getData(i)->read (input);
  17631. }
  17632. void AudioThumbnail::saveTo (OutputStream& output) const
  17633. {
  17634. const ScopedLock sl (lock);
  17635. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17636. output.write ("jatm", 4);
  17637. output.writeInt (samplesPerThumbSample);
  17638. output.writeInt64 (totalSamples);
  17639. output.writeInt64 (numSamplesFinished);
  17640. output.writeInt (numThumbnailSamples);
  17641. output.writeInt (numChannels);
  17642. output.writeInt ((int) sampleRate);
  17643. output.writeInt64 (0);
  17644. output.writeInt64 (0);
  17645. for (int i = 0; i < numThumbnailSamples; ++i)
  17646. for (int chan = 0; chan < numChannels; ++chan)
  17647. channels.getUnchecked(chan)->getData(i)->write (output);
  17648. }
  17649. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17650. {
  17651. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17652. numSamplesFinished = 0;
  17653. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17654. {
  17655. source = newSource; // (make sure this isn't done before loadThumb is called)
  17656. source->lengthInSamples = totalSamples;
  17657. source->sampleRate = sampleRate;
  17658. source->numChannels = numChannels;
  17659. source->numSamplesFinished = numSamplesFinished;
  17660. }
  17661. else
  17662. {
  17663. source = newSource; // (make sure this isn't done before loadThumb is called)
  17664. const ScopedLock sl (lock);
  17665. source->initialise (numSamplesFinished);
  17666. totalSamples = source->lengthInSamples;
  17667. sampleRate = source->sampleRate;
  17668. numChannels = source->numChannels;
  17669. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17670. }
  17671. return sampleRate > 0 && totalSamples > 0;
  17672. }
  17673. bool AudioThumbnail::setSource (InputSource* const newSource)
  17674. {
  17675. clear();
  17676. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17677. }
  17678. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17679. {
  17680. clear();
  17681. if (newReader != 0)
  17682. setDataSource (new LevelDataSource (*this, newReader, hash));
  17683. }
  17684. int64 AudioThumbnail::getHashCode() const
  17685. {
  17686. return source == 0 ? 0 : source->hashCode;
  17687. }
  17688. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17689. int startOffsetInBuffer, int numSamples)
  17690. {
  17691. jassert (startSample >= 0);
  17692. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17693. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17694. const int numToDo = lastThumbIndex - firstThumbIndex;
  17695. if (numToDo > 0)
  17696. {
  17697. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17698. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17699. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17700. for (int chan = 0; chan < numChans; ++chan)
  17701. {
  17702. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17703. MinMaxValue* const dest = thumbData + numToDo * chan;
  17704. thumbChannels [chan] = dest;
  17705. for (int i = 0; i < numToDo; ++i)
  17706. {
  17707. float low, high;
  17708. const int start = i * samplesPerThumbSample;
  17709. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17710. dest[i].setFloat (low, high);
  17711. }
  17712. }
  17713. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17714. }
  17715. }
  17716. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17717. {
  17718. const ScopedLock sl (lock);
  17719. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17720. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17721. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17722. totalSamples = jmax (numSamplesFinished, totalSamples);
  17723. window->invalidate();
  17724. sendChangeMessage();
  17725. }
  17726. int AudioThumbnail::getNumChannels() const throw()
  17727. {
  17728. return numChannels;
  17729. }
  17730. double AudioThumbnail::getTotalLength() const throw()
  17731. {
  17732. return totalSamples / sampleRate;
  17733. }
  17734. bool AudioThumbnail::isFullyLoaded() const throw()
  17735. {
  17736. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17737. }
  17738. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17739. {
  17740. return numSamplesFinished;
  17741. }
  17742. float AudioThumbnail::getApproximatePeak() const
  17743. {
  17744. int peak = 0;
  17745. for (int i = channels.size(); --i >= 0;)
  17746. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17747. return jlimit (0, 127, peak) / 127.0f;
  17748. }
  17749. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17750. double endTime, int channelNum, float verticalZoomFactor)
  17751. {
  17752. const ScopedLock sl (lock);
  17753. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17754. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17755. }
  17756. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17757. double endTimeSeconds, float verticalZoomFactor)
  17758. {
  17759. for (int i = 0; i < numChannels; ++i)
  17760. {
  17761. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17762. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17763. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17764. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17765. }
  17766. }
  17767. END_JUCE_NAMESPACE
  17768. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17769. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17770. BEGIN_JUCE_NAMESPACE
  17771. struct ThumbnailCacheEntry
  17772. {
  17773. int64 hash;
  17774. uint32 lastUsed;
  17775. MemoryBlock data;
  17776. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  17777. };
  17778. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17779. : TimeSliceThread ("thumb cache"),
  17780. maxNumThumbsToStore (maxNumThumbsToStore_)
  17781. {
  17782. startThread (2);
  17783. }
  17784. AudioThumbnailCache::~AudioThumbnailCache()
  17785. {
  17786. }
  17787. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  17788. {
  17789. for (int i = thumbs.size(); --i >= 0;)
  17790. if (thumbs.getUnchecked(i)->hash == hash)
  17791. return thumbs.getUnchecked(i);
  17792. return 0;
  17793. }
  17794. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17795. {
  17796. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17797. if (te != 0)
  17798. {
  17799. te->lastUsed = Time::getMillisecondCounter();
  17800. MemoryInputStream in (te->data, false);
  17801. thumb.loadFrom (in);
  17802. return true;
  17803. }
  17804. return false;
  17805. }
  17806. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17807. const int64 hashCode)
  17808. {
  17809. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17810. if (te == 0)
  17811. {
  17812. te = new ThumbnailCacheEntry();
  17813. te->hash = hashCode;
  17814. if (thumbs.size() < maxNumThumbsToStore)
  17815. {
  17816. thumbs.add (te);
  17817. }
  17818. else
  17819. {
  17820. int oldest = 0;
  17821. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  17822. for (int i = thumbs.size(); --i >= 0;)
  17823. {
  17824. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  17825. {
  17826. oldest = i;
  17827. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  17828. }
  17829. }
  17830. thumbs.set (oldest, te);
  17831. }
  17832. }
  17833. te->lastUsed = Time::getMillisecondCounter();
  17834. MemoryOutputStream out (te->data, false);
  17835. thumb.saveTo (out);
  17836. }
  17837. void AudioThumbnailCache::clear()
  17838. {
  17839. thumbs.clear();
  17840. }
  17841. END_JUCE_NAMESPACE
  17842. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17843. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17844. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17845. #if ! JUCE_WINDOWS
  17846. #include <QuickTime/Movies.h>
  17847. #include <QuickTime/QTML.h>
  17848. #include <QuickTime/QuickTimeComponents.h>
  17849. #include <QuickTime/MediaHandlers.h>
  17850. #include <QuickTime/ImageCodec.h>
  17851. #else
  17852. #if JUCE_MSVC
  17853. #pragma warning (push)
  17854. #pragma warning (disable : 4100)
  17855. #endif
  17856. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17857. add its header directory to your include path.
  17858. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  17859. flag in juce_Config.h
  17860. */
  17861. #include <Movies.h>
  17862. #include <QTML.h>
  17863. #include <QuickTimeComponents.h>
  17864. #include <MediaHandlers.h>
  17865. #include <ImageCodec.h>
  17866. #if JUCE_MSVC
  17867. #pragma warning (pop)
  17868. #endif
  17869. #endif
  17870. BEGIN_JUCE_NAMESPACE
  17871. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17872. static const char* const quickTimeFormatName = "QuickTime file";
  17873. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  17874. class QTAudioReader : public AudioFormatReader
  17875. {
  17876. public:
  17877. QTAudioReader (InputStream* const input_, const int trackNum_)
  17878. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17879. ok (false),
  17880. movie (0),
  17881. trackNum (trackNum_),
  17882. lastSampleRead (0),
  17883. lastThreadId (0),
  17884. extractor (0),
  17885. dataHandle (0)
  17886. {
  17887. JUCE_AUTORELEASEPOOL
  17888. bufferList.calloc (256, 1);
  17889. #if JUCE_WINDOWS
  17890. if (InitializeQTML (0) != noErr)
  17891. return;
  17892. #endif
  17893. if (EnterMovies() != noErr)
  17894. return;
  17895. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17896. if (! opened)
  17897. return;
  17898. {
  17899. const int numTracks = GetMovieTrackCount (movie);
  17900. int trackCount = 0;
  17901. for (int i = 1; i <= numTracks; ++i)
  17902. {
  17903. track = GetMovieIndTrack (movie, i);
  17904. media = GetTrackMedia (track);
  17905. OSType mediaType;
  17906. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17907. if (mediaType == SoundMediaType
  17908. && trackCount++ == trackNum_)
  17909. {
  17910. ok = true;
  17911. break;
  17912. }
  17913. }
  17914. }
  17915. if (! ok)
  17916. return;
  17917. ok = false;
  17918. lengthInSamples = GetMediaDecodeDuration (media);
  17919. usesFloatingPointData = false;
  17920. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17921. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17922. / GetMediaTimeScale (media);
  17923. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17924. unsigned long output_layout_size;
  17925. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17926. kQTPropertyClass_MovieAudioExtraction_Audio,
  17927. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17928. 0, &output_layout_size, 0);
  17929. if (err != noErr)
  17930. return;
  17931. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17932. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17933. err = MovieAudioExtractionGetProperty (extractor,
  17934. kQTPropertyClass_MovieAudioExtraction_Audio,
  17935. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17936. output_layout_size, qt_audio_channel_layout, 0);
  17937. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17938. err = MovieAudioExtractionSetProperty (extractor,
  17939. kQTPropertyClass_MovieAudioExtraction_Audio,
  17940. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17941. output_layout_size,
  17942. qt_audio_channel_layout);
  17943. err = MovieAudioExtractionGetProperty (extractor,
  17944. kQTPropertyClass_MovieAudioExtraction_Audio,
  17945. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17946. sizeof (inputStreamDesc),
  17947. &inputStreamDesc, 0);
  17948. if (err != noErr)
  17949. return;
  17950. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17951. | kAudioFormatFlagIsPacked
  17952. | kAudioFormatFlagsNativeEndian;
  17953. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17954. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17955. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17956. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17957. err = MovieAudioExtractionSetProperty (extractor,
  17958. kQTPropertyClass_MovieAudioExtraction_Audio,
  17959. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17960. sizeof (inputStreamDesc),
  17961. &inputStreamDesc);
  17962. if (err != noErr)
  17963. return;
  17964. Boolean allChannelsDiscrete = false;
  17965. err = MovieAudioExtractionSetProperty (extractor,
  17966. kQTPropertyClass_MovieAudioExtraction_Movie,
  17967. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17968. sizeof (allChannelsDiscrete),
  17969. &allChannelsDiscrete);
  17970. if (err != noErr)
  17971. return;
  17972. bufferList->mNumberBuffers = 1;
  17973. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17974. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  17975. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17976. bufferList->mBuffers[0].mData = dataBuffer;
  17977. sampleRate = inputStreamDesc.mSampleRate;
  17978. bitsPerSample = 16;
  17979. numChannels = inputStreamDesc.mChannelsPerFrame;
  17980. detachThread();
  17981. ok = true;
  17982. }
  17983. ~QTAudioReader()
  17984. {
  17985. JUCE_AUTORELEASEPOOL
  17986. checkThreadIsAttached();
  17987. if (dataHandle != 0)
  17988. DisposeHandle (dataHandle);
  17989. if (extractor != 0)
  17990. {
  17991. MovieAudioExtractionEnd (extractor);
  17992. extractor = 0;
  17993. }
  17994. DisposeMovie (movie);
  17995. #if JUCE_MAC
  17996. ExitMoviesOnThread ();
  17997. #endif
  17998. }
  17999. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18000. int64 startSampleInFile, int numSamples)
  18001. {
  18002. JUCE_AUTORELEASEPOOL
  18003. checkThreadIsAttached();
  18004. bool ok = true;
  18005. while (numSamples > 0)
  18006. {
  18007. if (lastSampleRead != startSampleInFile)
  18008. {
  18009. TimeRecord time;
  18010. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18011. time.base = 0;
  18012. time.value.hi = 0;
  18013. time.value.lo = (UInt32) startSampleInFile;
  18014. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18015. kQTPropertyClass_MovieAudioExtraction_Movie,
  18016. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18017. sizeof (time), &time);
  18018. if (err != noErr)
  18019. {
  18020. ok = false;
  18021. break;
  18022. }
  18023. }
  18024. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18025. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18026. UInt32 outFlags = 0;
  18027. UInt32 actualNumFrames = framesToDo;
  18028. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18029. if (err != noErr)
  18030. {
  18031. ok = false;
  18032. break;
  18033. }
  18034. lastSampleRead = startSampleInFile + actualNumFrames;
  18035. const int samplesReceived = actualNumFrames;
  18036. for (int j = numDestChannels; --j >= 0;)
  18037. {
  18038. if (destSamples[j] != 0)
  18039. {
  18040. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18041. for (int i = 0; i < samplesReceived; ++i)
  18042. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18043. }
  18044. }
  18045. startOffsetInDestBuffer += samplesReceived;
  18046. startSampleInFile += samplesReceived;
  18047. numSamples -= samplesReceived;
  18048. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18049. {
  18050. for (int j = numDestChannels; --j >= 0;)
  18051. if (destSamples[j] != 0)
  18052. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18053. break;
  18054. }
  18055. }
  18056. detachThread();
  18057. return ok;
  18058. }
  18059. bool ok;
  18060. private:
  18061. Movie movie;
  18062. Media media;
  18063. Track track;
  18064. const int trackNum;
  18065. double trackUnitsPerFrame;
  18066. int samplesPerFrame;
  18067. int64 lastSampleRead;
  18068. Thread::ThreadID lastThreadId;
  18069. MovieAudioExtractionRef extractor;
  18070. AudioStreamBasicDescription inputStreamDesc;
  18071. HeapBlock <AudioBufferList> bufferList;
  18072. HeapBlock <char> dataBuffer;
  18073. Handle dataHandle;
  18074. void checkThreadIsAttached()
  18075. {
  18076. #if JUCE_MAC
  18077. if (Thread::getCurrentThreadId() != lastThreadId)
  18078. EnterMoviesOnThread (0);
  18079. AttachMovieToCurrentThread (movie);
  18080. #endif
  18081. }
  18082. void detachThread()
  18083. {
  18084. #if JUCE_MAC
  18085. DetachMovieFromCurrentThread (movie);
  18086. #endif
  18087. }
  18088. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18089. };
  18090. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18091. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18092. {
  18093. }
  18094. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18095. {
  18096. }
  18097. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18098. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18099. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18100. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18101. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18102. const bool deleteStreamIfOpeningFails)
  18103. {
  18104. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18105. if (r->ok)
  18106. return r.release();
  18107. if (! deleteStreamIfOpeningFails)
  18108. r->input = 0;
  18109. return 0;
  18110. }
  18111. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18112. double /*sampleRateToUse*/,
  18113. unsigned int /*numberOfChannels*/,
  18114. int /*bitsPerSample*/,
  18115. const StringPairArray& /*metadataValues*/,
  18116. int /*qualityOptionIndex*/)
  18117. {
  18118. jassertfalse; // not yet implemented!
  18119. return 0;
  18120. }
  18121. END_JUCE_NAMESPACE
  18122. #endif
  18123. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18124. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18125. BEGIN_JUCE_NAMESPACE
  18126. static const char* const wavFormatName = "WAV file";
  18127. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18128. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18129. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18130. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18131. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18132. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18133. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18134. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18135. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18136. const String& originator,
  18137. const String& originatorRef,
  18138. const Time& date,
  18139. const int64 timeReferenceSamples,
  18140. const String& codingHistory)
  18141. {
  18142. StringPairArray m;
  18143. m.set (bwavDescription, description);
  18144. m.set (bwavOriginator, originator);
  18145. m.set (bwavOriginatorRef, originatorRef);
  18146. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18147. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18148. m.set (bwavTimeReference, String (timeReferenceSamples));
  18149. m.set (bwavCodingHistory, codingHistory);
  18150. return m;
  18151. }
  18152. namespace WavFileHelpers
  18153. {
  18154. #if JUCE_MSVC
  18155. #pragma pack (push, 1)
  18156. #define PACKED
  18157. #elif JUCE_GCC
  18158. #define PACKED __attribute__((packed))
  18159. #else
  18160. #define PACKED
  18161. #endif
  18162. struct BWAVChunk
  18163. {
  18164. char description [256];
  18165. char originator [32];
  18166. char originatorRef [32];
  18167. char originationDate [10];
  18168. char originationTime [8];
  18169. uint32 timeRefLow;
  18170. uint32 timeRefHigh;
  18171. uint16 version;
  18172. uint8 umid[64];
  18173. uint8 reserved[190];
  18174. char codingHistory[1];
  18175. void copyTo (StringPairArray& values) const
  18176. {
  18177. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18178. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18179. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18180. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18181. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18182. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18183. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18184. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18185. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18186. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18187. }
  18188. static MemoryBlock createFrom (const StringPairArray& values)
  18189. {
  18190. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18191. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18192. data.fillWith (0);
  18193. BWAVChunk* b = (BWAVChunk*) data.getData();
  18194. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18195. // as they get called in the right order..
  18196. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18197. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18198. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18199. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18200. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18201. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18202. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18203. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18204. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18205. if (b->description[0] != 0
  18206. || b->originator[0] != 0
  18207. || b->originationDate[0] != 0
  18208. || b->originationTime[0] != 0
  18209. || b->codingHistory[0] != 0
  18210. || time != 0)
  18211. {
  18212. return data;
  18213. }
  18214. return MemoryBlock();
  18215. }
  18216. } PACKED;
  18217. struct SMPLChunk
  18218. {
  18219. struct SampleLoop
  18220. {
  18221. uint32 identifier;
  18222. uint32 type;
  18223. uint32 start;
  18224. uint32 end;
  18225. uint32 fraction;
  18226. uint32 playCount;
  18227. } PACKED;
  18228. uint32 manufacturer;
  18229. uint32 product;
  18230. uint32 samplePeriod;
  18231. uint32 midiUnityNote;
  18232. uint32 midiPitchFraction;
  18233. uint32 smpteFormat;
  18234. uint32 smpteOffset;
  18235. uint32 numSampleLoops;
  18236. uint32 samplerData;
  18237. SampleLoop loops[1];
  18238. void copyTo (StringPairArray& values, const int totalSize) const
  18239. {
  18240. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18241. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18242. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18243. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18244. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18245. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18246. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18247. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18248. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18249. for (uint32 i = 0; i < numSampleLoops; ++i)
  18250. {
  18251. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18252. break;
  18253. const String prefix ("Loop" + String(i));
  18254. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18255. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18256. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18257. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18258. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18259. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18260. }
  18261. }
  18262. static MemoryBlock createFrom (const StringPairArray& values)
  18263. {
  18264. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18265. if (numLoops <= 0)
  18266. return MemoryBlock();
  18267. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18268. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18269. data.fillWith (0);
  18270. SMPLChunk* s = (SMPLChunk*) data.getData();
  18271. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18272. // as they get called in the right order..
  18273. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18274. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18275. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18276. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18277. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18278. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18279. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18280. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18281. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18282. for (int i = 0; i < numLoops; ++i)
  18283. {
  18284. const String prefix ("Loop" + String(i));
  18285. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18286. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18287. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18288. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18289. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18290. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18291. }
  18292. return data;
  18293. }
  18294. } PACKED;
  18295. struct ExtensibleWavSubFormat
  18296. {
  18297. uint32 data1;
  18298. uint16 data2;
  18299. uint16 data3;
  18300. uint8 data4[8];
  18301. } PACKED;
  18302. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  18303. {
  18304. uint32 riffSizeLow; // low 4 byte size of RF64 block
  18305. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  18306. uint32 dataSizeLow; // low 4 byte size of data chunk
  18307. uint32 dataSizeHigh; // high 4 byte size of data chunk
  18308. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  18309. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  18310. uint32 tableLength; // number of valid entries in array 'table'
  18311. } PACKED;
  18312. #if JUCE_MSVC
  18313. #pragma pack (pop)
  18314. #endif
  18315. #undef PACKED
  18316. inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18317. }
  18318. class WavAudioFormatReader : public AudioFormatReader
  18319. {
  18320. public:
  18321. WavAudioFormatReader (InputStream* const in)
  18322. : AudioFormatReader (in, TRANS (wavFormatName)),
  18323. bwavChunkStart (0),
  18324. bwavSize (0),
  18325. dataLength (0),
  18326. isRF64 (false)
  18327. {
  18328. using namespace WavFileHelpers;
  18329. uint64 len = 0;
  18330. int64 end = 0;
  18331. bool hasGotType = false;
  18332. bool hasGotData = false;
  18333. const int firstChunkType = input->readInt();
  18334. if (firstChunkType == chunkName ("RF64"))
  18335. {
  18336. input->skipNextBytes (4); // size is -1 for RF64
  18337. isRF64 = true;
  18338. }
  18339. else if (firstChunkType == chunkName ("RIFF"))
  18340. {
  18341. len = (uint64) input->readInt();
  18342. end = input->getPosition() + len;
  18343. }
  18344. else
  18345. {
  18346. return;
  18347. }
  18348. const int64 startOfRIFFChunk = input->getPosition();
  18349. if (input->readInt() == chunkName ("WAVE"))
  18350. {
  18351. if (isRF64 && input->readInt() == chunkName ("ds64"))
  18352. {
  18353. uint32 length = (uint32) input->readInt();
  18354. if (length < 28)
  18355. {
  18356. return;
  18357. }
  18358. else
  18359. {
  18360. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18361. len = input->readInt64();
  18362. end = startOfRIFFChunk + len;
  18363. dataLength = input->readInt64();
  18364. input->setPosition (chunkEnd);
  18365. }
  18366. }
  18367. while (input->getPosition() < end && ! input->isExhausted())
  18368. {
  18369. const int chunkType = input->readInt();
  18370. uint32 length = (uint32) input->readInt();
  18371. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18372. if (chunkType == chunkName ("fmt "))
  18373. {
  18374. // read the format chunk
  18375. const unsigned short format = input->readShort();
  18376. const short numChans = input->readShort();
  18377. sampleRate = input->readInt();
  18378. const int bytesPerSec = input->readInt();
  18379. numChannels = numChans;
  18380. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18381. bitsPerSample = 8 * bytesPerFrame / numChans;
  18382. if (format == 3)
  18383. {
  18384. usesFloatingPointData = true;
  18385. }
  18386. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18387. {
  18388. if (length < 40) // too short
  18389. {
  18390. bytesPerFrame = 0;
  18391. }
  18392. else
  18393. {
  18394. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18395. ExtensibleWavSubFormat subFormat;
  18396. subFormat.data1 = input->readInt();
  18397. subFormat.data2 = input->readShort();
  18398. subFormat.data3 = input->readShort();
  18399. input->read (subFormat.data4, sizeof (subFormat.data4));
  18400. const ExtensibleWavSubFormat pcmFormat
  18401. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18402. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18403. {
  18404. const ExtensibleWavSubFormat ambisonicFormat
  18405. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18406. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18407. bytesPerFrame = 0;
  18408. }
  18409. }
  18410. }
  18411. else if (format != 1)
  18412. {
  18413. bytesPerFrame = 0;
  18414. }
  18415. hasGotType = true;
  18416. }
  18417. else if (chunkType == chunkName ("data"))
  18418. {
  18419. // get the data chunk's position
  18420. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  18421. dataLength = length;
  18422. dataChunkStart = input->getPosition();
  18423. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18424. hasGotData = true;
  18425. }
  18426. else if (chunkType == chunkName ("bext"))
  18427. {
  18428. bwavChunkStart = input->getPosition();
  18429. bwavSize = length;
  18430. // Broadcast-wav extension chunk..
  18431. HeapBlock <BWAVChunk> bwav;
  18432. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18433. input->read (bwav, length);
  18434. bwav->copyTo (metadataValues);
  18435. }
  18436. else if (chunkType == chunkName ("smpl"))
  18437. {
  18438. HeapBlock <SMPLChunk> smpl;
  18439. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18440. input->read (smpl, length);
  18441. smpl->copyTo (metadataValues, length);
  18442. }
  18443. else if (chunkEnd <= input->getPosition())
  18444. {
  18445. break;
  18446. }
  18447. input->setPosition (chunkEnd);
  18448. }
  18449. }
  18450. }
  18451. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18452. int64 startSampleInFile, int numSamples)
  18453. {
  18454. jassert (destSamples != 0);
  18455. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18456. if (samplesAvailable < numSamples)
  18457. {
  18458. for (int i = numDestChannels; --i >= 0;)
  18459. if (destSamples[i] != 0)
  18460. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18461. numSamples = (int) samplesAvailable;
  18462. }
  18463. if (numSamples <= 0)
  18464. return true;
  18465. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18466. while (numSamples > 0)
  18467. {
  18468. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18469. char tempBuffer [tempBufSize];
  18470. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18471. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18472. if (bytesRead < numThisTime * bytesPerFrame)
  18473. {
  18474. jassert (bytesRead >= 0);
  18475. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18476. }
  18477. switch (bitsPerSample)
  18478. {
  18479. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18480. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18481. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18482. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18483. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18484. default: jassertfalse; break;
  18485. }
  18486. startOffsetInDestBuffer += numThisTime;
  18487. numSamples -= numThisTime;
  18488. }
  18489. return true;
  18490. }
  18491. int64 bwavChunkStart, bwavSize;
  18492. private:
  18493. ScopedPointer<AudioData::Converter> converter;
  18494. int bytesPerFrame;
  18495. int64 dataChunkStart, dataLength;
  18496. bool isRF64;
  18497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18498. };
  18499. class WavAudioFormatWriter : public AudioFormatWriter
  18500. {
  18501. public:
  18502. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  18503. const unsigned int numChannels_, const int bits,
  18504. const StringPairArray& metadataValues)
  18505. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  18506. lengthInSamples (0),
  18507. bytesWritten (0),
  18508. writeFailed (false)
  18509. {
  18510. using namespace WavFileHelpers;
  18511. if (metadataValues.size() > 0)
  18512. {
  18513. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18514. smplChunk = SMPLChunk::createFrom (metadataValues);
  18515. }
  18516. headerPosition = out->getPosition();
  18517. writeHeader();
  18518. }
  18519. ~WavAudioFormatWriter()
  18520. {
  18521. if ((bytesWritten & 1) != 0) // pad to an even length
  18522. {
  18523. ++bytesWritten;
  18524. output->writeByte (0);
  18525. }
  18526. writeHeader();
  18527. }
  18528. bool write (const int** data, int numSamples)
  18529. {
  18530. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18531. if (writeFailed)
  18532. return false;
  18533. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18534. tempBlock.ensureSize (bytes, false);
  18535. switch (bitsPerSample)
  18536. {
  18537. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18538. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18539. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18540. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18541. default: jassertfalse; break;
  18542. }
  18543. if (! output->write (tempBlock.getData(), bytes))
  18544. {
  18545. // failed to write to disk, so let's try writing the header.
  18546. // If it's just run out of disk space, then if it does manage
  18547. // to write the header, we'll still have a useable file..
  18548. writeHeader();
  18549. writeFailed = true;
  18550. return false;
  18551. }
  18552. else
  18553. {
  18554. bytesWritten += bytes;
  18555. lengthInSamples += numSamples;
  18556. return true;
  18557. }
  18558. }
  18559. private:
  18560. ScopedPointer<AudioData::Converter> converter;
  18561. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18562. uint64 lengthInSamples, bytesWritten;
  18563. int64 headerPosition;
  18564. bool writeFailed;
  18565. static int getChannelMask (const int numChannels) throw()
  18566. {
  18567. switch (numChannels)
  18568. {
  18569. case 1: return 0;
  18570. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  18571. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18572. case 6: return 1 + 2 + 4 + 8 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18573. default: break;
  18574. }
  18575. return 0;
  18576. }
  18577. void writeHeader()
  18578. {
  18579. using namespace WavFileHelpers;
  18580. const bool seekedOk = output->setPosition (headerPosition);
  18581. (void) seekedOk;
  18582. // if this fails, you've given it an output stream that can't seek! It needs
  18583. // to be able to seek back to write the header
  18584. jassert (seekedOk);
  18585. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18586. int64 audioDataSize = bytesPerFrame * lengthInSamples;
  18587. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  18588. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  18589. + 8 + audioDataSize + (audioDataSize & 1)
  18590. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  18591. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  18592. + (8 + 28); // (ds64 chunk)
  18593. riffChunkSize += (riffChunkSize & 0x1);
  18594. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  18595. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  18596. output->writeInt (chunkName ("WAVE"));
  18597. if (! isRF64)
  18598. {
  18599. output->writeInt (chunkName ("JUNK"));
  18600. output->writeInt (28 + 24);
  18601. output->writeRepeatedByte (0, 28 /* ds64 */ + 24 /* extra waveformatex */);
  18602. }
  18603. else
  18604. {
  18605. // write ds64 chunk
  18606. output->writeInt (chunkName ("ds64"));
  18607. output->writeInt (28); // chunk size for uncompressed data (no table)
  18608. output->writeInt64 (riffChunkSize);
  18609. output->writeInt64 (audioDataSize);
  18610. output->writeRepeatedByte (0, 12);
  18611. }
  18612. output->writeInt (chunkName ("fmt "));
  18613. if (isRF64)
  18614. {
  18615. output->writeInt (40); // chunk size
  18616. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  18617. }
  18618. else
  18619. {
  18620. output->writeInt (16); // chunk size
  18621. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  18622. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18623. }
  18624. output->writeShort ((short) numChannels);
  18625. output->writeInt ((int) sampleRate);
  18626. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  18627. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  18628. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  18629. if (isRF64)
  18630. {
  18631. output->writeShort (22); // cbSize (size of the extension)
  18632. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  18633. output->writeInt (getChannelMask (numChannels));
  18634. const ExtensibleWavSubFormat pcmFormat
  18635. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18636. const ExtensibleWavSubFormat IEEEFloatFormat
  18637. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18638. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  18639. output->writeInt ((int) subFormat.data1);
  18640. output->writeShort ((short) subFormat.data2);
  18641. output->writeShort ((short) subFormat.data3);
  18642. output->write (subFormat.data4, sizeof (subFormat.data4));
  18643. }
  18644. if (bwavChunk.getSize() > 0)
  18645. {
  18646. output->writeInt (chunkName ("bext"));
  18647. output->writeInt ((int) bwavChunk.getSize());
  18648. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18649. }
  18650. if (smplChunk.getSize() > 0)
  18651. {
  18652. output->writeInt (chunkName ("smpl"));
  18653. output->writeInt ((int) smplChunk.getSize());
  18654. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18655. }
  18656. output->writeInt (chunkName ("data"));
  18657. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  18658. usesFloatingPointData = (bitsPerSample == 32);
  18659. }
  18660. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18661. };
  18662. WavAudioFormat::WavAudioFormat()
  18663. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18664. {
  18665. }
  18666. WavAudioFormat::~WavAudioFormat()
  18667. {
  18668. }
  18669. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18670. {
  18671. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18672. return Array <int> (rates);
  18673. }
  18674. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18675. {
  18676. const int depths[] = { 8, 16, 24, 32, 0 };
  18677. return Array <int> (depths);
  18678. }
  18679. bool WavAudioFormat::canDoStereo() { return true; }
  18680. bool WavAudioFormat::canDoMono() { return true; }
  18681. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18682. const bool deleteStreamIfOpeningFails)
  18683. {
  18684. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18685. if (r->sampleRate != 0)
  18686. return r.release();
  18687. if (! deleteStreamIfOpeningFails)
  18688. r->input = 0;
  18689. return 0;
  18690. }
  18691. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  18692. unsigned int numChannels, int bitsPerSample,
  18693. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  18694. {
  18695. if (getPossibleBitDepths().contains (bitsPerSample))
  18696. return new WavAudioFormatWriter (out, sampleRate, numChannels, bitsPerSample, metadataValues);
  18697. return 0;
  18698. }
  18699. namespace WavFileHelpers
  18700. {
  18701. bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18702. {
  18703. TemporaryFile tempFile (file);
  18704. WavAudioFormat wav;
  18705. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18706. if (reader != 0)
  18707. {
  18708. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18709. if (outStream != 0)
  18710. {
  18711. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18712. reader->numChannels, reader->bitsPerSample,
  18713. metadata, 0));
  18714. if (writer != 0)
  18715. {
  18716. outStream.release();
  18717. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18718. writer = 0;
  18719. reader = 0;
  18720. return ok && tempFile.overwriteTargetFileWithTemporary();
  18721. }
  18722. }
  18723. }
  18724. return false;
  18725. }
  18726. }
  18727. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18728. {
  18729. using namespace WavFileHelpers;
  18730. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  18731. if (reader != 0)
  18732. {
  18733. const int64 bwavPos = reader->bwavChunkStart;
  18734. const int64 bwavSize = reader->bwavSize;
  18735. reader = 0;
  18736. if (bwavSize > 0)
  18737. {
  18738. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18739. if (chunk.getSize() <= (size_t) bwavSize)
  18740. {
  18741. // the new one will fit in the space available, so write it directly..
  18742. const int64 oldSize = wavFile.getSize();
  18743. {
  18744. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18745. out->setPosition (bwavPos);
  18746. out->write (chunk.getData(), (int) chunk.getSize());
  18747. out->setPosition (oldSize);
  18748. }
  18749. jassert (wavFile.getSize() == oldSize);
  18750. return true;
  18751. }
  18752. }
  18753. }
  18754. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  18755. }
  18756. END_JUCE_NAMESPACE
  18757. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18758. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18759. #if JUCE_USE_CDREADER
  18760. BEGIN_JUCE_NAMESPACE
  18761. int AudioCDReader::getNumTracks() const
  18762. {
  18763. return trackStartSamples.size() - 1;
  18764. }
  18765. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18766. {
  18767. return trackStartSamples [trackNum];
  18768. }
  18769. const Array<int>& AudioCDReader::getTrackOffsets() const
  18770. {
  18771. return trackStartSamples;
  18772. }
  18773. int AudioCDReader::getCDDBId()
  18774. {
  18775. int checksum = 0;
  18776. const int numTracks = getNumTracks();
  18777. for (int i = 0; i < numTracks; ++i)
  18778. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18779. checksum += offset % 10;
  18780. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18781. // CCLLLLTT: checksum, length, tracks
  18782. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18783. }
  18784. END_JUCE_NAMESPACE
  18785. #endif
  18786. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18787. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18788. BEGIN_JUCE_NAMESPACE
  18789. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18790. const bool deleteReaderWhenThisIsDeleted)
  18791. : reader (reader_),
  18792. deleteReader (deleteReaderWhenThisIsDeleted),
  18793. nextPlayPos (0),
  18794. looping (false)
  18795. {
  18796. jassert (reader != 0);
  18797. }
  18798. AudioFormatReaderSource::~AudioFormatReaderSource()
  18799. {
  18800. releaseResources();
  18801. if (deleteReader)
  18802. delete reader;
  18803. }
  18804. void AudioFormatReaderSource::setNextReadPosition (int64 newPosition)
  18805. {
  18806. nextPlayPos = newPosition;
  18807. }
  18808. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18809. {
  18810. looping = shouldLoop;
  18811. }
  18812. int64 AudioFormatReaderSource::getNextReadPosition() const
  18813. {
  18814. return looping ? nextPlayPos % reader->lengthInSamples
  18815. : nextPlayPos;
  18816. }
  18817. int64 AudioFormatReaderSource::getTotalLength() const
  18818. {
  18819. return reader->lengthInSamples;
  18820. }
  18821. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18822. double /*sampleRate*/)
  18823. {
  18824. }
  18825. void AudioFormatReaderSource::releaseResources()
  18826. {
  18827. }
  18828. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18829. {
  18830. if (info.numSamples > 0)
  18831. {
  18832. const int64 start = nextPlayPos;
  18833. if (looping)
  18834. {
  18835. const int newStart = start % (int) reader->lengthInSamples;
  18836. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18837. if (newEnd > newStart)
  18838. {
  18839. info.buffer->readFromAudioReader (reader,
  18840. info.startSample,
  18841. newEnd - newStart,
  18842. newStart,
  18843. true, true);
  18844. }
  18845. else
  18846. {
  18847. const int endSamps = (int) reader->lengthInSamples - newStart;
  18848. info.buffer->readFromAudioReader (reader,
  18849. info.startSample,
  18850. endSamps,
  18851. newStart,
  18852. true, true);
  18853. info.buffer->readFromAudioReader (reader,
  18854. info.startSample + endSamps,
  18855. newEnd,
  18856. 0,
  18857. true, true);
  18858. }
  18859. nextPlayPos = newEnd;
  18860. }
  18861. else
  18862. {
  18863. info.buffer->readFromAudioReader (reader,
  18864. info.startSample,
  18865. info.numSamples,
  18866. start,
  18867. true, true);
  18868. nextPlayPos += info.numSamples;
  18869. }
  18870. }
  18871. }
  18872. END_JUCE_NAMESPACE
  18873. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18874. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18875. BEGIN_JUCE_NAMESPACE
  18876. AudioSourcePlayer::AudioSourcePlayer()
  18877. : source (0),
  18878. sampleRate (0),
  18879. bufferSize (0),
  18880. tempBuffer (2, 8),
  18881. lastGain (1.0f),
  18882. gain (1.0f)
  18883. {
  18884. }
  18885. AudioSourcePlayer::~AudioSourcePlayer()
  18886. {
  18887. setSource (0);
  18888. }
  18889. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18890. {
  18891. if (source != newSource)
  18892. {
  18893. AudioSource* const oldSource = source;
  18894. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18895. newSource->prepareToPlay (bufferSize, sampleRate);
  18896. {
  18897. const ScopedLock sl (readLock);
  18898. source = newSource;
  18899. }
  18900. if (oldSource != 0)
  18901. oldSource->releaseResources();
  18902. }
  18903. }
  18904. void AudioSourcePlayer::setGain (const float newGain) throw()
  18905. {
  18906. gain = newGain;
  18907. }
  18908. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18909. int totalNumInputChannels,
  18910. float** outputChannelData,
  18911. int totalNumOutputChannels,
  18912. int numSamples)
  18913. {
  18914. // these should have been prepared by audioDeviceAboutToStart()...
  18915. jassert (sampleRate > 0 && bufferSize > 0);
  18916. const ScopedLock sl (readLock);
  18917. if (source != 0)
  18918. {
  18919. AudioSourceChannelInfo info;
  18920. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18921. // messy stuff needed to compact the channels down into an array
  18922. // of non-zero pointers..
  18923. for (i = 0; i < totalNumInputChannels; ++i)
  18924. {
  18925. if (inputChannelData[i] != 0)
  18926. {
  18927. inputChans [numInputs++] = inputChannelData[i];
  18928. if (numInputs >= numElementsInArray (inputChans))
  18929. break;
  18930. }
  18931. }
  18932. for (i = 0; i < totalNumOutputChannels; ++i)
  18933. {
  18934. if (outputChannelData[i] != 0)
  18935. {
  18936. outputChans [numOutputs++] = outputChannelData[i];
  18937. if (numOutputs >= numElementsInArray (outputChans))
  18938. break;
  18939. }
  18940. }
  18941. if (numInputs > numOutputs)
  18942. {
  18943. // if there aren't enough output channels for the number of
  18944. // inputs, we need to create some temporary extra ones (can't
  18945. // use the input data in case it gets written to)
  18946. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18947. false, false, true);
  18948. for (i = 0; i < numOutputs; ++i)
  18949. {
  18950. channels[numActiveChans] = outputChans[i];
  18951. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18952. ++numActiveChans;
  18953. }
  18954. for (i = numOutputs; i < numInputs; ++i)
  18955. {
  18956. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18957. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18958. ++numActiveChans;
  18959. }
  18960. }
  18961. else
  18962. {
  18963. for (i = 0; i < numInputs; ++i)
  18964. {
  18965. channels[numActiveChans] = outputChans[i];
  18966. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18967. ++numActiveChans;
  18968. }
  18969. for (i = numInputs; i < numOutputs; ++i)
  18970. {
  18971. channels[numActiveChans] = outputChans[i];
  18972. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18973. ++numActiveChans;
  18974. }
  18975. }
  18976. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18977. info.buffer = &buffer;
  18978. info.startSample = 0;
  18979. info.numSamples = numSamples;
  18980. source->getNextAudioBlock (info);
  18981. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18982. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18983. lastGain = gain;
  18984. }
  18985. else
  18986. {
  18987. for (int i = 0; i < totalNumOutputChannels; ++i)
  18988. if (outputChannelData[i] != 0)
  18989. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18990. }
  18991. }
  18992. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18993. {
  18994. sampleRate = device->getCurrentSampleRate();
  18995. bufferSize = device->getCurrentBufferSizeSamples();
  18996. zeromem (channels, sizeof (channels));
  18997. if (source != 0)
  18998. source->prepareToPlay (bufferSize, sampleRate);
  18999. }
  19000. void AudioSourcePlayer::audioDeviceStopped()
  19001. {
  19002. if (source != 0)
  19003. source->releaseResources();
  19004. sampleRate = 0.0;
  19005. bufferSize = 0;
  19006. tempBuffer.setSize (2, 8);
  19007. }
  19008. END_JUCE_NAMESPACE
  19009. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19010. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19011. BEGIN_JUCE_NAMESPACE
  19012. AudioTransportSource::AudioTransportSource()
  19013. : source (0),
  19014. resamplerSource (0),
  19015. bufferingSource (0),
  19016. positionableSource (0),
  19017. masterSource (0),
  19018. gain (1.0f),
  19019. lastGain (1.0f),
  19020. playing (false),
  19021. stopped (true),
  19022. sampleRate (44100.0),
  19023. sourceSampleRate (0.0),
  19024. blockSize (128),
  19025. readAheadBufferSize (0),
  19026. isPrepared (false),
  19027. inputStreamEOF (false)
  19028. {
  19029. }
  19030. AudioTransportSource::~AudioTransportSource()
  19031. {
  19032. setSource (0);
  19033. releaseResources();
  19034. }
  19035. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19036. int readAheadBufferSize_,
  19037. double sourceSampleRateToCorrectFor,
  19038. int maxNumChannels)
  19039. {
  19040. if (source == newSource)
  19041. {
  19042. if (source == 0)
  19043. return;
  19044. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19045. }
  19046. readAheadBufferSize = readAheadBufferSize_;
  19047. sourceSampleRate = sourceSampleRateToCorrectFor;
  19048. ResamplingAudioSource* newResamplerSource = 0;
  19049. BufferingAudioSource* newBufferingSource = 0;
  19050. PositionableAudioSource* newPositionableSource = 0;
  19051. AudioSource* newMasterSource = 0;
  19052. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19053. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19054. AudioSource* oldMasterSource = masterSource;
  19055. if (newSource != 0)
  19056. {
  19057. newPositionableSource = newSource;
  19058. if (readAheadBufferSize_ > 0)
  19059. newPositionableSource = newBufferingSource
  19060. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19061. newPositionableSource->setNextReadPosition (0);
  19062. if (sourceSampleRateToCorrectFor != 0)
  19063. newMasterSource = newResamplerSource
  19064. = new ResamplingAudioSource (newPositionableSource, false, maxNumChannels);
  19065. else
  19066. newMasterSource = newPositionableSource;
  19067. if (isPrepared)
  19068. {
  19069. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19070. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19071. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19072. }
  19073. }
  19074. {
  19075. const ScopedLock sl (callbackLock);
  19076. source = newSource;
  19077. resamplerSource = newResamplerSource;
  19078. bufferingSource = newBufferingSource;
  19079. masterSource = newMasterSource;
  19080. positionableSource = newPositionableSource;
  19081. playing = false;
  19082. }
  19083. if (oldMasterSource != 0)
  19084. oldMasterSource->releaseResources();
  19085. }
  19086. void AudioTransportSource::start()
  19087. {
  19088. if ((! playing) && masterSource != 0)
  19089. {
  19090. {
  19091. const ScopedLock sl (callbackLock);
  19092. playing = true;
  19093. stopped = false;
  19094. inputStreamEOF = false;
  19095. }
  19096. sendChangeMessage();
  19097. }
  19098. }
  19099. void AudioTransportSource::stop()
  19100. {
  19101. if (playing)
  19102. {
  19103. {
  19104. const ScopedLock sl (callbackLock);
  19105. playing = false;
  19106. }
  19107. int n = 500;
  19108. while (--n >= 0 && ! stopped)
  19109. Thread::sleep (2);
  19110. sendChangeMessage();
  19111. }
  19112. }
  19113. void AudioTransportSource::setPosition (double newPosition)
  19114. {
  19115. if (sampleRate > 0.0)
  19116. setNextReadPosition ((int64) (newPosition * sampleRate));
  19117. }
  19118. double AudioTransportSource::getCurrentPosition() const
  19119. {
  19120. if (sampleRate > 0.0)
  19121. return getNextReadPosition() / sampleRate;
  19122. else
  19123. return 0.0;
  19124. }
  19125. double AudioTransportSource::getLengthInSeconds() const
  19126. {
  19127. return getTotalLength() / sampleRate;
  19128. }
  19129. void AudioTransportSource::setNextReadPosition (int64 newPosition)
  19130. {
  19131. if (positionableSource != 0)
  19132. {
  19133. if (sampleRate > 0 && sourceSampleRate > 0)
  19134. newPosition = (int64) (newPosition * sourceSampleRate / sampleRate);
  19135. positionableSource->setNextReadPosition (newPosition);
  19136. }
  19137. }
  19138. int64 AudioTransportSource::getNextReadPosition() const
  19139. {
  19140. if (positionableSource != 0)
  19141. {
  19142. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19143. return (int64) (positionableSource->getNextReadPosition() * ratio);
  19144. }
  19145. return 0;
  19146. }
  19147. int64 AudioTransportSource::getTotalLength() const
  19148. {
  19149. const ScopedLock sl (callbackLock);
  19150. if (positionableSource != 0)
  19151. {
  19152. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19153. return (int64) (positionableSource->getTotalLength() * ratio);
  19154. }
  19155. return 0;
  19156. }
  19157. bool AudioTransportSource::isLooping() const
  19158. {
  19159. const ScopedLock sl (callbackLock);
  19160. return positionableSource != 0
  19161. && positionableSource->isLooping();
  19162. }
  19163. void AudioTransportSource::setGain (const float newGain) throw()
  19164. {
  19165. gain = newGain;
  19166. }
  19167. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19168. double sampleRate_)
  19169. {
  19170. const ScopedLock sl (callbackLock);
  19171. sampleRate = sampleRate_;
  19172. blockSize = samplesPerBlockExpected;
  19173. if (masterSource != 0)
  19174. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19175. if (resamplerSource != 0 && sourceSampleRate != 0)
  19176. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19177. isPrepared = true;
  19178. }
  19179. void AudioTransportSource::releaseResources()
  19180. {
  19181. const ScopedLock sl (callbackLock);
  19182. if (masterSource != 0)
  19183. masterSource->releaseResources();
  19184. isPrepared = false;
  19185. }
  19186. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19187. {
  19188. const ScopedLock sl (callbackLock);
  19189. inputStreamEOF = false;
  19190. if (masterSource != 0 && ! stopped)
  19191. {
  19192. masterSource->getNextAudioBlock (info);
  19193. if (! playing)
  19194. {
  19195. // just stopped playing, so fade out the last block..
  19196. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19197. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19198. if (info.numSamples > 256)
  19199. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19200. }
  19201. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19202. && ! positionableSource->isLooping())
  19203. {
  19204. playing = false;
  19205. inputStreamEOF = true;
  19206. sendChangeMessage();
  19207. }
  19208. stopped = ! playing;
  19209. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19210. {
  19211. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19212. lastGain, gain);
  19213. }
  19214. }
  19215. else
  19216. {
  19217. info.clearActiveBufferRegion();
  19218. stopped = true;
  19219. }
  19220. lastGain = gain;
  19221. }
  19222. END_JUCE_NAMESPACE
  19223. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19224. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19225. BEGIN_JUCE_NAMESPACE
  19226. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19227. public Thread,
  19228. private Timer
  19229. {
  19230. public:
  19231. SharedBufferingAudioSourceThread()
  19232. : Thread ("Audio Buffer")
  19233. {
  19234. }
  19235. ~SharedBufferingAudioSourceThread()
  19236. {
  19237. stopThread (10000);
  19238. clearSingletonInstance();
  19239. }
  19240. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19241. void addSource (BufferingAudioSource* source)
  19242. {
  19243. const ScopedLock sl (lock);
  19244. if (! sources.contains (source))
  19245. {
  19246. sources.add (source);
  19247. startThread();
  19248. stopTimer();
  19249. }
  19250. notify();
  19251. }
  19252. void removeSource (BufferingAudioSource* source)
  19253. {
  19254. const ScopedLock sl (lock);
  19255. sources.removeValue (source);
  19256. if (sources.size() == 0)
  19257. startTimer (5000);
  19258. }
  19259. private:
  19260. Array <BufferingAudioSource*> sources;
  19261. CriticalSection lock;
  19262. void run()
  19263. {
  19264. while (! threadShouldExit())
  19265. {
  19266. bool busy = false;
  19267. for (int i = sources.size(); --i >= 0;)
  19268. {
  19269. if (threadShouldExit())
  19270. return;
  19271. const ScopedLock sl (lock);
  19272. BufferingAudioSource* const b = sources[i];
  19273. if (b != 0 && b->readNextBufferChunk())
  19274. busy = true;
  19275. }
  19276. if (! busy)
  19277. wait (500);
  19278. }
  19279. }
  19280. void timerCallback()
  19281. {
  19282. stopTimer();
  19283. if (sources.size() == 0)
  19284. deleteInstance();
  19285. }
  19286. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19287. };
  19288. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19289. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19290. const bool deleteSourceWhenDeleted_,
  19291. int numberOfSamplesToBuffer_)
  19292. : source (source_),
  19293. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19294. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19295. buffer (2, 0),
  19296. bufferValidStart (0),
  19297. bufferValidEnd (0),
  19298. nextPlayPos (0),
  19299. wasSourceLooping (false)
  19300. {
  19301. jassert (source_ != 0);
  19302. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19303. // not using a larger buffer..
  19304. }
  19305. BufferingAudioSource::~BufferingAudioSource()
  19306. {
  19307. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19308. if (thread != 0)
  19309. thread->removeSource (this);
  19310. if (deleteSourceWhenDeleted)
  19311. delete source;
  19312. }
  19313. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19314. {
  19315. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19316. sampleRate = sampleRate_;
  19317. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19318. buffer.clear();
  19319. bufferValidStart = 0;
  19320. bufferValidEnd = 0;
  19321. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19322. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19323. buffer.getNumSamples() / 2))
  19324. {
  19325. SharedBufferingAudioSourceThread::getInstance()->notify();
  19326. Thread::sleep (5);
  19327. }
  19328. }
  19329. void BufferingAudioSource::releaseResources()
  19330. {
  19331. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19332. if (thread != 0)
  19333. thread->removeSource (this);
  19334. buffer.setSize (2, 0);
  19335. source->releaseResources();
  19336. }
  19337. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19338. {
  19339. const ScopedLock sl (bufferStartPosLock);
  19340. const int validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  19341. const int validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  19342. if (validStart == validEnd)
  19343. {
  19344. // total cache miss
  19345. info.clearActiveBufferRegion();
  19346. }
  19347. else
  19348. {
  19349. if (validStart > 0)
  19350. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19351. if (validEnd < info.numSamples)
  19352. info.buffer->clear (info.startSample + validEnd,
  19353. info.numSamples - validEnd); // partial cache miss at end
  19354. if (validStart < validEnd)
  19355. {
  19356. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19357. {
  19358. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19359. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19360. if (startBufferIndex < endBufferIndex)
  19361. {
  19362. info.buffer->copyFrom (chan, info.startSample + validStart,
  19363. buffer,
  19364. chan, startBufferIndex,
  19365. validEnd - validStart);
  19366. }
  19367. else
  19368. {
  19369. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19370. info.buffer->copyFrom (chan, info.startSample + validStart,
  19371. buffer,
  19372. chan, startBufferIndex,
  19373. initialSize);
  19374. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19375. buffer,
  19376. chan, 0,
  19377. (validEnd - validStart) - initialSize);
  19378. }
  19379. }
  19380. }
  19381. nextPlayPos += info.numSamples;
  19382. if (source->isLooping() && nextPlayPos > 0)
  19383. nextPlayPos %= source->getTotalLength();
  19384. }
  19385. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19386. if (thread != 0)
  19387. thread->notify();
  19388. }
  19389. int64 BufferingAudioSource::getNextReadPosition() const
  19390. {
  19391. return (source->isLooping() && nextPlayPos > 0)
  19392. ? nextPlayPos % source->getTotalLength()
  19393. : nextPlayPos;
  19394. }
  19395. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  19396. {
  19397. const ScopedLock sl (bufferStartPosLock);
  19398. nextPlayPos = newPosition;
  19399. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19400. if (thread != 0)
  19401. thread->notify();
  19402. }
  19403. bool BufferingAudioSource::readNextBufferChunk()
  19404. {
  19405. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19406. {
  19407. const ScopedLock sl (bufferStartPosLock);
  19408. if (wasSourceLooping != isLooping())
  19409. {
  19410. wasSourceLooping = isLooping();
  19411. bufferValidStart = 0;
  19412. bufferValidEnd = 0;
  19413. }
  19414. newBVS = jmax ((int64) 0, nextPlayPos);
  19415. newBVE = newBVS + buffer.getNumSamples() - 4;
  19416. sectionToReadStart = 0;
  19417. sectionToReadEnd = 0;
  19418. const int maxChunkSize = 2048;
  19419. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19420. {
  19421. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19422. sectionToReadStart = newBVS;
  19423. sectionToReadEnd = newBVE;
  19424. bufferValidStart = 0;
  19425. bufferValidEnd = 0;
  19426. }
  19427. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  19428. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  19429. {
  19430. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19431. sectionToReadStart = bufferValidEnd;
  19432. sectionToReadEnd = newBVE;
  19433. bufferValidStart = newBVS;
  19434. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19435. }
  19436. }
  19437. if (sectionToReadStart != sectionToReadEnd)
  19438. {
  19439. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19440. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19441. if (bufferIndexStart < bufferIndexEnd)
  19442. {
  19443. readBufferSection (sectionToReadStart,
  19444. (int) (sectionToReadEnd - sectionToReadStart),
  19445. bufferIndexStart);
  19446. }
  19447. else
  19448. {
  19449. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19450. readBufferSection (sectionToReadStart,
  19451. initialSize,
  19452. bufferIndexStart);
  19453. readBufferSection (sectionToReadStart + initialSize,
  19454. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  19455. 0);
  19456. }
  19457. const ScopedLock sl2 (bufferStartPosLock);
  19458. bufferValidStart = newBVS;
  19459. bufferValidEnd = newBVE;
  19460. return true;
  19461. }
  19462. else
  19463. {
  19464. return false;
  19465. }
  19466. }
  19467. void BufferingAudioSource::readBufferSection (const int64 start, const int length, const int bufferOffset)
  19468. {
  19469. if (source->getNextReadPosition() != start)
  19470. source->setNextReadPosition (start);
  19471. AudioSourceChannelInfo info;
  19472. info.buffer = &buffer;
  19473. info.startSample = bufferOffset;
  19474. info.numSamples = length;
  19475. source->getNextAudioBlock (info);
  19476. }
  19477. END_JUCE_NAMESPACE
  19478. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19479. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19480. BEGIN_JUCE_NAMESPACE
  19481. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19482. const bool deleteSourceWhenDeleted_)
  19483. : requiredNumberOfChannels (2),
  19484. source (source_),
  19485. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19486. buffer (2, 16)
  19487. {
  19488. remappedInfo.buffer = &buffer;
  19489. remappedInfo.startSample = 0;
  19490. }
  19491. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19492. {
  19493. if (deleteSourceWhenDeleted)
  19494. delete source;
  19495. }
  19496. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19497. {
  19498. const ScopedLock sl (lock);
  19499. requiredNumberOfChannels = requiredNumberOfChannels_;
  19500. }
  19501. void ChannelRemappingAudioSource::clearAllMappings()
  19502. {
  19503. const ScopedLock sl (lock);
  19504. remappedInputs.clear();
  19505. remappedOutputs.clear();
  19506. }
  19507. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19508. {
  19509. const ScopedLock sl (lock);
  19510. while (remappedInputs.size() < destIndex)
  19511. remappedInputs.add (-1);
  19512. remappedInputs.set (destIndex, sourceIndex);
  19513. }
  19514. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19515. {
  19516. const ScopedLock sl (lock);
  19517. while (remappedOutputs.size() < sourceIndex)
  19518. remappedOutputs.add (-1);
  19519. remappedOutputs.set (sourceIndex, destIndex);
  19520. }
  19521. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19522. {
  19523. const ScopedLock sl (lock);
  19524. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19525. return remappedInputs.getUnchecked (inputChannelIndex);
  19526. return -1;
  19527. }
  19528. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19529. {
  19530. const ScopedLock sl (lock);
  19531. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19532. return remappedOutputs .getUnchecked (outputChannelIndex);
  19533. return -1;
  19534. }
  19535. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19536. {
  19537. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19538. }
  19539. void ChannelRemappingAudioSource::releaseResources()
  19540. {
  19541. source->releaseResources();
  19542. }
  19543. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19544. {
  19545. const ScopedLock sl (lock);
  19546. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19547. const int numChans = bufferToFill.buffer->getNumChannels();
  19548. int i;
  19549. for (i = 0; i < buffer.getNumChannels(); ++i)
  19550. {
  19551. const int remappedChan = getRemappedInputChannel (i);
  19552. if (remappedChan >= 0 && remappedChan < numChans)
  19553. {
  19554. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19555. remappedChan,
  19556. bufferToFill.startSample,
  19557. bufferToFill.numSamples);
  19558. }
  19559. else
  19560. {
  19561. buffer.clear (i, 0, bufferToFill.numSamples);
  19562. }
  19563. }
  19564. remappedInfo.numSamples = bufferToFill.numSamples;
  19565. source->getNextAudioBlock (remappedInfo);
  19566. bufferToFill.clearActiveBufferRegion();
  19567. for (i = 0; i < requiredNumberOfChannels; ++i)
  19568. {
  19569. const int remappedChan = getRemappedOutputChannel (i);
  19570. if (remappedChan >= 0 && remappedChan < numChans)
  19571. {
  19572. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19573. buffer, i, 0, bufferToFill.numSamples);
  19574. }
  19575. }
  19576. }
  19577. XmlElement* ChannelRemappingAudioSource::createXml() const
  19578. {
  19579. XmlElement* e = new XmlElement ("MAPPINGS");
  19580. String ins, outs;
  19581. int i;
  19582. const ScopedLock sl (lock);
  19583. for (i = 0; i < remappedInputs.size(); ++i)
  19584. ins << remappedInputs.getUnchecked(i) << ' ';
  19585. for (i = 0; i < remappedOutputs.size(); ++i)
  19586. outs << remappedOutputs.getUnchecked(i) << ' ';
  19587. e->setAttribute ("inputs", ins.trimEnd());
  19588. e->setAttribute ("outputs", outs.trimEnd());
  19589. return e;
  19590. }
  19591. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19592. {
  19593. if (e.hasTagName ("MAPPINGS"))
  19594. {
  19595. const ScopedLock sl (lock);
  19596. clearAllMappings();
  19597. StringArray ins, outs;
  19598. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19599. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19600. int i;
  19601. for (i = 0; i < ins.size(); ++i)
  19602. remappedInputs.add (ins[i].getIntValue());
  19603. for (i = 0; i < outs.size(); ++i)
  19604. remappedOutputs.add (outs[i].getIntValue());
  19605. }
  19606. }
  19607. END_JUCE_NAMESPACE
  19608. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19609. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19610. BEGIN_JUCE_NAMESPACE
  19611. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19612. const bool deleteInputWhenDeleted_)
  19613. : input (inputSource),
  19614. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19615. {
  19616. jassert (inputSource != 0);
  19617. for (int i = 2; --i >= 0;)
  19618. iirFilters.add (new IIRFilter());
  19619. }
  19620. IIRFilterAudioSource::~IIRFilterAudioSource()
  19621. {
  19622. if (deleteInputWhenDeleted)
  19623. delete input;
  19624. }
  19625. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19626. {
  19627. for (int i = iirFilters.size(); --i >= 0;)
  19628. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19629. }
  19630. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19631. {
  19632. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19633. for (int i = iirFilters.size(); --i >= 0;)
  19634. iirFilters.getUnchecked(i)->reset();
  19635. }
  19636. void IIRFilterAudioSource::releaseResources()
  19637. {
  19638. input->releaseResources();
  19639. }
  19640. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19641. {
  19642. input->getNextAudioBlock (bufferToFill);
  19643. const int numChannels = bufferToFill.buffer->getNumChannels();
  19644. while (numChannels > iirFilters.size())
  19645. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19646. for (int i = 0; i < numChannels; ++i)
  19647. iirFilters.getUnchecked(i)
  19648. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19649. bufferToFill.numSamples);
  19650. }
  19651. END_JUCE_NAMESPACE
  19652. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19653. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19654. BEGIN_JUCE_NAMESPACE
  19655. MixerAudioSource::MixerAudioSource()
  19656. : tempBuffer (2, 0),
  19657. currentSampleRate (0.0),
  19658. bufferSizeExpected (0)
  19659. {
  19660. }
  19661. MixerAudioSource::~MixerAudioSource()
  19662. {
  19663. removeAllInputs();
  19664. }
  19665. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19666. {
  19667. if (input != 0 && ! inputs.contains (input))
  19668. {
  19669. double localRate;
  19670. int localBufferSize;
  19671. {
  19672. const ScopedLock sl (lock);
  19673. localRate = currentSampleRate;
  19674. localBufferSize = bufferSizeExpected;
  19675. }
  19676. if (localRate != 0.0)
  19677. input->prepareToPlay (localBufferSize, localRate);
  19678. const ScopedLock sl (lock);
  19679. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19680. inputs.add (input);
  19681. }
  19682. }
  19683. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19684. {
  19685. if (input != 0)
  19686. {
  19687. int index;
  19688. {
  19689. const ScopedLock sl (lock);
  19690. index = inputs.indexOf (input);
  19691. if (index >= 0)
  19692. {
  19693. inputsToDelete.shiftBits (index, 1);
  19694. inputs.remove (index);
  19695. }
  19696. }
  19697. if (index >= 0)
  19698. {
  19699. input->releaseResources();
  19700. if (deleteInput)
  19701. delete input;
  19702. }
  19703. }
  19704. }
  19705. void MixerAudioSource::removeAllInputs()
  19706. {
  19707. OwnedArray<AudioSource> toDelete;
  19708. {
  19709. const ScopedLock sl (lock);
  19710. for (int i = inputs.size(); --i >= 0;)
  19711. if (inputsToDelete[i])
  19712. toDelete.add (inputs.getUnchecked(i));
  19713. }
  19714. }
  19715. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19716. {
  19717. tempBuffer.setSize (2, samplesPerBlockExpected);
  19718. const ScopedLock sl (lock);
  19719. currentSampleRate = sampleRate;
  19720. bufferSizeExpected = samplesPerBlockExpected;
  19721. for (int i = inputs.size(); --i >= 0;)
  19722. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19723. }
  19724. void MixerAudioSource::releaseResources()
  19725. {
  19726. const ScopedLock sl (lock);
  19727. for (int i = inputs.size(); --i >= 0;)
  19728. inputs.getUnchecked(i)->releaseResources();
  19729. tempBuffer.setSize (2, 0);
  19730. currentSampleRate = 0;
  19731. bufferSizeExpected = 0;
  19732. }
  19733. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19734. {
  19735. const ScopedLock sl (lock);
  19736. if (inputs.size() > 0)
  19737. {
  19738. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19739. if (inputs.size() > 1)
  19740. {
  19741. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19742. info.buffer->getNumSamples());
  19743. AudioSourceChannelInfo info2;
  19744. info2.buffer = &tempBuffer;
  19745. info2.numSamples = info.numSamples;
  19746. info2.startSample = 0;
  19747. for (int i = 1; i < inputs.size(); ++i)
  19748. {
  19749. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19750. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19751. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19752. }
  19753. }
  19754. }
  19755. else
  19756. {
  19757. info.clearActiveBufferRegion();
  19758. }
  19759. }
  19760. END_JUCE_NAMESPACE
  19761. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19762. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19763. BEGIN_JUCE_NAMESPACE
  19764. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19765. const bool deleteInputWhenDeleted_,
  19766. const int numChannels_)
  19767. : input (inputSource),
  19768. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19769. ratio (1.0),
  19770. lastRatio (1.0),
  19771. buffer (numChannels_, 0),
  19772. sampsInBuffer (0),
  19773. numChannels (numChannels_)
  19774. {
  19775. jassert (input != 0);
  19776. }
  19777. ResamplingAudioSource::~ResamplingAudioSource()
  19778. {
  19779. if (deleteInputWhenDeleted)
  19780. delete input;
  19781. }
  19782. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19783. {
  19784. jassert (samplesInPerOutputSample > 0);
  19785. const ScopedLock sl (ratioLock);
  19786. ratio = jmax (0.0, samplesInPerOutputSample);
  19787. }
  19788. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19789. double sampleRate)
  19790. {
  19791. const ScopedLock sl (ratioLock);
  19792. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19793. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19794. buffer.clear();
  19795. sampsInBuffer = 0;
  19796. bufferPos = 0;
  19797. subSampleOffset = 0.0;
  19798. filterStates.calloc (numChannels);
  19799. srcBuffers.calloc (numChannels);
  19800. destBuffers.calloc (numChannels);
  19801. createLowPass (ratio);
  19802. resetFilters();
  19803. }
  19804. void ResamplingAudioSource::releaseResources()
  19805. {
  19806. input->releaseResources();
  19807. buffer.setSize (numChannels, 0);
  19808. }
  19809. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19810. {
  19811. double localRatio;
  19812. {
  19813. const ScopedLock sl (ratioLock);
  19814. localRatio = ratio;
  19815. }
  19816. if (lastRatio != localRatio)
  19817. {
  19818. createLowPass (localRatio);
  19819. lastRatio = localRatio;
  19820. }
  19821. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19822. int bufferSize = buffer.getNumSamples();
  19823. if (bufferSize < sampsNeeded + 8)
  19824. {
  19825. bufferPos %= bufferSize;
  19826. bufferSize = sampsNeeded + 32;
  19827. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19828. }
  19829. bufferPos %= bufferSize;
  19830. int endOfBufferPos = bufferPos + sampsInBuffer;
  19831. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19832. while (sampsNeeded > sampsInBuffer)
  19833. {
  19834. endOfBufferPos %= bufferSize;
  19835. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19836. bufferSize - endOfBufferPos);
  19837. AudioSourceChannelInfo readInfo;
  19838. readInfo.buffer = &buffer;
  19839. readInfo.numSamples = numToDo;
  19840. readInfo.startSample = endOfBufferPos;
  19841. input->getNextAudioBlock (readInfo);
  19842. if (localRatio > 1.0001)
  19843. {
  19844. // for down-sampling, pre-apply the filter..
  19845. for (int i = channelsToProcess; --i >= 0;)
  19846. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19847. }
  19848. sampsInBuffer += numToDo;
  19849. endOfBufferPos += numToDo;
  19850. }
  19851. for (int channel = 0; channel < channelsToProcess; ++channel)
  19852. {
  19853. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19854. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19855. }
  19856. int nextPos = (bufferPos + 1) % bufferSize;
  19857. for (int m = info.numSamples; --m >= 0;)
  19858. {
  19859. const float alpha = (float) subSampleOffset;
  19860. const float invAlpha = 1.0f - alpha;
  19861. for (int channel = 0; channel < channelsToProcess; ++channel)
  19862. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19863. subSampleOffset += localRatio;
  19864. jassert (sampsInBuffer > 0);
  19865. while (subSampleOffset >= 1.0)
  19866. {
  19867. if (++bufferPos >= bufferSize)
  19868. bufferPos = 0;
  19869. --sampsInBuffer;
  19870. nextPos = (bufferPos + 1) % bufferSize;
  19871. subSampleOffset -= 1.0;
  19872. }
  19873. }
  19874. if (localRatio < 0.9999)
  19875. {
  19876. // for up-sampling, apply the filter after transposing..
  19877. for (int i = channelsToProcess; --i >= 0;)
  19878. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19879. }
  19880. else if (localRatio <= 1.0001)
  19881. {
  19882. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19883. for (int i = channelsToProcess; --i >= 0;)
  19884. {
  19885. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19886. FilterState& fs = filterStates[i];
  19887. if (info.numSamples > 1)
  19888. {
  19889. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19890. }
  19891. else
  19892. {
  19893. fs.y2 = fs.y1;
  19894. fs.x2 = fs.x1;
  19895. }
  19896. fs.y1 = fs.x1 = *endOfBuffer;
  19897. }
  19898. }
  19899. jassert (sampsInBuffer >= 0);
  19900. }
  19901. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19902. {
  19903. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19904. : 0.5 * frequencyRatio;
  19905. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  19906. const double nSquared = n * n;
  19907. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19908. setFilterCoefficients (c1,
  19909. c1 * 2.0f,
  19910. c1,
  19911. 1.0,
  19912. c1 * 2.0 * (1.0 - nSquared),
  19913. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19914. }
  19915. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19916. {
  19917. const double a = 1.0 / c4;
  19918. c1 *= a;
  19919. c2 *= a;
  19920. c3 *= a;
  19921. c5 *= a;
  19922. c6 *= a;
  19923. coefficients[0] = c1;
  19924. coefficients[1] = c2;
  19925. coefficients[2] = c3;
  19926. coefficients[3] = c4;
  19927. coefficients[4] = c5;
  19928. coefficients[5] = c6;
  19929. }
  19930. void ResamplingAudioSource::resetFilters()
  19931. {
  19932. zeromem (filterStates, sizeof (FilterState) * numChannels);
  19933. }
  19934. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19935. {
  19936. while (--num >= 0)
  19937. {
  19938. const double in = *samples;
  19939. double out = coefficients[0] * in
  19940. + coefficients[1] * fs.x1
  19941. + coefficients[2] * fs.x2
  19942. - coefficients[4] * fs.y1
  19943. - coefficients[5] * fs.y2;
  19944. #if JUCE_INTEL
  19945. if (! (out < -1.0e-8 || out > 1.0e-8))
  19946. out = 0;
  19947. #endif
  19948. fs.x2 = fs.x1;
  19949. fs.x1 = in;
  19950. fs.y2 = fs.y1;
  19951. fs.y1 = out;
  19952. *samples++ = (float) out;
  19953. }
  19954. }
  19955. END_JUCE_NAMESPACE
  19956. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19957. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19958. BEGIN_JUCE_NAMESPACE
  19959. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19960. : frequency (1000.0),
  19961. sampleRate (44100.0),
  19962. currentPhase (0.0),
  19963. phasePerSample (0.0),
  19964. amplitude (0.5f)
  19965. {
  19966. }
  19967. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19968. {
  19969. }
  19970. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19971. {
  19972. amplitude = newAmplitude;
  19973. }
  19974. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19975. {
  19976. frequency = newFrequencyHz;
  19977. phasePerSample = 0.0;
  19978. }
  19979. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19980. double sampleRate_)
  19981. {
  19982. currentPhase = 0.0;
  19983. phasePerSample = 0.0;
  19984. sampleRate = sampleRate_;
  19985. }
  19986. void ToneGeneratorAudioSource::releaseResources()
  19987. {
  19988. }
  19989. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19990. {
  19991. if (phasePerSample == 0.0)
  19992. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19993. for (int i = 0; i < info.numSamples; ++i)
  19994. {
  19995. const float sample = amplitude * (float) std::sin (currentPhase);
  19996. currentPhase += phasePerSample;
  19997. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19998. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19999. }
  20000. }
  20001. END_JUCE_NAMESPACE
  20002. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20003. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20004. BEGIN_JUCE_NAMESPACE
  20005. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20006. : sampleRate (0),
  20007. bufferSize (0),
  20008. useDefaultInputChannels (true),
  20009. useDefaultOutputChannels (true)
  20010. {
  20011. }
  20012. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20013. {
  20014. return outputDeviceName == other.outputDeviceName
  20015. && inputDeviceName == other.inputDeviceName
  20016. && sampleRate == other.sampleRate
  20017. && bufferSize == other.bufferSize
  20018. && inputChannels == other.inputChannels
  20019. && useDefaultInputChannels == other.useDefaultInputChannels
  20020. && outputChannels == other.outputChannels
  20021. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20022. }
  20023. AudioDeviceManager::AudioDeviceManager()
  20024. : currentAudioDevice (0),
  20025. numInputChansNeeded (0),
  20026. numOutputChansNeeded (2),
  20027. listNeedsScanning (true),
  20028. useInputNames (false),
  20029. inputLevelMeasurementEnabledCount (0),
  20030. inputLevel (0),
  20031. tempBuffer (2, 2),
  20032. defaultMidiOutput (0),
  20033. cpuUsageMs (0),
  20034. timeToCpuScale (0)
  20035. {
  20036. callbackHandler.owner = this;
  20037. }
  20038. AudioDeviceManager::~AudioDeviceManager()
  20039. {
  20040. currentAudioDevice = 0;
  20041. defaultMidiOutput = 0;
  20042. }
  20043. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20044. {
  20045. if (availableDeviceTypes.size() == 0)
  20046. {
  20047. createAudioDeviceTypes (availableDeviceTypes);
  20048. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20049. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20050. if (availableDeviceTypes.size() > 0)
  20051. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20052. }
  20053. }
  20054. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20055. {
  20056. scanDevicesIfNeeded();
  20057. return availableDeviceTypes;
  20058. }
  20059. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20060. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20061. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20062. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20063. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20064. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20065. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20066. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20067. {
  20068. (void) list; // (to avoid 'unused param' warnings)
  20069. #if JUCE_WINDOWS
  20070. #if JUCE_WASAPI
  20071. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20072. list.add (juce_createAudioIODeviceType_WASAPI());
  20073. #endif
  20074. #if JUCE_DIRECTSOUND
  20075. list.add (juce_createAudioIODeviceType_DirectSound());
  20076. #endif
  20077. #if JUCE_ASIO
  20078. list.add (juce_createAudioIODeviceType_ASIO());
  20079. #endif
  20080. #endif
  20081. #if JUCE_MAC
  20082. list.add (juce_createAudioIODeviceType_CoreAudio());
  20083. #endif
  20084. #if JUCE_IOS
  20085. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20086. #endif
  20087. #if JUCE_LINUX && JUCE_ALSA
  20088. list.add (juce_createAudioIODeviceType_ALSA());
  20089. #endif
  20090. #if JUCE_LINUX && JUCE_JACK
  20091. list.add (juce_createAudioIODeviceType_JACK());
  20092. #endif
  20093. }
  20094. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20095. const int numOutputChannelsNeeded,
  20096. const XmlElement* const e,
  20097. const bool selectDefaultDeviceOnFailure,
  20098. const String& preferredDefaultDeviceName,
  20099. const AudioDeviceSetup* preferredSetupOptions)
  20100. {
  20101. scanDevicesIfNeeded();
  20102. numInputChansNeeded = numInputChannelsNeeded;
  20103. numOutputChansNeeded = numOutputChannelsNeeded;
  20104. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20105. {
  20106. lastExplicitSettings = new XmlElement (*e);
  20107. String error;
  20108. AudioDeviceSetup setup;
  20109. if (preferredSetupOptions != 0)
  20110. setup = *preferredSetupOptions;
  20111. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20112. {
  20113. setup.inputDeviceName = setup.outputDeviceName
  20114. = e->getStringAttribute ("audioDeviceName");
  20115. }
  20116. else
  20117. {
  20118. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20119. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20120. }
  20121. currentDeviceType = e->getStringAttribute ("deviceType");
  20122. if (currentDeviceType.isEmpty())
  20123. {
  20124. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20125. if (type != 0)
  20126. currentDeviceType = type->getTypeName();
  20127. else if (availableDeviceTypes.size() > 0)
  20128. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20129. }
  20130. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20131. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20132. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20133. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20134. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20135. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20136. error = setAudioDeviceSetup (setup, true);
  20137. midiInsFromXml.clear();
  20138. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20139. midiInsFromXml.add (c->getStringAttribute ("name"));
  20140. const StringArray allMidiIns (MidiInput::getDevices());
  20141. for (int i = allMidiIns.size(); --i >= 0;)
  20142. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20143. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20144. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20145. false, preferredDefaultDeviceName);
  20146. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20147. return error;
  20148. }
  20149. else
  20150. {
  20151. AudioDeviceSetup setup;
  20152. if (preferredSetupOptions != 0)
  20153. {
  20154. setup = *preferredSetupOptions;
  20155. }
  20156. else if (preferredDefaultDeviceName.isNotEmpty())
  20157. {
  20158. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20159. {
  20160. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20161. StringArray outs (type->getDeviceNames (false));
  20162. int i;
  20163. for (i = 0; i < outs.size(); ++i)
  20164. {
  20165. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20166. {
  20167. setup.outputDeviceName = outs[i];
  20168. break;
  20169. }
  20170. }
  20171. StringArray ins (type->getDeviceNames (true));
  20172. for (i = 0; i < ins.size(); ++i)
  20173. {
  20174. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20175. {
  20176. setup.inputDeviceName = ins[i];
  20177. break;
  20178. }
  20179. }
  20180. }
  20181. }
  20182. insertDefaultDeviceNames (setup);
  20183. return setAudioDeviceSetup (setup, false);
  20184. }
  20185. }
  20186. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20187. {
  20188. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20189. if (type != 0)
  20190. {
  20191. if (setup.outputDeviceName.isEmpty())
  20192. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20193. if (setup.inputDeviceName.isEmpty())
  20194. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20195. }
  20196. }
  20197. XmlElement* AudioDeviceManager::createStateXml() const
  20198. {
  20199. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20200. }
  20201. void AudioDeviceManager::scanDevicesIfNeeded()
  20202. {
  20203. if (listNeedsScanning)
  20204. {
  20205. listNeedsScanning = false;
  20206. createDeviceTypesIfNeeded();
  20207. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20208. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20209. }
  20210. }
  20211. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20212. {
  20213. scanDevicesIfNeeded();
  20214. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20215. {
  20216. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20217. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20218. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20219. {
  20220. return type;
  20221. }
  20222. }
  20223. return 0;
  20224. }
  20225. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20226. {
  20227. setup = currentSetup;
  20228. }
  20229. void AudioDeviceManager::deleteCurrentDevice()
  20230. {
  20231. currentAudioDevice = 0;
  20232. currentSetup.inputDeviceName = String::empty;
  20233. currentSetup.outputDeviceName = String::empty;
  20234. }
  20235. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20236. const bool treatAsChosenDevice)
  20237. {
  20238. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20239. {
  20240. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20241. && currentDeviceType != type)
  20242. {
  20243. currentDeviceType = type;
  20244. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20245. insertDefaultDeviceNames (s);
  20246. setAudioDeviceSetup (s, treatAsChosenDevice);
  20247. sendChangeMessage();
  20248. break;
  20249. }
  20250. }
  20251. }
  20252. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20253. {
  20254. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20255. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20256. return availableDeviceTypes[i];
  20257. return availableDeviceTypes[0];
  20258. }
  20259. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20260. const bool treatAsChosenDevice)
  20261. {
  20262. jassert (&newSetup != &currentSetup); // this will have no effect
  20263. if (newSetup == currentSetup && currentAudioDevice != 0)
  20264. return String::empty;
  20265. if (! (newSetup == currentSetup))
  20266. sendChangeMessage();
  20267. stopDevice();
  20268. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20269. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20270. String error;
  20271. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20272. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20273. {
  20274. deleteCurrentDevice();
  20275. if (treatAsChosenDevice)
  20276. updateXml();
  20277. return String::empty;
  20278. }
  20279. if (currentSetup.inputDeviceName != newInputDeviceName
  20280. || currentSetup.outputDeviceName != newOutputDeviceName
  20281. || currentAudioDevice == 0)
  20282. {
  20283. deleteCurrentDevice();
  20284. scanDevicesIfNeeded();
  20285. if (newOutputDeviceName.isNotEmpty()
  20286. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20287. {
  20288. return "No such device: " + newOutputDeviceName;
  20289. }
  20290. if (newInputDeviceName.isNotEmpty()
  20291. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20292. {
  20293. return "No such device: " + newInputDeviceName;
  20294. }
  20295. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20296. if (currentAudioDevice == 0)
  20297. 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!";
  20298. else
  20299. error = currentAudioDevice->getLastError();
  20300. if (error.isNotEmpty())
  20301. {
  20302. deleteCurrentDevice();
  20303. return error;
  20304. }
  20305. if (newSetup.useDefaultInputChannels)
  20306. {
  20307. inputChannels.clear();
  20308. inputChannels.setRange (0, numInputChansNeeded, true);
  20309. }
  20310. if (newSetup.useDefaultOutputChannels)
  20311. {
  20312. outputChannels.clear();
  20313. outputChannels.setRange (0, numOutputChansNeeded, true);
  20314. }
  20315. if (newInputDeviceName.isEmpty())
  20316. inputChannels.clear();
  20317. if (newOutputDeviceName.isEmpty())
  20318. outputChannels.clear();
  20319. }
  20320. if (! newSetup.useDefaultInputChannels)
  20321. inputChannels = newSetup.inputChannels;
  20322. if (! newSetup.useDefaultOutputChannels)
  20323. outputChannels = newSetup.outputChannels;
  20324. currentSetup = newSetup;
  20325. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20326. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20327. error = currentAudioDevice->open (inputChannels,
  20328. outputChannels,
  20329. currentSetup.sampleRate,
  20330. currentSetup.bufferSize);
  20331. if (error.isEmpty())
  20332. {
  20333. currentDeviceType = currentAudioDevice->getTypeName();
  20334. currentAudioDevice->start (&callbackHandler);
  20335. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20336. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20337. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20338. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20339. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20340. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20341. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20342. if (treatAsChosenDevice)
  20343. updateXml();
  20344. }
  20345. else
  20346. {
  20347. deleteCurrentDevice();
  20348. }
  20349. return error;
  20350. }
  20351. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20352. {
  20353. jassert (currentAudioDevice != 0);
  20354. if (rate > 0)
  20355. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20356. if (currentAudioDevice->getSampleRate (i) == rate)
  20357. return rate;
  20358. double lowestAbove44 = 0.0;
  20359. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20360. {
  20361. const double sr = currentAudioDevice->getSampleRate (i);
  20362. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20363. lowestAbove44 = sr;
  20364. }
  20365. if (lowestAbove44 > 0.0)
  20366. return lowestAbove44;
  20367. return currentAudioDevice->getSampleRate (0);
  20368. }
  20369. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20370. {
  20371. jassert (currentAudioDevice != 0);
  20372. if (bufferSize > 0)
  20373. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20374. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20375. return bufferSize;
  20376. return currentAudioDevice->getDefaultBufferSize();
  20377. }
  20378. void AudioDeviceManager::stopDevice()
  20379. {
  20380. if (currentAudioDevice != 0)
  20381. currentAudioDevice->stop();
  20382. testSound = 0;
  20383. }
  20384. void AudioDeviceManager::closeAudioDevice()
  20385. {
  20386. stopDevice();
  20387. currentAudioDevice = 0;
  20388. }
  20389. void AudioDeviceManager::restartLastAudioDevice()
  20390. {
  20391. if (currentAudioDevice == 0)
  20392. {
  20393. if (currentSetup.inputDeviceName.isEmpty()
  20394. && currentSetup.outputDeviceName.isEmpty())
  20395. {
  20396. // This method will only reload the last device that was running
  20397. // before closeAudioDevice() was called - you need to actually open
  20398. // one first, with setAudioDevice().
  20399. jassertfalse;
  20400. return;
  20401. }
  20402. AudioDeviceSetup s (currentSetup);
  20403. setAudioDeviceSetup (s, false);
  20404. }
  20405. }
  20406. void AudioDeviceManager::updateXml()
  20407. {
  20408. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20409. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20410. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20411. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20412. if (currentAudioDevice != 0)
  20413. {
  20414. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20415. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20416. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20417. if (! currentSetup.useDefaultInputChannels)
  20418. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20419. if (! currentSetup.useDefaultOutputChannels)
  20420. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20421. }
  20422. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20423. {
  20424. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20425. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20426. }
  20427. if (midiInsFromXml.size() > 0)
  20428. {
  20429. // Add any midi devices that have been enabled before, but which aren't currently
  20430. // open because the device has been disconnected.
  20431. const StringArray availableMidiDevices (MidiInput::getDevices());
  20432. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20433. {
  20434. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20435. {
  20436. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20437. m->setAttribute ("name", midiInsFromXml[i]);
  20438. }
  20439. }
  20440. }
  20441. if (defaultMidiOutputName.isNotEmpty())
  20442. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20443. }
  20444. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20445. {
  20446. {
  20447. const ScopedLock sl (audioCallbackLock);
  20448. if (callbacks.contains (newCallback))
  20449. return;
  20450. }
  20451. if (currentAudioDevice != 0 && newCallback != 0)
  20452. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20453. const ScopedLock sl (audioCallbackLock);
  20454. callbacks.add (newCallback);
  20455. }
  20456. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20457. {
  20458. if (callbackToRemove != 0)
  20459. {
  20460. bool needsDeinitialising = currentAudioDevice != 0;
  20461. {
  20462. const ScopedLock sl (audioCallbackLock);
  20463. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20464. callbacks.removeValue (callbackToRemove);
  20465. }
  20466. if (needsDeinitialising)
  20467. callbackToRemove->audioDeviceStopped();
  20468. }
  20469. }
  20470. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20471. int numInputChannels,
  20472. float** outputChannelData,
  20473. int numOutputChannels,
  20474. int numSamples)
  20475. {
  20476. const ScopedLock sl (audioCallbackLock);
  20477. if (inputLevelMeasurementEnabledCount > 0)
  20478. {
  20479. for (int j = 0; j < numSamples; ++j)
  20480. {
  20481. float s = 0;
  20482. for (int i = 0; i < numInputChannels; ++i)
  20483. s += std::abs (inputChannelData[i][j]);
  20484. s /= numInputChannels;
  20485. const double decayFactor = 0.99992;
  20486. if (s > inputLevel)
  20487. inputLevel = s;
  20488. else if (inputLevel > 0.001f)
  20489. inputLevel *= decayFactor;
  20490. else
  20491. inputLevel = 0;
  20492. }
  20493. }
  20494. if (callbacks.size() > 0)
  20495. {
  20496. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20497. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20498. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20499. outputChannelData, numOutputChannels, numSamples);
  20500. float** const tempChans = tempBuffer.getArrayOfChannels();
  20501. for (int i = callbacks.size(); --i > 0;)
  20502. {
  20503. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20504. tempChans, numOutputChannels, numSamples);
  20505. for (int chan = 0; chan < numOutputChannels; ++chan)
  20506. {
  20507. const float* const src = tempChans [chan];
  20508. float* const dst = outputChannelData [chan];
  20509. if (src != 0 && dst != 0)
  20510. for (int j = 0; j < numSamples; ++j)
  20511. dst[j] += src[j];
  20512. }
  20513. }
  20514. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20515. const double filterAmount = 0.2;
  20516. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20517. }
  20518. else
  20519. {
  20520. for (int i = 0; i < numOutputChannels; ++i)
  20521. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20522. }
  20523. if (testSound != 0)
  20524. {
  20525. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20526. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20527. for (int i = 0; i < numOutputChannels; ++i)
  20528. for (int j = 0; j < numSamps; ++j)
  20529. outputChannelData [i][j] += src[j];
  20530. testSoundPosition += numSamps;
  20531. if (testSoundPosition >= testSound->getNumSamples())
  20532. testSound = 0;
  20533. }
  20534. }
  20535. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20536. {
  20537. cpuUsageMs = 0;
  20538. const double sampleRate = device->getCurrentSampleRate();
  20539. const int blockSize = device->getCurrentBufferSizeSamples();
  20540. if (sampleRate > 0.0 && blockSize > 0)
  20541. {
  20542. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20543. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20544. }
  20545. {
  20546. const ScopedLock sl (audioCallbackLock);
  20547. for (int i = callbacks.size(); --i >= 0;)
  20548. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20549. }
  20550. sendChangeMessage();
  20551. }
  20552. void AudioDeviceManager::audioDeviceStoppedInt()
  20553. {
  20554. cpuUsageMs = 0;
  20555. timeToCpuScale = 0;
  20556. sendChangeMessage();
  20557. const ScopedLock sl (audioCallbackLock);
  20558. for (int i = callbacks.size(); --i >= 0;)
  20559. callbacks.getUnchecked(i)->audioDeviceStopped();
  20560. }
  20561. double AudioDeviceManager::getCpuUsage() const
  20562. {
  20563. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20564. }
  20565. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20566. const bool enabled)
  20567. {
  20568. if (enabled != isMidiInputEnabled (name))
  20569. {
  20570. if (enabled)
  20571. {
  20572. const int index = MidiInput::getDevices().indexOf (name);
  20573. if (index >= 0)
  20574. {
  20575. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20576. if (min != 0)
  20577. {
  20578. enabledMidiInputs.add (min);
  20579. min->start();
  20580. }
  20581. }
  20582. }
  20583. else
  20584. {
  20585. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20586. if (enabledMidiInputs[i]->getName() == name)
  20587. enabledMidiInputs.remove (i);
  20588. }
  20589. updateXml();
  20590. sendChangeMessage();
  20591. }
  20592. }
  20593. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20594. {
  20595. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20596. if (enabledMidiInputs[i]->getName() == name)
  20597. return true;
  20598. return false;
  20599. }
  20600. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20601. MidiInputCallback* callbackToAdd)
  20602. {
  20603. removeMidiInputCallback (name, callbackToAdd);
  20604. if (name.isEmpty())
  20605. {
  20606. midiCallbacks.add (callbackToAdd);
  20607. midiCallbackDevices.add (String::empty);
  20608. }
  20609. else
  20610. {
  20611. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20612. {
  20613. if (enabledMidiInputs[i]->getName() == name)
  20614. {
  20615. const ScopedLock sl (midiCallbackLock);
  20616. midiCallbacks.add (callbackToAdd);
  20617. midiCallbackDevices.add (enabledMidiInputs[i]->getName());
  20618. break;
  20619. }
  20620. }
  20621. }
  20622. }
  20623. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* /*callback*/)
  20624. {
  20625. const ScopedLock sl (midiCallbackLock);
  20626. for (int i = midiCallbacks.size(); --i >= 0;)
  20627. {
  20628. if (midiCallbackDevices[i] == name)
  20629. {
  20630. midiCallbacks.remove (i);
  20631. midiCallbackDevices.remove (i);
  20632. }
  20633. }
  20634. }
  20635. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20636. const MidiMessage& message)
  20637. {
  20638. if (! message.isActiveSense())
  20639. {
  20640. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20641. const ScopedLock sl (midiCallbackLock);
  20642. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20643. {
  20644. const String name (midiCallbackDevices[i]);
  20645. if ((isDefaultSource && name.isEmpty()) || (name.isNotEmpty() && name == source->getName()))
  20646. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20647. }
  20648. }
  20649. }
  20650. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20651. {
  20652. if (defaultMidiOutputName != deviceName)
  20653. {
  20654. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20655. {
  20656. const ScopedLock sl (audioCallbackLock);
  20657. oldCallbacks = callbacks;
  20658. callbacks.clear();
  20659. }
  20660. if (currentAudioDevice != 0)
  20661. for (int i = oldCallbacks.size(); --i >= 0;)
  20662. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20663. defaultMidiOutput = 0;
  20664. defaultMidiOutputName = deviceName;
  20665. if (deviceName.isNotEmpty())
  20666. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20667. if (currentAudioDevice != 0)
  20668. for (int i = oldCallbacks.size(); --i >= 0;)
  20669. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20670. {
  20671. const ScopedLock sl (audioCallbackLock);
  20672. callbacks = oldCallbacks;
  20673. }
  20674. updateXml();
  20675. sendChangeMessage();
  20676. }
  20677. }
  20678. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20679. int numInputChannels,
  20680. float** outputChannelData,
  20681. int numOutputChannels,
  20682. int numSamples)
  20683. {
  20684. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20685. }
  20686. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20687. {
  20688. owner->audioDeviceAboutToStartInt (device);
  20689. }
  20690. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20691. {
  20692. owner->audioDeviceStoppedInt();
  20693. }
  20694. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20695. {
  20696. owner->handleIncomingMidiMessageInt (source, message);
  20697. }
  20698. void AudioDeviceManager::playTestSound()
  20699. {
  20700. { // cunningly nested to swap, unlock and delete in that order.
  20701. ScopedPointer <AudioSampleBuffer> oldSound;
  20702. {
  20703. const ScopedLock sl (audioCallbackLock);
  20704. oldSound = testSound;
  20705. }
  20706. }
  20707. testSoundPosition = 0;
  20708. if (currentAudioDevice != 0)
  20709. {
  20710. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20711. const int soundLength = (int) sampleRate;
  20712. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20713. float* samples = newSound->getSampleData (0);
  20714. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20715. const float amplitude = 0.5f;
  20716. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20717. for (int i = 0; i < soundLength; ++i)
  20718. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20719. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20720. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20721. const ScopedLock sl (audioCallbackLock);
  20722. testSound = newSound;
  20723. }
  20724. }
  20725. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20726. {
  20727. const ScopedLock sl (audioCallbackLock);
  20728. if (enableMeasurement)
  20729. ++inputLevelMeasurementEnabledCount;
  20730. else
  20731. --inputLevelMeasurementEnabledCount;
  20732. inputLevel = 0;
  20733. }
  20734. double AudioDeviceManager::getCurrentInputLevel() const
  20735. {
  20736. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20737. return inputLevel;
  20738. }
  20739. END_JUCE_NAMESPACE
  20740. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20741. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20742. BEGIN_JUCE_NAMESPACE
  20743. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20744. : name (deviceName),
  20745. typeName (typeName_)
  20746. {
  20747. }
  20748. AudioIODevice::~AudioIODevice()
  20749. {
  20750. }
  20751. bool AudioIODevice::hasControlPanel() const
  20752. {
  20753. return false;
  20754. }
  20755. bool AudioIODevice::showControlPanel()
  20756. {
  20757. jassertfalse; // this should only be called for devices which return true from
  20758. // their hasControlPanel() method.
  20759. return false;
  20760. }
  20761. END_JUCE_NAMESPACE
  20762. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20763. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20764. BEGIN_JUCE_NAMESPACE
  20765. AudioIODeviceType::AudioIODeviceType (const String& name)
  20766. : typeName (name)
  20767. {
  20768. }
  20769. AudioIODeviceType::~AudioIODeviceType()
  20770. {
  20771. }
  20772. END_JUCE_NAMESPACE
  20773. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20774. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20775. BEGIN_JUCE_NAMESPACE
  20776. MidiOutput::MidiOutput()
  20777. : Thread ("midi out"),
  20778. internal (0),
  20779. firstMessage (0)
  20780. {
  20781. }
  20782. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20783. const double sampleNumber)
  20784. : message (data, len, sampleNumber)
  20785. {
  20786. }
  20787. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20788. const double millisecondCounterToStartAt,
  20789. double samplesPerSecondForBuffer)
  20790. {
  20791. // You've got to call startBackgroundThread() for this to actually work..
  20792. jassert (isThreadRunning());
  20793. // this needs to be a value in the future - RTFM for this method!
  20794. jassert (millisecondCounterToStartAt > 0);
  20795. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20796. MidiBuffer::Iterator i (buffer);
  20797. const uint8* data;
  20798. int len, time;
  20799. while (i.getNextEvent (data, len, time))
  20800. {
  20801. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20802. PendingMessage* const m
  20803. = new PendingMessage (data, len, eventTime);
  20804. const ScopedLock sl (lock);
  20805. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20806. {
  20807. m->next = firstMessage;
  20808. firstMessage = m;
  20809. }
  20810. else
  20811. {
  20812. PendingMessage* mm = firstMessage;
  20813. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20814. mm = mm->next;
  20815. m->next = mm->next;
  20816. mm->next = m;
  20817. }
  20818. }
  20819. notify();
  20820. }
  20821. void MidiOutput::clearAllPendingMessages()
  20822. {
  20823. const ScopedLock sl (lock);
  20824. while (firstMessage != 0)
  20825. {
  20826. PendingMessage* const m = firstMessage;
  20827. firstMessage = firstMessage->next;
  20828. delete m;
  20829. }
  20830. }
  20831. void MidiOutput::startBackgroundThread()
  20832. {
  20833. startThread (9);
  20834. }
  20835. void MidiOutput::stopBackgroundThread()
  20836. {
  20837. stopThread (5000);
  20838. }
  20839. void MidiOutput::run()
  20840. {
  20841. while (! threadShouldExit())
  20842. {
  20843. uint32 now = Time::getMillisecondCounter();
  20844. uint32 eventTime = 0;
  20845. uint32 timeToWait = 500;
  20846. PendingMessage* message;
  20847. {
  20848. const ScopedLock sl (lock);
  20849. message = firstMessage;
  20850. if (message != 0)
  20851. {
  20852. eventTime = roundToInt (message->message.getTimeStamp());
  20853. if (eventTime > now + 20)
  20854. {
  20855. timeToWait = eventTime - (now + 20);
  20856. message = 0;
  20857. }
  20858. else
  20859. {
  20860. firstMessage = message->next;
  20861. }
  20862. }
  20863. }
  20864. if (message != 0)
  20865. {
  20866. if (eventTime > now)
  20867. {
  20868. Time::waitForMillisecondCounter (eventTime);
  20869. if (threadShouldExit())
  20870. break;
  20871. }
  20872. if (eventTime > now - 200)
  20873. sendMessageNow (message->message);
  20874. delete message;
  20875. }
  20876. else
  20877. {
  20878. jassert (timeToWait < 1000 * 30);
  20879. wait (timeToWait);
  20880. }
  20881. }
  20882. clearAllPendingMessages();
  20883. }
  20884. END_JUCE_NAMESPACE
  20885. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20886. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20887. BEGIN_JUCE_NAMESPACE
  20888. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20889. {
  20890. const double maxVal = (double) 0x7fff;
  20891. char* intData = static_cast <char*> (dest);
  20892. if (dest != (void*) source || destBytesPerSample <= 4)
  20893. {
  20894. for (int i = 0; i < numSamples; ++i)
  20895. {
  20896. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20897. intData += destBytesPerSample;
  20898. }
  20899. }
  20900. else
  20901. {
  20902. intData += destBytesPerSample * numSamples;
  20903. for (int i = numSamples; --i >= 0;)
  20904. {
  20905. intData -= destBytesPerSample;
  20906. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20907. }
  20908. }
  20909. }
  20910. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20911. {
  20912. const double maxVal = (double) 0x7fff;
  20913. char* intData = static_cast <char*> (dest);
  20914. if (dest != (void*) source || destBytesPerSample <= 4)
  20915. {
  20916. for (int i = 0; i < numSamples; ++i)
  20917. {
  20918. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20919. intData += destBytesPerSample;
  20920. }
  20921. }
  20922. else
  20923. {
  20924. intData += destBytesPerSample * numSamples;
  20925. for (int i = numSamples; --i >= 0;)
  20926. {
  20927. intData -= destBytesPerSample;
  20928. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20929. }
  20930. }
  20931. }
  20932. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20933. {
  20934. const double maxVal = (double) 0x7fffff;
  20935. char* intData = static_cast <char*> (dest);
  20936. if (dest != (void*) source || destBytesPerSample <= 4)
  20937. {
  20938. for (int i = 0; i < numSamples; ++i)
  20939. {
  20940. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20941. intData += destBytesPerSample;
  20942. }
  20943. }
  20944. else
  20945. {
  20946. intData += destBytesPerSample * numSamples;
  20947. for (int i = numSamples; --i >= 0;)
  20948. {
  20949. intData -= destBytesPerSample;
  20950. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20951. }
  20952. }
  20953. }
  20954. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20955. {
  20956. const double maxVal = (double) 0x7fffff;
  20957. char* intData = static_cast <char*> (dest);
  20958. if (dest != (void*) source || destBytesPerSample <= 4)
  20959. {
  20960. for (int i = 0; i < numSamples; ++i)
  20961. {
  20962. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20963. intData += destBytesPerSample;
  20964. }
  20965. }
  20966. else
  20967. {
  20968. intData += destBytesPerSample * numSamples;
  20969. for (int i = numSamples; --i >= 0;)
  20970. {
  20971. intData -= destBytesPerSample;
  20972. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20973. }
  20974. }
  20975. }
  20976. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20977. {
  20978. const double maxVal = (double) 0x7fffffff;
  20979. char* intData = static_cast <char*> (dest);
  20980. if (dest != (void*) source || destBytesPerSample <= 4)
  20981. {
  20982. for (int i = 0; i < numSamples; ++i)
  20983. {
  20984. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20985. intData += destBytesPerSample;
  20986. }
  20987. }
  20988. else
  20989. {
  20990. intData += destBytesPerSample * numSamples;
  20991. for (int i = numSamples; --i >= 0;)
  20992. {
  20993. intData -= destBytesPerSample;
  20994. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20995. }
  20996. }
  20997. }
  20998. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20999. {
  21000. const double maxVal = (double) 0x7fffffff;
  21001. char* intData = static_cast <char*> (dest);
  21002. if (dest != (void*) source || destBytesPerSample <= 4)
  21003. {
  21004. for (int i = 0; i < numSamples; ++i)
  21005. {
  21006. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21007. intData += destBytesPerSample;
  21008. }
  21009. }
  21010. else
  21011. {
  21012. intData += destBytesPerSample * numSamples;
  21013. for (int i = numSamples; --i >= 0;)
  21014. {
  21015. intData -= destBytesPerSample;
  21016. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21017. }
  21018. }
  21019. }
  21020. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21021. {
  21022. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21023. char* d = static_cast <char*> (dest);
  21024. for (int i = 0; i < numSamples; ++i)
  21025. {
  21026. *(float*) d = source[i];
  21027. #if JUCE_BIG_ENDIAN
  21028. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21029. #endif
  21030. d += destBytesPerSample;
  21031. }
  21032. }
  21033. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21034. {
  21035. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21036. char* d = static_cast <char*> (dest);
  21037. for (int i = 0; i < numSamples; ++i)
  21038. {
  21039. *(float*) d = source[i];
  21040. #if JUCE_LITTLE_ENDIAN
  21041. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21042. #endif
  21043. d += destBytesPerSample;
  21044. }
  21045. }
  21046. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21047. {
  21048. const float scale = 1.0f / 0x7fff;
  21049. const char* intData = static_cast <const char*> (source);
  21050. if (source != (void*) dest || srcBytesPerSample >= 4)
  21051. {
  21052. for (int i = 0; i < numSamples; ++i)
  21053. {
  21054. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21055. intData += srcBytesPerSample;
  21056. }
  21057. }
  21058. else
  21059. {
  21060. intData += srcBytesPerSample * numSamples;
  21061. for (int i = numSamples; --i >= 0;)
  21062. {
  21063. intData -= srcBytesPerSample;
  21064. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21065. }
  21066. }
  21067. }
  21068. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21069. {
  21070. const float scale = 1.0f / 0x7fff;
  21071. const char* intData = static_cast <const char*> (source);
  21072. if (source != (void*) dest || srcBytesPerSample >= 4)
  21073. {
  21074. for (int i = 0; i < numSamples; ++i)
  21075. {
  21076. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21077. intData += srcBytesPerSample;
  21078. }
  21079. }
  21080. else
  21081. {
  21082. intData += srcBytesPerSample * numSamples;
  21083. for (int i = numSamples; --i >= 0;)
  21084. {
  21085. intData -= srcBytesPerSample;
  21086. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21087. }
  21088. }
  21089. }
  21090. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21091. {
  21092. const float scale = 1.0f / 0x7fffff;
  21093. const char* intData = static_cast <const char*> (source);
  21094. if (source != (void*) dest || srcBytesPerSample >= 4)
  21095. {
  21096. for (int i = 0; i < numSamples; ++i)
  21097. {
  21098. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21099. intData += srcBytesPerSample;
  21100. }
  21101. }
  21102. else
  21103. {
  21104. intData += srcBytesPerSample * numSamples;
  21105. for (int i = numSamples; --i >= 0;)
  21106. {
  21107. intData -= srcBytesPerSample;
  21108. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21109. }
  21110. }
  21111. }
  21112. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21113. {
  21114. const float scale = 1.0f / 0x7fffff;
  21115. const char* intData = static_cast <const char*> (source);
  21116. if (source != (void*) dest || srcBytesPerSample >= 4)
  21117. {
  21118. for (int i = 0; i < numSamples; ++i)
  21119. {
  21120. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21121. intData += srcBytesPerSample;
  21122. }
  21123. }
  21124. else
  21125. {
  21126. intData += srcBytesPerSample * numSamples;
  21127. for (int i = numSamples; --i >= 0;)
  21128. {
  21129. intData -= srcBytesPerSample;
  21130. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21131. }
  21132. }
  21133. }
  21134. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21135. {
  21136. const float scale = 1.0f / 0x7fffffff;
  21137. const char* intData = static_cast <const char*> (source);
  21138. if (source != (void*) dest || srcBytesPerSample >= 4)
  21139. {
  21140. for (int i = 0; i < numSamples; ++i)
  21141. {
  21142. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21143. intData += srcBytesPerSample;
  21144. }
  21145. }
  21146. else
  21147. {
  21148. intData += srcBytesPerSample * numSamples;
  21149. for (int i = numSamples; --i >= 0;)
  21150. {
  21151. intData -= srcBytesPerSample;
  21152. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21153. }
  21154. }
  21155. }
  21156. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21157. {
  21158. const float scale = 1.0f / 0x7fffffff;
  21159. const char* intData = static_cast <const char*> (source);
  21160. if (source != (void*) dest || srcBytesPerSample >= 4)
  21161. {
  21162. for (int i = 0; i < numSamples; ++i)
  21163. {
  21164. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21165. intData += srcBytesPerSample;
  21166. }
  21167. }
  21168. else
  21169. {
  21170. intData += srcBytesPerSample * numSamples;
  21171. for (int i = numSamples; --i >= 0;)
  21172. {
  21173. intData -= srcBytesPerSample;
  21174. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21175. }
  21176. }
  21177. }
  21178. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21179. {
  21180. const char* s = static_cast <const char*> (source);
  21181. for (int i = 0; i < numSamples; ++i)
  21182. {
  21183. dest[i] = *(float*)s;
  21184. #if JUCE_BIG_ENDIAN
  21185. uint32* const d = (uint32*) (dest + i);
  21186. *d = ByteOrder::swap (*d);
  21187. #endif
  21188. s += srcBytesPerSample;
  21189. }
  21190. }
  21191. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21192. {
  21193. const char* s = static_cast <const char*> (source);
  21194. for (int i = 0; i < numSamples; ++i)
  21195. {
  21196. dest[i] = *(float*)s;
  21197. #if JUCE_LITTLE_ENDIAN
  21198. uint32* const d = (uint32*) (dest + i);
  21199. *d = ByteOrder::swap (*d);
  21200. #endif
  21201. s += srcBytesPerSample;
  21202. }
  21203. }
  21204. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21205. const float* const source,
  21206. void* const dest,
  21207. const int numSamples)
  21208. {
  21209. switch (destFormat)
  21210. {
  21211. case int16LE:
  21212. convertFloatToInt16LE (source, dest, numSamples);
  21213. break;
  21214. case int16BE:
  21215. convertFloatToInt16BE (source, dest, numSamples);
  21216. break;
  21217. case int24LE:
  21218. convertFloatToInt24LE (source, dest, numSamples);
  21219. break;
  21220. case int24BE:
  21221. convertFloatToInt24BE (source, dest, numSamples);
  21222. break;
  21223. case int32LE:
  21224. convertFloatToInt32LE (source, dest, numSamples);
  21225. break;
  21226. case int32BE:
  21227. convertFloatToInt32BE (source, dest, numSamples);
  21228. break;
  21229. case float32LE:
  21230. convertFloatToFloat32LE (source, dest, numSamples);
  21231. break;
  21232. case float32BE:
  21233. convertFloatToFloat32BE (source, dest, numSamples);
  21234. break;
  21235. default:
  21236. jassertfalse;
  21237. break;
  21238. }
  21239. }
  21240. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21241. const void* const source,
  21242. float* const dest,
  21243. const int numSamples)
  21244. {
  21245. switch (sourceFormat)
  21246. {
  21247. case int16LE:
  21248. convertInt16LEToFloat (source, dest, numSamples);
  21249. break;
  21250. case int16BE:
  21251. convertInt16BEToFloat (source, dest, numSamples);
  21252. break;
  21253. case int24LE:
  21254. convertInt24LEToFloat (source, dest, numSamples);
  21255. break;
  21256. case int24BE:
  21257. convertInt24BEToFloat (source, dest, numSamples);
  21258. break;
  21259. case int32LE:
  21260. convertInt32LEToFloat (source, dest, numSamples);
  21261. break;
  21262. case int32BE:
  21263. convertInt32BEToFloat (source, dest, numSamples);
  21264. break;
  21265. case float32LE:
  21266. convertFloat32LEToFloat (source, dest, numSamples);
  21267. break;
  21268. case float32BE:
  21269. convertFloat32BEToFloat (source, dest, numSamples);
  21270. break;
  21271. default:
  21272. jassertfalse;
  21273. break;
  21274. }
  21275. }
  21276. void AudioDataConverters::interleaveSamples (const float** const source,
  21277. float* const dest,
  21278. const int numSamples,
  21279. const int numChannels)
  21280. {
  21281. for (int chan = 0; chan < numChannels; ++chan)
  21282. {
  21283. int i = chan;
  21284. const float* src = source [chan];
  21285. for (int j = 0; j < numSamples; ++j)
  21286. {
  21287. dest [i] = src [j];
  21288. i += numChannels;
  21289. }
  21290. }
  21291. }
  21292. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21293. float** const dest,
  21294. const int numSamples,
  21295. const int numChannels)
  21296. {
  21297. for (int chan = 0; chan < numChannels; ++chan)
  21298. {
  21299. int i = chan;
  21300. float* dst = dest [chan];
  21301. for (int j = 0; j < numSamples; ++j)
  21302. {
  21303. dst [j] = source [i];
  21304. i += numChannels;
  21305. }
  21306. }
  21307. }
  21308. #if JUCE_UNIT_TESTS
  21309. class AudioConversionTests : public UnitTest
  21310. {
  21311. public:
  21312. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21313. template <class F1, class E1, class F2, class E2>
  21314. struct Test5
  21315. {
  21316. static void test (UnitTest& unitTest)
  21317. {
  21318. test (unitTest, false);
  21319. test (unitTest, true);
  21320. }
  21321. static void test (UnitTest& unitTest, bool inPlace)
  21322. {
  21323. const int numSamples = 2048;
  21324. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21325. {
  21326. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21327. bool clippingFailed = false;
  21328. for (int i = 0; i < numSamples / 2; ++i)
  21329. {
  21330. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21331. if (! d.isFloatingPoint())
  21332. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21333. ++d;
  21334. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21335. ++d;
  21336. }
  21337. unitTest.expect (! clippingFailed);
  21338. }
  21339. // convert data from the source to dest format..
  21340. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21341. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21342. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21343. // ..and back again..
  21344. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21345. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21346. if (! inPlace)
  21347. zerostruct (reversed);
  21348. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21349. {
  21350. int biggestDiff = 0;
  21351. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21352. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21353. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21354. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21355. for (int i = 0; i < numSamples; ++i)
  21356. {
  21357. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21358. ++d1;
  21359. ++d2;
  21360. }
  21361. unitTest.expect (biggestDiff <= errorMargin);
  21362. }
  21363. }
  21364. };
  21365. template <class F1, class E1, class FormatType>
  21366. struct Test3
  21367. {
  21368. static void test (UnitTest& unitTest)
  21369. {
  21370. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21371. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21372. }
  21373. };
  21374. template <class FormatType, class Endianness>
  21375. struct Test2
  21376. {
  21377. static void test (UnitTest& unitTest)
  21378. {
  21379. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21380. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21381. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21382. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21383. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21384. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21385. }
  21386. };
  21387. template <class FormatType>
  21388. struct Test1
  21389. {
  21390. static void test (UnitTest& unitTest)
  21391. {
  21392. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21393. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21394. }
  21395. };
  21396. void runTest()
  21397. {
  21398. beginTest ("Round-trip conversion");
  21399. Test1 <AudioData::Int8>::test (*this);
  21400. Test1 <AudioData::Int16>::test (*this);
  21401. Test1 <AudioData::Int24>::test (*this);
  21402. Test1 <AudioData::Int32>::test (*this);
  21403. Test1 <AudioData::Float32>::test (*this);
  21404. }
  21405. };
  21406. static AudioConversionTests audioConversionUnitTests;
  21407. #endif
  21408. END_JUCE_NAMESPACE
  21409. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21410. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21411. BEGIN_JUCE_NAMESPACE
  21412. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21413. const int numSamples) throw()
  21414. : numChannels (numChannels_),
  21415. size (numSamples)
  21416. {
  21417. jassert (numSamples >= 0);
  21418. jassert (numChannels_ > 0);
  21419. allocateData();
  21420. }
  21421. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21422. : numChannels (other.numChannels),
  21423. size (other.size)
  21424. {
  21425. allocateData();
  21426. const size_t numBytes = size * sizeof (float);
  21427. for (int i = 0; i < numChannels; ++i)
  21428. memcpy (channels[i], other.channels[i], numBytes);
  21429. }
  21430. void AudioSampleBuffer::allocateData()
  21431. {
  21432. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21433. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21434. allocatedData.malloc (allocatedBytes);
  21435. channels = reinterpret_cast <float**> (allocatedData.getData());
  21436. float* chan = (float*) (allocatedData + channelListSize);
  21437. for (int i = 0; i < numChannels; ++i)
  21438. {
  21439. channels[i] = chan;
  21440. chan += size;
  21441. }
  21442. channels [numChannels] = 0;
  21443. }
  21444. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21445. const int numChannels_,
  21446. const int numSamples) throw()
  21447. : numChannels (numChannels_),
  21448. size (numSamples),
  21449. allocatedBytes (0)
  21450. {
  21451. jassert (numChannels_ > 0);
  21452. allocateChannels (dataToReferTo);
  21453. }
  21454. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21455. const int newNumChannels,
  21456. const int newNumSamples) throw()
  21457. {
  21458. jassert (newNumChannels > 0);
  21459. allocatedBytes = 0;
  21460. allocatedData.free();
  21461. numChannels = newNumChannels;
  21462. size = newNumSamples;
  21463. allocateChannels (dataToReferTo);
  21464. }
  21465. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21466. {
  21467. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21468. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21469. {
  21470. channels = static_cast <float**> (preallocatedChannelSpace);
  21471. }
  21472. else
  21473. {
  21474. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21475. channels = reinterpret_cast <float**> (allocatedData.getData());
  21476. }
  21477. for (int i = 0; i < numChannels; ++i)
  21478. {
  21479. // you have to pass in the same number of valid pointers as numChannels
  21480. jassert (dataToReferTo[i] != 0);
  21481. channels[i] = dataToReferTo[i];
  21482. }
  21483. channels [numChannels] = 0;
  21484. }
  21485. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21486. {
  21487. if (this != &other)
  21488. {
  21489. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21490. const size_t numBytes = size * sizeof (float);
  21491. for (int i = 0; i < numChannels; ++i)
  21492. memcpy (channels[i], other.channels[i], numBytes);
  21493. }
  21494. return *this;
  21495. }
  21496. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21497. {
  21498. }
  21499. void AudioSampleBuffer::setSize (const int newNumChannels,
  21500. const int newNumSamples,
  21501. const bool keepExistingContent,
  21502. const bool clearExtraSpace,
  21503. const bool avoidReallocating) throw()
  21504. {
  21505. jassert (newNumChannels > 0);
  21506. if (newNumSamples != size || newNumChannels != numChannels)
  21507. {
  21508. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21509. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21510. if (keepExistingContent)
  21511. {
  21512. HeapBlock <char> newData;
  21513. newData.allocate (newTotalBytes, clearExtraSpace);
  21514. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21515. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21516. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21517. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21518. for (int i = 0; i < numChansToCopy; ++i)
  21519. {
  21520. memcpy (newChan, channels[i], numBytesToCopy);
  21521. newChannels[i] = newChan;
  21522. newChan += newNumSamples;
  21523. }
  21524. allocatedData.swapWith (newData);
  21525. allocatedBytes = (int) newTotalBytes;
  21526. channels = newChannels;
  21527. }
  21528. else
  21529. {
  21530. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21531. {
  21532. if (clearExtraSpace)
  21533. zeromem (allocatedData, newTotalBytes);
  21534. }
  21535. else
  21536. {
  21537. allocatedBytes = newTotalBytes;
  21538. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21539. channels = reinterpret_cast <float**> (allocatedData.getData());
  21540. }
  21541. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21542. for (int i = 0; i < newNumChannels; ++i)
  21543. {
  21544. channels[i] = chan;
  21545. chan += newNumSamples;
  21546. }
  21547. }
  21548. channels [newNumChannels] = 0;
  21549. size = newNumSamples;
  21550. numChannels = newNumChannels;
  21551. }
  21552. }
  21553. void AudioSampleBuffer::clear() throw()
  21554. {
  21555. for (int i = 0; i < numChannels; ++i)
  21556. zeromem (channels[i], size * sizeof (float));
  21557. }
  21558. void AudioSampleBuffer::clear (const int startSample,
  21559. const int numSamples) throw()
  21560. {
  21561. jassert (startSample >= 0 && startSample + numSamples <= size);
  21562. for (int i = 0; i < numChannels; ++i)
  21563. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21564. }
  21565. void AudioSampleBuffer::clear (const int channel,
  21566. const int startSample,
  21567. const int numSamples) throw()
  21568. {
  21569. jassert (isPositiveAndBelow (channel, numChannels));
  21570. jassert (startSample >= 0 && startSample + numSamples <= size);
  21571. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21572. }
  21573. void AudioSampleBuffer::applyGain (const int channel,
  21574. const int startSample,
  21575. int numSamples,
  21576. const float gain) throw()
  21577. {
  21578. jassert (isPositiveAndBelow (channel, numChannels));
  21579. jassert (startSample >= 0 && startSample + numSamples <= size);
  21580. if (gain != 1.0f)
  21581. {
  21582. float* d = channels [channel] + startSample;
  21583. if (gain == 0.0f)
  21584. {
  21585. zeromem (d, sizeof (float) * numSamples);
  21586. }
  21587. else
  21588. {
  21589. while (--numSamples >= 0)
  21590. *d++ *= gain;
  21591. }
  21592. }
  21593. }
  21594. void AudioSampleBuffer::applyGainRamp (const int channel,
  21595. const int startSample,
  21596. int numSamples,
  21597. float startGain,
  21598. float endGain) throw()
  21599. {
  21600. if (startGain == endGain)
  21601. {
  21602. applyGain (channel, startSample, numSamples, startGain);
  21603. }
  21604. else
  21605. {
  21606. jassert (isPositiveAndBelow (channel, numChannels));
  21607. jassert (startSample >= 0 && startSample + numSamples <= size);
  21608. const float increment = (endGain - startGain) / numSamples;
  21609. float* d = channels [channel] + startSample;
  21610. while (--numSamples >= 0)
  21611. {
  21612. *d++ *= startGain;
  21613. startGain += increment;
  21614. }
  21615. }
  21616. }
  21617. void AudioSampleBuffer::applyGain (const int startSample,
  21618. const int numSamples,
  21619. const float gain) throw()
  21620. {
  21621. for (int i = 0; i < numChannels; ++i)
  21622. applyGain (i, startSample, numSamples, gain);
  21623. }
  21624. void AudioSampleBuffer::addFrom (const int destChannel,
  21625. const int destStartSample,
  21626. const AudioSampleBuffer& source,
  21627. const int sourceChannel,
  21628. const int sourceStartSample,
  21629. int numSamples,
  21630. const float gain) throw()
  21631. {
  21632. jassert (&source != this || sourceChannel != destChannel);
  21633. jassert (isPositiveAndBelow (destChannel, numChannels));
  21634. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21635. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21636. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21637. if (gain != 0.0f && numSamples > 0)
  21638. {
  21639. float* d = channels [destChannel] + destStartSample;
  21640. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21641. if (gain != 1.0f)
  21642. {
  21643. while (--numSamples >= 0)
  21644. *d++ += gain * *s++;
  21645. }
  21646. else
  21647. {
  21648. while (--numSamples >= 0)
  21649. *d++ += *s++;
  21650. }
  21651. }
  21652. }
  21653. void AudioSampleBuffer::addFrom (const int destChannel,
  21654. const int destStartSample,
  21655. const float* source,
  21656. int numSamples,
  21657. const float gain) throw()
  21658. {
  21659. jassert (isPositiveAndBelow (destChannel, numChannels));
  21660. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21661. jassert (source != 0);
  21662. if (gain != 0.0f && numSamples > 0)
  21663. {
  21664. float* d = channels [destChannel] + destStartSample;
  21665. if (gain != 1.0f)
  21666. {
  21667. while (--numSamples >= 0)
  21668. *d++ += gain * *source++;
  21669. }
  21670. else
  21671. {
  21672. while (--numSamples >= 0)
  21673. *d++ += *source++;
  21674. }
  21675. }
  21676. }
  21677. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21678. const int destStartSample,
  21679. const float* source,
  21680. int numSamples,
  21681. float startGain,
  21682. const float endGain) throw()
  21683. {
  21684. jassert (isPositiveAndBelow (destChannel, numChannels));
  21685. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21686. jassert (source != 0);
  21687. if (startGain == endGain)
  21688. {
  21689. addFrom (destChannel,
  21690. destStartSample,
  21691. source,
  21692. numSamples,
  21693. startGain);
  21694. }
  21695. else
  21696. {
  21697. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21698. {
  21699. const float increment = (endGain - startGain) / numSamples;
  21700. float* d = channels [destChannel] + destStartSample;
  21701. while (--numSamples >= 0)
  21702. {
  21703. *d++ += startGain * *source++;
  21704. startGain += increment;
  21705. }
  21706. }
  21707. }
  21708. }
  21709. void AudioSampleBuffer::copyFrom (const int destChannel,
  21710. const int destStartSample,
  21711. const AudioSampleBuffer& source,
  21712. const int sourceChannel,
  21713. const int sourceStartSample,
  21714. int numSamples) throw()
  21715. {
  21716. jassert (&source != this || sourceChannel != destChannel);
  21717. jassert (isPositiveAndBelow (destChannel, numChannels));
  21718. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21719. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21720. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21721. if (numSamples > 0)
  21722. {
  21723. memcpy (channels [destChannel] + destStartSample,
  21724. source.channels [sourceChannel] + sourceStartSample,
  21725. sizeof (float) * numSamples);
  21726. }
  21727. }
  21728. void AudioSampleBuffer::copyFrom (const int destChannel,
  21729. const int destStartSample,
  21730. const float* source,
  21731. int numSamples) throw()
  21732. {
  21733. jassert (isPositiveAndBelow (destChannel, numChannels));
  21734. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21735. jassert (source != 0);
  21736. if (numSamples > 0)
  21737. {
  21738. memcpy (channels [destChannel] + destStartSample,
  21739. source,
  21740. sizeof (float) * numSamples);
  21741. }
  21742. }
  21743. void AudioSampleBuffer::copyFrom (const int destChannel,
  21744. const int destStartSample,
  21745. const float* source,
  21746. int numSamples,
  21747. const float gain) throw()
  21748. {
  21749. jassert (isPositiveAndBelow (destChannel, numChannels));
  21750. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21751. jassert (source != 0);
  21752. if (numSamples > 0)
  21753. {
  21754. float* d = channels [destChannel] + destStartSample;
  21755. if (gain != 1.0f)
  21756. {
  21757. if (gain == 0)
  21758. {
  21759. zeromem (d, sizeof (float) * numSamples);
  21760. }
  21761. else
  21762. {
  21763. while (--numSamples >= 0)
  21764. *d++ = gain * *source++;
  21765. }
  21766. }
  21767. else
  21768. {
  21769. memcpy (d, source, sizeof (float) * numSamples);
  21770. }
  21771. }
  21772. }
  21773. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21774. const int destStartSample,
  21775. const float* source,
  21776. int numSamples,
  21777. float startGain,
  21778. float endGain) throw()
  21779. {
  21780. jassert (isPositiveAndBelow (destChannel, numChannels));
  21781. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21782. jassert (source != 0);
  21783. if (startGain == endGain)
  21784. {
  21785. copyFrom (destChannel,
  21786. destStartSample,
  21787. source,
  21788. numSamples,
  21789. startGain);
  21790. }
  21791. else
  21792. {
  21793. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21794. {
  21795. const float increment = (endGain - startGain) / numSamples;
  21796. float* d = channels [destChannel] + destStartSample;
  21797. while (--numSamples >= 0)
  21798. {
  21799. *d++ = startGain * *source++;
  21800. startGain += increment;
  21801. }
  21802. }
  21803. }
  21804. }
  21805. void AudioSampleBuffer::findMinMax (const int channel,
  21806. const int startSample,
  21807. int numSamples,
  21808. float& minVal,
  21809. float& maxVal) const throw()
  21810. {
  21811. jassert (isPositiveAndBelow (channel, numChannels));
  21812. jassert (startSample >= 0 && startSample + numSamples <= size);
  21813. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21814. }
  21815. float AudioSampleBuffer::getMagnitude (const int channel,
  21816. const int startSample,
  21817. const int numSamples) const throw()
  21818. {
  21819. jassert (isPositiveAndBelow (channel, numChannels));
  21820. jassert (startSample >= 0 && startSample + numSamples <= size);
  21821. float mn, mx;
  21822. findMinMax (channel, startSample, numSamples, mn, mx);
  21823. return jmax (mn, -mn, mx, -mx);
  21824. }
  21825. float AudioSampleBuffer::getMagnitude (const int startSample,
  21826. const int numSamples) const throw()
  21827. {
  21828. float mag = 0.0f;
  21829. for (int i = 0; i < numChannels; ++i)
  21830. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21831. return mag;
  21832. }
  21833. float AudioSampleBuffer::getRMSLevel (const int channel,
  21834. const int startSample,
  21835. const int numSamples) const throw()
  21836. {
  21837. jassert (isPositiveAndBelow (channel, numChannels));
  21838. jassert (startSample >= 0 && startSample + numSamples <= size);
  21839. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21840. return 0.0f;
  21841. const float* const data = channels [channel] + startSample;
  21842. double sum = 0.0;
  21843. for (int i = 0; i < numSamples; ++i)
  21844. {
  21845. const float sample = data [i];
  21846. sum += sample * sample;
  21847. }
  21848. return (float) std::sqrt (sum / numSamples);
  21849. }
  21850. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21851. const int startSample,
  21852. const int numSamples,
  21853. const int64 readerStartSample,
  21854. const bool useLeftChan,
  21855. const bool useRightChan)
  21856. {
  21857. jassert (reader != 0);
  21858. jassert (startSample >= 0 && startSample + numSamples <= size);
  21859. if (numSamples > 0)
  21860. {
  21861. int* chans[3];
  21862. if (useLeftChan == useRightChan)
  21863. {
  21864. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21865. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  21866. }
  21867. else if (useLeftChan || (reader->numChannels == 1))
  21868. {
  21869. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21870. chans[1] = 0;
  21871. }
  21872. else if (useRightChan)
  21873. {
  21874. chans[0] = 0;
  21875. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21876. }
  21877. chans[2] = 0;
  21878. reader->read (chans, 2, readerStartSample, numSamples, true);
  21879. if (! reader->usesFloatingPointData)
  21880. {
  21881. for (int j = 0; j < 2; ++j)
  21882. {
  21883. float* const d = reinterpret_cast <float*> (chans[j]);
  21884. if (d != 0)
  21885. {
  21886. const float multiplier = 1.0f / 0x7fffffff;
  21887. for (int i = 0; i < numSamples; ++i)
  21888. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  21889. }
  21890. }
  21891. }
  21892. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21893. {
  21894. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21895. memcpy (getSampleData (1, startSample),
  21896. getSampleData (0, startSample),
  21897. sizeof (float) * numSamples);
  21898. }
  21899. }
  21900. }
  21901. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21902. const int startSample,
  21903. const int numSamples) const
  21904. {
  21905. jassert (writer != 0);
  21906. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  21907. }
  21908. END_JUCE_NAMESPACE
  21909. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21910. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21911. BEGIN_JUCE_NAMESPACE
  21912. IIRFilter::IIRFilter()
  21913. : active (false)
  21914. {
  21915. reset();
  21916. }
  21917. IIRFilter::IIRFilter (const IIRFilter& other)
  21918. : active (other.active)
  21919. {
  21920. const ScopedLock sl (other.processLock);
  21921. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21922. reset();
  21923. }
  21924. IIRFilter::~IIRFilter()
  21925. {
  21926. }
  21927. void IIRFilter::reset() throw()
  21928. {
  21929. const ScopedLock sl (processLock);
  21930. x1 = 0;
  21931. x2 = 0;
  21932. y1 = 0;
  21933. y2 = 0;
  21934. }
  21935. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21936. {
  21937. float out = coefficients[0] * in
  21938. + coefficients[1] * x1
  21939. + coefficients[2] * x2
  21940. - coefficients[4] * y1
  21941. - coefficients[5] * y2;
  21942. #if JUCE_INTEL
  21943. if (! (out < -1.0e-8 || out > 1.0e-8))
  21944. out = 0;
  21945. #endif
  21946. x2 = x1;
  21947. x1 = in;
  21948. y2 = y1;
  21949. y1 = out;
  21950. return out;
  21951. }
  21952. void IIRFilter::processSamples (float* const samples,
  21953. const int numSamples) throw()
  21954. {
  21955. const ScopedLock sl (processLock);
  21956. if (active)
  21957. {
  21958. for (int i = 0; i < numSamples; ++i)
  21959. {
  21960. const float in = samples[i];
  21961. float out = coefficients[0] * in
  21962. + coefficients[1] * x1
  21963. + coefficients[2] * x2
  21964. - coefficients[4] * y1
  21965. - coefficients[5] * y2;
  21966. #if JUCE_INTEL
  21967. if (! (out < -1.0e-8 || out > 1.0e-8))
  21968. out = 0;
  21969. #endif
  21970. x2 = x1;
  21971. x1 = in;
  21972. y2 = y1;
  21973. y1 = out;
  21974. samples[i] = out;
  21975. }
  21976. }
  21977. }
  21978. void IIRFilter::makeLowPass (const double sampleRate,
  21979. const double frequency) throw()
  21980. {
  21981. jassert (sampleRate > 0);
  21982. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21983. const double nSquared = n * n;
  21984. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21985. setCoefficients (c1,
  21986. c1 * 2.0f,
  21987. c1,
  21988. 1.0,
  21989. c1 * 2.0 * (1.0 - nSquared),
  21990. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21991. }
  21992. void IIRFilter::makeHighPass (const double sampleRate,
  21993. const double frequency) throw()
  21994. {
  21995. const double n = tan (double_Pi * frequency / sampleRate);
  21996. const double nSquared = n * n;
  21997. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21998. setCoefficients (c1,
  21999. c1 * -2.0f,
  22000. c1,
  22001. 1.0,
  22002. c1 * 2.0 * (nSquared - 1.0),
  22003. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22004. }
  22005. void IIRFilter::makeLowShelf (const double sampleRate,
  22006. const double cutOffFrequency,
  22007. const double Q,
  22008. const float gainFactor) throw()
  22009. {
  22010. jassert (sampleRate > 0);
  22011. jassert (Q > 0);
  22012. const double A = jmax (0.0f, gainFactor);
  22013. const double aminus1 = A - 1.0;
  22014. const double aplus1 = A + 1.0;
  22015. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22016. const double coso = std::cos (omega);
  22017. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22018. const double aminus1TimesCoso = aminus1 * coso;
  22019. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22020. A * 2.0 * (aminus1 - aplus1 * coso),
  22021. A * (aplus1 - aminus1TimesCoso - beta),
  22022. aplus1 + aminus1TimesCoso + beta,
  22023. -2.0 * (aminus1 + aplus1 * coso),
  22024. aplus1 + aminus1TimesCoso - beta);
  22025. }
  22026. void IIRFilter::makeHighShelf (const double sampleRate,
  22027. const double cutOffFrequency,
  22028. const double Q,
  22029. const float gainFactor) throw()
  22030. {
  22031. jassert (sampleRate > 0);
  22032. jassert (Q > 0);
  22033. const double A = jmax (0.0f, gainFactor);
  22034. const double aminus1 = A - 1.0;
  22035. const double aplus1 = A + 1.0;
  22036. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22037. const double coso = std::cos (omega);
  22038. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22039. const double aminus1TimesCoso = aminus1 * coso;
  22040. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22041. A * -2.0 * (aminus1 + aplus1 * coso),
  22042. A * (aplus1 + aminus1TimesCoso - beta),
  22043. aplus1 - aminus1TimesCoso + beta,
  22044. 2.0 * (aminus1 - aplus1 * coso),
  22045. aplus1 - aminus1TimesCoso - beta);
  22046. }
  22047. void IIRFilter::makeBandPass (const double sampleRate,
  22048. const double centreFrequency,
  22049. const double Q,
  22050. const float gainFactor) throw()
  22051. {
  22052. jassert (sampleRate > 0);
  22053. jassert (Q > 0);
  22054. const double A = jmax (0.0f, gainFactor);
  22055. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22056. const double alpha = 0.5 * std::sin (omega) / Q;
  22057. const double c2 = -2.0 * std::cos (omega);
  22058. const double alphaTimesA = alpha * A;
  22059. const double alphaOverA = alpha / A;
  22060. setCoefficients (1.0 + alphaTimesA,
  22061. c2,
  22062. 1.0 - alphaTimesA,
  22063. 1.0 + alphaOverA,
  22064. c2,
  22065. 1.0 - alphaOverA);
  22066. }
  22067. void IIRFilter::makeInactive() throw()
  22068. {
  22069. const ScopedLock sl (processLock);
  22070. active = false;
  22071. }
  22072. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22073. {
  22074. const ScopedLock sl (processLock);
  22075. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22076. active = other.active;
  22077. }
  22078. void IIRFilter::setCoefficients (double c1,
  22079. double c2,
  22080. double c3,
  22081. double c4,
  22082. double c5,
  22083. double c6) throw()
  22084. {
  22085. const double a = 1.0 / c4;
  22086. c1 *= a;
  22087. c2 *= a;
  22088. c3 *= a;
  22089. c5 *= a;
  22090. c6 *= a;
  22091. const ScopedLock sl (processLock);
  22092. coefficients[0] = (float) c1;
  22093. coefficients[1] = (float) c2;
  22094. coefficients[2] = (float) c3;
  22095. coefficients[3] = (float) c4;
  22096. coefficients[4] = (float) c5;
  22097. coefficients[5] = (float) c6;
  22098. active = true;
  22099. }
  22100. END_JUCE_NAMESPACE
  22101. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22102. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22103. BEGIN_JUCE_NAMESPACE
  22104. MidiBuffer::MidiBuffer() throw()
  22105. : bytesUsed (0)
  22106. {
  22107. }
  22108. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22109. : bytesUsed (0)
  22110. {
  22111. addEvent (message, 0);
  22112. }
  22113. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22114. : data (other.data),
  22115. bytesUsed (other.bytesUsed)
  22116. {
  22117. }
  22118. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22119. {
  22120. bytesUsed = other.bytesUsed;
  22121. data = other.data;
  22122. return *this;
  22123. }
  22124. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22125. {
  22126. data.swapWith (other.data);
  22127. swapVariables <int> (bytesUsed, other.bytesUsed);
  22128. }
  22129. MidiBuffer::~MidiBuffer()
  22130. {
  22131. }
  22132. inline uint8* MidiBuffer::getData() const throw()
  22133. {
  22134. return static_cast <uint8*> (data.getData());
  22135. }
  22136. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22137. {
  22138. return *static_cast <const int*> (d);
  22139. }
  22140. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22141. {
  22142. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22143. }
  22144. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22145. {
  22146. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22147. }
  22148. void MidiBuffer::clear() throw()
  22149. {
  22150. bytesUsed = 0;
  22151. }
  22152. void MidiBuffer::clear (const int startSample, const int numSamples)
  22153. {
  22154. uint8* const start = findEventAfter (getData(), startSample - 1);
  22155. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22156. if (end > start)
  22157. {
  22158. const int bytesToMove = bytesUsed - (int) (end - getData());
  22159. if (bytesToMove > 0)
  22160. memmove (start, end, bytesToMove);
  22161. bytesUsed -= (int) (end - start);
  22162. }
  22163. }
  22164. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22165. {
  22166. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22167. }
  22168. namespace MidiBufferHelpers
  22169. {
  22170. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22171. {
  22172. unsigned int byte = (unsigned int) *data;
  22173. int size = 0;
  22174. if (byte == 0xf0 || byte == 0xf7)
  22175. {
  22176. const uint8* d = data + 1;
  22177. while (d < data + maxBytes)
  22178. if (*d++ == 0xf7)
  22179. break;
  22180. size = (int) (d - data);
  22181. }
  22182. else if (byte == 0xff)
  22183. {
  22184. int n;
  22185. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22186. size = jmin (maxBytes, n + 2 + bytesLeft);
  22187. }
  22188. else if (byte >= 0x80)
  22189. {
  22190. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22191. }
  22192. return size;
  22193. }
  22194. }
  22195. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22196. {
  22197. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22198. if (numBytes > 0)
  22199. {
  22200. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22201. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22202. uint8* d = findEventAfter (getData(), sampleNumber);
  22203. const int bytesToMove = bytesUsed - (int) (d - getData());
  22204. if (bytesToMove > 0)
  22205. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22206. *reinterpret_cast <int*> (d) = sampleNumber;
  22207. d += sizeof (int);
  22208. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22209. d += sizeof (uint16);
  22210. memcpy (d, newData, numBytes);
  22211. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22212. }
  22213. }
  22214. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22215. const int startSample,
  22216. const int numSamples,
  22217. const int sampleDeltaToAdd)
  22218. {
  22219. Iterator i (otherBuffer);
  22220. i.setNextSamplePosition (startSample);
  22221. const uint8* eventData;
  22222. int eventSize, position;
  22223. while (i.getNextEvent (eventData, eventSize, position)
  22224. && (position < startSample + numSamples || numSamples < 0))
  22225. {
  22226. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22227. }
  22228. }
  22229. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22230. {
  22231. data.ensureSize (minimumNumBytes);
  22232. }
  22233. bool MidiBuffer::isEmpty() const throw()
  22234. {
  22235. return bytesUsed == 0;
  22236. }
  22237. int MidiBuffer::getNumEvents() const throw()
  22238. {
  22239. int n = 0;
  22240. const uint8* d = getData();
  22241. const uint8* const end = d + bytesUsed;
  22242. while (d < end)
  22243. {
  22244. d += getEventTotalSize (d);
  22245. ++n;
  22246. }
  22247. return n;
  22248. }
  22249. int MidiBuffer::getFirstEventTime() const throw()
  22250. {
  22251. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22252. }
  22253. int MidiBuffer::getLastEventTime() const throw()
  22254. {
  22255. if (bytesUsed == 0)
  22256. return 0;
  22257. const uint8* d = getData();
  22258. const uint8* const endData = d + bytesUsed;
  22259. for (;;)
  22260. {
  22261. const uint8* const nextOne = d + getEventTotalSize (d);
  22262. if (nextOne >= endData)
  22263. return getEventTime (d);
  22264. d = nextOne;
  22265. }
  22266. }
  22267. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22268. {
  22269. const uint8* const endData = getData() + bytesUsed;
  22270. while (d < endData && getEventTime (d) <= samplePosition)
  22271. d += getEventTotalSize (d);
  22272. return d;
  22273. }
  22274. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22275. : buffer (buffer_),
  22276. data (buffer_.getData())
  22277. {
  22278. }
  22279. MidiBuffer::Iterator::~Iterator() throw()
  22280. {
  22281. }
  22282. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22283. {
  22284. data = buffer.getData();
  22285. const uint8* dataEnd = data + buffer.bytesUsed;
  22286. while (data < dataEnd && getEventTime (data) < samplePosition)
  22287. data += getEventTotalSize (data);
  22288. }
  22289. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22290. {
  22291. if (data >= buffer.getData() + buffer.bytesUsed)
  22292. return false;
  22293. samplePosition = getEventTime (data);
  22294. numBytes = getEventDataSize (data);
  22295. data += sizeof (int) + sizeof (uint16);
  22296. midiData = data;
  22297. data += numBytes;
  22298. return true;
  22299. }
  22300. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22301. {
  22302. if (data >= buffer.getData() + buffer.bytesUsed)
  22303. return false;
  22304. samplePosition = getEventTime (data);
  22305. const int numBytes = getEventDataSize (data);
  22306. data += sizeof (int) + sizeof (uint16);
  22307. result = MidiMessage (data, numBytes, samplePosition);
  22308. data += numBytes;
  22309. return true;
  22310. }
  22311. END_JUCE_NAMESPACE
  22312. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22313. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22314. BEGIN_JUCE_NAMESPACE
  22315. namespace MidiFileHelpers
  22316. {
  22317. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22318. {
  22319. unsigned int buffer = v & 0x7F;
  22320. while ((v >>= 7) != 0)
  22321. {
  22322. buffer <<= 8;
  22323. buffer |= ((v & 0x7F) | 0x80);
  22324. }
  22325. for (;;)
  22326. {
  22327. out.writeByte ((char) buffer);
  22328. if (buffer & 0x80)
  22329. buffer >>= 8;
  22330. else
  22331. break;
  22332. }
  22333. }
  22334. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22335. {
  22336. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22337. data += 4;
  22338. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22339. {
  22340. bool ok = false;
  22341. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22342. {
  22343. for (int i = 0; i < 8; ++i)
  22344. {
  22345. ch = ByteOrder::bigEndianInt (data);
  22346. data += 4;
  22347. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22348. {
  22349. ok = true;
  22350. break;
  22351. }
  22352. }
  22353. }
  22354. if (! ok)
  22355. return false;
  22356. }
  22357. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22358. data += 4;
  22359. fileType = (short) ByteOrder::bigEndianShort (data);
  22360. data += 2;
  22361. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22362. data += 2;
  22363. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22364. data += 2;
  22365. bytesRemaining -= 6;
  22366. data += bytesRemaining;
  22367. return true;
  22368. }
  22369. double convertTicksToSeconds (const double time,
  22370. const MidiMessageSequence& tempoEvents,
  22371. const int timeFormat)
  22372. {
  22373. if (timeFormat > 0)
  22374. {
  22375. int numer = 4, denom = 4;
  22376. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22377. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22378. double secsPerTick = 0.5 * tickLen;
  22379. const int numEvents = tempoEvents.getNumEvents();
  22380. for (int i = 0; i < numEvents; ++i)
  22381. {
  22382. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22383. if (time <= m.getTimeStamp())
  22384. break;
  22385. if (timeFormat > 0)
  22386. {
  22387. correctedTempoTime = correctedTempoTime
  22388. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22389. }
  22390. else
  22391. {
  22392. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22393. }
  22394. tempoTime = m.getTimeStamp();
  22395. if (m.isTempoMetaEvent())
  22396. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22397. else if (m.isTimeSignatureMetaEvent())
  22398. m.getTimeSignatureInfo (numer, denom);
  22399. while (i + 1 < numEvents)
  22400. {
  22401. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22402. if (m2.getTimeStamp() == tempoTime)
  22403. {
  22404. ++i;
  22405. if (m2.isTempoMetaEvent())
  22406. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22407. else if (m2.isTimeSignatureMetaEvent())
  22408. m2.getTimeSignatureInfo (numer, denom);
  22409. }
  22410. else
  22411. {
  22412. break;
  22413. }
  22414. }
  22415. }
  22416. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22417. }
  22418. else
  22419. {
  22420. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22421. }
  22422. }
  22423. // a comparator that puts all the note-offs before note-ons that have the same time
  22424. struct Sorter
  22425. {
  22426. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22427. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22428. {
  22429. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22430. if (diff == 0)
  22431. {
  22432. if (first->message.isNoteOff() && second->message.isNoteOn())
  22433. return -1;
  22434. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22435. return 1;
  22436. else
  22437. return 0;
  22438. }
  22439. else
  22440. {
  22441. return (diff > 0) ? 1 : -1;
  22442. }
  22443. }
  22444. };
  22445. }
  22446. MidiFile::MidiFile()
  22447. : timeFormat ((short) (unsigned short) 0xe728)
  22448. {
  22449. }
  22450. MidiFile::~MidiFile()
  22451. {
  22452. clear();
  22453. }
  22454. void MidiFile::clear()
  22455. {
  22456. tracks.clear();
  22457. }
  22458. int MidiFile::getNumTracks() const throw()
  22459. {
  22460. return tracks.size();
  22461. }
  22462. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22463. {
  22464. return tracks [index];
  22465. }
  22466. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22467. {
  22468. tracks.add (new MidiMessageSequence (trackSequence));
  22469. }
  22470. short MidiFile::getTimeFormat() const throw()
  22471. {
  22472. return timeFormat;
  22473. }
  22474. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22475. {
  22476. timeFormat = (short) ticks;
  22477. }
  22478. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22479. const int subframeResolution) throw()
  22480. {
  22481. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22482. }
  22483. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22484. {
  22485. for (int i = tracks.size(); --i >= 0;)
  22486. {
  22487. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22488. for (int j = 0; j < numEvents; ++j)
  22489. {
  22490. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22491. if (m.isTempoMetaEvent())
  22492. tempoChangeEvents.addEvent (m);
  22493. }
  22494. }
  22495. }
  22496. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22497. {
  22498. for (int i = tracks.size(); --i >= 0;)
  22499. {
  22500. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22501. for (int j = 0; j < numEvents; ++j)
  22502. {
  22503. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22504. if (m.isTimeSignatureMetaEvent())
  22505. timeSigEvents.addEvent (m);
  22506. }
  22507. }
  22508. }
  22509. double MidiFile::getLastTimestamp() const
  22510. {
  22511. double t = 0.0;
  22512. for (int i = tracks.size(); --i >= 0;)
  22513. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22514. return t;
  22515. }
  22516. bool MidiFile::readFrom (InputStream& sourceStream)
  22517. {
  22518. clear();
  22519. MemoryBlock data;
  22520. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22521. // (put a sanity-check on the file size, as midi files are generally small)
  22522. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22523. {
  22524. size_t size = data.getSize();
  22525. const uint8* d = static_cast <const uint8*> (data.getData());
  22526. short fileType, expectedTracks;
  22527. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22528. {
  22529. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22530. int track = 0;
  22531. while (size > 0 && track < expectedTracks)
  22532. {
  22533. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22534. d += 4;
  22535. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22536. d += 4;
  22537. if (chunkSize <= 0)
  22538. break;
  22539. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22540. {
  22541. readNextTrack (d, chunkSize);
  22542. }
  22543. size -= chunkSize + 8;
  22544. d += chunkSize;
  22545. ++track;
  22546. }
  22547. return true;
  22548. }
  22549. }
  22550. return false;
  22551. }
  22552. void MidiFile::readNextTrack (const uint8* data, int size)
  22553. {
  22554. double time = 0;
  22555. char lastStatusByte = 0;
  22556. MidiMessageSequence result;
  22557. while (size > 0)
  22558. {
  22559. int bytesUsed;
  22560. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22561. data += bytesUsed;
  22562. size -= bytesUsed;
  22563. time += delay;
  22564. int messSize = 0;
  22565. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22566. if (messSize <= 0)
  22567. break;
  22568. size -= messSize;
  22569. data += messSize;
  22570. result.addEvent (mm);
  22571. const char firstByte = *(mm.getRawData());
  22572. if ((firstByte & 0xf0) != 0xf0)
  22573. lastStatusByte = firstByte;
  22574. }
  22575. // use a sort that puts all the note-offs before note-ons that have the same time
  22576. MidiFileHelpers::Sorter sorter;
  22577. result.list.sort (sorter, true);
  22578. result.updateMatchedPairs();
  22579. addTrack (result);
  22580. }
  22581. void MidiFile::convertTimestampTicksToSeconds()
  22582. {
  22583. MidiMessageSequence tempoEvents;
  22584. findAllTempoEvents (tempoEvents);
  22585. findAllTimeSigEvents (tempoEvents);
  22586. for (int i = 0; i < tracks.size(); ++i)
  22587. {
  22588. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22589. for (int j = ms.getNumEvents(); --j >= 0;)
  22590. {
  22591. MidiMessage& m = ms.getEventPointer(j)->message;
  22592. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22593. tempoEvents,
  22594. timeFormat));
  22595. }
  22596. }
  22597. }
  22598. bool MidiFile::writeTo (OutputStream& out)
  22599. {
  22600. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22601. out.writeIntBigEndian (6);
  22602. out.writeShortBigEndian (1); // type
  22603. out.writeShortBigEndian ((short) tracks.size());
  22604. out.writeShortBigEndian (timeFormat);
  22605. for (int i = 0; i < tracks.size(); ++i)
  22606. writeTrack (out, i);
  22607. out.flush();
  22608. return true;
  22609. }
  22610. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22611. {
  22612. MemoryOutputStream out;
  22613. const MidiMessageSequence& ms = *tracks[trackNum];
  22614. int lastTick = 0;
  22615. char lastStatusByte = 0;
  22616. for (int i = 0; i < ms.getNumEvents(); ++i)
  22617. {
  22618. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22619. const int tick = roundToInt (mm.getTimeStamp());
  22620. const int delta = jmax (0, tick - lastTick);
  22621. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22622. lastTick = tick;
  22623. const char statusByte = *(mm.getRawData());
  22624. if ((statusByte == lastStatusByte)
  22625. && ((statusByte & 0xf0) != 0xf0)
  22626. && i > 0
  22627. && mm.getRawDataSize() > 1)
  22628. {
  22629. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22630. }
  22631. else
  22632. {
  22633. out.write (mm.getRawData(), mm.getRawDataSize());
  22634. }
  22635. lastStatusByte = statusByte;
  22636. }
  22637. out.writeByte (0);
  22638. const MidiMessage m (MidiMessage::endOfTrack());
  22639. out.write (m.getRawData(),
  22640. m.getRawDataSize());
  22641. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22642. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22643. mainOut.write (out.getData(), (int) out.getDataSize());
  22644. }
  22645. END_JUCE_NAMESPACE
  22646. /*** End of inlined file: juce_MidiFile.cpp ***/
  22647. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22648. BEGIN_JUCE_NAMESPACE
  22649. MidiKeyboardState::MidiKeyboardState()
  22650. {
  22651. zerostruct (noteStates);
  22652. }
  22653. MidiKeyboardState::~MidiKeyboardState()
  22654. {
  22655. }
  22656. void MidiKeyboardState::reset()
  22657. {
  22658. const ScopedLock sl (lock);
  22659. zerostruct (noteStates);
  22660. eventsToAdd.clear();
  22661. }
  22662. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22663. {
  22664. jassert (midiChannel >= 0 && midiChannel <= 16);
  22665. return isPositiveAndBelow (n, (int) 128)
  22666. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22667. }
  22668. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22669. {
  22670. return isPositiveAndBelow (n, (int) 128)
  22671. && (noteStates[n] & midiChannelMask) != 0;
  22672. }
  22673. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22674. {
  22675. jassert (midiChannel >= 0 && midiChannel <= 16);
  22676. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22677. const ScopedLock sl (lock);
  22678. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22679. {
  22680. const int timeNow = (int) Time::getMillisecondCounter();
  22681. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22682. eventsToAdd.clear (0, timeNow - 500);
  22683. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22684. }
  22685. }
  22686. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22687. {
  22688. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22689. {
  22690. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22691. for (int i = listeners.size(); --i >= 0;)
  22692. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22693. }
  22694. }
  22695. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22696. {
  22697. const ScopedLock sl (lock);
  22698. if (isNoteOn (midiChannel, midiNoteNumber))
  22699. {
  22700. const int timeNow = (int) Time::getMillisecondCounter();
  22701. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22702. eventsToAdd.clear (0, timeNow - 500);
  22703. noteOffInternal (midiChannel, midiNoteNumber);
  22704. }
  22705. }
  22706. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22707. {
  22708. if (isNoteOn (midiChannel, midiNoteNumber))
  22709. {
  22710. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22711. for (int i = listeners.size(); --i >= 0;)
  22712. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22713. }
  22714. }
  22715. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22716. {
  22717. const ScopedLock sl (lock);
  22718. if (midiChannel <= 0)
  22719. {
  22720. for (int i = 1; i <= 16; ++i)
  22721. allNotesOff (i);
  22722. }
  22723. else
  22724. {
  22725. for (int i = 0; i < 128; ++i)
  22726. noteOff (midiChannel, i);
  22727. }
  22728. }
  22729. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22730. {
  22731. if (message.isNoteOn())
  22732. {
  22733. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22734. }
  22735. else if (message.isNoteOff())
  22736. {
  22737. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22738. }
  22739. else if (message.isAllNotesOff())
  22740. {
  22741. for (int i = 0; i < 128; ++i)
  22742. noteOffInternal (message.getChannel(), i);
  22743. }
  22744. }
  22745. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22746. const int startSample,
  22747. const int numSamples,
  22748. const bool injectIndirectEvents)
  22749. {
  22750. MidiBuffer::Iterator i (buffer);
  22751. MidiMessage message (0xf4, 0.0);
  22752. int time;
  22753. const ScopedLock sl (lock);
  22754. while (i.getNextEvent (message, time))
  22755. processNextMidiEvent (message);
  22756. if (injectIndirectEvents)
  22757. {
  22758. MidiBuffer::Iterator i2 (eventsToAdd);
  22759. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22760. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22761. while (i2.getNextEvent (message, time))
  22762. {
  22763. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22764. buffer.addEvent (message, startSample + pos);
  22765. }
  22766. }
  22767. eventsToAdd.clear();
  22768. }
  22769. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22770. {
  22771. const ScopedLock sl (lock);
  22772. listeners.addIfNotAlreadyThere (listener);
  22773. }
  22774. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22775. {
  22776. const ScopedLock sl (lock);
  22777. listeners.removeValue (listener);
  22778. }
  22779. END_JUCE_NAMESPACE
  22780. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22781. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22782. BEGIN_JUCE_NAMESPACE
  22783. namespace MidiHelpers
  22784. {
  22785. inline uint8 initialByte (const int type, const int channel) throw()
  22786. {
  22787. return (uint8) (type | jlimit (0, 15, channel - 1));
  22788. }
  22789. inline uint8 validVelocity (const int v) throw()
  22790. {
  22791. return (uint8) jlimit (0, 127, v);
  22792. }
  22793. }
  22794. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22795. {
  22796. numBytesUsed = 0;
  22797. int v = 0;
  22798. int i;
  22799. do
  22800. {
  22801. i = (int) *data++;
  22802. if (++numBytesUsed > 6)
  22803. break;
  22804. v = (v << 7) + (i & 0x7f);
  22805. } while (i & 0x80);
  22806. return v;
  22807. }
  22808. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22809. {
  22810. // this method only works for valid starting bytes of a short midi message
  22811. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22812. static const char messageLengths[] =
  22813. {
  22814. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22815. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22816. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22817. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22818. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22819. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22820. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22821. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22822. };
  22823. return messageLengths [firstByte & 0x7f];
  22824. }
  22825. MidiMessage::MidiMessage() throw()
  22826. : timeStamp (0),
  22827. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22828. size (2)
  22829. {
  22830. data[0] = 0xf0;
  22831. data[1] = 0xf7;
  22832. }
  22833. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22834. : timeStamp (t),
  22835. size (dataSize)
  22836. {
  22837. jassert (dataSize > 0);
  22838. if (dataSize <= 4)
  22839. data = static_cast<uint8*> (preallocatedData.asBytes);
  22840. else
  22841. data = new uint8 [dataSize];
  22842. memcpy (data, d, dataSize);
  22843. // check that the length matches the data..
  22844. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22845. }
  22846. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22847. : timeStamp (t),
  22848. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22849. size (1)
  22850. {
  22851. data[0] = (uint8) byte1;
  22852. // check that the length matches the data..
  22853. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22854. }
  22855. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22856. : timeStamp (t),
  22857. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22858. size (2)
  22859. {
  22860. data[0] = (uint8) byte1;
  22861. data[1] = (uint8) byte2;
  22862. // check that the length matches the data..
  22863. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22864. }
  22865. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22866. : timeStamp (t),
  22867. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22868. size (3)
  22869. {
  22870. data[0] = (uint8) byte1;
  22871. data[1] = (uint8) byte2;
  22872. data[2] = (uint8) byte3;
  22873. // check that the length matches the data..
  22874. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22875. }
  22876. MidiMessage::MidiMessage (const MidiMessage& other)
  22877. : timeStamp (other.timeStamp),
  22878. size (other.size)
  22879. {
  22880. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22881. {
  22882. data = new uint8 [size];
  22883. memcpy (data, other.data, size);
  22884. }
  22885. else
  22886. {
  22887. data = static_cast<uint8*> (preallocatedData.asBytes);
  22888. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22889. }
  22890. }
  22891. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22892. : timeStamp (newTimeStamp),
  22893. size (other.size)
  22894. {
  22895. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22896. {
  22897. data = new uint8 [size];
  22898. memcpy (data, other.data, size);
  22899. }
  22900. else
  22901. {
  22902. data = static_cast<uint8*> (preallocatedData.asBytes);
  22903. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22904. }
  22905. }
  22906. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22907. : timeStamp (t),
  22908. data (static_cast<uint8*> (preallocatedData.asBytes))
  22909. {
  22910. const uint8* src = static_cast <const uint8*> (src_);
  22911. unsigned int byte = (unsigned int) *src;
  22912. if (byte < 0x80)
  22913. {
  22914. byte = (unsigned int) (uint8) lastStatusByte;
  22915. numBytesUsed = -1;
  22916. }
  22917. else
  22918. {
  22919. numBytesUsed = 0;
  22920. --sz;
  22921. ++src;
  22922. }
  22923. if (byte >= 0x80)
  22924. {
  22925. if (byte == 0xf0)
  22926. {
  22927. const uint8* d = src;
  22928. bool haveReadAllLengthBytes = false;
  22929. while (d < src + sz)
  22930. {
  22931. if (*d >= 0x80)
  22932. {
  22933. if (*d == 0xf7)
  22934. {
  22935. ++d; // include the trailing 0xf7 when we hit it
  22936. break;
  22937. }
  22938. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  22939. break; // bytes, assume it's the end of the sysex
  22940. ++d;
  22941. continue;
  22942. }
  22943. haveReadAllLengthBytes = true;
  22944. ++d;
  22945. }
  22946. size = 1 + (int) (d - src);
  22947. data = new uint8 [size];
  22948. *data = (uint8) byte;
  22949. memcpy (data + 1, src, size - 1);
  22950. }
  22951. else if (byte == 0xff)
  22952. {
  22953. int n;
  22954. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22955. size = jmin (sz + 1, n + 2 + bytesLeft);
  22956. data = new uint8 [size];
  22957. *data = (uint8) byte;
  22958. memcpy (data + 1, src, size - 1);
  22959. }
  22960. else
  22961. {
  22962. preallocatedData.asInt32 = 0;
  22963. size = getMessageLengthFromFirstByte ((uint8) byte);
  22964. data[0] = (uint8) byte;
  22965. if (size > 1)
  22966. {
  22967. data[1] = src[0];
  22968. if (size > 2)
  22969. data[2] = src[1];
  22970. }
  22971. }
  22972. numBytesUsed += size;
  22973. }
  22974. else
  22975. {
  22976. preallocatedData.asInt32 = 0;
  22977. size = 0;
  22978. }
  22979. }
  22980. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22981. {
  22982. if (this != &other)
  22983. {
  22984. timeStamp = other.timeStamp;
  22985. size = other.size;
  22986. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22987. delete[] data;
  22988. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22989. {
  22990. data = new uint8 [size];
  22991. memcpy (data, other.data, size);
  22992. }
  22993. else
  22994. {
  22995. data = static_cast<uint8*> (preallocatedData.asBytes);
  22996. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22997. }
  22998. }
  22999. return *this;
  23000. }
  23001. MidiMessage::~MidiMessage()
  23002. {
  23003. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23004. delete[] data;
  23005. }
  23006. int MidiMessage::getChannel() const throw()
  23007. {
  23008. if ((data[0] & 0xf0) != 0xf0)
  23009. return (data[0] & 0xf) + 1;
  23010. else
  23011. return 0;
  23012. }
  23013. bool MidiMessage::isForChannel (const int channel) const throw()
  23014. {
  23015. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23016. return ((data[0] & 0xf) == channel - 1)
  23017. && ((data[0] & 0xf0) != 0xf0);
  23018. }
  23019. void MidiMessage::setChannel (const int channel) throw()
  23020. {
  23021. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23022. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23023. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23024. | (uint8)(channel - 1));
  23025. }
  23026. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23027. {
  23028. return ((data[0] & 0xf0) == 0x90)
  23029. && (returnTrueForVelocity0 || data[2] != 0);
  23030. }
  23031. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23032. {
  23033. return ((data[0] & 0xf0) == 0x80)
  23034. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23035. }
  23036. bool MidiMessage::isNoteOnOrOff() const throw()
  23037. {
  23038. const int d = data[0] & 0xf0;
  23039. return (d == 0x90) || (d == 0x80);
  23040. }
  23041. int MidiMessage::getNoteNumber() const throw()
  23042. {
  23043. return data[1];
  23044. }
  23045. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23046. {
  23047. if (isNoteOnOrOff())
  23048. data[1] = newNoteNumber & 127;
  23049. }
  23050. uint8 MidiMessage::getVelocity() const throw()
  23051. {
  23052. if (isNoteOnOrOff())
  23053. return data[2];
  23054. else
  23055. return 0;
  23056. }
  23057. float MidiMessage::getFloatVelocity() const throw()
  23058. {
  23059. return getVelocity() * (1.0f / 127.0f);
  23060. }
  23061. void MidiMessage::setVelocity (const float newVelocity) throw()
  23062. {
  23063. if (isNoteOnOrOff())
  23064. data[2] = MidiHelpers::validVelocity (roundToInt (newVelocity * 127.0f));
  23065. }
  23066. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23067. {
  23068. if (isNoteOnOrOff())
  23069. data[2] = MidiHelpers::validVelocity (roundToInt (scaleFactor * data[2]));
  23070. }
  23071. bool MidiMessage::isAftertouch() const throw()
  23072. {
  23073. return (data[0] & 0xf0) == 0xa0;
  23074. }
  23075. int MidiMessage::getAfterTouchValue() const throw()
  23076. {
  23077. return data[2];
  23078. }
  23079. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23080. const int noteNum,
  23081. const int aftertouchValue) throw()
  23082. {
  23083. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23084. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23085. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23086. return MidiMessage (MidiHelpers::initialByte (0xa0, channel),
  23087. noteNum & 0x7f,
  23088. aftertouchValue & 0x7f);
  23089. }
  23090. bool MidiMessage::isChannelPressure() const throw()
  23091. {
  23092. return (data[0] & 0xf0) == 0xd0;
  23093. }
  23094. int MidiMessage::getChannelPressureValue() const throw()
  23095. {
  23096. jassert (isChannelPressure());
  23097. return data[1];
  23098. }
  23099. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23100. const int pressure) throw()
  23101. {
  23102. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23103. jassert (isPositiveAndBelow (pressure, (int) 128));
  23104. return MidiMessage (MidiHelpers::initialByte (0xd0, channel), pressure & 0x7f);
  23105. }
  23106. bool MidiMessage::isProgramChange() const throw()
  23107. {
  23108. return (data[0] & 0xf0) == 0xc0;
  23109. }
  23110. int MidiMessage::getProgramChangeNumber() const throw()
  23111. {
  23112. return data[1];
  23113. }
  23114. const MidiMessage MidiMessage::programChange (const int channel,
  23115. const int programNumber) throw()
  23116. {
  23117. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23118. return MidiMessage (MidiHelpers::initialByte (0xc0, channel), programNumber & 0x7f);
  23119. }
  23120. bool MidiMessage::isPitchWheel() const throw()
  23121. {
  23122. return (data[0] & 0xf0) == 0xe0;
  23123. }
  23124. int MidiMessage::getPitchWheelValue() const throw()
  23125. {
  23126. return data[1] | (data[2] << 7);
  23127. }
  23128. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23129. const int position) throw()
  23130. {
  23131. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23132. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23133. return MidiMessage (MidiHelpers::initialByte (0xe0, channel), position & 127, (position >> 7) & 127);
  23134. }
  23135. bool MidiMessage::isController() const throw()
  23136. {
  23137. return (data[0] & 0xf0) == 0xb0;
  23138. }
  23139. int MidiMessage::getControllerNumber() const throw()
  23140. {
  23141. jassert (isController());
  23142. return data[1];
  23143. }
  23144. int MidiMessage::getControllerValue() const throw()
  23145. {
  23146. jassert (isController());
  23147. return data[2];
  23148. }
  23149. const MidiMessage MidiMessage::controllerEvent (const int channel, const int controllerType, const int value) throw()
  23150. {
  23151. // the channel must be between 1 and 16 inclusive
  23152. jassert (channel > 0 && channel <= 16);
  23153. return MidiMessage (MidiHelpers::initialByte (0xb0, channel), controllerType & 127, value & 127);
  23154. }
  23155. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const float velocity) throw()
  23156. {
  23157. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23158. }
  23159. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const uint8 velocity) throw()
  23160. {
  23161. jassert (channel > 0 && channel <= 16);
  23162. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23163. return MidiMessage (MidiHelpers::initialByte (0x90, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23164. }
  23165. const MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, uint8 velocity) throw()
  23166. {
  23167. jassert (channel > 0 && channel <= 16);
  23168. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23169. return MidiMessage (MidiHelpers::initialByte (0x80, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23170. }
  23171. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23172. {
  23173. return controllerEvent (channel, 123, 0);
  23174. }
  23175. bool MidiMessage::isAllNotesOff() const throw()
  23176. {
  23177. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23178. }
  23179. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23180. {
  23181. return controllerEvent (channel, 120, 0);
  23182. }
  23183. bool MidiMessage::isAllSoundOff() const throw()
  23184. {
  23185. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23186. }
  23187. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23188. {
  23189. return controllerEvent (channel, 121, 0);
  23190. }
  23191. const MidiMessage MidiMessage::masterVolume (const float volume)
  23192. {
  23193. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23194. uint8 buf[8];
  23195. buf[0] = 0xf0;
  23196. buf[1] = 0x7f;
  23197. buf[2] = 0x7f;
  23198. buf[3] = 0x04;
  23199. buf[4] = 0x01;
  23200. buf[5] = (uint8) (vol & 0x7f);
  23201. buf[6] = (uint8) (vol >> 7);
  23202. buf[7] = 0xf7;
  23203. return MidiMessage (buf, 8);
  23204. }
  23205. bool MidiMessage::isSysEx() const throw()
  23206. {
  23207. return *data == 0xf0;
  23208. }
  23209. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23210. {
  23211. HeapBlock<uint8> m (dataSize + 2);
  23212. m[0] = 0xf0;
  23213. memcpy (m + 1, sysexData, dataSize);
  23214. m[dataSize + 1] = 0xf7;
  23215. return MidiMessage (m, dataSize + 2);
  23216. }
  23217. const uint8* MidiMessage::getSysExData() const throw()
  23218. {
  23219. return isSysEx() ? getRawData() + 1 : 0;
  23220. }
  23221. int MidiMessage::getSysExDataSize() const throw()
  23222. {
  23223. return isSysEx() ? size - 2 : 0;
  23224. }
  23225. bool MidiMessage::isMetaEvent() const throw()
  23226. {
  23227. return *data == 0xff;
  23228. }
  23229. bool MidiMessage::isActiveSense() const throw()
  23230. {
  23231. return *data == 0xfe;
  23232. }
  23233. int MidiMessage::getMetaEventType() const throw()
  23234. {
  23235. return *data != 0xff ? -1 : data[1];
  23236. }
  23237. int MidiMessage::getMetaEventLength() const throw()
  23238. {
  23239. if (*data == 0xff)
  23240. {
  23241. int n;
  23242. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23243. }
  23244. return 0;
  23245. }
  23246. const uint8* MidiMessage::getMetaEventData() const throw()
  23247. {
  23248. int n;
  23249. const uint8* d = data + 2;
  23250. readVariableLengthVal (d, n);
  23251. return d + n;
  23252. }
  23253. bool MidiMessage::isTrackMetaEvent() const throw()
  23254. {
  23255. return getMetaEventType() == 0;
  23256. }
  23257. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23258. {
  23259. return getMetaEventType() == 47;
  23260. }
  23261. bool MidiMessage::isTextMetaEvent() const throw()
  23262. {
  23263. const int t = getMetaEventType();
  23264. return t > 0 && t < 16;
  23265. }
  23266. const String MidiMessage::getTextFromTextMetaEvent() const
  23267. {
  23268. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23269. }
  23270. bool MidiMessage::isTrackNameEvent() const throw()
  23271. {
  23272. return (data[1] == 3) && (*data == 0xff);
  23273. }
  23274. bool MidiMessage::isTempoMetaEvent() const throw()
  23275. {
  23276. return (data[1] == 81) && (*data == 0xff);
  23277. }
  23278. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23279. {
  23280. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23281. }
  23282. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23283. {
  23284. return data[3] + 1;
  23285. }
  23286. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23287. {
  23288. if (! isTempoMetaEvent())
  23289. return 0.0;
  23290. const uint8* const d = getMetaEventData();
  23291. return (((unsigned int) d[0] << 16)
  23292. | ((unsigned int) d[1] << 8)
  23293. | d[2])
  23294. / 1000000.0;
  23295. }
  23296. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23297. {
  23298. if (timeFormat > 0)
  23299. {
  23300. if (! isTempoMetaEvent())
  23301. return 0.5 / timeFormat;
  23302. return getTempoSecondsPerQuarterNote() / timeFormat;
  23303. }
  23304. else
  23305. {
  23306. const int frameCode = (-timeFormat) >> 8;
  23307. double framesPerSecond;
  23308. switch (frameCode)
  23309. {
  23310. case 24: framesPerSecond = 24.0; break;
  23311. case 25: framesPerSecond = 25.0; break;
  23312. case 29: framesPerSecond = 29.97; break;
  23313. case 30: framesPerSecond = 30.0; break;
  23314. default: framesPerSecond = 30.0; break;
  23315. }
  23316. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23317. }
  23318. }
  23319. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23320. {
  23321. uint8 d[8];
  23322. d[0] = 0xff;
  23323. d[1] = 81;
  23324. d[2] = 3;
  23325. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23326. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23327. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23328. return MidiMessage (d, 6, 0.0);
  23329. }
  23330. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23331. {
  23332. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23333. }
  23334. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23335. {
  23336. if (isTimeSignatureMetaEvent())
  23337. {
  23338. const uint8* const d = getMetaEventData();
  23339. numerator = d[0];
  23340. denominator = 1 << d[1];
  23341. }
  23342. else
  23343. {
  23344. numerator = 4;
  23345. denominator = 4;
  23346. }
  23347. }
  23348. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23349. {
  23350. uint8 d[8];
  23351. d[0] = 0xff;
  23352. d[1] = 0x58;
  23353. d[2] = 0x04;
  23354. d[3] = (uint8) numerator;
  23355. int n = 1;
  23356. int powerOfTwo = 0;
  23357. while (n < denominator)
  23358. {
  23359. n <<= 1;
  23360. ++powerOfTwo;
  23361. }
  23362. d[4] = (uint8) powerOfTwo;
  23363. d[5] = 0x01;
  23364. d[6] = 96;
  23365. return MidiMessage (d, 7, 0.0);
  23366. }
  23367. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23368. {
  23369. uint8 d[8];
  23370. d[0] = 0xff;
  23371. d[1] = 0x20;
  23372. d[2] = 0x01;
  23373. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23374. return MidiMessage (d, 4, 0.0);
  23375. }
  23376. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23377. {
  23378. return getMetaEventType() == 89;
  23379. }
  23380. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23381. {
  23382. return (int) *getMetaEventData();
  23383. }
  23384. const MidiMessage MidiMessage::endOfTrack() throw()
  23385. {
  23386. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23387. }
  23388. bool MidiMessage::isSongPositionPointer() const throw()
  23389. {
  23390. return *data == 0xf2;
  23391. }
  23392. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23393. {
  23394. return data[1] | (data[2] << 7);
  23395. }
  23396. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23397. {
  23398. return MidiMessage (0xf2,
  23399. positionInMidiBeats & 127,
  23400. (positionInMidiBeats >> 7) & 127);
  23401. }
  23402. bool MidiMessage::isMidiStart() const throw()
  23403. {
  23404. return *data == 0xfa;
  23405. }
  23406. const MidiMessage MidiMessage::midiStart() throw()
  23407. {
  23408. return MidiMessage (0xfa);
  23409. }
  23410. bool MidiMessage::isMidiContinue() const throw()
  23411. {
  23412. return *data == 0xfb;
  23413. }
  23414. const MidiMessage MidiMessage::midiContinue() throw()
  23415. {
  23416. return MidiMessage (0xfb);
  23417. }
  23418. bool MidiMessage::isMidiStop() const throw()
  23419. {
  23420. return *data == 0xfc;
  23421. }
  23422. const MidiMessage MidiMessage::midiStop() throw()
  23423. {
  23424. return MidiMessage (0xfc);
  23425. }
  23426. bool MidiMessage::isMidiClock() const throw()
  23427. {
  23428. return *data == 0xf8;
  23429. }
  23430. const MidiMessage MidiMessage::midiClock() throw()
  23431. {
  23432. return MidiMessage (0xf8);
  23433. }
  23434. bool MidiMessage::isQuarterFrame() const throw()
  23435. {
  23436. return *data == 0xf1;
  23437. }
  23438. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23439. {
  23440. return ((int) data[1]) >> 4;
  23441. }
  23442. int MidiMessage::getQuarterFrameValue() const throw()
  23443. {
  23444. return ((int) data[1]) & 0x0f;
  23445. }
  23446. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23447. const int value) throw()
  23448. {
  23449. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23450. }
  23451. bool MidiMessage::isFullFrame() const throw()
  23452. {
  23453. return data[0] == 0xf0
  23454. && data[1] == 0x7f
  23455. && size >= 10
  23456. && data[3] == 0x01
  23457. && data[4] == 0x01;
  23458. }
  23459. void MidiMessage::getFullFrameParameters (int& hours,
  23460. int& minutes,
  23461. int& seconds,
  23462. int& frames,
  23463. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23464. {
  23465. jassert (isFullFrame());
  23466. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23467. hours = data[5] & 0x1f;
  23468. minutes = data[6];
  23469. seconds = data[7];
  23470. frames = data[8];
  23471. }
  23472. const MidiMessage MidiMessage::fullFrame (const int hours,
  23473. const int minutes,
  23474. const int seconds,
  23475. const int frames,
  23476. MidiMessage::SmpteTimecodeType timecodeType)
  23477. {
  23478. uint8 d[10];
  23479. d[0] = 0xf0;
  23480. d[1] = 0x7f;
  23481. d[2] = 0x7f;
  23482. d[3] = 0x01;
  23483. d[4] = 0x01;
  23484. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23485. d[6] = (uint8) minutes;
  23486. d[7] = (uint8) seconds;
  23487. d[8] = (uint8) frames;
  23488. d[9] = 0xf7;
  23489. return MidiMessage (d, 10, 0.0);
  23490. }
  23491. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23492. {
  23493. return data[0] == 0xf0
  23494. && data[1] == 0x7f
  23495. && data[3] == 0x06
  23496. && size > 5;
  23497. }
  23498. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23499. {
  23500. jassert (isMidiMachineControlMessage());
  23501. return (MidiMachineControlCommand) data[4];
  23502. }
  23503. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23504. {
  23505. uint8 d[6];
  23506. d[0] = 0xf0;
  23507. d[1] = 0x7f;
  23508. d[2] = 0x00;
  23509. d[3] = 0x06;
  23510. d[4] = (uint8) command;
  23511. d[5] = 0xf7;
  23512. return MidiMessage (d, 6, 0.0);
  23513. }
  23514. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23515. int& minutes,
  23516. int& seconds,
  23517. int& frames) const throw()
  23518. {
  23519. if (size >= 12
  23520. && data[0] == 0xf0
  23521. && data[1] == 0x7f
  23522. && data[3] == 0x06
  23523. && data[4] == 0x44
  23524. && data[5] == 0x06
  23525. && data[6] == 0x01)
  23526. {
  23527. hours = data[7] % 24; // (that some machines send out hours > 24)
  23528. minutes = data[8];
  23529. seconds = data[9];
  23530. frames = data[10];
  23531. return true;
  23532. }
  23533. return false;
  23534. }
  23535. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23536. int minutes,
  23537. int seconds,
  23538. int frames)
  23539. {
  23540. uint8 d[12];
  23541. d[0] = 0xf0;
  23542. d[1] = 0x7f;
  23543. d[2] = 0x00;
  23544. d[3] = 0x06;
  23545. d[4] = 0x44;
  23546. d[5] = 0x06;
  23547. d[6] = 0x01;
  23548. d[7] = (uint8) hours;
  23549. d[8] = (uint8) minutes;
  23550. d[9] = (uint8) seconds;
  23551. d[10] = (uint8) frames;
  23552. d[11] = 0xf7;
  23553. return MidiMessage (d, 12, 0.0);
  23554. }
  23555. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23556. {
  23557. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23558. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23559. if (isPositiveAndBelow (note, (int) 128))
  23560. {
  23561. String s (useSharps ? sharpNoteNames [note % 12]
  23562. : flatNoteNames [note % 12]);
  23563. if (includeOctaveNumber)
  23564. s << (note / 12 + (octaveNumForMiddleC - 5));
  23565. return s;
  23566. }
  23567. return String::empty;
  23568. }
  23569. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23570. {
  23571. noteNumber -= 12 * 6 + 9; // now 0 = A
  23572. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23573. }
  23574. const String MidiMessage::getGMInstrumentName (const int n)
  23575. {
  23576. const char* names[] =
  23577. {
  23578. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23579. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23580. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23581. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23582. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23583. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23584. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23585. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23586. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23587. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23588. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23589. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23590. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23591. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23592. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23593. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23594. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23595. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23596. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23597. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23598. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23599. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23600. "Applause", "Gunshot"
  23601. };
  23602. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23603. }
  23604. const String MidiMessage::getGMInstrumentBankName (const int n)
  23605. {
  23606. const char* names[] =
  23607. {
  23608. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23609. "Bass", "Strings", "Ensemble", "Brass",
  23610. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23611. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23612. };
  23613. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23614. }
  23615. const String MidiMessage::getRhythmInstrumentName (const int n)
  23616. {
  23617. const char* names[] =
  23618. {
  23619. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23620. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23621. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23622. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23623. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23624. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23625. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23626. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23627. "Mute Triangle", "Open Triangle"
  23628. };
  23629. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23630. }
  23631. const String MidiMessage::getControllerName (const int n)
  23632. {
  23633. const char* names[] =
  23634. {
  23635. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23636. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23637. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23638. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23639. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23640. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23641. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23642. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23643. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23644. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23645. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23646. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23647. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23648. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23649. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23650. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23651. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23652. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23653. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23655. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23656. "Poly Operation"
  23657. };
  23658. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23659. }
  23660. END_JUCE_NAMESPACE
  23661. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23662. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23663. BEGIN_JUCE_NAMESPACE
  23664. MidiMessageCollector::MidiMessageCollector()
  23665. : lastCallbackTime (0),
  23666. sampleRate (44100.0001)
  23667. {
  23668. }
  23669. MidiMessageCollector::~MidiMessageCollector()
  23670. {
  23671. }
  23672. void MidiMessageCollector::reset (const double sampleRate_)
  23673. {
  23674. jassert (sampleRate_ > 0);
  23675. const ScopedLock sl (midiCallbackLock);
  23676. sampleRate = sampleRate_;
  23677. incomingMessages.clear();
  23678. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23679. }
  23680. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23681. {
  23682. // you need to call reset() to set the correct sample rate before using this object
  23683. jassert (sampleRate != 44100.0001);
  23684. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23685. // for details of what the number should be.
  23686. jassert (message.getTimeStamp() != 0);
  23687. const ScopedLock sl (midiCallbackLock);
  23688. const int sampleNumber
  23689. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23690. incomingMessages.addEvent (message, sampleNumber);
  23691. // if the messages don't get used for over a second, we'd better
  23692. // get rid of any old ones to avoid the queue getting too big
  23693. if (sampleNumber > sampleRate)
  23694. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23695. }
  23696. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23697. const int numSamples)
  23698. {
  23699. // you need to call reset() to set the correct sample rate before using this object
  23700. jassert (sampleRate != 44100.0001);
  23701. const double timeNow = Time::getMillisecondCounterHiRes();
  23702. const double msElapsed = timeNow - lastCallbackTime;
  23703. const ScopedLock sl (midiCallbackLock);
  23704. lastCallbackTime = timeNow;
  23705. if (! incomingMessages.isEmpty())
  23706. {
  23707. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23708. int startSample = 0;
  23709. int scale = 1 << 16;
  23710. const uint8* midiData;
  23711. int numBytes, samplePosition;
  23712. MidiBuffer::Iterator iter (incomingMessages);
  23713. if (numSourceSamples > numSamples)
  23714. {
  23715. // if our list of events is longer than the buffer we're being
  23716. // asked for, scale them down to squeeze them all in..
  23717. const int maxBlockLengthToUse = numSamples << 5;
  23718. if (numSourceSamples > maxBlockLengthToUse)
  23719. {
  23720. startSample = numSourceSamples - maxBlockLengthToUse;
  23721. numSourceSamples = maxBlockLengthToUse;
  23722. iter.setNextSamplePosition (startSample);
  23723. }
  23724. scale = (numSamples << 10) / numSourceSamples;
  23725. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23726. {
  23727. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23728. destBuffer.addEvent (midiData, numBytes,
  23729. jlimit (0, numSamples - 1, samplePosition));
  23730. }
  23731. }
  23732. else
  23733. {
  23734. // if our event list is shorter than the number we need, put them
  23735. // towards the end of the buffer
  23736. startSample = numSamples - numSourceSamples;
  23737. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23738. {
  23739. destBuffer.addEvent (midiData, numBytes,
  23740. jlimit (0, numSamples - 1, samplePosition + startSample));
  23741. }
  23742. }
  23743. incomingMessages.clear();
  23744. }
  23745. }
  23746. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23747. {
  23748. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23749. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23750. addMessageToQueue (m);
  23751. }
  23752. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23753. {
  23754. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23755. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23756. addMessageToQueue (m);
  23757. }
  23758. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23759. {
  23760. addMessageToQueue (message);
  23761. }
  23762. END_JUCE_NAMESPACE
  23763. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23764. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23765. BEGIN_JUCE_NAMESPACE
  23766. MidiMessageSequence::MidiMessageSequence()
  23767. {
  23768. }
  23769. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23770. {
  23771. list.ensureStorageAllocated (other.list.size());
  23772. for (int i = 0; i < other.list.size(); ++i)
  23773. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23774. }
  23775. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23776. {
  23777. MidiMessageSequence otherCopy (other);
  23778. swapWith (otherCopy);
  23779. return *this;
  23780. }
  23781. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23782. {
  23783. list.swapWithArray (other.list);
  23784. }
  23785. MidiMessageSequence::~MidiMessageSequence()
  23786. {
  23787. }
  23788. void MidiMessageSequence::clear()
  23789. {
  23790. list.clear();
  23791. }
  23792. int MidiMessageSequence::getNumEvents() const
  23793. {
  23794. return list.size();
  23795. }
  23796. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23797. {
  23798. return list [index];
  23799. }
  23800. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23801. {
  23802. const MidiEventHolder* const meh = list [index];
  23803. if (meh != 0 && meh->noteOffObject != 0)
  23804. return meh->noteOffObject->message.getTimeStamp();
  23805. else
  23806. return 0.0;
  23807. }
  23808. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23809. {
  23810. const MidiEventHolder* const meh = list [index];
  23811. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23812. }
  23813. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23814. {
  23815. return list.indexOf (event);
  23816. }
  23817. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23818. {
  23819. const int numEvents = list.size();
  23820. int i;
  23821. for (i = 0; i < numEvents; ++i)
  23822. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23823. break;
  23824. return i;
  23825. }
  23826. double MidiMessageSequence::getStartTime() const
  23827. {
  23828. if (list.size() > 0)
  23829. return list.getUnchecked(0)->message.getTimeStamp();
  23830. else
  23831. return 0;
  23832. }
  23833. double MidiMessageSequence::getEndTime() const
  23834. {
  23835. if (list.size() > 0)
  23836. return list.getLast()->message.getTimeStamp();
  23837. else
  23838. return 0;
  23839. }
  23840. double MidiMessageSequence::getEventTime (const int index) const
  23841. {
  23842. if (isPositiveAndBelow (index, list.size()))
  23843. return list.getUnchecked (index)->message.getTimeStamp();
  23844. return 0.0;
  23845. }
  23846. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23847. double timeAdjustment)
  23848. {
  23849. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23850. timeAdjustment += newMessage.getTimeStamp();
  23851. newOne->message.setTimeStamp (timeAdjustment);
  23852. int i;
  23853. for (i = list.size(); --i >= 0;)
  23854. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23855. break;
  23856. list.insert (i + 1, newOne);
  23857. }
  23858. void MidiMessageSequence::deleteEvent (const int index,
  23859. const bool deleteMatchingNoteUp)
  23860. {
  23861. if (isPositiveAndBelow (index, list.size()))
  23862. {
  23863. if (deleteMatchingNoteUp)
  23864. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23865. list.remove (index);
  23866. }
  23867. }
  23868. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23869. double timeAdjustment,
  23870. double firstAllowableTime,
  23871. double endOfAllowableDestTimes)
  23872. {
  23873. firstAllowableTime -= timeAdjustment;
  23874. endOfAllowableDestTimes -= timeAdjustment;
  23875. for (int i = 0; i < other.list.size(); ++i)
  23876. {
  23877. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23878. const double t = m.getTimeStamp();
  23879. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23880. {
  23881. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23882. newOne->message.setTimeStamp (timeAdjustment + t);
  23883. list.add (newOne);
  23884. }
  23885. }
  23886. sort();
  23887. }
  23888. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23889. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23890. {
  23891. const double diff = first->message.getTimeStamp()
  23892. - second->message.getTimeStamp();
  23893. return (diff > 0) - (diff < 0);
  23894. }
  23895. void MidiMessageSequence::sort()
  23896. {
  23897. list.sort (*this, true);
  23898. }
  23899. void MidiMessageSequence::updateMatchedPairs()
  23900. {
  23901. for (int i = 0; i < list.size(); ++i)
  23902. {
  23903. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23904. if (m1.isNoteOn())
  23905. {
  23906. list.getUnchecked(i)->noteOffObject = 0;
  23907. const int note = m1.getNoteNumber();
  23908. const int chan = m1.getChannel();
  23909. const int len = list.size();
  23910. for (int j = i + 1; j < len; ++j)
  23911. {
  23912. const MidiMessage& m = list.getUnchecked(j)->message;
  23913. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23914. {
  23915. if (m.isNoteOff())
  23916. {
  23917. list.getUnchecked(i)->noteOffObject = list[j];
  23918. break;
  23919. }
  23920. else if (m.isNoteOn())
  23921. {
  23922. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23923. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23924. list.getUnchecked(i)->noteOffObject = list[j];
  23925. break;
  23926. }
  23927. }
  23928. }
  23929. }
  23930. }
  23931. }
  23932. void MidiMessageSequence::addTimeToMessages (const double delta)
  23933. {
  23934. for (int i = list.size(); --i >= 0;)
  23935. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23936. + delta);
  23937. }
  23938. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23939. MidiMessageSequence& destSequence,
  23940. const bool alsoIncludeMetaEvents) const
  23941. {
  23942. for (int i = 0; i < list.size(); ++i)
  23943. {
  23944. const MidiMessage& mm = list.getUnchecked(i)->message;
  23945. if (mm.isForChannel (channelNumberToExtract)
  23946. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23947. {
  23948. destSequence.addEvent (mm);
  23949. }
  23950. }
  23951. }
  23952. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23953. {
  23954. for (int i = 0; i < list.size(); ++i)
  23955. {
  23956. const MidiMessage& mm = list.getUnchecked(i)->message;
  23957. if (mm.isSysEx())
  23958. destSequence.addEvent (mm);
  23959. }
  23960. }
  23961. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23962. {
  23963. for (int i = list.size(); --i >= 0;)
  23964. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23965. list.remove(i);
  23966. }
  23967. void MidiMessageSequence::deleteSysExMessages()
  23968. {
  23969. for (int i = list.size(); --i >= 0;)
  23970. if (list.getUnchecked(i)->message.isSysEx())
  23971. list.remove(i);
  23972. }
  23973. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23974. const double time,
  23975. OwnedArray<MidiMessage>& dest)
  23976. {
  23977. bool doneProg = false;
  23978. bool donePitchWheel = false;
  23979. Array <int> doneControllers;
  23980. doneControllers.ensureStorageAllocated (32);
  23981. for (int i = list.size(); --i >= 0;)
  23982. {
  23983. const MidiMessage& mm = list.getUnchecked(i)->message;
  23984. if (mm.isForChannel (channelNumber)
  23985. && mm.getTimeStamp() <= time)
  23986. {
  23987. if (mm.isProgramChange())
  23988. {
  23989. if (! doneProg)
  23990. {
  23991. dest.add (new MidiMessage (mm, 0.0));
  23992. doneProg = true;
  23993. }
  23994. }
  23995. else if (mm.isController())
  23996. {
  23997. if (! doneControllers.contains (mm.getControllerNumber()))
  23998. {
  23999. dest.add (new MidiMessage (mm, 0.0));
  24000. doneControllers.add (mm.getControllerNumber());
  24001. }
  24002. }
  24003. else if (mm.isPitchWheel())
  24004. {
  24005. if (! donePitchWheel)
  24006. {
  24007. dest.add (new MidiMessage (mm, 0.0));
  24008. donePitchWheel = true;
  24009. }
  24010. }
  24011. }
  24012. }
  24013. }
  24014. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24015. : message (message_),
  24016. noteOffObject (0)
  24017. {
  24018. }
  24019. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24020. {
  24021. }
  24022. END_JUCE_NAMESPACE
  24023. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24024. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24025. BEGIN_JUCE_NAMESPACE
  24026. AudioPluginFormat::AudioPluginFormat() throw()
  24027. {
  24028. }
  24029. AudioPluginFormat::~AudioPluginFormat()
  24030. {
  24031. }
  24032. END_JUCE_NAMESPACE
  24033. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24034. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24035. BEGIN_JUCE_NAMESPACE
  24036. AudioPluginFormatManager::AudioPluginFormatManager()
  24037. {
  24038. }
  24039. AudioPluginFormatManager::~AudioPluginFormatManager()
  24040. {
  24041. clearSingletonInstance();
  24042. }
  24043. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24044. void AudioPluginFormatManager::addDefaultFormats()
  24045. {
  24046. #if JUCE_DEBUG
  24047. // you should only call this method once!
  24048. for (int i = formats.size(); --i >= 0;)
  24049. {
  24050. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24051. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24052. #endif
  24053. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24054. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24055. #endif
  24056. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24057. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24058. #endif
  24059. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24060. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24061. #endif
  24062. }
  24063. #endif
  24064. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24065. formats.add (new AudioUnitPluginFormat());
  24066. #endif
  24067. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24068. formats.add (new VSTPluginFormat());
  24069. #endif
  24070. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24071. formats.add (new DirectXPluginFormat());
  24072. #endif
  24073. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24074. formats.add (new LADSPAPluginFormat());
  24075. #endif
  24076. }
  24077. int AudioPluginFormatManager::getNumFormats()
  24078. {
  24079. return formats.size();
  24080. }
  24081. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24082. {
  24083. return formats [index];
  24084. }
  24085. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24086. {
  24087. formats.add (format);
  24088. }
  24089. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24090. String& errorMessage) const
  24091. {
  24092. AudioPluginInstance* result = 0;
  24093. for (int i = 0; i < formats.size(); ++i)
  24094. {
  24095. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24096. if (result != 0)
  24097. break;
  24098. }
  24099. if (result == 0)
  24100. {
  24101. if (! doesPluginStillExist (description))
  24102. errorMessage = TRANS ("This plug-in file no longer exists");
  24103. else
  24104. errorMessage = TRANS ("This plug-in failed to load correctly");
  24105. }
  24106. return result;
  24107. }
  24108. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24109. {
  24110. for (int i = 0; i < formats.size(); ++i)
  24111. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24112. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24113. return false;
  24114. }
  24115. END_JUCE_NAMESPACE
  24116. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24117. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24118. #define JUCE_PLUGIN_HOST 1
  24119. BEGIN_JUCE_NAMESPACE
  24120. AudioPluginInstance::AudioPluginInstance()
  24121. {
  24122. }
  24123. AudioPluginInstance::~AudioPluginInstance()
  24124. {
  24125. }
  24126. void* AudioPluginInstance::getPlatformSpecificData()
  24127. {
  24128. return 0;
  24129. }
  24130. END_JUCE_NAMESPACE
  24131. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24132. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24133. BEGIN_JUCE_NAMESPACE
  24134. KnownPluginList::KnownPluginList()
  24135. {
  24136. }
  24137. KnownPluginList::~KnownPluginList()
  24138. {
  24139. }
  24140. void KnownPluginList::clear()
  24141. {
  24142. if (types.size() > 0)
  24143. {
  24144. types.clear();
  24145. sendChangeMessage();
  24146. }
  24147. }
  24148. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24149. {
  24150. for (int i = 0; i < types.size(); ++i)
  24151. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24152. return types.getUnchecked(i);
  24153. return 0;
  24154. }
  24155. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24156. {
  24157. for (int i = 0; i < types.size(); ++i)
  24158. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24159. return types.getUnchecked(i);
  24160. return 0;
  24161. }
  24162. bool KnownPluginList::addType (const PluginDescription& type)
  24163. {
  24164. for (int i = types.size(); --i >= 0;)
  24165. {
  24166. if (types.getUnchecked(i)->isDuplicateOf (type))
  24167. {
  24168. // strange - found a duplicate plugin with different info..
  24169. jassert (types.getUnchecked(i)->name == type.name);
  24170. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24171. *types.getUnchecked(i) = type;
  24172. return false;
  24173. }
  24174. }
  24175. types.add (new PluginDescription (type));
  24176. sendChangeMessage();
  24177. return true;
  24178. }
  24179. void KnownPluginList::removeType (const int index)
  24180. {
  24181. types.remove (index);
  24182. sendChangeMessage();
  24183. }
  24184. namespace
  24185. {
  24186. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24187. {
  24188. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24189. return File (fileOrIdentifier).getLastModificationTime();
  24190. return Time();
  24191. }
  24192. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24193. {
  24194. return t1 != t2 || t1 == Time();
  24195. }
  24196. }
  24197. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24198. {
  24199. if (getTypeForFile (fileOrIdentifier) == 0)
  24200. return false;
  24201. for (int i = types.size(); --i >= 0;)
  24202. {
  24203. const PluginDescription* const d = types.getUnchecked(i);
  24204. if (d->fileOrIdentifier == fileOrIdentifier
  24205. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24206. {
  24207. return false;
  24208. }
  24209. }
  24210. return true;
  24211. }
  24212. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24213. const bool dontRescanIfAlreadyInList,
  24214. OwnedArray <PluginDescription>& typesFound,
  24215. AudioPluginFormat& format)
  24216. {
  24217. bool addedOne = false;
  24218. if (dontRescanIfAlreadyInList
  24219. && getTypeForFile (fileOrIdentifier) != 0)
  24220. {
  24221. bool needsRescanning = false;
  24222. for (int i = types.size(); --i >= 0;)
  24223. {
  24224. const PluginDescription* const d = types.getUnchecked(i);
  24225. if (d->fileOrIdentifier == fileOrIdentifier)
  24226. {
  24227. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24228. needsRescanning = true;
  24229. else
  24230. typesFound.add (new PluginDescription (*d));
  24231. }
  24232. }
  24233. if (! needsRescanning)
  24234. return false;
  24235. }
  24236. OwnedArray <PluginDescription> found;
  24237. format.findAllTypesForFile (found, fileOrIdentifier);
  24238. for (int i = 0; i < found.size(); ++i)
  24239. {
  24240. PluginDescription* const desc = found.getUnchecked(i);
  24241. jassert (desc != 0);
  24242. if (addType (*desc))
  24243. addedOne = true;
  24244. typesFound.add (new PluginDescription (*desc));
  24245. }
  24246. return addedOne;
  24247. }
  24248. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24249. OwnedArray <PluginDescription>& typesFound)
  24250. {
  24251. for (int i = 0; i < files.size(); ++i)
  24252. {
  24253. bool loaded = false;
  24254. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24255. {
  24256. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24257. if (scanAndAddFile (files[i], true, typesFound, *format))
  24258. loaded = true;
  24259. }
  24260. if (! loaded)
  24261. {
  24262. const File f (files[i]);
  24263. if (f.isDirectory())
  24264. {
  24265. StringArray s;
  24266. {
  24267. Array<File> subFiles;
  24268. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24269. for (int j = 0; j < subFiles.size(); ++j)
  24270. s.add (subFiles.getReference(j).getFullPathName());
  24271. }
  24272. scanAndAddDragAndDroppedFiles (s, typesFound);
  24273. }
  24274. }
  24275. }
  24276. }
  24277. class PluginSorter
  24278. {
  24279. public:
  24280. KnownPluginList::SortMethod method;
  24281. PluginSorter() throw() {}
  24282. int compareElements (const PluginDescription* const first,
  24283. const PluginDescription* const second) const
  24284. {
  24285. int diff = 0;
  24286. if (method == KnownPluginList::sortByCategory)
  24287. diff = first->category.compareLexicographically (second->category);
  24288. else if (method == KnownPluginList::sortByManufacturer)
  24289. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24290. else if (method == KnownPluginList::sortByFileSystemLocation)
  24291. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24292. .upToLastOccurrenceOf ("/", false, false)
  24293. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24294. .upToLastOccurrenceOf ("/", false, false));
  24295. if (diff == 0)
  24296. diff = first->name.compareLexicographically (second->name);
  24297. return diff;
  24298. }
  24299. };
  24300. void KnownPluginList::sort (const SortMethod method)
  24301. {
  24302. if (method != defaultOrder)
  24303. {
  24304. PluginSorter sorter;
  24305. sorter.method = method;
  24306. types.sort (sorter, true);
  24307. sendChangeMessage();
  24308. }
  24309. }
  24310. XmlElement* KnownPluginList::createXml() const
  24311. {
  24312. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24313. for (int i = 0; i < types.size(); ++i)
  24314. e->addChildElement (types.getUnchecked(i)->createXml());
  24315. return e;
  24316. }
  24317. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24318. {
  24319. clear();
  24320. if (xml.hasTagName ("KNOWNPLUGINS"))
  24321. {
  24322. forEachXmlChildElement (xml, e)
  24323. {
  24324. PluginDescription info;
  24325. if (info.loadFromXml (*e))
  24326. addType (info);
  24327. }
  24328. }
  24329. }
  24330. const int menuIdBase = 0x324503f4;
  24331. // This is used to turn a bunch of paths into a nested menu structure.
  24332. struct PluginFilesystemTree
  24333. {
  24334. private:
  24335. String folder;
  24336. OwnedArray <PluginFilesystemTree> subFolders;
  24337. Array <PluginDescription*> plugins;
  24338. void addPlugin (PluginDescription* const pd, const String& path)
  24339. {
  24340. if (path.isEmpty())
  24341. {
  24342. plugins.add (pd);
  24343. }
  24344. else
  24345. {
  24346. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24347. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24348. for (int i = subFolders.size(); --i >= 0;)
  24349. {
  24350. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24351. {
  24352. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24353. return;
  24354. }
  24355. }
  24356. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24357. newFolder->folder = firstSubFolder;
  24358. subFolders.add (newFolder);
  24359. newFolder->addPlugin (pd, remainingPath);
  24360. }
  24361. }
  24362. // removes any deeply nested folders that don't contain any actual plugins
  24363. void optimise()
  24364. {
  24365. for (int i = subFolders.size(); --i >= 0;)
  24366. {
  24367. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24368. sub->optimise();
  24369. if (sub->plugins.size() == 0)
  24370. {
  24371. for (int j = 0; j < sub->subFolders.size(); ++j)
  24372. subFolders.add (sub->subFolders.getUnchecked(j));
  24373. sub->subFolders.clear (false);
  24374. subFolders.remove (i);
  24375. }
  24376. }
  24377. }
  24378. public:
  24379. void buildTree (const Array <PluginDescription*>& allPlugins)
  24380. {
  24381. for (int i = 0; i < allPlugins.size(); ++i)
  24382. {
  24383. String path (allPlugins.getUnchecked(i)
  24384. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24385. .upToLastOccurrenceOf ("/", false, false));
  24386. if (path.substring (1, 2) == ":")
  24387. path = path.substring (2);
  24388. addPlugin (allPlugins.getUnchecked(i), path);
  24389. }
  24390. optimise();
  24391. }
  24392. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24393. {
  24394. int i;
  24395. for (i = 0; i < subFolders.size(); ++i)
  24396. {
  24397. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24398. PopupMenu subMenu;
  24399. sub->addToMenu (subMenu, allPlugins);
  24400. #if JUCE_MAC
  24401. // avoid the special AU formatting nonsense on Mac..
  24402. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24403. #else
  24404. m.addSubMenu (sub->folder, subMenu);
  24405. #endif
  24406. }
  24407. for (i = 0; i < plugins.size(); ++i)
  24408. {
  24409. PluginDescription* const plugin = plugins.getUnchecked(i);
  24410. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24411. plugin->name, true, false);
  24412. }
  24413. }
  24414. };
  24415. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24416. {
  24417. Array <PluginDescription*> sorted;
  24418. {
  24419. PluginSorter sorter;
  24420. sorter.method = sortMethod;
  24421. for (int i = 0; i < types.size(); ++i)
  24422. sorted.addSorted (sorter, types.getUnchecked(i));
  24423. }
  24424. if (sortMethod == sortByCategory
  24425. || sortMethod == sortByManufacturer)
  24426. {
  24427. String lastSubMenuName;
  24428. PopupMenu sub;
  24429. for (int i = 0; i < sorted.size(); ++i)
  24430. {
  24431. const PluginDescription* const pd = sorted.getUnchecked(i);
  24432. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24433. : pd->manufacturerName);
  24434. if (! thisSubMenuName.containsNonWhitespaceChars())
  24435. thisSubMenuName = "Other";
  24436. if (thisSubMenuName != lastSubMenuName)
  24437. {
  24438. if (sub.getNumItems() > 0)
  24439. {
  24440. menu.addSubMenu (lastSubMenuName, sub);
  24441. sub.clear();
  24442. }
  24443. lastSubMenuName = thisSubMenuName;
  24444. }
  24445. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24446. }
  24447. if (sub.getNumItems() > 0)
  24448. menu.addSubMenu (lastSubMenuName, sub);
  24449. }
  24450. else if (sortMethod == sortByFileSystemLocation)
  24451. {
  24452. PluginFilesystemTree root;
  24453. root.buildTree (sorted);
  24454. root.addToMenu (menu, types);
  24455. }
  24456. else
  24457. {
  24458. for (int i = 0; i < sorted.size(); ++i)
  24459. {
  24460. const PluginDescription* const pd = sorted.getUnchecked(i);
  24461. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24462. }
  24463. }
  24464. }
  24465. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24466. {
  24467. const int i = menuResultCode - menuIdBase;
  24468. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24469. }
  24470. END_JUCE_NAMESPACE
  24471. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24472. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24473. BEGIN_JUCE_NAMESPACE
  24474. PluginDescription::PluginDescription()
  24475. : uid (0),
  24476. isInstrument (false),
  24477. numInputChannels (0),
  24478. numOutputChannels (0)
  24479. {
  24480. }
  24481. PluginDescription::~PluginDescription()
  24482. {
  24483. }
  24484. PluginDescription::PluginDescription (const PluginDescription& other)
  24485. : name (other.name),
  24486. descriptiveName (other.descriptiveName),
  24487. pluginFormatName (other.pluginFormatName),
  24488. category (other.category),
  24489. manufacturerName (other.manufacturerName),
  24490. version (other.version),
  24491. fileOrIdentifier (other.fileOrIdentifier),
  24492. lastFileModTime (other.lastFileModTime),
  24493. uid (other.uid),
  24494. isInstrument (other.isInstrument),
  24495. numInputChannels (other.numInputChannels),
  24496. numOutputChannels (other.numOutputChannels)
  24497. {
  24498. }
  24499. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24500. {
  24501. name = other.name;
  24502. descriptiveName = other.descriptiveName;
  24503. pluginFormatName = other.pluginFormatName;
  24504. category = other.category;
  24505. manufacturerName = other.manufacturerName;
  24506. version = other.version;
  24507. fileOrIdentifier = other.fileOrIdentifier;
  24508. uid = other.uid;
  24509. isInstrument = other.isInstrument;
  24510. lastFileModTime = other.lastFileModTime;
  24511. numInputChannels = other.numInputChannels;
  24512. numOutputChannels = other.numOutputChannels;
  24513. return *this;
  24514. }
  24515. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24516. {
  24517. return fileOrIdentifier == other.fileOrIdentifier
  24518. && uid == other.uid;
  24519. }
  24520. const String PluginDescription::createIdentifierString() const
  24521. {
  24522. return pluginFormatName
  24523. + "-" + name
  24524. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24525. + "-" + String::toHexString (uid);
  24526. }
  24527. XmlElement* PluginDescription::createXml() const
  24528. {
  24529. XmlElement* const e = new XmlElement ("PLUGIN");
  24530. e->setAttribute ("name", name);
  24531. if (descriptiveName != name)
  24532. e->setAttribute ("descriptiveName", descriptiveName);
  24533. e->setAttribute ("format", pluginFormatName);
  24534. e->setAttribute ("category", category);
  24535. e->setAttribute ("manufacturer", manufacturerName);
  24536. e->setAttribute ("version", version);
  24537. e->setAttribute ("file", fileOrIdentifier);
  24538. e->setAttribute ("uid", String::toHexString (uid));
  24539. e->setAttribute ("isInstrument", isInstrument);
  24540. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24541. e->setAttribute ("numInputs", numInputChannels);
  24542. e->setAttribute ("numOutputs", numOutputChannels);
  24543. return e;
  24544. }
  24545. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24546. {
  24547. if (xml.hasTagName ("PLUGIN"))
  24548. {
  24549. name = xml.getStringAttribute ("name");
  24550. descriptiveName = xml.getStringAttribute ("name", name);
  24551. pluginFormatName = xml.getStringAttribute ("format");
  24552. category = xml.getStringAttribute ("category");
  24553. manufacturerName = xml.getStringAttribute ("manufacturer");
  24554. version = xml.getStringAttribute ("version");
  24555. fileOrIdentifier = xml.getStringAttribute ("file");
  24556. uid = xml.getStringAttribute ("uid").getHexValue32();
  24557. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24558. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24559. numInputChannels = xml.getIntAttribute ("numInputs");
  24560. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24561. return true;
  24562. }
  24563. return false;
  24564. }
  24565. END_JUCE_NAMESPACE
  24566. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24567. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24568. BEGIN_JUCE_NAMESPACE
  24569. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24570. AudioPluginFormat& formatToLookFor,
  24571. FileSearchPath directoriesToSearch,
  24572. const bool recursive,
  24573. const File& deadMansPedalFile_)
  24574. : list (listToAddTo),
  24575. format (formatToLookFor),
  24576. deadMansPedalFile (deadMansPedalFile_),
  24577. nextIndex (0),
  24578. progress (0)
  24579. {
  24580. directoriesToSearch.removeRedundantPaths();
  24581. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24582. // If any plugins have crashed recently when being loaded, move them to the
  24583. // end of the list to give the others a chance to load correctly..
  24584. const StringArray crashedPlugins (getDeadMansPedalFile());
  24585. for (int i = 0; i < crashedPlugins.size(); ++i)
  24586. {
  24587. const String f = crashedPlugins[i];
  24588. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24589. if (f == filesOrIdentifiersToScan[j])
  24590. filesOrIdentifiersToScan.move (j, -1);
  24591. }
  24592. }
  24593. PluginDirectoryScanner::~PluginDirectoryScanner()
  24594. {
  24595. }
  24596. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24597. {
  24598. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24599. }
  24600. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24601. {
  24602. String file (filesOrIdentifiersToScan [nextIndex]);
  24603. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24604. {
  24605. OwnedArray <PluginDescription> typesFound;
  24606. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24607. StringArray crashedPlugins (getDeadMansPedalFile());
  24608. crashedPlugins.removeString (file);
  24609. crashedPlugins.add (file);
  24610. setDeadMansPedalFile (crashedPlugins);
  24611. list.scanAndAddFile (file,
  24612. dontRescanIfAlreadyInList,
  24613. typesFound,
  24614. format);
  24615. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24616. crashedPlugins.removeString (file);
  24617. setDeadMansPedalFile (crashedPlugins);
  24618. if (typesFound.size() == 0)
  24619. failedFiles.add (file);
  24620. }
  24621. return skipNextFile();
  24622. }
  24623. bool PluginDirectoryScanner::skipNextFile()
  24624. {
  24625. if (nextIndex >= filesOrIdentifiersToScan.size())
  24626. return false;
  24627. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24628. return nextIndex < filesOrIdentifiersToScan.size();
  24629. }
  24630. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24631. {
  24632. StringArray lines;
  24633. if (deadMansPedalFile != File::nonexistent)
  24634. {
  24635. lines.addLines (deadMansPedalFile.loadFileAsString());
  24636. lines.removeEmptyStrings();
  24637. }
  24638. return lines;
  24639. }
  24640. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24641. {
  24642. if (deadMansPedalFile != File::nonexistent)
  24643. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24644. }
  24645. END_JUCE_NAMESPACE
  24646. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24647. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24648. BEGIN_JUCE_NAMESPACE
  24649. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24650. const File& deadMansPedalFile_,
  24651. PropertiesFile* const propertiesToUse_)
  24652. : list (listToEdit),
  24653. deadMansPedalFile (deadMansPedalFile_),
  24654. optionsButton ("Options..."),
  24655. propertiesToUse (propertiesToUse_)
  24656. {
  24657. listBox.setModel (this);
  24658. addAndMakeVisible (&listBox);
  24659. addAndMakeVisible (&optionsButton);
  24660. optionsButton.addListener (this);
  24661. optionsButton.setTriggeredOnMouseDown (true);
  24662. setSize (400, 600);
  24663. list.addChangeListener (this);
  24664. changeListenerCallback (0);
  24665. }
  24666. PluginListComponent::~PluginListComponent()
  24667. {
  24668. list.removeChangeListener (this);
  24669. }
  24670. void PluginListComponent::resized()
  24671. {
  24672. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24673. optionsButton.changeWidthToFitText (24);
  24674. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24675. }
  24676. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24677. {
  24678. listBox.updateContent();
  24679. listBox.repaint();
  24680. }
  24681. int PluginListComponent::getNumRows()
  24682. {
  24683. return list.getNumTypes();
  24684. }
  24685. void PluginListComponent::paintListBoxItem (int row,
  24686. Graphics& g,
  24687. int width, int height,
  24688. bool rowIsSelected)
  24689. {
  24690. if (rowIsSelected)
  24691. g.fillAll (findColour (TextEditor::highlightColourId));
  24692. const PluginDescription* const pd = list.getType (row);
  24693. if (pd != 0)
  24694. {
  24695. GlyphArrangement ga;
  24696. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24697. g.setColour (Colours::black);
  24698. ga.draw (g);
  24699. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24700. String desc;
  24701. desc << pd->pluginFormatName
  24702. << (pd->isInstrument ? " instrument" : " effect")
  24703. << " - "
  24704. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24705. << " / "
  24706. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24707. if (pd->manufacturerName.isNotEmpty())
  24708. desc << " - " << pd->manufacturerName;
  24709. if (pd->version.isNotEmpty())
  24710. desc << " - " << pd->version;
  24711. if (pd->category.isNotEmpty())
  24712. desc << " - category: '" << pd->category << '\'';
  24713. g.setColour (Colours::grey);
  24714. ga.clear();
  24715. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24716. ga.draw (g);
  24717. }
  24718. }
  24719. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24720. {
  24721. list.removeType (lastRowSelected);
  24722. }
  24723. void PluginListComponent::buttonClicked (Button* button)
  24724. {
  24725. if (button == &optionsButton)
  24726. {
  24727. PopupMenu menu;
  24728. menu.addItem (1, TRANS("Clear list"));
  24729. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24730. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24731. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24732. menu.addSeparator();
  24733. menu.addItem (2, TRANS("Sort alphabetically"));
  24734. menu.addItem (3, TRANS("Sort by category"));
  24735. menu.addItem (4, TRANS("Sort by manufacturer"));
  24736. menu.addSeparator();
  24737. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24738. {
  24739. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24740. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24741. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24742. }
  24743. const int r = menu.showAt (&optionsButton);
  24744. if (r == 1)
  24745. {
  24746. list.clear();
  24747. }
  24748. else if (r == 2)
  24749. {
  24750. list.sort (KnownPluginList::sortAlphabetically);
  24751. }
  24752. else if (r == 3)
  24753. {
  24754. list.sort (KnownPluginList::sortByCategory);
  24755. }
  24756. else if (r == 4)
  24757. {
  24758. list.sort (KnownPluginList::sortByManufacturer);
  24759. }
  24760. else if (r == 5)
  24761. {
  24762. const SparseSet <int> selected (listBox.getSelectedRows());
  24763. for (int i = list.getNumTypes(); --i >= 0;)
  24764. if (selected.contains (i))
  24765. list.removeType (i);
  24766. }
  24767. else if (r == 6)
  24768. {
  24769. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24770. if (desc != 0)
  24771. {
  24772. if (File (desc->fileOrIdentifier).existsAsFile())
  24773. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24774. }
  24775. }
  24776. else if (r == 7)
  24777. {
  24778. for (int i = list.getNumTypes(); --i >= 0;)
  24779. {
  24780. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24781. {
  24782. list.removeType (i);
  24783. }
  24784. }
  24785. }
  24786. else if (r != 0)
  24787. {
  24788. typeToScan = r - 10;
  24789. startTimer (1);
  24790. }
  24791. }
  24792. }
  24793. void PluginListComponent::timerCallback()
  24794. {
  24795. stopTimer();
  24796. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24797. }
  24798. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24799. {
  24800. return true;
  24801. }
  24802. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24803. {
  24804. OwnedArray <PluginDescription> typesFound;
  24805. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24806. }
  24807. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24808. {
  24809. if (format == 0)
  24810. return;
  24811. FileSearchPath path (format->getDefaultLocationsToSearch());
  24812. if (propertiesToUse != 0)
  24813. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24814. {
  24815. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24816. FileSearchPathListComponent pathList;
  24817. pathList.setSize (500, 300);
  24818. pathList.setPath (path);
  24819. aw.addCustomComponent (&pathList);
  24820. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24821. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24822. if (aw.runModalLoop() == 0)
  24823. return;
  24824. path = pathList.getPath();
  24825. }
  24826. if (propertiesToUse != 0)
  24827. {
  24828. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24829. propertiesToUse->saveIfNeeded();
  24830. }
  24831. double progress = 0.0;
  24832. AlertWindow aw (TRANS("Scanning for plugins..."),
  24833. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24834. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24835. aw.addProgressBarComponent (progress);
  24836. aw.enterModalState();
  24837. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24838. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24839. for (;;)
  24840. {
  24841. aw.setMessage (TRANS("Testing:\n\n")
  24842. + scanner.getNextPluginFileThatWillBeScanned());
  24843. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24844. if (! scanner.scanNextFile (true))
  24845. break;
  24846. if (! aw.isCurrentlyModal())
  24847. break;
  24848. progress = scanner.getProgress();
  24849. }
  24850. if (scanner.getFailedFiles().size() > 0)
  24851. {
  24852. StringArray shortNames;
  24853. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24854. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24855. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24856. TRANS("Scan complete"),
  24857. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24858. + shortNames.joinIntoString (", "));
  24859. }
  24860. }
  24861. END_JUCE_NAMESPACE
  24862. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24863. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24864. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24865. #include <AudioUnit/AudioUnit.h>
  24866. #include <AudioUnit/AUCocoaUIView.h>
  24867. #include <CoreAudioKit/AUGenericView.h>
  24868. #if JUCE_SUPPORT_CARBON
  24869. #include <AudioToolbox/AudioUnitUtilities.h>
  24870. #include <AudioUnit/AudioUnitCarbonView.h>
  24871. #endif
  24872. BEGIN_JUCE_NAMESPACE
  24873. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24874. #endif
  24875. #if JUCE_MAC
  24876. // Change this to disable logging of various activities
  24877. #ifndef AU_LOGGING
  24878. #define AU_LOGGING 1
  24879. #endif
  24880. #if AU_LOGGING
  24881. #define log(a) Logger::writeToLog(a);
  24882. #else
  24883. #define log(a)
  24884. #endif
  24885. namespace AudioUnitFormatHelpers
  24886. {
  24887. static int insideCallback = 0;
  24888. const String osTypeToString (OSType type)
  24889. {
  24890. char s[4];
  24891. s[0] = (char) (((uint32) type) >> 24);
  24892. s[1] = (char) (((uint32) type) >> 16);
  24893. s[2] = (char) (((uint32) type) >> 8);
  24894. s[3] = (char) ((uint32) type);
  24895. return String (s, 4);
  24896. }
  24897. OSType stringToOSType (const String& s1)
  24898. {
  24899. const String s (s1 + " ");
  24900. return (((OSType) (unsigned char) s[0]) << 24)
  24901. | (((OSType) (unsigned char) s[1]) << 16)
  24902. | (((OSType) (unsigned char) s[2]) << 8)
  24903. | ((OSType) (unsigned char) s[3]);
  24904. }
  24905. static const char* auIdentifierPrefix = "AudioUnit:";
  24906. const String createAUPluginIdentifier (const ComponentDescription& desc)
  24907. {
  24908. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24909. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24910. String s (auIdentifierPrefix);
  24911. if (desc.componentType == kAudioUnitType_MusicDevice)
  24912. s << "Synths/";
  24913. else if (desc.componentType == kAudioUnitType_MusicEffect
  24914. || desc.componentType == kAudioUnitType_Effect)
  24915. s << "Effects/";
  24916. else if (desc.componentType == kAudioUnitType_Generator)
  24917. s << "Generators/";
  24918. else if (desc.componentType == kAudioUnitType_Panner)
  24919. s << "Panners/";
  24920. s << osTypeToString (desc.componentType) << ","
  24921. << osTypeToString (desc.componentSubType) << ","
  24922. << osTypeToString (desc.componentManufacturer);
  24923. return s;
  24924. }
  24925. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24926. {
  24927. Handle componentNameHandle = NewHandle (sizeof (void*));
  24928. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24929. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24930. {
  24931. ComponentDescription desc;
  24932. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24933. {
  24934. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24935. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24936. if (nameString != 0 && nameString[0] != 0)
  24937. {
  24938. const String all ((const char*) nameString + 1, nameString[0]);
  24939. DBG ("name: "+ all);
  24940. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24941. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24942. }
  24943. if (infoString != 0 && infoString[0] != 0)
  24944. {
  24945. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24946. }
  24947. if (name.isEmpty())
  24948. name = "<Unknown>";
  24949. }
  24950. DisposeHandle (componentNameHandle);
  24951. DisposeHandle (componentInfoHandle);
  24952. }
  24953. }
  24954. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24955. String& name, String& version, String& manufacturer)
  24956. {
  24957. zerostruct (desc);
  24958. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24959. {
  24960. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24961. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24962. StringArray tokens;
  24963. tokens.addTokens (s, ",", String::empty);
  24964. tokens.trim();
  24965. tokens.removeEmptyStrings();
  24966. if (tokens.size() == 3)
  24967. {
  24968. desc.componentType = stringToOSType (tokens[0]);
  24969. desc.componentSubType = stringToOSType (tokens[1]);
  24970. desc.componentManufacturer = stringToOSType (tokens[2]);
  24971. ComponentRecord* comp = FindNextComponent (0, &desc);
  24972. if (comp != 0)
  24973. {
  24974. getAUDetails (comp, name, manufacturer);
  24975. return true;
  24976. }
  24977. }
  24978. }
  24979. return false;
  24980. }
  24981. }
  24982. class AudioUnitPluginWindowCarbon;
  24983. class AudioUnitPluginWindowCocoa;
  24984. class AudioUnitPluginInstance : public AudioPluginInstance
  24985. {
  24986. public:
  24987. ~AudioUnitPluginInstance();
  24988. void initialise();
  24989. // AudioPluginInstance methods:
  24990. void fillInPluginDescription (PluginDescription& desc) const
  24991. {
  24992. desc.name = pluginName;
  24993. desc.descriptiveName = pluginName;
  24994. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24995. desc.uid = ((int) componentDesc.componentType)
  24996. ^ ((int) componentDesc.componentSubType)
  24997. ^ ((int) componentDesc.componentManufacturer);
  24998. desc.lastFileModTime = Time();
  24999. desc.pluginFormatName = "AudioUnit";
  25000. desc.category = getCategory();
  25001. desc.manufacturerName = manufacturer;
  25002. desc.version = version;
  25003. desc.numInputChannels = getNumInputChannels();
  25004. desc.numOutputChannels = getNumOutputChannels();
  25005. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25006. }
  25007. void* getPlatformSpecificData() { return audioUnit; }
  25008. const String getName() const { return pluginName; }
  25009. bool acceptsMidi() const { return wantsMidiMessages; }
  25010. bool producesMidi() const { return false; }
  25011. // AudioProcessor methods:
  25012. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25013. void releaseResources();
  25014. void processBlock (AudioSampleBuffer& buffer,
  25015. MidiBuffer& midiMessages);
  25016. bool hasEditor() const;
  25017. AudioProcessorEditor* createEditor();
  25018. const String getInputChannelName (int index) const;
  25019. bool isInputChannelStereoPair (int index) const;
  25020. const String getOutputChannelName (int index) const;
  25021. bool isOutputChannelStereoPair (int index) const;
  25022. int getNumParameters();
  25023. float getParameter (int index);
  25024. void setParameter (int index, float newValue);
  25025. const String getParameterName (int index);
  25026. const String getParameterText (int index);
  25027. bool isParameterAutomatable (int index) const;
  25028. int getNumPrograms();
  25029. int getCurrentProgram();
  25030. void setCurrentProgram (int index);
  25031. const String getProgramName (int index);
  25032. void changeProgramName (int index, const String& newName);
  25033. void getStateInformation (MemoryBlock& destData);
  25034. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25035. void setStateInformation (const void* data, int sizeInBytes);
  25036. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25037. private:
  25038. friend class AudioUnitPluginWindowCarbon;
  25039. friend class AudioUnitPluginWindowCocoa;
  25040. friend class AudioUnitPluginFormat;
  25041. ComponentDescription componentDesc;
  25042. String pluginName, manufacturer, version;
  25043. String fileOrIdentifier;
  25044. CriticalSection lock;
  25045. bool wantsMidiMessages, wasPlaying, prepared;
  25046. HeapBlock <AudioBufferList> outputBufferList;
  25047. AudioTimeStamp timeStamp;
  25048. AudioSampleBuffer* currentBuffer;
  25049. AudioUnit audioUnit;
  25050. Array <int> parameterIds;
  25051. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25052. void setPluginCallbacks();
  25053. void getParameterListFromPlugin();
  25054. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25055. const AudioTimeStamp* inTimeStamp,
  25056. UInt32 inBusNumber,
  25057. UInt32 inNumberFrames,
  25058. AudioBufferList* ioData) const;
  25059. static OSStatus renderGetInputCallback (void* inRefCon,
  25060. AudioUnitRenderActionFlags* ioActionFlags,
  25061. const AudioTimeStamp* inTimeStamp,
  25062. UInt32 inBusNumber,
  25063. UInt32 inNumberFrames,
  25064. AudioBufferList* ioData)
  25065. {
  25066. return ((AudioUnitPluginInstance*) inRefCon)
  25067. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25068. }
  25069. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25070. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25071. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25072. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25073. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25074. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25075. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25076. {
  25077. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25078. }
  25079. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25080. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25081. Float64* outCurrentMeasureDownBeat)
  25082. {
  25083. return ((AudioUnitPluginInstance*) inHostUserData)
  25084. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25085. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25086. }
  25087. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25088. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25089. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25090. {
  25091. return ((AudioUnitPluginInstance*) inHostUserData)
  25092. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25093. outCurrentSampleInTimeLine, outIsCycling,
  25094. outCycleStartBeat, outCycleEndBeat);
  25095. }
  25096. void getNumChannels (int& numIns, int& numOuts)
  25097. {
  25098. numIns = 0;
  25099. numOuts = 0;
  25100. AUChannelInfo supportedChannels [128];
  25101. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25102. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25103. 0, supportedChannels, &supportedChannelsSize) == noErr
  25104. && supportedChannelsSize > 0)
  25105. {
  25106. int explicitNumIns = 0;
  25107. int explicitNumOuts = 0;
  25108. int maximumNumIns = 0;
  25109. int maximumNumOuts = 0;
  25110. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25111. {
  25112. const int inChannels = (int) supportedChannels[i].inChannels;
  25113. const int outChannels = (int) supportedChannels[i].outChannels;
  25114. if (inChannels < 0)
  25115. maximumNumIns = jmin (maximumNumIns, inChannels);
  25116. else
  25117. explicitNumIns = jmax (explicitNumIns, inChannels);
  25118. if (outChannels < 0)
  25119. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25120. else
  25121. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25122. }
  25123. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25124. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25125. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25126. {
  25127. numIns = numOuts = 2;
  25128. }
  25129. else
  25130. {
  25131. numIns = explicitNumIns;
  25132. numOuts = explicitNumOuts;
  25133. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25134. numIns = 2;
  25135. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25136. numOuts = 2;
  25137. }
  25138. }
  25139. else
  25140. {
  25141. // (this really means the plugin will take any number of ins/outs as long
  25142. // as they are the same)
  25143. numIns = numOuts = 2;
  25144. }
  25145. }
  25146. const String getCategory() const;
  25147. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25148. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25149. };
  25150. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25151. : fileOrIdentifier (fileOrIdentifier),
  25152. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25153. currentBuffer (0),
  25154. audioUnit (0)
  25155. {
  25156. using namespace AudioUnitFormatHelpers;
  25157. try
  25158. {
  25159. ++insideCallback;
  25160. log ("Opening AU: " + fileOrIdentifier);
  25161. if (getComponentDescFromFile (fileOrIdentifier))
  25162. {
  25163. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25164. if (comp != 0)
  25165. {
  25166. audioUnit = (AudioUnit) OpenComponent (comp);
  25167. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25168. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25169. }
  25170. }
  25171. --insideCallback;
  25172. }
  25173. catch (...)
  25174. {
  25175. --insideCallback;
  25176. }
  25177. }
  25178. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25179. {
  25180. const ScopedLock sl (lock);
  25181. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25182. if (audioUnit != 0)
  25183. {
  25184. AudioUnitUninitialize (audioUnit);
  25185. CloseComponent (audioUnit);
  25186. audioUnit = 0;
  25187. }
  25188. }
  25189. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25190. {
  25191. zerostruct (componentDesc);
  25192. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25193. return true;
  25194. const File file (fileOrIdentifier);
  25195. if (! file.hasFileExtension (".component"))
  25196. return false;
  25197. const char* const utf8 = fileOrIdentifier.toUTF8();
  25198. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25199. strlen (utf8), file.isDirectory());
  25200. if (url != 0)
  25201. {
  25202. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25203. CFRelease (url);
  25204. if (bundleRef != 0)
  25205. {
  25206. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25207. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25208. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25209. if (pluginName.isEmpty())
  25210. pluginName = file.getFileNameWithoutExtension();
  25211. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25212. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25213. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25214. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25215. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25216. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25217. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25218. UseResFile (resFileId);
  25219. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25220. {
  25221. Handle h = Get1IndResource ('thng', i);
  25222. if (h != 0)
  25223. {
  25224. HLock (h);
  25225. const uint32* const types = (const uint32*) *h;
  25226. if (types[0] == kAudioUnitType_MusicDevice
  25227. || types[0] == kAudioUnitType_MusicEffect
  25228. || types[0] == kAudioUnitType_Effect
  25229. || types[0] == kAudioUnitType_Generator
  25230. || types[0] == kAudioUnitType_Panner)
  25231. {
  25232. componentDesc.componentType = types[0];
  25233. componentDesc.componentSubType = types[1];
  25234. componentDesc.componentManufacturer = types[2];
  25235. break;
  25236. }
  25237. HUnlock (h);
  25238. ReleaseResource (h);
  25239. }
  25240. }
  25241. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25242. CFRelease (bundleRef);
  25243. }
  25244. }
  25245. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25246. }
  25247. void AudioUnitPluginInstance::initialise()
  25248. {
  25249. getParameterListFromPlugin();
  25250. setPluginCallbacks();
  25251. int numIns, numOuts;
  25252. getNumChannels (numIns, numOuts);
  25253. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25254. setLatencySamples (0);
  25255. }
  25256. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25257. {
  25258. parameterIds.clear();
  25259. if (audioUnit != 0)
  25260. {
  25261. UInt32 paramListSize = 0;
  25262. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25263. 0, 0, &paramListSize);
  25264. if (paramListSize > 0)
  25265. {
  25266. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25267. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25268. 0, &parameterIds.getReference(0), &paramListSize);
  25269. }
  25270. }
  25271. }
  25272. void AudioUnitPluginInstance::setPluginCallbacks()
  25273. {
  25274. if (audioUnit != 0)
  25275. {
  25276. {
  25277. AURenderCallbackStruct info;
  25278. zerostruct (info);
  25279. info.inputProcRefCon = this;
  25280. info.inputProc = renderGetInputCallback;
  25281. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25282. 0, &info, sizeof (info));
  25283. }
  25284. {
  25285. HostCallbackInfo info;
  25286. zerostruct (info);
  25287. info.hostUserData = this;
  25288. info.beatAndTempoProc = getBeatAndTempoCallback;
  25289. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25290. info.transportStateProc = getTransportStateCallback;
  25291. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25292. 0, &info, sizeof (info));
  25293. }
  25294. }
  25295. }
  25296. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25297. int samplesPerBlockExpected)
  25298. {
  25299. if (audioUnit != 0)
  25300. {
  25301. releaseResources();
  25302. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25303. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25304. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25305. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25306. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25307. {
  25308. Float64 sr = sampleRate_;
  25309. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25310. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25311. }
  25312. int numIns, numOuts;
  25313. getNumChannels (numIns, numOuts);
  25314. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25315. Float64 latencySecs = 0.0;
  25316. UInt32 latencySize = sizeof (latencySecs);
  25317. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25318. 0, &latencySecs, &latencySize);
  25319. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25320. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25321. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25322. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25323. {
  25324. AudioStreamBasicDescription stream;
  25325. zerostruct (stream);
  25326. stream.mSampleRate = sampleRate_;
  25327. stream.mFormatID = kAudioFormatLinearPCM;
  25328. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25329. stream.mFramesPerPacket = 1;
  25330. stream.mBytesPerPacket = 4;
  25331. stream.mBytesPerFrame = 4;
  25332. stream.mBitsPerChannel = 32;
  25333. stream.mChannelsPerFrame = numIns;
  25334. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25335. 0, &stream, sizeof (stream));
  25336. stream.mChannelsPerFrame = numOuts;
  25337. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25338. 0, &stream, sizeof (stream));
  25339. }
  25340. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25341. outputBufferList->mNumberBuffers = numOuts;
  25342. for (int i = numOuts; --i >= 0;)
  25343. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25344. zerostruct (timeStamp);
  25345. timeStamp.mSampleTime = 0;
  25346. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25347. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25348. currentBuffer = 0;
  25349. wasPlaying = false;
  25350. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25351. }
  25352. }
  25353. void AudioUnitPluginInstance::releaseResources()
  25354. {
  25355. if (prepared)
  25356. {
  25357. AudioUnitUninitialize (audioUnit);
  25358. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25359. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25360. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25361. outputBufferList.free();
  25362. currentBuffer = 0;
  25363. prepared = false;
  25364. }
  25365. }
  25366. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25367. const AudioTimeStamp* inTimeStamp,
  25368. UInt32 inBusNumber,
  25369. UInt32 inNumberFrames,
  25370. AudioBufferList* ioData) const
  25371. {
  25372. if (inBusNumber == 0
  25373. && currentBuffer != 0)
  25374. {
  25375. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25376. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25377. {
  25378. if (i < currentBuffer->getNumChannels())
  25379. {
  25380. memcpy (ioData->mBuffers[i].mData,
  25381. currentBuffer->getSampleData (i, 0),
  25382. sizeof (float) * inNumberFrames);
  25383. }
  25384. else
  25385. {
  25386. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25387. }
  25388. }
  25389. }
  25390. return noErr;
  25391. }
  25392. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25393. MidiBuffer& midiMessages)
  25394. {
  25395. const int numSamples = buffer.getNumSamples();
  25396. if (prepared)
  25397. {
  25398. AudioUnitRenderActionFlags flags = 0;
  25399. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25400. for (int i = getNumOutputChannels(); --i >= 0;)
  25401. {
  25402. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25403. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25404. }
  25405. currentBuffer = &buffer;
  25406. if (wantsMidiMessages)
  25407. {
  25408. const uint8* midiEventData;
  25409. int midiEventSize, midiEventPosition;
  25410. MidiBuffer::Iterator i (midiMessages);
  25411. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25412. {
  25413. if (midiEventSize <= 3)
  25414. MusicDeviceMIDIEvent (audioUnit,
  25415. midiEventData[0], midiEventData[1], midiEventData[2],
  25416. midiEventPosition);
  25417. else
  25418. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25419. }
  25420. midiMessages.clear();
  25421. }
  25422. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25423. 0, numSamples, outputBufferList);
  25424. timeStamp.mSampleTime += numSamples;
  25425. }
  25426. else
  25427. {
  25428. // Plugin not working correctly, so just bypass..
  25429. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25430. buffer.clear (i, 0, buffer.getNumSamples());
  25431. }
  25432. }
  25433. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25434. {
  25435. AudioPlayHead* const ph = getPlayHead();
  25436. AudioPlayHead::CurrentPositionInfo result;
  25437. if (ph != 0 && ph->getCurrentPosition (result))
  25438. {
  25439. if (outCurrentBeat != 0)
  25440. *outCurrentBeat = result.ppqPosition;
  25441. if (outCurrentTempo != 0)
  25442. *outCurrentTempo = result.bpm;
  25443. }
  25444. else
  25445. {
  25446. if (outCurrentBeat != 0)
  25447. *outCurrentBeat = 0;
  25448. if (outCurrentTempo != 0)
  25449. *outCurrentTempo = 120.0;
  25450. }
  25451. return noErr;
  25452. }
  25453. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25454. Float32* outTimeSig_Numerator,
  25455. UInt32* outTimeSig_Denominator,
  25456. Float64* outCurrentMeasureDownBeat) const
  25457. {
  25458. AudioPlayHead* const ph = getPlayHead();
  25459. AudioPlayHead::CurrentPositionInfo result;
  25460. if (ph != 0 && ph->getCurrentPosition (result))
  25461. {
  25462. if (outTimeSig_Numerator != 0)
  25463. *outTimeSig_Numerator = result.timeSigNumerator;
  25464. if (outTimeSig_Denominator != 0)
  25465. *outTimeSig_Denominator = result.timeSigDenominator;
  25466. if (outDeltaSampleOffsetToNextBeat != 0)
  25467. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25468. if (outCurrentMeasureDownBeat != 0)
  25469. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25470. }
  25471. else
  25472. {
  25473. if (outDeltaSampleOffsetToNextBeat != 0)
  25474. *outDeltaSampleOffsetToNextBeat = 0;
  25475. if (outTimeSig_Numerator != 0)
  25476. *outTimeSig_Numerator = 4;
  25477. if (outTimeSig_Denominator != 0)
  25478. *outTimeSig_Denominator = 4;
  25479. if (outCurrentMeasureDownBeat != 0)
  25480. *outCurrentMeasureDownBeat = 0;
  25481. }
  25482. return noErr;
  25483. }
  25484. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25485. Boolean* outTransportStateChanged,
  25486. Float64* outCurrentSampleInTimeLine,
  25487. Boolean* outIsCycling,
  25488. Float64* outCycleStartBeat,
  25489. Float64* outCycleEndBeat)
  25490. {
  25491. AudioPlayHead* const ph = getPlayHead();
  25492. AudioPlayHead::CurrentPositionInfo result;
  25493. if (ph != 0 && ph->getCurrentPosition (result))
  25494. {
  25495. if (outIsPlaying != 0)
  25496. *outIsPlaying = result.isPlaying;
  25497. if (outTransportStateChanged != 0)
  25498. {
  25499. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25500. wasPlaying = result.isPlaying;
  25501. }
  25502. if (outCurrentSampleInTimeLine != 0)
  25503. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25504. if (outIsCycling != 0)
  25505. *outIsCycling = false;
  25506. if (outCycleStartBeat != 0)
  25507. *outCycleStartBeat = 0;
  25508. if (outCycleEndBeat != 0)
  25509. *outCycleEndBeat = 0;
  25510. }
  25511. else
  25512. {
  25513. if (outIsPlaying != 0)
  25514. *outIsPlaying = false;
  25515. if (outTransportStateChanged != 0)
  25516. *outTransportStateChanged = false;
  25517. if (outCurrentSampleInTimeLine != 0)
  25518. *outCurrentSampleInTimeLine = 0;
  25519. if (outIsCycling != 0)
  25520. *outIsCycling = false;
  25521. if (outCycleStartBeat != 0)
  25522. *outCycleStartBeat = 0;
  25523. if (outCycleEndBeat != 0)
  25524. *outCycleEndBeat = 0;
  25525. }
  25526. return noErr;
  25527. }
  25528. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25529. public Timer
  25530. {
  25531. public:
  25532. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25533. : AudioProcessorEditor (&plugin_),
  25534. plugin (plugin_)
  25535. {
  25536. addAndMakeVisible (&wrapper);
  25537. setOpaque (true);
  25538. setVisible (true);
  25539. setSize (100, 100);
  25540. createView (createGenericViewIfNeeded);
  25541. }
  25542. ~AudioUnitPluginWindowCocoa()
  25543. {
  25544. const bool wasValid = isValid();
  25545. wrapper.setView (0);
  25546. if (wasValid)
  25547. plugin.editorBeingDeleted (this);
  25548. }
  25549. bool isValid() const { return wrapper.getView() != 0; }
  25550. void paint (Graphics& g)
  25551. {
  25552. g.fillAll (Colours::white);
  25553. }
  25554. void resized()
  25555. {
  25556. wrapper.setSize (getWidth(), getHeight());
  25557. }
  25558. void timerCallback()
  25559. {
  25560. wrapper.resizeToFitView();
  25561. startTimer (jmin (713, getTimerInterval() + 51));
  25562. }
  25563. void childBoundsChanged (Component* child)
  25564. {
  25565. setSize (wrapper.getWidth(), wrapper.getHeight());
  25566. startTimer (70);
  25567. }
  25568. private:
  25569. AudioUnitPluginInstance& plugin;
  25570. NSViewComponent wrapper;
  25571. bool createView (const bool createGenericViewIfNeeded)
  25572. {
  25573. NSView* pluginView = 0;
  25574. UInt32 dataSize = 0;
  25575. Boolean isWritable = false;
  25576. AudioUnitInitialize (plugin.audioUnit);
  25577. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25578. 0, &dataSize, &isWritable) == noErr
  25579. && dataSize != 0
  25580. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25581. 0, &dataSize, &isWritable) == noErr)
  25582. {
  25583. HeapBlock <AudioUnitCocoaViewInfo> info;
  25584. info.calloc (dataSize, 1);
  25585. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25586. 0, info, &dataSize) == noErr)
  25587. {
  25588. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25589. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25590. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25591. Class viewClass = [viewBundle classNamed: viewClassName];
  25592. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25593. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25594. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25595. {
  25596. id factory = [[[viewClass alloc] init] autorelease];
  25597. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25598. withSize: NSMakeSize (getWidth(), getHeight())];
  25599. }
  25600. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25601. CFRelease (info->mCocoaAUViewClass[i]);
  25602. CFRelease (info->mCocoaAUViewBundleLocation);
  25603. }
  25604. }
  25605. if (createGenericViewIfNeeded && (pluginView == 0))
  25606. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25607. wrapper.setView (pluginView);
  25608. if (pluginView != 0)
  25609. {
  25610. timerCallback();
  25611. startTimer (70);
  25612. }
  25613. return pluginView != 0;
  25614. }
  25615. };
  25616. #if JUCE_SUPPORT_CARBON
  25617. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25618. {
  25619. public:
  25620. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25621. : AudioProcessorEditor (&plugin_),
  25622. plugin (plugin_),
  25623. viewComponent (0)
  25624. {
  25625. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25626. setOpaque (true);
  25627. setVisible (true);
  25628. setSize (400, 300);
  25629. ComponentDescription viewList [16];
  25630. UInt32 viewListSize = sizeof (viewList);
  25631. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25632. 0, &viewList, &viewListSize);
  25633. componentRecord = FindNextComponent (0, &viewList[0]);
  25634. }
  25635. ~AudioUnitPluginWindowCarbon()
  25636. {
  25637. innerWrapper = 0;
  25638. if (isValid())
  25639. plugin.editorBeingDeleted (this);
  25640. }
  25641. bool isValid() const throw() { return componentRecord != 0; }
  25642. void paint (Graphics& g)
  25643. {
  25644. g.fillAll (Colours::black);
  25645. }
  25646. void resized()
  25647. {
  25648. innerWrapper->setSize (getWidth(), getHeight());
  25649. }
  25650. bool keyStateChanged (bool)
  25651. {
  25652. return false;
  25653. }
  25654. bool keyPressed (const KeyPress&)
  25655. {
  25656. return false;
  25657. }
  25658. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25659. AudioUnitCarbonView getViewComponent()
  25660. {
  25661. if (viewComponent == 0 && componentRecord != 0)
  25662. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25663. return viewComponent;
  25664. }
  25665. void closeViewComponent()
  25666. {
  25667. if (viewComponent != 0)
  25668. {
  25669. log ("Closing AU GUI: " + plugin.getName());
  25670. CloseComponent (viewComponent);
  25671. viewComponent = 0;
  25672. }
  25673. }
  25674. private:
  25675. AudioUnitPluginInstance& plugin;
  25676. ComponentRecord* componentRecord;
  25677. AudioUnitCarbonView viewComponent;
  25678. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25679. {
  25680. public:
  25681. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25682. : owner (owner_)
  25683. {
  25684. }
  25685. ~InnerWrapperComponent()
  25686. {
  25687. deleteWindow();
  25688. }
  25689. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25690. {
  25691. log ("Opening AU GUI: " + owner->plugin.getName());
  25692. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25693. if (viewComponent == 0)
  25694. return 0;
  25695. Float32Point pos = { 0, 0 };
  25696. Float32Point size = { 250, 200 };
  25697. HIViewRef pluginView = 0;
  25698. AudioUnitCarbonViewCreate (viewComponent,
  25699. owner->getAudioUnit(),
  25700. windowRef,
  25701. rootView,
  25702. &pos,
  25703. &size,
  25704. (ControlRef*) &pluginView);
  25705. return pluginView;
  25706. }
  25707. void removeView (HIViewRef)
  25708. {
  25709. owner->closeViewComponent();
  25710. }
  25711. private:
  25712. AudioUnitPluginWindowCarbon* const owner;
  25713. };
  25714. friend class InnerWrapperComponent;
  25715. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25716. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25717. };
  25718. #endif
  25719. bool AudioUnitPluginInstance::hasEditor() const
  25720. {
  25721. return true;
  25722. }
  25723. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25724. {
  25725. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25726. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25727. w = 0;
  25728. #if JUCE_SUPPORT_CARBON
  25729. if (w == 0)
  25730. {
  25731. w = new AudioUnitPluginWindowCarbon (*this);
  25732. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25733. w = 0;
  25734. }
  25735. #endif
  25736. if (w == 0)
  25737. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25738. return w.release();
  25739. }
  25740. const String AudioUnitPluginInstance::getCategory() const
  25741. {
  25742. const char* result = 0;
  25743. switch (componentDesc.componentType)
  25744. {
  25745. case kAudioUnitType_Effect:
  25746. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25747. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25748. case kAudioUnitType_Generator: result = "Generator"; break;
  25749. case kAudioUnitType_Panner: result = "Panner"; break;
  25750. default: break;
  25751. }
  25752. return result;
  25753. }
  25754. int AudioUnitPluginInstance::getNumParameters()
  25755. {
  25756. return parameterIds.size();
  25757. }
  25758. float AudioUnitPluginInstance::getParameter (int index)
  25759. {
  25760. const ScopedLock sl (lock);
  25761. Float32 value = 0.0f;
  25762. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25763. {
  25764. AudioUnitGetParameter (audioUnit,
  25765. (UInt32) parameterIds.getUnchecked (index),
  25766. kAudioUnitScope_Global, 0,
  25767. &value);
  25768. }
  25769. return value;
  25770. }
  25771. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25772. {
  25773. const ScopedLock sl (lock);
  25774. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25775. {
  25776. AudioUnitSetParameter (audioUnit,
  25777. (UInt32) parameterIds.getUnchecked (index),
  25778. kAudioUnitScope_Global, 0,
  25779. newValue, 0);
  25780. }
  25781. }
  25782. const String AudioUnitPluginInstance::getParameterName (int index)
  25783. {
  25784. AudioUnitParameterInfo info;
  25785. zerostruct (info);
  25786. UInt32 sz = sizeof (info);
  25787. String name;
  25788. if (AudioUnitGetProperty (audioUnit,
  25789. kAudioUnitProperty_ParameterInfo,
  25790. kAudioUnitScope_Global,
  25791. parameterIds [index], &info, &sz) == noErr)
  25792. {
  25793. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25794. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25795. else
  25796. name = String (info.name, sizeof (info.name));
  25797. }
  25798. return name;
  25799. }
  25800. const String AudioUnitPluginInstance::getParameterText (int index)
  25801. {
  25802. return String (getParameter (index));
  25803. }
  25804. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25805. {
  25806. AudioUnitParameterInfo info;
  25807. UInt32 sz = sizeof (info);
  25808. if (AudioUnitGetProperty (audioUnit,
  25809. kAudioUnitProperty_ParameterInfo,
  25810. kAudioUnitScope_Global,
  25811. parameterIds [index], &info, &sz) == noErr)
  25812. {
  25813. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25814. }
  25815. return true;
  25816. }
  25817. int AudioUnitPluginInstance::getNumPrograms()
  25818. {
  25819. CFArrayRef presets;
  25820. UInt32 sz = sizeof (CFArrayRef);
  25821. int num = 0;
  25822. if (AudioUnitGetProperty (audioUnit,
  25823. kAudioUnitProperty_FactoryPresets,
  25824. kAudioUnitScope_Global,
  25825. 0, &presets, &sz) == noErr)
  25826. {
  25827. num = (int) CFArrayGetCount (presets);
  25828. CFRelease (presets);
  25829. }
  25830. return num;
  25831. }
  25832. int AudioUnitPluginInstance::getCurrentProgram()
  25833. {
  25834. AUPreset current;
  25835. current.presetNumber = 0;
  25836. UInt32 sz = sizeof (AUPreset);
  25837. AudioUnitGetProperty (audioUnit,
  25838. kAudioUnitProperty_FactoryPresets,
  25839. kAudioUnitScope_Global,
  25840. 0, &current, &sz);
  25841. return current.presetNumber;
  25842. }
  25843. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25844. {
  25845. AUPreset current;
  25846. current.presetNumber = newIndex;
  25847. current.presetName = 0;
  25848. AudioUnitSetProperty (audioUnit,
  25849. kAudioUnitProperty_FactoryPresets,
  25850. kAudioUnitScope_Global,
  25851. 0, &current, sizeof (AUPreset));
  25852. }
  25853. const String AudioUnitPluginInstance::getProgramName (int index)
  25854. {
  25855. String s;
  25856. CFArrayRef presets;
  25857. UInt32 sz = sizeof (CFArrayRef);
  25858. if (AudioUnitGetProperty (audioUnit,
  25859. kAudioUnitProperty_FactoryPresets,
  25860. kAudioUnitScope_Global,
  25861. 0, &presets, &sz) == noErr)
  25862. {
  25863. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25864. {
  25865. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25866. if (p != 0 && p->presetNumber == index)
  25867. {
  25868. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25869. break;
  25870. }
  25871. }
  25872. CFRelease (presets);
  25873. }
  25874. return s;
  25875. }
  25876. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25877. {
  25878. jassertfalse; // xxx not implemented!
  25879. }
  25880. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  25881. {
  25882. if (isPositiveAndBelow (index, getNumInputChannels()))
  25883. return "Input " + String (index + 1);
  25884. return String::empty;
  25885. }
  25886. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25887. {
  25888. if (! isPositiveAndBelow (index, getNumInputChannels()))
  25889. return false;
  25890. return true;
  25891. }
  25892. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  25893. {
  25894. if (isPositiveAndBelow (index, getNumOutputChannels()))
  25895. return "Output " + String (index + 1);
  25896. return String::empty;
  25897. }
  25898. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25899. {
  25900. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  25901. return false;
  25902. return true;
  25903. }
  25904. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25905. {
  25906. getCurrentProgramStateInformation (destData);
  25907. }
  25908. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25909. {
  25910. CFPropertyListRef propertyList = 0;
  25911. UInt32 sz = sizeof (CFPropertyListRef);
  25912. if (AudioUnitGetProperty (audioUnit,
  25913. kAudioUnitProperty_ClassInfo,
  25914. kAudioUnitScope_Global,
  25915. 0, &propertyList, &sz) == noErr)
  25916. {
  25917. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25918. CFWriteStreamOpen (stream);
  25919. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25920. CFWriteStreamClose (stream);
  25921. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25922. destData.setSize (bytesWritten);
  25923. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25924. CFRelease (data);
  25925. CFRelease (stream);
  25926. CFRelease (propertyList);
  25927. }
  25928. }
  25929. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25930. {
  25931. setCurrentProgramStateInformation (data, sizeInBytes);
  25932. }
  25933. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25934. {
  25935. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25936. (const UInt8*) data,
  25937. sizeInBytes,
  25938. kCFAllocatorNull);
  25939. CFReadStreamOpen (stream);
  25940. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25941. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25942. stream,
  25943. 0,
  25944. kCFPropertyListImmutable,
  25945. &format,
  25946. 0);
  25947. CFRelease (stream);
  25948. if (propertyList != 0)
  25949. AudioUnitSetProperty (audioUnit,
  25950. kAudioUnitProperty_ClassInfo,
  25951. kAudioUnitScope_Global,
  25952. 0, &propertyList, sizeof (propertyList));
  25953. }
  25954. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25955. {
  25956. }
  25957. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25958. {
  25959. }
  25960. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25961. const String& fileOrIdentifier)
  25962. {
  25963. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25964. return;
  25965. PluginDescription desc;
  25966. desc.fileOrIdentifier = fileOrIdentifier;
  25967. desc.uid = 0;
  25968. try
  25969. {
  25970. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25971. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25972. if (auInstance != 0)
  25973. {
  25974. auInstance->fillInPluginDescription (desc);
  25975. results.add (new PluginDescription (desc));
  25976. }
  25977. }
  25978. catch (...)
  25979. {
  25980. // crashed while loading...
  25981. }
  25982. }
  25983. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25984. {
  25985. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25986. {
  25987. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25988. if (result->audioUnit != 0)
  25989. {
  25990. result->initialise();
  25991. return result.release();
  25992. }
  25993. }
  25994. return 0;
  25995. }
  25996. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25997. const bool /*recursive*/)
  25998. {
  25999. StringArray result;
  26000. ComponentRecord* comp = 0;
  26001. ComponentDescription desc;
  26002. zerostruct (desc);
  26003. for (;;)
  26004. {
  26005. zerostruct (desc);
  26006. comp = FindNextComponent (comp, &desc);
  26007. if (comp == 0)
  26008. break;
  26009. GetComponentInfo (comp, &desc, 0, 0, 0);
  26010. if (desc.componentType == kAudioUnitType_MusicDevice
  26011. || desc.componentType == kAudioUnitType_MusicEffect
  26012. || desc.componentType == kAudioUnitType_Effect
  26013. || desc.componentType == kAudioUnitType_Generator
  26014. || desc.componentType == kAudioUnitType_Panner)
  26015. {
  26016. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26017. DBG (s);
  26018. result.add (s);
  26019. }
  26020. }
  26021. return result;
  26022. }
  26023. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26024. {
  26025. ComponentDescription desc;
  26026. String name, version, manufacturer;
  26027. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26028. return FindNextComponent (0, &desc) != 0;
  26029. const File f (fileOrIdentifier);
  26030. return f.hasFileExtension (".component")
  26031. && f.isDirectory();
  26032. }
  26033. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26034. {
  26035. ComponentDescription desc;
  26036. String name, version, manufacturer;
  26037. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26038. if (name.isEmpty())
  26039. name = fileOrIdentifier;
  26040. return name;
  26041. }
  26042. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26043. {
  26044. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26045. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26046. else
  26047. return File (desc.fileOrIdentifier).exists();
  26048. }
  26049. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26050. {
  26051. return FileSearchPath ("/(Default AudioUnit locations)");
  26052. }
  26053. #endif
  26054. END_JUCE_NAMESPACE
  26055. #undef log
  26056. #endif
  26057. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26058. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26059. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26060. #define JUCE_MAC_VST_INCLUDED 1
  26061. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26062. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26063. #if JUCE_WINDOWS
  26064. #undef _WIN32_WINNT
  26065. #define _WIN32_WINNT 0x500
  26066. #undef STRICT
  26067. #define STRICT
  26068. #include <windows.h>
  26069. #include <float.h>
  26070. #pragma warning (disable : 4312 4355)
  26071. #ifdef __INTEL_COMPILER
  26072. #pragma warning (disable : 1899)
  26073. #endif
  26074. #elif JUCE_LINUX
  26075. #include <float.h>
  26076. #include <sys/time.h>
  26077. #include <X11/Xlib.h>
  26078. #include <X11/Xutil.h>
  26079. #include <X11/Xatom.h>
  26080. #undef Font
  26081. #undef KeyPress
  26082. #undef Drawable
  26083. #undef Time
  26084. #else
  26085. #include <Cocoa/Cocoa.h>
  26086. #include <Carbon/Carbon.h>
  26087. #endif
  26088. #if ! (JUCE_MAC && JUCE_64BIT)
  26089. BEGIN_JUCE_NAMESPACE
  26090. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26091. #endif
  26092. #undef PRAGMA_ALIGN_SUPPORTED
  26093. #define VST_FORCE_DEPRECATED 0
  26094. #if JUCE_MSVC
  26095. #pragma warning (push)
  26096. #pragma warning (disable: 4996)
  26097. #endif
  26098. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26099. your include path if you want to add VST support.
  26100. If you're not interested in VSTs, you can disable them by changing the
  26101. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26102. */
  26103. #include <pluginterfaces/vst2.x/aeffectx.h>
  26104. #if JUCE_MSVC
  26105. #pragma warning (pop)
  26106. #endif
  26107. #if JUCE_LINUX
  26108. #define Font JUCE_NAMESPACE::Font
  26109. #define KeyPress JUCE_NAMESPACE::KeyPress
  26110. #define Drawable JUCE_NAMESPACE::Drawable
  26111. #define Time JUCE_NAMESPACE::Time
  26112. #endif
  26113. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26114. #ifdef __aeffect__
  26115. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26116. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26117. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26118. events to the list.
  26119. This is used by both the VST hosting code and the plugin wrapper.
  26120. */
  26121. class VSTMidiEventList
  26122. {
  26123. public:
  26124. VSTMidiEventList()
  26125. : numEventsUsed (0), numEventsAllocated (0)
  26126. {
  26127. }
  26128. ~VSTMidiEventList()
  26129. {
  26130. freeEvents();
  26131. }
  26132. void clear()
  26133. {
  26134. numEventsUsed = 0;
  26135. if (events != 0)
  26136. events->numEvents = 0;
  26137. }
  26138. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26139. {
  26140. ensureSize (numEventsUsed + 1);
  26141. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26142. events->numEvents = ++numEventsUsed;
  26143. if (numBytes <= 4)
  26144. {
  26145. if (e->type == kVstSysExType)
  26146. {
  26147. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26148. e->type = kVstMidiType;
  26149. e->byteSize = sizeof (VstMidiEvent);
  26150. e->noteLength = 0;
  26151. e->noteOffset = 0;
  26152. e->detune = 0;
  26153. e->noteOffVelocity = 0;
  26154. }
  26155. e->deltaFrames = frameOffset;
  26156. memcpy (e->midiData, midiData, numBytes);
  26157. }
  26158. else
  26159. {
  26160. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26161. if (se->type == kVstSysExType)
  26162. delete[] se->sysexDump;
  26163. se->sysexDump = new char [numBytes];
  26164. memcpy (se->sysexDump, midiData, numBytes);
  26165. se->type = kVstSysExType;
  26166. se->byteSize = sizeof (VstMidiSysexEvent);
  26167. se->deltaFrames = frameOffset;
  26168. se->flags = 0;
  26169. se->dumpBytes = numBytes;
  26170. se->resvd1 = 0;
  26171. se->resvd2 = 0;
  26172. }
  26173. }
  26174. // Handy method to pull the events out of an event buffer supplied by the host
  26175. // or plugin.
  26176. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26177. {
  26178. for (int i = 0; i < events->numEvents; ++i)
  26179. {
  26180. const VstEvent* const e = events->events[i];
  26181. if (e != 0)
  26182. {
  26183. if (e->type == kVstMidiType)
  26184. {
  26185. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26186. 4, e->deltaFrames);
  26187. }
  26188. else if (e->type == kVstSysExType)
  26189. {
  26190. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26191. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26192. e->deltaFrames);
  26193. }
  26194. }
  26195. }
  26196. }
  26197. void ensureSize (int numEventsNeeded)
  26198. {
  26199. if (numEventsNeeded > numEventsAllocated)
  26200. {
  26201. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26202. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26203. if (events == 0)
  26204. events.calloc (size, 1);
  26205. else
  26206. events.realloc (size, 1);
  26207. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26208. {
  26209. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26210. (int) sizeof (VstMidiSysexEvent)));
  26211. e->type = kVstMidiType;
  26212. e->byteSize = sizeof (VstMidiEvent);
  26213. events->events[i] = (VstEvent*) e;
  26214. }
  26215. numEventsAllocated = numEventsNeeded;
  26216. }
  26217. }
  26218. void freeEvents()
  26219. {
  26220. if (events != 0)
  26221. {
  26222. for (int i = numEventsAllocated; --i >= 0;)
  26223. {
  26224. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26225. if (e->type == kVstSysExType)
  26226. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26227. juce_free (e);
  26228. }
  26229. events.free();
  26230. numEventsUsed = 0;
  26231. numEventsAllocated = 0;
  26232. }
  26233. }
  26234. HeapBlock <VstEvents> events;
  26235. private:
  26236. int numEventsUsed, numEventsAllocated;
  26237. };
  26238. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26239. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26240. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26241. #if ! JUCE_WINDOWS
  26242. static void _fpreset() {}
  26243. static void _clearfp() {}
  26244. #endif
  26245. extern void juce_callAnyTimersSynchronously();
  26246. const int fxbVersionNum = 1;
  26247. struct fxProgram
  26248. {
  26249. long chunkMagic; // 'CcnK'
  26250. long byteSize; // of this chunk, excl. magic + byteSize
  26251. long fxMagic; // 'FxCk'
  26252. long version;
  26253. long fxID; // fx unique id
  26254. long fxVersion;
  26255. long numParams;
  26256. char prgName[28];
  26257. float params[1]; // variable no. of parameters
  26258. };
  26259. struct fxSet
  26260. {
  26261. long chunkMagic; // 'CcnK'
  26262. long byteSize; // of this chunk, excl. magic + byteSize
  26263. long fxMagic; // 'FxBk'
  26264. long version;
  26265. long fxID; // fx unique id
  26266. long fxVersion;
  26267. long numPrograms;
  26268. char future[128];
  26269. fxProgram programs[1]; // variable no. of programs
  26270. };
  26271. struct fxChunkSet
  26272. {
  26273. long chunkMagic; // 'CcnK'
  26274. long byteSize; // of this chunk, excl. magic + byteSize
  26275. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26276. long version;
  26277. long fxID; // fx unique id
  26278. long fxVersion;
  26279. long numPrograms;
  26280. char future[128];
  26281. long chunkSize;
  26282. char chunk[8]; // variable
  26283. };
  26284. struct fxProgramSet
  26285. {
  26286. long chunkMagic; // 'CcnK'
  26287. long byteSize; // of this chunk, excl. magic + byteSize
  26288. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26289. long version;
  26290. long fxID; // fx unique id
  26291. long fxVersion;
  26292. long numPrograms;
  26293. char name[28];
  26294. long chunkSize;
  26295. char chunk[8]; // variable
  26296. };
  26297. namespace
  26298. {
  26299. long vst_swap (const long x) throw()
  26300. {
  26301. #ifdef JUCE_LITTLE_ENDIAN
  26302. return (long) ByteOrder::swap ((uint32) x);
  26303. #else
  26304. return x;
  26305. #endif
  26306. }
  26307. float vst_swapFloat (const float x) throw()
  26308. {
  26309. #ifdef JUCE_LITTLE_ENDIAN
  26310. union { uint32 asInt; float asFloat; } n;
  26311. n.asFloat = x;
  26312. n.asInt = ByteOrder::swap (n.asInt);
  26313. return n.asFloat;
  26314. #else
  26315. return x;
  26316. #endif
  26317. }
  26318. double getVSTHostTimeNanoseconds()
  26319. {
  26320. #if JUCE_WINDOWS
  26321. return timeGetTime() * 1000000.0;
  26322. #elif JUCE_LINUX
  26323. timeval micro;
  26324. gettimeofday (&micro, 0);
  26325. return micro.tv_usec * 1000.0;
  26326. #elif JUCE_MAC
  26327. UnsignedWide micro;
  26328. Microseconds (&micro);
  26329. return micro.lo * 1000.0;
  26330. #endif
  26331. }
  26332. }
  26333. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26334. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26335. static int shellUIDToCreate = 0;
  26336. static int insideVSTCallback = 0;
  26337. class VSTPluginWindow;
  26338. // Change this to disable logging of various VST activities
  26339. #ifndef VST_LOGGING
  26340. #define VST_LOGGING 1
  26341. #endif
  26342. #if VST_LOGGING
  26343. #define log(a) Logger::writeToLog(a);
  26344. #else
  26345. #define log(a)
  26346. #endif
  26347. #if JUCE_MAC && JUCE_PPC
  26348. static void* NewCFMFromMachO (void* const machofp) throw()
  26349. {
  26350. void* result = (void*) new char[8];
  26351. ((void**) result)[0] = machofp;
  26352. ((void**) result)[1] = result;
  26353. return result;
  26354. }
  26355. #endif
  26356. #if JUCE_LINUX
  26357. extern Display* display;
  26358. extern XContext windowHandleXContext;
  26359. typedef void (*EventProcPtr) (XEvent* ev);
  26360. static bool xErrorTriggered;
  26361. namespace
  26362. {
  26363. int temporaryErrorHandler (Display*, XErrorEvent*)
  26364. {
  26365. xErrorTriggered = true;
  26366. return 0;
  26367. }
  26368. int getPropertyFromXWindow (Window handle, Atom atom)
  26369. {
  26370. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26371. xErrorTriggered = false;
  26372. int userSize;
  26373. unsigned long bytes, userCount;
  26374. unsigned char* data;
  26375. Atom userType;
  26376. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26377. &userType, &userSize, &userCount, &bytes, &data);
  26378. XSetErrorHandler (oldErrorHandler);
  26379. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26380. : 0;
  26381. }
  26382. Window getChildWindow (Window windowToCheck)
  26383. {
  26384. Window rootWindow, parentWindow;
  26385. Window* childWindows;
  26386. unsigned int numChildren;
  26387. XQueryTree (display,
  26388. windowToCheck,
  26389. &rootWindow,
  26390. &parentWindow,
  26391. &childWindows,
  26392. &numChildren);
  26393. if (numChildren > 0)
  26394. return childWindows [0];
  26395. return 0;
  26396. }
  26397. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26398. {
  26399. if (e.mods.isLeftButtonDown())
  26400. {
  26401. ev.xbutton.button = Button1;
  26402. ev.xbutton.state |= Button1Mask;
  26403. }
  26404. else if (e.mods.isRightButtonDown())
  26405. {
  26406. ev.xbutton.button = Button3;
  26407. ev.xbutton.state |= Button3Mask;
  26408. }
  26409. else if (e.mods.isMiddleButtonDown())
  26410. {
  26411. ev.xbutton.button = Button2;
  26412. ev.xbutton.state |= Button2Mask;
  26413. }
  26414. }
  26415. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26416. {
  26417. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26418. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26419. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26420. }
  26421. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26422. {
  26423. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26424. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26425. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26426. }
  26427. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26428. {
  26429. if (increment < 0)
  26430. {
  26431. ev.xbutton.button = Button5;
  26432. ev.xbutton.state |= Button5Mask;
  26433. }
  26434. else if (increment > 0)
  26435. {
  26436. ev.xbutton.button = Button4;
  26437. ev.xbutton.state |= Button4Mask;
  26438. }
  26439. }
  26440. }
  26441. #endif
  26442. class ModuleHandle : public ReferenceCountedObject
  26443. {
  26444. public:
  26445. File file;
  26446. MainCall moduleMain;
  26447. String pluginName;
  26448. static Array <ModuleHandle*>& getActiveModules()
  26449. {
  26450. static Array <ModuleHandle*> activeModules;
  26451. return activeModules;
  26452. }
  26453. static ModuleHandle* findOrCreateModule (const File& file)
  26454. {
  26455. for (int i = getActiveModules().size(); --i >= 0;)
  26456. {
  26457. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26458. if (module->file == file)
  26459. return module;
  26460. }
  26461. _fpreset(); // (doesn't do any harm)
  26462. ++insideVSTCallback;
  26463. shellUIDToCreate = 0;
  26464. log ("Attempting to load VST: " + file.getFullPathName());
  26465. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26466. if (! m->open())
  26467. m = 0;
  26468. --insideVSTCallback;
  26469. _fpreset(); // (doesn't do any harm)
  26470. return m.release();
  26471. }
  26472. ModuleHandle (const File& file_)
  26473. : file (file_),
  26474. moduleMain (0),
  26475. #if JUCE_WINDOWS || JUCE_LINUX
  26476. hModule (0)
  26477. #elif JUCE_MAC
  26478. fragId (0),
  26479. resHandle (0),
  26480. bundleRef (0),
  26481. resFileId (0)
  26482. #endif
  26483. {
  26484. getActiveModules().add (this);
  26485. #if JUCE_WINDOWS || JUCE_LINUX
  26486. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26487. #elif JUCE_MAC
  26488. FSRef ref;
  26489. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26490. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26491. #endif
  26492. }
  26493. ~ModuleHandle()
  26494. {
  26495. getActiveModules().removeValue (this);
  26496. close();
  26497. }
  26498. #if JUCE_WINDOWS || JUCE_LINUX
  26499. void* hModule;
  26500. String fullParentDirectoryPathName;
  26501. bool open()
  26502. {
  26503. #if JUCE_WINDOWS
  26504. static bool timePeriodSet = false;
  26505. if (! timePeriodSet)
  26506. {
  26507. timePeriodSet = true;
  26508. timeBeginPeriod (2);
  26509. }
  26510. #endif
  26511. pluginName = file.getFileNameWithoutExtension();
  26512. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26513. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26514. if (moduleMain == 0)
  26515. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26516. return moduleMain != 0;
  26517. }
  26518. void close()
  26519. {
  26520. _fpreset(); // (doesn't do any harm)
  26521. PlatformUtilities::freeDynamicLibrary (hModule);
  26522. }
  26523. void closeEffect (AEffect* eff)
  26524. {
  26525. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26526. }
  26527. #else
  26528. CFragConnectionID fragId;
  26529. Handle resHandle;
  26530. CFBundleRef bundleRef;
  26531. FSSpec parentDirFSSpec;
  26532. short resFileId;
  26533. bool open()
  26534. {
  26535. bool ok = false;
  26536. const String filename (file.getFullPathName());
  26537. if (file.hasFileExtension (".vst"))
  26538. {
  26539. const char* const utf8 = filename.toUTF8();
  26540. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26541. strlen (utf8), file.isDirectory());
  26542. if (url != 0)
  26543. {
  26544. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26545. CFRelease (url);
  26546. if (bundleRef != 0)
  26547. {
  26548. if (CFBundleLoadExecutable (bundleRef))
  26549. {
  26550. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26551. if (moduleMain == 0)
  26552. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26553. if (moduleMain != 0)
  26554. {
  26555. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26556. if (name != 0)
  26557. {
  26558. if (CFGetTypeID (name) == CFStringGetTypeID())
  26559. {
  26560. char buffer[1024];
  26561. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26562. pluginName = buffer;
  26563. }
  26564. }
  26565. if (pluginName.isEmpty())
  26566. pluginName = file.getFileNameWithoutExtension();
  26567. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26568. ok = true;
  26569. }
  26570. }
  26571. if (! ok)
  26572. {
  26573. CFBundleUnloadExecutable (bundleRef);
  26574. CFRelease (bundleRef);
  26575. bundleRef = 0;
  26576. }
  26577. }
  26578. }
  26579. }
  26580. #if JUCE_PPC
  26581. else
  26582. {
  26583. FSRef fn;
  26584. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26585. {
  26586. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26587. if (resFileId != -1)
  26588. {
  26589. const int numEffs = Count1Resources ('aEff');
  26590. for (int i = 0; i < numEffs; ++i)
  26591. {
  26592. resHandle = Get1IndResource ('aEff', i + 1);
  26593. if (resHandle != 0)
  26594. {
  26595. OSType type;
  26596. Str255 name;
  26597. SInt16 id;
  26598. GetResInfo (resHandle, &id, &type, name);
  26599. pluginName = String ((const char*) name + 1, name[0]);
  26600. DetachResource (resHandle);
  26601. HLock (resHandle);
  26602. Ptr ptr;
  26603. Str255 errorText;
  26604. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26605. name, kPrivateCFragCopy,
  26606. &fragId, &ptr, errorText);
  26607. if (err == noErr)
  26608. {
  26609. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26610. ok = true;
  26611. }
  26612. else
  26613. {
  26614. HUnlock (resHandle);
  26615. }
  26616. break;
  26617. }
  26618. }
  26619. if (! ok)
  26620. CloseResFile (resFileId);
  26621. }
  26622. }
  26623. }
  26624. #endif
  26625. return ok;
  26626. }
  26627. void close()
  26628. {
  26629. #if JUCE_PPC
  26630. if (fragId != 0)
  26631. {
  26632. if (moduleMain != 0)
  26633. disposeMachOFromCFM ((void*) moduleMain);
  26634. CloseConnection (&fragId);
  26635. HUnlock (resHandle);
  26636. if (resFileId != 0)
  26637. CloseResFile (resFileId);
  26638. }
  26639. else
  26640. #endif
  26641. if (bundleRef != 0)
  26642. {
  26643. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26644. if (CFGetRetainCount (bundleRef) == 1)
  26645. CFBundleUnloadExecutable (bundleRef);
  26646. if (CFGetRetainCount (bundleRef) > 0)
  26647. CFRelease (bundleRef);
  26648. }
  26649. }
  26650. void closeEffect (AEffect* eff)
  26651. {
  26652. #if JUCE_PPC
  26653. if (fragId != 0)
  26654. {
  26655. Array<void*> thingsToDelete;
  26656. thingsToDelete.add ((void*) eff->dispatcher);
  26657. thingsToDelete.add ((void*) eff->process);
  26658. thingsToDelete.add ((void*) eff->setParameter);
  26659. thingsToDelete.add ((void*) eff->getParameter);
  26660. thingsToDelete.add ((void*) eff->processReplacing);
  26661. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26662. for (int i = thingsToDelete.size(); --i >= 0;)
  26663. disposeMachOFromCFM (thingsToDelete[i]);
  26664. }
  26665. else
  26666. #endif
  26667. {
  26668. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26669. }
  26670. }
  26671. #if JUCE_PPC
  26672. static void* newMachOFromCFM (void* cfmfp)
  26673. {
  26674. if (cfmfp == 0)
  26675. return 0;
  26676. UInt32* const mfp = new UInt32[6];
  26677. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26678. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26679. mfp[2] = 0x800c0000;
  26680. mfp[3] = 0x804c0004;
  26681. mfp[4] = 0x7c0903a6;
  26682. mfp[5] = 0x4e800420;
  26683. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26684. return mfp;
  26685. }
  26686. static void disposeMachOFromCFM (void* ptr)
  26687. {
  26688. delete[] static_cast <UInt32*> (ptr);
  26689. }
  26690. void coerceAEffectFunctionCalls (AEffect* eff)
  26691. {
  26692. if (fragId != 0)
  26693. {
  26694. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26695. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26696. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26697. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26698. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26699. }
  26700. }
  26701. #endif
  26702. #endif
  26703. private:
  26704. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26705. };
  26706. /**
  26707. An instance of a plugin, created by a VSTPluginFormat.
  26708. */
  26709. class VSTPluginInstance : public AudioPluginInstance,
  26710. private Timer,
  26711. private AsyncUpdater
  26712. {
  26713. public:
  26714. ~VSTPluginInstance();
  26715. // AudioPluginInstance methods:
  26716. void fillInPluginDescription (PluginDescription& desc) const
  26717. {
  26718. desc.name = name;
  26719. {
  26720. char buffer [512];
  26721. zerostruct (buffer);
  26722. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26723. desc.descriptiveName = String (buffer).trim();
  26724. if (desc.descriptiveName.isEmpty())
  26725. desc.descriptiveName = name;
  26726. }
  26727. desc.fileOrIdentifier = module->file.getFullPathName();
  26728. desc.uid = getUID();
  26729. desc.lastFileModTime = module->file.getLastModificationTime();
  26730. desc.pluginFormatName = "VST";
  26731. desc.category = getCategory();
  26732. {
  26733. char buffer [kVstMaxVendorStrLen + 8];
  26734. zerostruct (buffer);
  26735. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26736. desc.manufacturerName = buffer;
  26737. }
  26738. desc.version = getVersion();
  26739. desc.numInputChannels = getNumInputChannels();
  26740. desc.numOutputChannels = getNumOutputChannels();
  26741. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26742. }
  26743. void* getPlatformSpecificData() { return effect; }
  26744. const String getName() const { return name; }
  26745. int getUID() const;
  26746. bool acceptsMidi() const { return wantsMidiMessages; }
  26747. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26748. // AudioProcessor methods:
  26749. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26750. void releaseResources();
  26751. void processBlock (AudioSampleBuffer& buffer,
  26752. MidiBuffer& midiMessages);
  26753. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26754. AudioProcessorEditor* createEditor();
  26755. const String getInputChannelName (int index) const;
  26756. bool isInputChannelStereoPair (int index) const;
  26757. const String getOutputChannelName (int index) const;
  26758. bool isOutputChannelStereoPair (int index) const;
  26759. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26760. float getParameter (int index);
  26761. void setParameter (int index, float newValue);
  26762. const String getParameterName (int index);
  26763. const String getParameterText (int index);
  26764. bool isParameterAutomatable (int index) const;
  26765. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26766. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26767. void setCurrentProgram (int index);
  26768. const String getProgramName (int index);
  26769. void changeProgramName (int index, const String& newName);
  26770. void getStateInformation (MemoryBlock& destData);
  26771. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26772. void setStateInformation (const void* data, int sizeInBytes);
  26773. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26774. void timerCallback();
  26775. void handleAsyncUpdate();
  26776. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26777. private:
  26778. friend class VSTPluginWindow;
  26779. friend class VSTPluginFormat;
  26780. AEffect* effect;
  26781. String name;
  26782. CriticalSection lock;
  26783. bool wantsMidiMessages, initialised, isPowerOn;
  26784. mutable StringArray programNames;
  26785. AudioSampleBuffer tempBuffer;
  26786. CriticalSection midiInLock;
  26787. MidiBuffer incomingMidi;
  26788. VSTMidiEventList midiEventsToSend;
  26789. VstTimeInfo vstHostTime;
  26790. ReferenceCountedObjectPtr <ModuleHandle> module;
  26791. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26792. bool restoreProgramSettings (const fxProgram* const prog);
  26793. const String getCurrentProgramName();
  26794. void setParamsInProgramBlock (fxProgram* const prog);
  26795. void updateStoredProgramNames();
  26796. void initialise();
  26797. void handleMidiFromPlugin (const VstEvents* const events);
  26798. void createTempParameterStore (MemoryBlock& dest);
  26799. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26800. const String getParameterLabel (int index) const;
  26801. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26802. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26803. void setChunkData (const char* data, int size, bool isPreset);
  26804. bool loadFromFXBFile (const void* data, int numBytes);
  26805. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26806. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26807. const String getVersion() const;
  26808. const String getCategory() const;
  26809. void setPower (const bool on);
  26810. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26811. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26812. };
  26813. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26814. : effect (0),
  26815. wantsMidiMessages (false),
  26816. initialised (false),
  26817. isPowerOn (false),
  26818. tempBuffer (1, 1),
  26819. module (module_)
  26820. {
  26821. try
  26822. {
  26823. _fpreset();
  26824. ++insideVSTCallback;
  26825. name = module->pluginName;
  26826. log ("Creating VST instance: " + name);
  26827. #if JUCE_MAC
  26828. if (module->resFileId != 0)
  26829. UseResFile (module->resFileId);
  26830. #if JUCE_PPC
  26831. if (module->fragId != 0)
  26832. {
  26833. static void* audioMasterCoerced = 0;
  26834. if (audioMasterCoerced == 0)
  26835. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26836. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26837. }
  26838. else
  26839. #endif
  26840. #endif
  26841. {
  26842. effect = module->moduleMain (&audioMaster);
  26843. }
  26844. --insideVSTCallback;
  26845. if (effect != 0 && effect->magic == kEffectMagic)
  26846. {
  26847. #if JUCE_PPC
  26848. module->coerceAEffectFunctionCalls (effect);
  26849. #endif
  26850. jassert (effect->resvd2 == 0);
  26851. jassert (effect->object != 0);
  26852. _fpreset(); // some dodgy plugs fuck around with this
  26853. }
  26854. else
  26855. {
  26856. effect = 0;
  26857. }
  26858. }
  26859. catch (...)
  26860. {
  26861. --insideVSTCallback;
  26862. }
  26863. }
  26864. VSTPluginInstance::~VSTPluginInstance()
  26865. {
  26866. const ScopedLock sl (lock);
  26867. jassert (insideVSTCallback == 0);
  26868. if (effect != 0 && effect->magic == kEffectMagic)
  26869. {
  26870. try
  26871. {
  26872. #if JUCE_MAC
  26873. if (module->resFileId != 0)
  26874. UseResFile (module->resFileId);
  26875. #endif
  26876. // Must delete any editors before deleting the plugin instance!
  26877. jassert (getActiveEditor() == 0);
  26878. _fpreset(); // some dodgy plugs fuck around with this
  26879. module->closeEffect (effect);
  26880. }
  26881. catch (...)
  26882. {}
  26883. }
  26884. module = 0;
  26885. effect = 0;
  26886. }
  26887. void VSTPluginInstance::initialise()
  26888. {
  26889. if (initialised || effect == 0)
  26890. return;
  26891. log ("Initialising VST: " + module->pluginName);
  26892. initialised = true;
  26893. dispatch (effIdentify, 0, 0, 0, 0);
  26894. if (getSampleRate() > 0)
  26895. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26896. if (getBlockSize() > 0)
  26897. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26898. dispatch (effOpen, 0, 0, 0, 0);
  26899. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26900. getSampleRate(), getBlockSize());
  26901. if (getNumPrograms() > 1)
  26902. setCurrentProgram (0);
  26903. else
  26904. dispatch (effSetProgram, 0, 0, 0, 0);
  26905. int i;
  26906. for (i = effect->numInputs; --i >= 0;)
  26907. dispatch (effConnectInput, i, 1, 0, 0);
  26908. for (i = effect->numOutputs; --i >= 0;)
  26909. dispatch (effConnectOutput, i, 1, 0, 0);
  26910. updateStoredProgramNames();
  26911. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26912. setLatencySamples (effect->initialDelay);
  26913. }
  26914. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26915. int samplesPerBlockExpected)
  26916. {
  26917. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26918. sampleRate_, samplesPerBlockExpected);
  26919. setLatencySamples (effect->initialDelay);
  26920. vstHostTime.tempo = 120.0;
  26921. vstHostTime.timeSigNumerator = 4;
  26922. vstHostTime.timeSigDenominator = 4;
  26923. vstHostTime.sampleRate = sampleRate_;
  26924. vstHostTime.samplePos = 0;
  26925. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26926. initialise();
  26927. if (initialised)
  26928. {
  26929. wantsMidiMessages = wantsMidiMessages
  26930. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26931. if (wantsMidiMessages)
  26932. midiEventsToSend.ensureSize (256);
  26933. else
  26934. midiEventsToSend.freeEvents();
  26935. incomingMidi.clear();
  26936. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26937. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26938. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26939. if (! isPowerOn)
  26940. setPower (true);
  26941. // dodgy hack to force some plugins to initialise the sample rate..
  26942. if ((! hasEditor()) && getNumParameters() > 0)
  26943. {
  26944. const float old = getParameter (0);
  26945. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26946. setParameter (0, old);
  26947. }
  26948. dispatch (effStartProcess, 0, 0, 0, 0);
  26949. }
  26950. }
  26951. void VSTPluginInstance::releaseResources()
  26952. {
  26953. if (initialised)
  26954. {
  26955. dispatch (effStopProcess, 0, 0, 0, 0);
  26956. setPower (false);
  26957. }
  26958. tempBuffer.setSize (1, 1);
  26959. incomingMidi.clear();
  26960. midiEventsToSend.freeEvents();
  26961. }
  26962. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26963. MidiBuffer& midiMessages)
  26964. {
  26965. const int numSamples = buffer.getNumSamples();
  26966. if (initialised)
  26967. {
  26968. AudioPlayHead* playHead = getPlayHead();
  26969. if (playHead != 0)
  26970. {
  26971. AudioPlayHead::CurrentPositionInfo position;
  26972. playHead->getCurrentPosition (position);
  26973. vstHostTime.tempo = position.bpm;
  26974. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26975. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26976. vstHostTime.ppqPos = position.ppqPosition;
  26977. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26978. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26979. if (position.isPlaying)
  26980. vstHostTime.flags |= kVstTransportPlaying;
  26981. else
  26982. vstHostTime.flags &= ~kVstTransportPlaying;
  26983. }
  26984. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  26985. if (wantsMidiMessages)
  26986. {
  26987. midiEventsToSend.clear();
  26988. midiEventsToSend.ensureSize (1);
  26989. MidiBuffer::Iterator iter (midiMessages);
  26990. const uint8* midiData;
  26991. int numBytesOfMidiData, samplePosition;
  26992. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26993. {
  26994. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26995. jlimit (0, numSamples - 1, samplePosition));
  26996. }
  26997. try
  26998. {
  26999. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27000. }
  27001. catch (...)
  27002. {}
  27003. }
  27004. _clearfp();
  27005. if ((effect->flags & effFlagsCanReplacing) != 0)
  27006. {
  27007. try
  27008. {
  27009. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27010. }
  27011. catch (...)
  27012. {}
  27013. }
  27014. else
  27015. {
  27016. tempBuffer.setSize (effect->numOutputs, numSamples);
  27017. tempBuffer.clear();
  27018. try
  27019. {
  27020. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27021. }
  27022. catch (...)
  27023. {}
  27024. for (int i = effect->numOutputs; --i >= 0;)
  27025. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27026. }
  27027. }
  27028. else
  27029. {
  27030. // Not initialised, so just bypass..
  27031. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27032. buffer.clear (i, 0, buffer.getNumSamples());
  27033. }
  27034. {
  27035. // copy any incoming midi..
  27036. const ScopedLock sl (midiInLock);
  27037. midiMessages.swapWith (incomingMidi);
  27038. incomingMidi.clear();
  27039. }
  27040. }
  27041. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27042. {
  27043. if (events != 0)
  27044. {
  27045. const ScopedLock sl (midiInLock);
  27046. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27047. }
  27048. }
  27049. static Array <VSTPluginWindow*> activeVSTWindows;
  27050. class VSTPluginWindow : public AudioProcessorEditor,
  27051. #if ! JUCE_MAC
  27052. public ComponentMovementWatcher,
  27053. #endif
  27054. public Timer
  27055. {
  27056. public:
  27057. VSTPluginWindow (VSTPluginInstance& plugin_)
  27058. : AudioProcessorEditor (&plugin_),
  27059. #if ! JUCE_MAC
  27060. ComponentMovementWatcher (this),
  27061. #endif
  27062. plugin (plugin_),
  27063. isOpen (false),
  27064. recursiveResize (false),
  27065. pluginWantsKeys (false),
  27066. pluginRefusesToResize (false),
  27067. alreadyInside (false)
  27068. {
  27069. #if JUCE_WINDOWS
  27070. sizeCheckCount = 0;
  27071. pluginHWND = 0;
  27072. #elif JUCE_LINUX
  27073. pluginWindow = None;
  27074. pluginProc = None;
  27075. #else
  27076. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27077. #endif
  27078. activeVSTWindows.add (this);
  27079. setSize (1, 1);
  27080. setOpaque (true);
  27081. setVisible (true);
  27082. }
  27083. ~VSTPluginWindow()
  27084. {
  27085. #if JUCE_MAC
  27086. innerWrapper = 0;
  27087. #else
  27088. closePluginWindow();
  27089. #endif
  27090. activeVSTWindows.removeValue (this);
  27091. plugin.editorBeingDeleted (this);
  27092. }
  27093. #if ! JUCE_MAC
  27094. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27095. {
  27096. if (recursiveResize)
  27097. return;
  27098. Component* const topComp = getTopLevelComponent();
  27099. if (topComp->getPeer() != 0)
  27100. {
  27101. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27102. recursiveResize = true;
  27103. #if JUCE_WINDOWS
  27104. if (pluginHWND != 0)
  27105. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27106. #elif JUCE_LINUX
  27107. if (pluginWindow != 0)
  27108. {
  27109. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27110. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27111. XMapRaised (display, pluginWindow);
  27112. }
  27113. #endif
  27114. recursiveResize = false;
  27115. }
  27116. }
  27117. void componentVisibilityChanged()
  27118. {
  27119. if (isShowing())
  27120. openPluginWindow();
  27121. else
  27122. closePluginWindow();
  27123. componentMovedOrResized (true, true);
  27124. }
  27125. void componentPeerChanged()
  27126. {
  27127. closePluginWindow();
  27128. openPluginWindow();
  27129. }
  27130. #endif
  27131. bool keyStateChanged (bool)
  27132. {
  27133. return pluginWantsKeys;
  27134. }
  27135. bool keyPressed (const KeyPress&)
  27136. {
  27137. return pluginWantsKeys;
  27138. }
  27139. #if JUCE_MAC
  27140. void paint (Graphics& g)
  27141. {
  27142. g.fillAll (Colours::black);
  27143. }
  27144. #else
  27145. void paint (Graphics& g)
  27146. {
  27147. if (isOpen)
  27148. {
  27149. ComponentPeer* const peer = getPeer();
  27150. if (peer != 0)
  27151. {
  27152. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27153. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27154. #if JUCE_LINUX
  27155. if (pluginWindow != 0)
  27156. {
  27157. const Rectangle<int> clip (g.getClipBounds());
  27158. XEvent ev;
  27159. zerostruct (ev);
  27160. ev.xexpose.type = Expose;
  27161. ev.xexpose.display = display;
  27162. ev.xexpose.window = pluginWindow;
  27163. ev.xexpose.x = clip.getX();
  27164. ev.xexpose.y = clip.getY();
  27165. ev.xexpose.width = clip.getWidth();
  27166. ev.xexpose.height = clip.getHeight();
  27167. sendEventToChild (&ev);
  27168. }
  27169. #endif
  27170. }
  27171. }
  27172. else
  27173. {
  27174. g.fillAll (Colours::black);
  27175. }
  27176. }
  27177. #endif
  27178. void timerCallback()
  27179. {
  27180. #if JUCE_WINDOWS
  27181. if (--sizeCheckCount <= 0)
  27182. {
  27183. sizeCheckCount = 10;
  27184. checkPluginWindowSize();
  27185. }
  27186. #endif
  27187. try
  27188. {
  27189. static bool reentrant = false;
  27190. if (! reentrant)
  27191. {
  27192. reentrant = true;
  27193. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27194. reentrant = false;
  27195. }
  27196. }
  27197. catch (...)
  27198. {}
  27199. }
  27200. void mouseDown (const MouseEvent& e)
  27201. {
  27202. #if JUCE_LINUX
  27203. if (pluginWindow == 0)
  27204. return;
  27205. toFront (true);
  27206. XEvent ev;
  27207. zerostruct (ev);
  27208. ev.xbutton.display = display;
  27209. ev.xbutton.type = ButtonPress;
  27210. ev.xbutton.window = pluginWindow;
  27211. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27212. ev.xbutton.time = CurrentTime;
  27213. ev.xbutton.x = e.x;
  27214. ev.xbutton.y = e.y;
  27215. ev.xbutton.x_root = e.getScreenX();
  27216. ev.xbutton.y_root = e.getScreenY();
  27217. translateJuceToXButtonModifiers (e, ev);
  27218. sendEventToChild (&ev);
  27219. #elif JUCE_WINDOWS
  27220. (void) e;
  27221. toFront (true);
  27222. #endif
  27223. }
  27224. void broughtToFront()
  27225. {
  27226. activeVSTWindows.removeValue (this);
  27227. activeVSTWindows.add (this);
  27228. #if JUCE_MAC
  27229. dispatch (effEditTop, 0, 0, 0, 0);
  27230. #endif
  27231. }
  27232. private:
  27233. VSTPluginInstance& plugin;
  27234. bool isOpen, recursiveResize;
  27235. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27236. #if JUCE_WINDOWS
  27237. HWND pluginHWND;
  27238. void* originalWndProc;
  27239. int sizeCheckCount;
  27240. #elif JUCE_LINUX
  27241. Window pluginWindow;
  27242. EventProcPtr pluginProc;
  27243. #endif
  27244. #if JUCE_MAC
  27245. void openPluginWindow (WindowRef parentWindow)
  27246. {
  27247. if (isOpen || parentWindow == 0)
  27248. return;
  27249. isOpen = true;
  27250. ERect* rect = 0;
  27251. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27252. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27253. // do this before and after like in the steinberg example
  27254. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27255. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27256. // Install keyboard hooks
  27257. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27258. // double-check it's not too tiny
  27259. int w = 250, h = 150;
  27260. if (rect != 0)
  27261. {
  27262. w = rect->right - rect->left;
  27263. h = rect->bottom - rect->top;
  27264. if (w == 0 || h == 0)
  27265. {
  27266. w = 250;
  27267. h = 150;
  27268. }
  27269. }
  27270. w = jmax (w, 32);
  27271. h = jmax (h, 32);
  27272. setSize (w, h);
  27273. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27274. repaint();
  27275. }
  27276. #else
  27277. void openPluginWindow()
  27278. {
  27279. if (isOpen || getWindowHandle() == 0)
  27280. return;
  27281. log ("Opening VST UI: " + plugin.name);
  27282. isOpen = true;
  27283. ERect* rect = 0;
  27284. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27285. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27286. // do this before and after like in the steinberg example
  27287. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27288. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27289. // Install keyboard hooks
  27290. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27291. #if JUCE_WINDOWS
  27292. originalWndProc = 0;
  27293. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27294. if (pluginHWND == 0)
  27295. {
  27296. isOpen = false;
  27297. setSize (300, 150);
  27298. return;
  27299. }
  27300. #pragma warning (push)
  27301. #pragma warning (disable: 4244)
  27302. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27303. if (! pluginWantsKeys)
  27304. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27305. #pragma warning (pop)
  27306. int w, h;
  27307. RECT r;
  27308. GetWindowRect (pluginHWND, &r);
  27309. w = r.right - r.left;
  27310. h = r.bottom - r.top;
  27311. if (rect != 0)
  27312. {
  27313. const int rw = rect->right - rect->left;
  27314. const int rh = rect->bottom - rect->top;
  27315. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27316. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27317. {
  27318. // very dodgy logic to decide which size is right.
  27319. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27320. {
  27321. SetWindowPos (pluginHWND, 0,
  27322. 0, 0, rw, rh,
  27323. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27324. GetWindowRect (pluginHWND, &r);
  27325. w = r.right - r.left;
  27326. h = r.bottom - r.top;
  27327. pluginRefusesToResize = (w != rw) || (h != rh);
  27328. w = rw;
  27329. h = rh;
  27330. }
  27331. }
  27332. }
  27333. #elif JUCE_LINUX
  27334. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27335. if (pluginWindow != 0)
  27336. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27337. XInternAtom (display, "_XEventProc", False));
  27338. int w = 250, h = 150;
  27339. if (rect != 0)
  27340. {
  27341. w = rect->right - rect->left;
  27342. h = rect->bottom - rect->top;
  27343. if (w == 0 || h == 0)
  27344. {
  27345. w = 250;
  27346. h = 150;
  27347. }
  27348. }
  27349. if (pluginWindow != 0)
  27350. XMapRaised (display, pluginWindow);
  27351. #endif
  27352. // double-check it's not too tiny
  27353. w = jmax (w, 32);
  27354. h = jmax (h, 32);
  27355. setSize (w, h);
  27356. #if JUCE_WINDOWS
  27357. checkPluginWindowSize();
  27358. #endif
  27359. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27360. repaint();
  27361. }
  27362. #endif
  27363. #if ! JUCE_MAC
  27364. void closePluginWindow()
  27365. {
  27366. if (isOpen)
  27367. {
  27368. log ("Closing VST UI: " + plugin.getName());
  27369. isOpen = false;
  27370. dispatch (effEditClose, 0, 0, 0, 0);
  27371. #if JUCE_WINDOWS
  27372. #pragma warning (push)
  27373. #pragma warning (disable: 4244)
  27374. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27375. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27376. #pragma warning (pop)
  27377. stopTimer();
  27378. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27379. DestroyWindow (pluginHWND);
  27380. pluginHWND = 0;
  27381. #elif JUCE_LINUX
  27382. stopTimer();
  27383. pluginWindow = 0;
  27384. pluginProc = 0;
  27385. #endif
  27386. }
  27387. }
  27388. #endif
  27389. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27390. {
  27391. return plugin.dispatch (opcode, index, value, ptr, opt);
  27392. }
  27393. #if JUCE_WINDOWS
  27394. void checkPluginWindowSize()
  27395. {
  27396. RECT r;
  27397. GetWindowRect (pluginHWND, &r);
  27398. const int w = r.right - r.left;
  27399. const int h = r.bottom - r.top;
  27400. if (isShowing() && w > 0 && h > 0
  27401. && (w != getWidth() || h != getHeight())
  27402. && ! pluginRefusesToResize)
  27403. {
  27404. setSize (w, h);
  27405. sizeCheckCount = 0;
  27406. }
  27407. }
  27408. // hooks to get keyboard events from VST windows..
  27409. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27410. {
  27411. for (int i = activeVSTWindows.size(); --i >= 0;)
  27412. {
  27413. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27414. if (w->pluginHWND == hW)
  27415. {
  27416. if (message == WM_CHAR
  27417. || message == WM_KEYDOWN
  27418. || message == WM_SYSKEYDOWN
  27419. || message == WM_KEYUP
  27420. || message == WM_SYSKEYUP
  27421. || message == WM_APPCOMMAND)
  27422. {
  27423. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27424. message, wParam, lParam);
  27425. }
  27426. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27427. (HWND) w->pluginHWND,
  27428. message,
  27429. wParam,
  27430. lParam);
  27431. }
  27432. }
  27433. return DefWindowProc (hW, message, wParam, lParam);
  27434. }
  27435. #endif
  27436. #if JUCE_LINUX
  27437. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27438. void sendEventToChild (XEvent* event)
  27439. {
  27440. if (pluginProc != 0)
  27441. {
  27442. // if the plugin publishes an event procedure, pass the event directly..
  27443. pluginProc (event);
  27444. }
  27445. else if (pluginWindow != 0)
  27446. {
  27447. // if the plugin has a window, then send the event to the window so that
  27448. // its message thread will pick it up..
  27449. XSendEvent (display, pluginWindow, False, 0L, event);
  27450. XFlush (display);
  27451. }
  27452. }
  27453. void mouseEnter (const MouseEvent& e)
  27454. {
  27455. if (pluginWindow != 0)
  27456. {
  27457. XEvent ev;
  27458. zerostruct (ev);
  27459. ev.xcrossing.display = display;
  27460. ev.xcrossing.type = EnterNotify;
  27461. ev.xcrossing.window = pluginWindow;
  27462. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27463. ev.xcrossing.time = CurrentTime;
  27464. ev.xcrossing.x = e.x;
  27465. ev.xcrossing.y = e.y;
  27466. ev.xcrossing.x_root = e.getScreenX();
  27467. ev.xcrossing.y_root = e.getScreenY();
  27468. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27469. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27470. translateJuceToXCrossingModifiers (e, ev);
  27471. sendEventToChild (&ev);
  27472. }
  27473. }
  27474. void mouseExit (const MouseEvent& e)
  27475. {
  27476. if (pluginWindow != 0)
  27477. {
  27478. XEvent ev;
  27479. zerostruct (ev);
  27480. ev.xcrossing.display = display;
  27481. ev.xcrossing.type = LeaveNotify;
  27482. ev.xcrossing.window = pluginWindow;
  27483. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27484. ev.xcrossing.time = CurrentTime;
  27485. ev.xcrossing.x = e.x;
  27486. ev.xcrossing.y = e.y;
  27487. ev.xcrossing.x_root = e.getScreenX();
  27488. ev.xcrossing.y_root = e.getScreenY();
  27489. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27490. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27491. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27492. translateJuceToXCrossingModifiers (e, ev);
  27493. sendEventToChild (&ev);
  27494. }
  27495. }
  27496. void mouseMove (const MouseEvent& e)
  27497. {
  27498. if (pluginWindow != 0)
  27499. {
  27500. XEvent ev;
  27501. zerostruct (ev);
  27502. ev.xmotion.display = display;
  27503. ev.xmotion.type = MotionNotify;
  27504. ev.xmotion.window = pluginWindow;
  27505. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27506. ev.xmotion.time = CurrentTime;
  27507. ev.xmotion.is_hint = NotifyNormal;
  27508. ev.xmotion.x = e.x;
  27509. ev.xmotion.y = e.y;
  27510. ev.xmotion.x_root = e.getScreenX();
  27511. ev.xmotion.y_root = e.getScreenY();
  27512. sendEventToChild (&ev);
  27513. }
  27514. }
  27515. void mouseDrag (const MouseEvent& e)
  27516. {
  27517. if (pluginWindow != 0)
  27518. {
  27519. XEvent ev;
  27520. zerostruct (ev);
  27521. ev.xmotion.display = display;
  27522. ev.xmotion.type = MotionNotify;
  27523. ev.xmotion.window = pluginWindow;
  27524. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27525. ev.xmotion.time = CurrentTime;
  27526. ev.xmotion.x = e.x ;
  27527. ev.xmotion.y = e.y;
  27528. ev.xmotion.x_root = e.getScreenX();
  27529. ev.xmotion.y_root = e.getScreenY();
  27530. ev.xmotion.is_hint = NotifyNormal;
  27531. translateJuceToXMotionModifiers (e, ev);
  27532. sendEventToChild (&ev);
  27533. }
  27534. }
  27535. void mouseUp (const MouseEvent& e)
  27536. {
  27537. if (pluginWindow != 0)
  27538. {
  27539. XEvent ev;
  27540. zerostruct (ev);
  27541. ev.xbutton.display = display;
  27542. ev.xbutton.type = ButtonRelease;
  27543. ev.xbutton.window = pluginWindow;
  27544. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27545. ev.xbutton.time = CurrentTime;
  27546. ev.xbutton.x = e.x;
  27547. ev.xbutton.y = e.y;
  27548. ev.xbutton.x_root = e.getScreenX();
  27549. ev.xbutton.y_root = e.getScreenY();
  27550. translateJuceToXButtonModifiers (e, ev);
  27551. sendEventToChild (&ev);
  27552. }
  27553. }
  27554. void mouseWheelMove (const MouseEvent& e,
  27555. float incrementX,
  27556. float incrementY)
  27557. {
  27558. if (pluginWindow != 0)
  27559. {
  27560. XEvent ev;
  27561. zerostruct (ev);
  27562. ev.xbutton.display = display;
  27563. ev.xbutton.type = ButtonPress;
  27564. ev.xbutton.window = pluginWindow;
  27565. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27566. ev.xbutton.time = CurrentTime;
  27567. ev.xbutton.x = e.x;
  27568. ev.xbutton.y = e.y;
  27569. ev.xbutton.x_root = e.getScreenX();
  27570. ev.xbutton.y_root = e.getScreenY();
  27571. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27572. sendEventToChild (&ev);
  27573. // TODO - put a usleep here ?
  27574. ev.xbutton.type = ButtonRelease;
  27575. sendEventToChild (&ev);
  27576. }
  27577. }
  27578. #endif
  27579. #if JUCE_MAC
  27580. #if ! JUCE_SUPPORT_CARBON
  27581. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27582. #endif
  27583. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27584. {
  27585. public:
  27586. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27587. : owner (owner_),
  27588. alreadyInside (false)
  27589. {
  27590. }
  27591. ~InnerWrapperComponent()
  27592. {
  27593. deleteWindow();
  27594. }
  27595. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27596. {
  27597. owner->openPluginWindow (windowRef);
  27598. return 0;
  27599. }
  27600. void removeView (HIViewRef)
  27601. {
  27602. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27603. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27604. }
  27605. bool getEmbeddedViewSize (int& w, int& h)
  27606. {
  27607. ERect* rect = 0;
  27608. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27609. w = rect->right - rect->left;
  27610. h = rect->bottom - rect->top;
  27611. return true;
  27612. }
  27613. void mouseDown (int x, int y)
  27614. {
  27615. if (! alreadyInside)
  27616. {
  27617. alreadyInside = true;
  27618. getTopLevelComponent()->toFront (true);
  27619. owner->dispatch (effEditMouse, x, y, 0, 0);
  27620. alreadyInside = false;
  27621. }
  27622. else
  27623. {
  27624. PostEvent (::mouseDown, 0);
  27625. }
  27626. }
  27627. void paint()
  27628. {
  27629. ComponentPeer* const peer = getPeer();
  27630. if (peer != 0)
  27631. {
  27632. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27633. ERect r;
  27634. r.left = pos.getX();
  27635. r.right = r.left + getWidth();
  27636. r.top = pos.getY();
  27637. r.bottom = r.top + getHeight();
  27638. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27639. }
  27640. }
  27641. private:
  27642. VSTPluginWindow* const owner;
  27643. bool alreadyInside;
  27644. };
  27645. friend class InnerWrapperComponent;
  27646. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27647. void resized()
  27648. {
  27649. innerWrapper->setSize (getWidth(), getHeight());
  27650. }
  27651. #endif
  27652. private:
  27653. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27654. };
  27655. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27656. {
  27657. if (hasEditor())
  27658. return new VSTPluginWindow (*this);
  27659. return 0;
  27660. }
  27661. void VSTPluginInstance::handleAsyncUpdate()
  27662. {
  27663. // indicates that something about the plugin has changed..
  27664. updateHostDisplay();
  27665. }
  27666. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27667. {
  27668. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27669. {
  27670. changeProgramName (getCurrentProgram(), prog->prgName);
  27671. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27672. setParameter (i, vst_swapFloat (prog->params[i]));
  27673. return true;
  27674. }
  27675. return false;
  27676. }
  27677. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27678. const int dataSize)
  27679. {
  27680. if (dataSize < 28)
  27681. return false;
  27682. const fxSet* const set = (const fxSet*) data;
  27683. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27684. || vst_swap (set->version) > fxbVersionNum)
  27685. return false;
  27686. if (vst_swap (set->fxMagic) == 'FxBk')
  27687. {
  27688. // bank of programs
  27689. if (vst_swap (set->numPrograms) >= 0)
  27690. {
  27691. const int oldProg = getCurrentProgram();
  27692. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27693. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27694. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27695. {
  27696. if (i != oldProg)
  27697. {
  27698. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27699. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27700. return false;
  27701. if (vst_swap (set->numPrograms) > 0)
  27702. setCurrentProgram (i);
  27703. if (! restoreProgramSettings (prog))
  27704. return false;
  27705. }
  27706. }
  27707. if (vst_swap (set->numPrograms) > 0)
  27708. setCurrentProgram (oldProg);
  27709. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27710. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27711. return false;
  27712. if (! restoreProgramSettings (prog))
  27713. return false;
  27714. }
  27715. }
  27716. else if (vst_swap (set->fxMagic) == 'FxCk')
  27717. {
  27718. // single program
  27719. const fxProgram* const prog = (const fxProgram*) data;
  27720. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27721. return false;
  27722. changeProgramName (getCurrentProgram(), prog->prgName);
  27723. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27724. setParameter (i, vst_swapFloat (prog->params[i]));
  27725. }
  27726. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27727. {
  27728. // non-preset chunk
  27729. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27730. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27731. return false;
  27732. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27733. }
  27734. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27735. {
  27736. // preset chunk
  27737. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27738. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27739. return false;
  27740. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27741. changeProgramName (getCurrentProgram(), cset->name);
  27742. }
  27743. else
  27744. {
  27745. return false;
  27746. }
  27747. return true;
  27748. }
  27749. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27750. {
  27751. const int numParams = getNumParameters();
  27752. prog->chunkMagic = vst_swap ('CcnK');
  27753. prog->byteSize = 0;
  27754. prog->fxMagic = vst_swap ('FxCk');
  27755. prog->version = vst_swap (fxbVersionNum);
  27756. prog->fxID = vst_swap (getUID());
  27757. prog->fxVersion = vst_swap (getVersionNumber());
  27758. prog->numParams = vst_swap (numParams);
  27759. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27760. for (int i = 0; i < numParams; ++i)
  27761. prog->params[i] = vst_swapFloat (getParameter (i));
  27762. }
  27763. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27764. {
  27765. const int numPrograms = getNumPrograms();
  27766. const int numParams = getNumParameters();
  27767. if (usesChunks())
  27768. {
  27769. if (isFXB)
  27770. {
  27771. MemoryBlock chunk;
  27772. getChunkData (chunk, false, maxSizeMB);
  27773. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27774. dest.setSize (totalLen, true);
  27775. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27776. set->chunkMagic = vst_swap ('CcnK');
  27777. set->byteSize = 0;
  27778. set->fxMagic = vst_swap ('FBCh');
  27779. set->version = vst_swap (fxbVersionNum);
  27780. set->fxID = vst_swap (getUID());
  27781. set->fxVersion = vst_swap (getVersionNumber());
  27782. set->numPrograms = vst_swap (numPrograms);
  27783. set->chunkSize = vst_swap ((long) chunk.getSize());
  27784. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27785. }
  27786. else
  27787. {
  27788. MemoryBlock chunk;
  27789. getChunkData (chunk, true, maxSizeMB);
  27790. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27791. dest.setSize (totalLen, true);
  27792. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27793. set->chunkMagic = vst_swap ('CcnK');
  27794. set->byteSize = 0;
  27795. set->fxMagic = vst_swap ('FPCh');
  27796. set->version = vst_swap (fxbVersionNum);
  27797. set->fxID = vst_swap (getUID());
  27798. set->fxVersion = vst_swap (getVersionNumber());
  27799. set->numPrograms = vst_swap (numPrograms);
  27800. set->chunkSize = vst_swap ((long) chunk.getSize());
  27801. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27802. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27803. }
  27804. }
  27805. else
  27806. {
  27807. if (isFXB)
  27808. {
  27809. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27810. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27811. dest.setSize (len, true);
  27812. fxSet* const set = (fxSet*) dest.getData();
  27813. set->chunkMagic = vst_swap ('CcnK');
  27814. set->byteSize = 0;
  27815. set->fxMagic = vst_swap ('FxBk');
  27816. set->version = vst_swap (fxbVersionNum);
  27817. set->fxID = vst_swap (getUID());
  27818. set->fxVersion = vst_swap (getVersionNumber());
  27819. set->numPrograms = vst_swap (numPrograms);
  27820. const int oldProgram = getCurrentProgram();
  27821. MemoryBlock oldSettings;
  27822. createTempParameterStore (oldSettings);
  27823. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27824. for (int i = 0; i < numPrograms; ++i)
  27825. {
  27826. if (i != oldProgram)
  27827. {
  27828. setCurrentProgram (i);
  27829. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27830. }
  27831. }
  27832. setCurrentProgram (oldProgram);
  27833. restoreFromTempParameterStore (oldSettings);
  27834. }
  27835. else
  27836. {
  27837. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27838. dest.setSize (totalLen, true);
  27839. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27840. }
  27841. }
  27842. return true;
  27843. }
  27844. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27845. {
  27846. if (usesChunks())
  27847. {
  27848. void* data = 0;
  27849. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27850. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27851. {
  27852. mb.setSize (bytes);
  27853. mb.copyFrom (data, 0, bytes);
  27854. }
  27855. }
  27856. }
  27857. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27858. {
  27859. if (size > 0 && usesChunks())
  27860. {
  27861. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27862. if (! isPreset)
  27863. updateStoredProgramNames();
  27864. }
  27865. }
  27866. void VSTPluginInstance::timerCallback()
  27867. {
  27868. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27869. stopTimer();
  27870. }
  27871. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27872. {
  27873. const ScopedLock sl (lock);
  27874. ++insideVSTCallback;
  27875. int result = 0;
  27876. try
  27877. {
  27878. if (effect != 0)
  27879. {
  27880. #if JUCE_MAC
  27881. if (module->resFileId != 0)
  27882. UseResFile (module->resFileId);
  27883. #endif
  27884. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27885. #if JUCE_MAC
  27886. module->resFileId = CurResFile();
  27887. #endif
  27888. --insideVSTCallback;
  27889. return result;
  27890. }
  27891. }
  27892. catch (...)
  27893. {
  27894. }
  27895. --insideVSTCallback;
  27896. return result;
  27897. }
  27898. namespace
  27899. {
  27900. static const int defaultVSTSampleRateValue = 16384;
  27901. static const int defaultVSTBlockSizeValue = 512;
  27902. // handles non plugin-specific callbacks..
  27903. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27904. {
  27905. (void) index;
  27906. (void) value;
  27907. (void) opt;
  27908. switch (opcode)
  27909. {
  27910. case audioMasterCanDo:
  27911. {
  27912. static const char* canDos[] = { "supplyIdle",
  27913. "sendVstEvents",
  27914. "sendVstMidiEvent",
  27915. "sendVstTimeInfo",
  27916. "receiveVstEvents",
  27917. "receiveVstMidiEvent",
  27918. "supportShell",
  27919. "shellCategory" };
  27920. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27921. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27922. return 1;
  27923. return 0;
  27924. }
  27925. case audioMasterVersion: return 0x2400;
  27926. case audioMasterCurrentId: return shellUIDToCreate;
  27927. case audioMasterGetNumAutomatableParameters: return 0;
  27928. case audioMasterGetAutomationState: return 1;
  27929. case audioMasterGetVendorVersion: return 0x0101;
  27930. case audioMasterGetVendorString:
  27931. case audioMasterGetProductString:
  27932. {
  27933. String hostName ("Juce VST Host");
  27934. if (JUCEApplication::getInstance() != 0)
  27935. hostName = JUCEApplication::getInstance()->getApplicationName();
  27936. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27937. break;
  27938. }
  27939. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  27940. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  27941. case audioMasterSetOutputSampleRate: return 0;
  27942. default:
  27943. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27944. break;
  27945. }
  27946. return 0;
  27947. }
  27948. }
  27949. // handles callbacks for a specific plugin
  27950. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27951. {
  27952. switch (opcode)
  27953. {
  27954. case audioMasterAutomate:
  27955. sendParamChangeMessageToListeners (index, opt);
  27956. break;
  27957. case audioMasterProcessEvents:
  27958. handleMidiFromPlugin ((const VstEvents*) ptr);
  27959. break;
  27960. case audioMasterGetTime:
  27961. #if JUCE_MSVC
  27962. #pragma warning (push)
  27963. #pragma warning (disable: 4311)
  27964. #endif
  27965. return (VstIntPtr) &vstHostTime;
  27966. #if JUCE_MSVC
  27967. #pragma warning (pop)
  27968. #endif
  27969. break;
  27970. case audioMasterIdle:
  27971. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27972. {
  27973. ++insideVSTCallback;
  27974. #if JUCE_MAC
  27975. if (getActiveEditor() != 0)
  27976. dispatch (effEditIdle, 0, 0, 0, 0);
  27977. #endif
  27978. juce_callAnyTimersSynchronously();
  27979. handleUpdateNowIfNeeded();
  27980. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27981. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27982. --insideVSTCallback;
  27983. }
  27984. break;
  27985. case audioMasterUpdateDisplay:
  27986. triggerAsyncUpdate();
  27987. break;
  27988. case audioMasterTempoAt:
  27989. // returns (10000 * bpm)
  27990. break;
  27991. case audioMasterNeedIdle:
  27992. startTimer (50);
  27993. break;
  27994. case audioMasterSizeWindow:
  27995. if (getActiveEditor() != 0)
  27996. getActiveEditor()->setSize (index, value);
  27997. return 1;
  27998. case audioMasterGetSampleRate:
  27999. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28000. case audioMasterGetBlockSize:
  28001. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28002. case audioMasterWantMidi:
  28003. wantsMidiMessages = true;
  28004. break;
  28005. case audioMasterGetDirectory:
  28006. #if JUCE_MAC
  28007. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28008. #else
  28009. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8().getAddress();
  28010. #endif
  28011. case audioMasterGetAutomationState:
  28012. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28013. break;
  28014. // none of these are handled (yet)..
  28015. case audioMasterBeginEdit:
  28016. case audioMasterEndEdit:
  28017. case audioMasterSetTime:
  28018. case audioMasterPinConnected:
  28019. case audioMasterGetParameterQuantization:
  28020. case audioMasterIOChanged:
  28021. case audioMasterGetInputLatency:
  28022. case audioMasterGetOutputLatency:
  28023. case audioMasterGetPreviousPlug:
  28024. case audioMasterGetNextPlug:
  28025. case audioMasterWillReplaceOrAccumulate:
  28026. case audioMasterGetCurrentProcessLevel:
  28027. case audioMasterOfflineStart:
  28028. case audioMasterOfflineRead:
  28029. case audioMasterOfflineWrite:
  28030. case audioMasterOfflineGetCurrentPass:
  28031. case audioMasterOfflineGetCurrentMetaPass:
  28032. case audioMasterVendorSpecific:
  28033. case audioMasterSetIcon:
  28034. case audioMasterGetLanguage:
  28035. case audioMasterOpenWindow:
  28036. case audioMasterCloseWindow:
  28037. break;
  28038. default:
  28039. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28040. }
  28041. return 0;
  28042. }
  28043. // entry point for all callbacks from the plugin
  28044. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28045. {
  28046. try
  28047. {
  28048. if (effect != 0 && effect->resvd2 != 0)
  28049. {
  28050. return ((VSTPluginInstance*)(effect->resvd2))
  28051. ->handleCallback (opcode, index, value, ptr, opt);
  28052. }
  28053. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28054. }
  28055. catch (...)
  28056. {
  28057. return 0;
  28058. }
  28059. }
  28060. const String VSTPluginInstance::getVersion() const
  28061. {
  28062. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28063. String s;
  28064. if (v == 0 || v == -1)
  28065. v = getVersionNumber();
  28066. if (v != 0)
  28067. {
  28068. int versionBits[4];
  28069. int n = 0;
  28070. while (v != 0)
  28071. {
  28072. versionBits [n++] = (v & 0xff);
  28073. v >>= 8;
  28074. }
  28075. s << 'V';
  28076. while (n > 0)
  28077. {
  28078. s << versionBits [--n];
  28079. if (n > 0)
  28080. s << '.';
  28081. }
  28082. }
  28083. return s;
  28084. }
  28085. int VSTPluginInstance::getUID() const
  28086. {
  28087. int uid = effect != 0 ? effect->uniqueID : 0;
  28088. if (uid == 0)
  28089. uid = module->file.hashCode();
  28090. return uid;
  28091. }
  28092. const String VSTPluginInstance::getCategory() const
  28093. {
  28094. const char* result = 0;
  28095. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28096. {
  28097. case kPlugCategEffect: result = "Effect"; break;
  28098. case kPlugCategSynth: result = "Synth"; break;
  28099. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28100. case kPlugCategMastering: result = "Mastering"; break;
  28101. case kPlugCategSpacializer: result = "Spacial"; break;
  28102. case kPlugCategRoomFx: result = "Reverb"; break;
  28103. case kPlugSurroundFx: result = "Surround"; break;
  28104. case kPlugCategRestoration: result = "Restoration"; break;
  28105. case kPlugCategGenerator: result = "Tone generation"; break;
  28106. default: break;
  28107. }
  28108. return result;
  28109. }
  28110. float VSTPluginInstance::getParameter (int index)
  28111. {
  28112. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28113. {
  28114. try
  28115. {
  28116. const ScopedLock sl (lock);
  28117. return effect->getParameter (effect, index);
  28118. }
  28119. catch (...)
  28120. {
  28121. }
  28122. }
  28123. return 0.0f;
  28124. }
  28125. void VSTPluginInstance::setParameter (int index, float newValue)
  28126. {
  28127. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28128. {
  28129. try
  28130. {
  28131. const ScopedLock sl (lock);
  28132. if (effect->getParameter (effect, index) != newValue)
  28133. effect->setParameter (effect, index, newValue);
  28134. }
  28135. catch (...)
  28136. {
  28137. }
  28138. }
  28139. }
  28140. const String VSTPluginInstance::getParameterName (int index)
  28141. {
  28142. if (effect != 0)
  28143. {
  28144. jassert (index >= 0 && index < effect->numParams);
  28145. char nm [256];
  28146. zerostruct (nm);
  28147. dispatch (effGetParamName, index, 0, nm, 0);
  28148. return String (nm).trim();
  28149. }
  28150. return String::empty;
  28151. }
  28152. const String VSTPluginInstance::getParameterLabel (int index) const
  28153. {
  28154. if (effect != 0)
  28155. {
  28156. jassert (index >= 0 && index < effect->numParams);
  28157. char nm [256];
  28158. zerostruct (nm);
  28159. dispatch (effGetParamLabel, index, 0, nm, 0);
  28160. return String (nm).trim();
  28161. }
  28162. return String::empty;
  28163. }
  28164. const String VSTPluginInstance::getParameterText (int index)
  28165. {
  28166. if (effect != 0)
  28167. {
  28168. jassert (index >= 0 && index < effect->numParams);
  28169. char nm [256];
  28170. zerostruct (nm);
  28171. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28172. return String (nm).trim();
  28173. }
  28174. return String::empty;
  28175. }
  28176. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28177. {
  28178. if (effect != 0)
  28179. {
  28180. jassert (index >= 0 && index < effect->numParams);
  28181. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28182. }
  28183. return false;
  28184. }
  28185. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28186. {
  28187. dest.setSize (64 + 4 * getNumParameters());
  28188. dest.fillWith (0);
  28189. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28190. float* const p = (float*) (((char*) dest.getData()) + 64);
  28191. for (int i = 0; i < getNumParameters(); ++i)
  28192. p[i] = getParameter(i);
  28193. }
  28194. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28195. {
  28196. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28197. float* p = (float*) (((char*) m.getData()) + 64);
  28198. for (int i = 0; i < getNumParameters(); ++i)
  28199. setParameter (i, p[i]);
  28200. }
  28201. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28202. {
  28203. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28204. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28205. }
  28206. const String VSTPluginInstance::getProgramName (int index)
  28207. {
  28208. if (index == getCurrentProgram())
  28209. {
  28210. return getCurrentProgramName();
  28211. }
  28212. else if (effect != 0)
  28213. {
  28214. char nm [256];
  28215. zerostruct (nm);
  28216. if (dispatch (effGetProgramNameIndexed,
  28217. jlimit (0, getNumPrograms(), index),
  28218. -1, nm, 0) != 0)
  28219. {
  28220. return String (nm).trim();
  28221. }
  28222. }
  28223. return programNames [index];
  28224. }
  28225. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28226. {
  28227. if (index == getCurrentProgram())
  28228. {
  28229. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28230. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28231. }
  28232. else
  28233. {
  28234. jassertfalse; // xxx not implemented!
  28235. }
  28236. }
  28237. void VSTPluginInstance::updateStoredProgramNames()
  28238. {
  28239. if (effect != 0 && getNumPrograms() > 0)
  28240. {
  28241. char nm [256];
  28242. zerostruct (nm);
  28243. // only do this if the plugin can't use indexed names..
  28244. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28245. {
  28246. const int oldProgram = getCurrentProgram();
  28247. MemoryBlock oldSettings;
  28248. createTempParameterStore (oldSettings);
  28249. for (int i = 0; i < getNumPrograms(); ++i)
  28250. {
  28251. setCurrentProgram (i);
  28252. getCurrentProgramName(); // (this updates the list)
  28253. }
  28254. setCurrentProgram (oldProgram);
  28255. restoreFromTempParameterStore (oldSettings);
  28256. }
  28257. }
  28258. }
  28259. const String VSTPluginInstance::getCurrentProgramName()
  28260. {
  28261. if (effect != 0)
  28262. {
  28263. char nm [256];
  28264. zerostruct (nm);
  28265. dispatch (effGetProgramName, 0, 0, nm, 0);
  28266. const int index = getCurrentProgram();
  28267. if (programNames[index].isEmpty())
  28268. {
  28269. while (programNames.size() < index)
  28270. programNames.add (String::empty);
  28271. programNames.set (index, String (nm).trim());
  28272. }
  28273. return String (nm).trim();
  28274. }
  28275. return String::empty;
  28276. }
  28277. const String VSTPluginInstance::getInputChannelName (int index) const
  28278. {
  28279. if (index >= 0 && index < getNumInputChannels())
  28280. {
  28281. VstPinProperties pinProps;
  28282. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28283. return String (pinProps.label, sizeof (pinProps.label));
  28284. }
  28285. return String::empty;
  28286. }
  28287. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28288. {
  28289. if (index < 0 || index >= getNumInputChannels())
  28290. return false;
  28291. VstPinProperties pinProps;
  28292. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28293. return (pinProps.flags & kVstPinIsStereo) != 0;
  28294. return true;
  28295. }
  28296. const String VSTPluginInstance::getOutputChannelName (int index) const
  28297. {
  28298. if (index >= 0 && index < getNumOutputChannels())
  28299. {
  28300. VstPinProperties pinProps;
  28301. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28302. return String (pinProps.label, sizeof (pinProps.label));
  28303. }
  28304. return String::empty;
  28305. }
  28306. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28307. {
  28308. if (index < 0 || index >= getNumOutputChannels())
  28309. return false;
  28310. VstPinProperties pinProps;
  28311. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28312. return (pinProps.flags & kVstPinIsStereo) != 0;
  28313. return true;
  28314. }
  28315. void VSTPluginInstance::setPower (const bool on)
  28316. {
  28317. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28318. isPowerOn = on;
  28319. }
  28320. const int defaultMaxSizeMB = 64;
  28321. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28322. {
  28323. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28324. }
  28325. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28326. {
  28327. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28328. }
  28329. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28330. {
  28331. loadFromFXBFile (data, sizeInBytes);
  28332. }
  28333. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28334. {
  28335. loadFromFXBFile (data, sizeInBytes);
  28336. }
  28337. VSTPluginFormat::VSTPluginFormat()
  28338. {
  28339. }
  28340. VSTPluginFormat::~VSTPluginFormat()
  28341. {
  28342. }
  28343. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28344. const String& fileOrIdentifier)
  28345. {
  28346. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28347. return;
  28348. PluginDescription desc;
  28349. desc.fileOrIdentifier = fileOrIdentifier;
  28350. desc.uid = 0;
  28351. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28352. if (instance == 0)
  28353. return;
  28354. try
  28355. {
  28356. #if JUCE_MAC
  28357. if (instance->module->resFileId != 0)
  28358. UseResFile (instance->module->resFileId);
  28359. #endif
  28360. instance->fillInPluginDescription (desc);
  28361. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28362. if (category != kPlugCategShell)
  28363. {
  28364. // Normal plugin...
  28365. results.add (new PluginDescription (desc));
  28366. ++insideVSTCallback;
  28367. instance->dispatch (effOpen, 0, 0, 0, 0);
  28368. --insideVSTCallback;
  28369. }
  28370. else
  28371. {
  28372. // It's a shell plugin, so iterate all the subtypes...
  28373. char shellEffectName [64];
  28374. for (;;)
  28375. {
  28376. zerostruct (shellEffectName);
  28377. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28378. if (uid == 0)
  28379. {
  28380. break;
  28381. }
  28382. else
  28383. {
  28384. desc.uid = uid;
  28385. desc.name = shellEffectName;
  28386. desc.descriptiveName = shellEffectName;
  28387. bool alreadyThere = false;
  28388. for (int i = results.size(); --i >= 0;)
  28389. {
  28390. PluginDescription* const d = results.getUnchecked(i);
  28391. if (d->isDuplicateOf (desc))
  28392. {
  28393. alreadyThere = true;
  28394. break;
  28395. }
  28396. }
  28397. if (! alreadyThere)
  28398. results.add (new PluginDescription (desc));
  28399. }
  28400. }
  28401. }
  28402. }
  28403. catch (...)
  28404. {
  28405. // crashed while loading...
  28406. }
  28407. }
  28408. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28409. {
  28410. ScopedPointer <VSTPluginInstance> result;
  28411. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28412. {
  28413. File file (desc.fileOrIdentifier);
  28414. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28415. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28416. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28417. if (module != 0)
  28418. {
  28419. shellUIDToCreate = desc.uid;
  28420. result = new VSTPluginInstance (module);
  28421. if (result->effect != 0)
  28422. {
  28423. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28424. result->initialise();
  28425. }
  28426. else
  28427. {
  28428. result = 0;
  28429. }
  28430. }
  28431. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28432. }
  28433. return result.release();
  28434. }
  28435. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28436. {
  28437. const File f (fileOrIdentifier);
  28438. #if JUCE_MAC
  28439. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28440. return true;
  28441. #if JUCE_PPC
  28442. FSRef fileRef;
  28443. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28444. {
  28445. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28446. if (resFileId != -1)
  28447. {
  28448. const int numEffects = Count1Resources ('aEff');
  28449. CloseResFile (resFileId);
  28450. if (numEffects > 0)
  28451. return true;
  28452. }
  28453. }
  28454. #endif
  28455. return false;
  28456. #elif JUCE_WINDOWS
  28457. return f.existsAsFile() && f.hasFileExtension (".dll");
  28458. #elif JUCE_LINUX
  28459. return f.existsAsFile() && f.hasFileExtension (".so");
  28460. #endif
  28461. }
  28462. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28463. {
  28464. return fileOrIdentifier;
  28465. }
  28466. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28467. {
  28468. return File (desc.fileOrIdentifier).exists();
  28469. }
  28470. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28471. {
  28472. StringArray results;
  28473. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28474. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28475. return results;
  28476. }
  28477. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28478. {
  28479. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28480. // .component or .vst directories.
  28481. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28482. while (iter.next())
  28483. {
  28484. const File f (iter.getFile());
  28485. bool isPlugin = false;
  28486. if (fileMightContainThisPluginType (f.getFullPathName()))
  28487. {
  28488. isPlugin = true;
  28489. results.add (f.getFullPathName());
  28490. }
  28491. if (recursive && (! isPlugin) && f.isDirectory())
  28492. recursiveFileSearch (results, f, true);
  28493. }
  28494. }
  28495. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28496. {
  28497. #if JUCE_MAC
  28498. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28499. #elif JUCE_WINDOWS
  28500. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28501. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28502. #elif JUCE_LINUX
  28503. return FileSearchPath ("/usr/lib/vst");
  28504. #endif
  28505. }
  28506. END_JUCE_NAMESPACE
  28507. #endif
  28508. #undef log
  28509. #endif
  28510. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28511. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28512. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28513. BEGIN_JUCE_NAMESPACE
  28514. AudioProcessor::AudioProcessor()
  28515. : playHead (0),
  28516. sampleRate (0),
  28517. blockSize (0),
  28518. numInputChannels (0),
  28519. numOutputChannels (0),
  28520. latencySamples (0),
  28521. suspended (false),
  28522. nonRealtime (false)
  28523. {
  28524. }
  28525. AudioProcessor::~AudioProcessor()
  28526. {
  28527. // ooh, nasty - the editor should have been deleted before the filter
  28528. // that it refers to is deleted..
  28529. jassert (activeEditor == 0);
  28530. #if JUCE_DEBUG
  28531. // This will fail if you've called beginParameterChangeGesture() for one
  28532. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28533. jassert (changingParams.countNumberOfSetBits() == 0);
  28534. #endif
  28535. }
  28536. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28537. {
  28538. playHead = newPlayHead;
  28539. }
  28540. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28541. {
  28542. const ScopedLock sl (listenerLock);
  28543. listeners.addIfNotAlreadyThere (newListener);
  28544. }
  28545. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28546. {
  28547. const ScopedLock sl (listenerLock);
  28548. listeners.removeValue (listenerToRemove);
  28549. }
  28550. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28551. const int numOuts,
  28552. const double sampleRate_,
  28553. const int blockSize_) throw()
  28554. {
  28555. numInputChannels = numIns;
  28556. numOutputChannels = numOuts;
  28557. sampleRate = sampleRate_;
  28558. blockSize = blockSize_;
  28559. }
  28560. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28561. {
  28562. nonRealtime = nonRealtime_;
  28563. }
  28564. void AudioProcessor::setLatencySamples (const int newLatency)
  28565. {
  28566. if (latencySamples != newLatency)
  28567. {
  28568. latencySamples = newLatency;
  28569. updateHostDisplay();
  28570. }
  28571. }
  28572. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28573. const float newValue)
  28574. {
  28575. setParameter (parameterIndex, newValue);
  28576. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28577. }
  28578. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28579. {
  28580. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28581. for (int i = listeners.size(); --i >= 0;)
  28582. {
  28583. AudioProcessorListener* l;
  28584. {
  28585. const ScopedLock sl (listenerLock);
  28586. l = listeners [i];
  28587. }
  28588. if (l != 0)
  28589. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28590. }
  28591. }
  28592. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28593. {
  28594. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28595. #if JUCE_DEBUG
  28596. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28597. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28598. jassert (! changingParams [parameterIndex]);
  28599. changingParams.setBit (parameterIndex);
  28600. #endif
  28601. for (int i = listeners.size(); --i >= 0;)
  28602. {
  28603. AudioProcessorListener* l;
  28604. {
  28605. const ScopedLock sl (listenerLock);
  28606. l = listeners [i];
  28607. }
  28608. if (l != 0)
  28609. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28610. }
  28611. }
  28612. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28613. {
  28614. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28615. #if JUCE_DEBUG
  28616. // This means you've called endParameterChangeGesture without having previously called
  28617. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28618. // calls matched correctly.
  28619. jassert (changingParams [parameterIndex]);
  28620. changingParams.clearBit (parameterIndex);
  28621. #endif
  28622. for (int i = listeners.size(); --i >= 0;)
  28623. {
  28624. AudioProcessorListener* l;
  28625. {
  28626. const ScopedLock sl (listenerLock);
  28627. l = listeners [i];
  28628. }
  28629. if (l != 0)
  28630. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28631. }
  28632. }
  28633. void AudioProcessor::updateHostDisplay()
  28634. {
  28635. for (int i = listeners.size(); --i >= 0;)
  28636. {
  28637. AudioProcessorListener* l;
  28638. {
  28639. const ScopedLock sl (listenerLock);
  28640. l = listeners [i];
  28641. }
  28642. if (l != 0)
  28643. l->audioProcessorChanged (this);
  28644. }
  28645. }
  28646. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28647. {
  28648. return true;
  28649. }
  28650. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28651. {
  28652. return false;
  28653. }
  28654. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28655. {
  28656. const ScopedLock sl (callbackLock);
  28657. suspended = shouldBeSuspended;
  28658. }
  28659. void AudioProcessor::reset()
  28660. {
  28661. }
  28662. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28663. {
  28664. const ScopedLock sl (callbackLock);
  28665. if (activeEditor == editor)
  28666. activeEditor = 0;
  28667. }
  28668. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28669. {
  28670. if (activeEditor != 0)
  28671. return activeEditor;
  28672. AudioProcessorEditor* const ed = createEditor();
  28673. // You must make your hasEditor() method return a consistent result!
  28674. jassert (hasEditor() == (ed != 0));
  28675. if (ed != 0)
  28676. {
  28677. // you must give your editor comp a size before returning it..
  28678. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28679. const ScopedLock sl (callbackLock);
  28680. activeEditor = ed;
  28681. }
  28682. return ed;
  28683. }
  28684. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28685. {
  28686. getStateInformation (destData);
  28687. }
  28688. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28689. {
  28690. setStateInformation (data, sizeInBytes);
  28691. }
  28692. // magic number to identify memory blocks that we've stored as XML
  28693. const uint32 magicXmlNumber = 0x21324356;
  28694. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28695. JUCE_NAMESPACE::MemoryBlock& destData)
  28696. {
  28697. const String xmlString (xml.createDocument (String::empty, true, false));
  28698. const int stringLength = xmlString.getNumBytesAsUTF8();
  28699. destData.setSize (stringLength + 10);
  28700. char* const d = static_cast<char*> (destData.getData());
  28701. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28702. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28703. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28704. }
  28705. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28706. const int sizeInBytes)
  28707. {
  28708. if (sizeInBytes > 8
  28709. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28710. {
  28711. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28712. if (stringLength > 0)
  28713. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28714. jmin ((sizeInBytes - 8), stringLength)));
  28715. }
  28716. return 0;
  28717. }
  28718. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28719. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28720. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28721. {
  28722. return timeInSeconds == other.timeInSeconds
  28723. && ppqPosition == other.ppqPosition
  28724. && editOriginTime == other.editOriginTime
  28725. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28726. && frameRate == other.frameRate
  28727. && isPlaying == other.isPlaying
  28728. && isRecording == other.isRecording
  28729. && bpm == other.bpm
  28730. && timeSigNumerator == other.timeSigNumerator
  28731. && timeSigDenominator == other.timeSigDenominator;
  28732. }
  28733. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28734. {
  28735. return ! operator== (other);
  28736. }
  28737. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28738. {
  28739. zerostruct (*this);
  28740. timeSigNumerator = 4;
  28741. timeSigDenominator = 4;
  28742. bpm = 120;
  28743. }
  28744. END_JUCE_NAMESPACE
  28745. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28746. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28747. BEGIN_JUCE_NAMESPACE
  28748. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28749. : owner (owner_)
  28750. {
  28751. // the filter must be valid..
  28752. jassert (owner != 0);
  28753. }
  28754. AudioProcessorEditor::~AudioProcessorEditor()
  28755. {
  28756. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28757. // filter for some reason..
  28758. jassert (owner->getActiveEditor() != this);
  28759. }
  28760. END_JUCE_NAMESPACE
  28761. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28762. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28763. BEGIN_JUCE_NAMESPACE
  28764. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28765. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28766. : id (id_),
  28767. processor (processor_),
  28768. isPrepared (false)
  28769. {
  28770. jassert (processor_ != 0);
  28771. }
  28772. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28773. AudioProcessorGraph* const graph)
  28774. {
  28775. if (! isPrepared)
  28776. {
  28777. isPrepared = true;
  28778. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28779. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28780. if (ioProc != 0)
  28781. ioProc->setParentGraph (graph);
  28782. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28783. processor->getNumOutputChannels(),
  28784. sampleRate, blockSize);
  28785. processor->prepareToPlay (sampleRate, blockSize);
  28786. }
  28787. }
  28788. void AudioProcessorGraph::Node::unprepare()
  28789. {
  28790. if (isPrepared)
  28791. {
  28792. isPrepared = false;
  28793. processor->releaseResources();
  28794. }
  28795. }
  28796. AudioProcessorGraph::AudioProcessorGraph()
  28797. : lastNodeId (0),
  28798. renderingBuffers (1, 1),
  28799. currentAudioOutputBuffer (1, 1)
  28800. {
  28801. }
  28802. AudioProcessorGraph::~AudioProcessorGraph()
  28803. {
  28804. clearRenderingSequence();
  28805. clear();
  28806. }
  28807. const String AudioProcessorGraph::getName() const
  28808. {
  28809. return "Audio Graph";
  28810. }
  28811. void AudioProcessorGraph::clear()
  28812. {
  28813. nodes.clear();
  28814. connections.clear();
  28815. triggerAsyncUpdate();
  28816. }
  28817. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28818. {
  28819. for (int i = nodes.size(); --i >= 0;)
  28820. if (nodes.getUnchecked(i)->id == nodeId)
  28821. return nodes.getUnchecked(i);
  28822. return 0;
  28823. }
  28824. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28825. uint32 nodeId)
  28826. {
  28827. if (newProcessor == 0)
  28828. {
  28829. jassertfalse;
  28830. return 0;
  28831. }
  28832. if (nodeId == 0)
  28833. {
  28834. nodeId = ++lastNodeId;
  28835. }
  28836. else
  28837. {
  28838. // you can't add a node with an id that already exists in the graph..
  28839. jassert (getNodeForId (nodeId) == 0);
  28840. removeNode (nodeId);
  28841. }
  28842. lastNodeId = nodeId;
  28843. Node* const n = new Node (nodeId, newProcessor);
  28844. nodes.add (n);
  28845. triggerAsyncUpdate();
  28846. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28847. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28848. if (ioProc != 0)
  28849. ioProc->setParentGraph (this);
  28850. return n;
  28851. }
  28852. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28853. {
  28854. disconnectNode (nodeId);
  28855. for (int i = nodes.size(); --i >= 0;)
  28856. {
  28857. if (nodes.getUnchecked(i)->id == nodeId)
  28858. {
  28859. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28860. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28861. if (ioProc != 0)
  28862. ioProc->setParentGraph (0);
  28863. nodes.remove (i);
  28864. triggerAsyncUpdate();
  28865. return true;
  28866. }
  28867. }
  28868. return false;
  28869. }
  28870. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28871. const int sourceChannelIndex,
  28872. const uint32 destNodeId,
  28873. const int destChannelIndex) const
  28874. {
  28875. for (int i = connections.size(); --i >= 0;)
  28876. {
  28877. const Connection* const c = connections.getUnchecked(i);
  28878. if (c->sourceNodeId == sourceNodeId
  28879. && c->destNodeId == destNodeId
  28880. && c->sourceChannelIndex == sourceChannelIndex
  28881. && c->destChannelIndex == destChannelIndex)
  28882. {
  28883. return c;
  28884. }
  28885. }
  28886. return 0;
  28887. }
  28888. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28889. const uint32 possibleDestNodeId) const
  28890. {
  28891. for (int i = connections.size(); --i >= 0;)
  28892. {
  28893. const Connection* const c = connections.getUnchecked(i);
  28894. if (c->sourceNodeId == possibleSourceNodeId
  28895. && c->destNodeId == possibleDestNodeId)
  28896. {
  28897. return true;
  28898. }
  28899. }
  28900. return false;
  28901. }
  28902. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28903. const int sourceChannelIndex,
  28904. const uint32 destNodeId,
  28905. const int destChannelIndex) const
  28906. {
  28907. if (sourceChannelIndex < 0
  28908. || destChannelIndex < 0
  28909. || sourceNodeId == destNodeId
  28910. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28911. return false;
  28912. const Node* const source = getNodeForId (sourceNodeId);
  28913. if (source == 0
  28914. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28915. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28916. return false;
  28917. const Node* const dest = getNodeForId (destNodeId);
  28918. if (dest == 0
  28919. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28920. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28921. return false;
  28922. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28923. destNodeId, destChannelIndex) == 0;
  28924. }
  28925. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28926. const int sourceChannelIndex,
  28927. const uint32 destNodeId,
  28928. const int destChannelIndex)
  28929. {
  28930. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28931. return false;
  28932. Connection* const c = new Connection();
  28933. c->sourceNodeId = sourceNodeId;
  28934. c->sourceChannelIndex = sourceChannelIndex;
  28935. c->destNodeId = destNodeId;
  28936. c->destChannelIndex = destChannelIndex;
  28937. connections.add (c);
  28938. triggerAsyncUpdate();
  28939. return true;
  28940. }
  28941. void AudioProcessorGraph::removeConnection (const int index)
  28942. {
  28943. connections.remove (index);
  28944. triggerAsyncUpdate();
  28945. }
  28946. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28947. const uint32 destNodeId, const int destChannelIndex)
  28948. {
  28949. bool doneAnything = false;
  28950. for (int i = connections.size(); --i >= 0;)
  28951. {
  28952. const Connection* const c = connections.getUnchecked(i);
  28953. if (c->sourceNodeId == sourceNodeId
  28954. && c->destNodeId == destNodeId
  28955. && c->sourceChannelIndex == sourceChannelIndex
  28956. && c->destChannelIndex == destChannelIndex)
  28957. {
  28958. removeConnection (i);
  28959. doneAnything = true;
  28960. triggerAsyncUpdate();
  28961. }
  28962. }
  28963. return doneAnything;
  28964. }
  28965. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28966. {
  28967. bool doneAnything = false;
  28968. for (int i = connections.size(); --i >= 0;)
  28969. {
  28970. const Connection* const c = connections.getUnchecked(i);
  28971. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28972. {
  28973. removeConnection (i);
  28974. doneAnything = true;
  28975. triggerAsyncUpdate();
  28976. }
  28977. }
  28978. return doneAnything;
  28979. }
  28980. bool AudioProcessorGraph::removeIllegalConnections()
  28981. {
  28982. bool doneAnything = false;
  28983. for (int i = connections.size(); --i >= 0;)
  28984. {
  28985. const Connection* const c = connections.getUnchecked(i);
  28986. const Node* const source = getNodeForId (c->sourceNodeId);
  28987. const Node* const dest = getNodeForId (c->destNodeId);
  28988. if (source == 0 || dest == 0
  28989. || (c->sourceChannelIndex != midiChannelIndex
  28990. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  28991. || (c->sourceChannelIndex == midiChannelIndex
  28992. && ! source->processor->producesMidi())
  28993. || (c->destChannelIndex != midiChannelIndex
  28994. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  28995. || (c->destChannelIndex == midiChannelIndex
  28996. && ! dest->processor->acceptsMidi()))
  28997. {
  28998. removeConnection (i);
  28999. doneAnything = true;
  29000. triggerAsyncUpdate();
  29001. }
  29002. }
  29003. return doneAnything;
  29004. }
  29005. namespace GraphRenderingOps
  29006. {
  29007. class AudioGraphRenderingOp
  29008. {
  29009. public:
  29010. AudioGraphRenderingOp() {}
  29011. virtual ~AudioGraphRenderingOp() {}
  29012. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29013. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29014. const int numSamples) = 0;
  29015. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29016. };
  29017. class ClearChannelOp : public AudioGraphRenderingOp
  29018. {
  29019. public:
  29020. ClearChannelOp (const int channelNum_)
  29021. : channelNum (channelNum_)
  29022. {}
  29023. ~ClearChannelOp() {}
  29024. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29025. {
  29026. sharedBufferChans.clear (channelNum, 0, numSamples);
  29027. }
  29028. private:
  29029. const int channelNum;
  29030. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29031. };
  29032. class CopyChannelOp : public AudioGraphRenderingOp
  29033. {
  29034. public:
  29035. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29036. : srcChannelNum (srcChannelNum_),
  29037. dstChannelNum (dstChannelNum_)
  29038. {}
  29039. ~CopyChannelOp() {}
  29040. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29041. {
  29042. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29043. }
  29044. private:
  29045. const int srcChannelNum, dstChannelNum;
  29046. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29047. };
  29048. class AddChannelOp : public AudioGraphRenderingOp
  29049. {
  29050. public:
  29051. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29052. : srcChannelNum (srcChannelNum_),
  29053. dstChannelNum (dstChannelNum_)
  29054. {}
  29055. ~AddChannelOp() {}
  29056. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29057. {
  29058. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29059. }
  29060. private:
  29061. const int srcChannelNum, dstChannelNum;
  29062. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29063. };
  29064. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29065. {
  29066. public:
  29067. ClearMidiBufferOp (const int bufferNum_)
  29068. : bufferNum (bufferNum_)
  29069. {}
  29070. ~ClearMidiBufferOp() {}
  29071. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29072. {
  29073. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29074. }
  29075. private:
  29076. const int bufferNum;
  29077. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29078. };
  29079. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29080. {
  29081. public:
  29082. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29083. : srcBufferNum (srcBufferNum_),
  29084. dstBufferNum (dstBufferNum_)
  29085. {}
  29086. ~CopyMidiBufferOp() {}
  29087. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29088. {
  29089. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29090. }
  29091. private:
  29092. const int srcBufferNum, dstBufferNum;
  29093. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29094. };
  29095. class AddMidiBufferOp : public AudioGraphRenderingOp
  29096. {
  29097. public:
  29098. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29099. : srcBufferNum (srcBufferNum_),
  29100. dstBufferNum (dstBufferNum_)
  29101. {}
  29102. ~AddMidiBufferOp() {}
  29103. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29104. {
  29105. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29106. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29107. }
  29108. private:
  29109. const int srcBufferNum, dstBufferNum;
  29110. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29111. };
  29112. class ProcessBufferOp : public AudioGraphRenderingOp
  29113. {
  29114. public:
  29115. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29116. const Array <int>& audioChannelsToUse_,
  29117. const int totalChans_,
  29118. const int midiBufferToUse_)
  29119. : node (node_),
  29120. processor (node_->getProcessor()),
  29121. audioChannelsToUse (audioChannelsToUse_),
  29122. totalChans (jmax (1, totalChans_)),
  29123. midiBufferToUse (midiBufferToUse_)
  29124. {
  29125. channels.calloc (totalChans);
  29126. while (audioChannelsToUse.size() < totalChans)
  29127. audioChannelsToUse.add (0);
  29128. }
  29129. ~ProcessBufferOp()
  29130. {
  29131. }
  29132. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29133. {
  29134. for (int i = totalChans; --i >= 0;)
  29135. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29136. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29137. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29138. }
  29139. const AudioProcessorGraph::Node::Ptr node;
  29140. AudioProcessor* const processor;
  29141. private:
  29142. Array <int> audioChannelsToUse;
  29143. HeapBlock <float*> channels;
  29144. int totalChans;
  29145. int midiBufferToUse;
  29146. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29147. };
  29148. /** Used to calculate the correct sequence of rendering ops needed, based on
  29149. the best re-use of shared buffers at each stage.
  29150. */
  29151. class RenderingOpSequenceCalculator
  29152. {
  29153. public:
  29154. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29155. const Array<void*>& orderedNodes_,
  29156. Array<void*>& renderingOps)
  29157. : graph (graph_),
  29158. orderedNodes (orderedNodes_)
  29159. {
  29160. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29161. channels.add (0);
  29162. midiNodeIds.add ((uint32) zeroNodeID);
  29163. for (int i = 0; i < orderedNodes.size(); ++i)
  29164. {
  29165. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29166. renderingOps, i);
  29167. markAnyUnusedBuffersAsFree (i);
  29168. }
  29169. }
  29170. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29171. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29172. private:
  29173. AudioProcessorGraph& graph;
  29174. const Array<void*>& orderedNodes;
  29175. Array <int> channels;
  29176. Array <uint32> nodeIds, midiNodeIds;
  29177. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29178. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29179. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29180. Array<void*>& renderingOps,
  29181. const int ourRenderingIndex)
  29182. {
  29183. const int numIns = node->getProcessor()->getNumInputChannels();
  29184. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29185. const int totalChans = jmax (numIns, numOuts);
  29186. Array <int> audioChannelsToUse;
  29187. int midiBufferToUse = -1;
  29188. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29189. {
  29190. // get a list of all the inputs to this node
  29191. Array <int> sourceNodes, sourceOutputChans;
  29192. for (int i = graph.getNumConnections(); --i >= 0;)
  29193. {
  29194. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29195. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29196. {
  29197. sourceNodes.add (c->sourceNodeId);
  29198. sourceOutputChans.add (c->sourceChannelIndex);
  29199. }
  29200. }
  29201. int bufIndex = -1;
  29202. if (sourceNodes.size() == 0)
  29203. {
  29204. // unconnected input channel
  29205. if (inputChan >= numOuts)
  29206. {
  29207. bufIndex = getReadOnlyEmptyBuffer();
  29208. jassert (bufIndex >= 0);
  29209. }
  29210. else
  29211. {
  29212. bufIndex = getFreeBuffer (false);
  29213. renderingOps.add (new ClearChannelOp (bufIndex));
  29214. }
  29215. }
  29216. else if (sourceNodes.size() == 1)
  29217. {
  29218. // channel with a straightforward single input..
  29219. const int srcNode = sourceNodes.getUnchecked(0);
  29220. const int srcChan = sourceOutputChans.getUnchecked(0);
  29221. bufIndex = getBufferContaining (srcNode, srcChan);
  29222. if (bufIndex < 0)
  29223. {
  29224. // if not found, this is probably a feedback loop
  29225. bufIndex = getReadOnlyEmptyBuffer();
  29226. jassert (bufIndex >= 0);
  29227. }
  29228. if (inputChan < numOuts
  29229. && isBufferNeededLater (ourRenderingIndex,
  29230. inputChan,
  29231. srcNode, srcChan))
  29232. {
  29233. // can't mess up this channel because it's needed later by another node, so we
  29234. // need to use a copy of it..
  29235. const int newFreeBuffer = getFreeBuffer (false);
  29236. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29237. bufIndex = newFreeBuffer;
  29238. }
  29239. }
  29240. else
  29241. {
  29242. // channel with a mix of several inputs..
  29243. // try to find a re-usable channel from our inputs..
  29244. int reusableInputIndex = -1;
  29245. for (int i = 0; i < sourceNodes.size(); ++i)
  29246. {
  29247. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29248. sourceOutputChans.getUnchecked(i));
  29249. if (sourceBufIndex >= 0
  29250. && ! isBufferNeededLater (ourRenderingIndex,
  29251. inputChan,
  29252. sourceNodes.getUnchecked(i),
  29253. sourceOutputChans.getUnchecked(i)))
  29254. {
  29255. // we've found one of our input chans that can be re-used..
  29256. reusableInputIndex = i;
  29257. bufIndex = sourceBufIndex;
  29258. break;
  29259. }
  29260. }
  29261. if (reusableInputIndex < 0)
  29262. {
  29263. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29264. bufIndex = getFreeBuffer (false);
  29265. jassert (bufIndex != 0);
  29266. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29267. sourceOutputChans.getUnchecked (0));
  29268. if (srcIndex < 0)
  29269. {
  29270. // if not found, this is probably a feedback loop
  29271. renderingOps.add (new ClearChannelOp (bufIndex));
  29272. }
  29273. else
  29274. {
  29275. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29276. }
  29277. reusableInputIndex = 0;
  29278. }
  29279. for (int j = 0; j < sourceNodes.size(); ++j)
  29280. {
  29281. if (j != reusableInputIndex)
  29282. {
  29283. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29284. sourceOutputChans.getUnchecked(j));
  29285. if (srcIndex >= 0)
  29286. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29287. }
  29288. }
  29289. }
  29290. jassert (bufIndex >= 0);
  29291. audioChannelsToUse.add (bufIndex);
  29292. if (inputChan < numOuts)
  29293. markBufferAsContaining (bufIndex, node->id, inputChan);
  29294. }
  29295. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29296. {
  29297. const int bufIndex = getFreeBuffer (false);
  29298. jassert (bufIndex != 0);
  29299. audioChannelsToUse.add (bufIndex);
  29300. markBufferAsContaining (bufIndex, node->id, outputChan);
  29301. }
  29302. // Now the same thing for midi..
  29303. Array <int> midiSourceNodes;
  29304. for (int i = graph.getNumConnections(); --i >= 0;)
  29305. {
  29306. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29307. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29308. midiSourceNodes.add (c->sourceNodeId);
  29309. }
  29310. if (midiSourceNodes.size() == 0)
  29311. {
  29312. // No midi inputs..
  29313. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29314. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29315. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29316. }
  29317. else if (midiSourceNodes.size() == 1)
  29318. {
  29319. // One midi input..
  29320. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29321. AudioProcessorGraph::midiChannelIndex);
  29322. if (midiBufferToUse >= 0)
  29323. {
  29324. if (isBufferNeededLater (ourRenderingIndex,
  29325. AudioProcessorGraph::midiChannelIndex,
  29326. midiSourceNodes.getUnchecked(0),
  29327. AudioProcessorGraph::midiChannelIndex))
  29328. {
  29329. // can't mess up this channel because it's needed later by another node, so we
  29330. // need to use a copy of it..
  29331. const int newFreeBuffer = getFreeBuffer (true);
  29332. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29333. midiBufferToUse = newFreeBuffer;
  29334. }
  29335. }
  29336. else
  29337. {
  29338. // probably a feedback loop, so just use an empty one..
  29339. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29340. }
  29341. }
  29342. else
  29343. {
  29344. // More than one midi input being mixed..
  29345. int reusableInputIndex = -1;
  29346. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29347. {
  29348. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29349. AudioProcessorGraph::midiChannelIndex);
  29350. if (sourceBufIndex >= 0
  29351. && ! isBufferNeededLater (ourRenderingIndex,
  29352. AudioProcessorGraph::midiChannelIndex,
  29353. midiSourceNodes.getUnchecked(i),
  29354. AudioProcessorGraph::midiChannelIndex))
  29355. {
  29356. // we've found one of our input buffers that can be re-used..
  29357. reusableInputIndex = i;
  29358. midiBufferToUse = sourceBufIndex;
  29359. break;
  29360. }
  29361. }
  29362. if (reusableInputIndex < 0)
  29363. {
  29364. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29365. midiBufferToUse = getFreeBuffer (true);
  29366. jassert (midiBufferToUse >= 0);
  29367. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29368. AudioProcessorGraph::midiChannelIndex);
  29369. if (srcIndex >= 0)
  29370. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29371. else
  29372. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29373. reusableInputIndex = 0;
  29374. }
  29375. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29376. {
  29377. if (j != reusableInputIndex)
  29378. {
  29379. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29380. AudioProcessorGraph::midiChannelIndex);
  29381. if (srcIndex >= 0)
  29382. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29383. }
  29384. }
  29385. }
  29386. if (node->getProcessor()->producesMidi())
  29387. markBufferAsContaining (midiBufferToUse, node->id,
  29388. AudioProcessorGraph::midiChannelIndex);
  29389. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29390. totalChans, midiBufferToUse));
  29391. }
  29392. int getFreeBuffer (const bool forMidi)
  29393. {
  29394. if (forMidi)
  29395. {
  29396. for (int i = 1; i < midiNodeIds.size(); ++i)
  29397. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29398. return i;
  29399. midiNodeIds.add ((uint32) freeNodeID);
  29400. return midiNodeIds.size() - 1;
  29401. }
  29402. else
  29403. {
  29404. for (int i = 1; i < nodeIds.size(); ++i)
  29405. if (nodeIds.getUnchecked(i) == freeNodeID)
  29406. return i;
  29407. nodeIds.add ((uint32) freeNodeID);
  29408. channels.add (0);
  29409. return nodeIds.size() - 1;
  29410. }
  29411. }
  29412. int getReadOnlyEmptyBuffer() const
  29413. {
  29414. return 0;
  29415. }
  29416. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29417. {
  29418. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29419. {
  29420. for (int i = midiNodeIds.size(); --i >= 0;)
  29421. if (midiNodeIds.getUnchecked(i) == nodeId)
  29422. return i;
  29423. }
  29424. else
  29425. {
  29426. for (int i = nodeIds.size(); --i >= 0;)
  29427. if (nodeIds.getUnchecked(i) == nodeId
  29428. && channels.getUnchecked(i) == outputChannel)
  29429. return i;
  29430. }
  29431. return -1;
  29432. }
  29433. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29434. {
  29435. int i;
  29436. for (i = 0; i < nodeIds.size(); ++i)
  29437. {
  29438. if (isNodeBusy (nodeIds.getUnchecked(i))
  29439. && ! isBufferNeededLater (stepIndex, -1,
  29440. nodeIds.getUnchecked(i),
  29441. channels.getUnchecked(i)))
  29442. {
  29443. nodeIds.set (i, (uint32) freeNodeID);
  29444. }
  29445. }
  29446. for (i = 0; i < midiNodeIds.size(); ++i)
  29447. {
  29448. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29449. && ! isBufferNeededLater (stepIndex, -1,
  29450. midiNodeIds.getUnchecked(i),
  29451. AudioProcessorGraph::midiChannelIndex))
  29452. {
  29453. midiNodeIds.set (i, (uint32) freeNodeID);
  29454. }
  29455. }
  29456. }
  29457. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29458. int inputChannelOfIndexToIgnore,
  29459. const uint32 nodeId,
  29460. const int outputChanIndex) const
  29461. {
  29462. while (stepIndexToSearchFrom < orderedNodes.size())
  29463. {
  29464. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29465. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29466. {
  29467. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29468. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29469. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29470. return true;
  29471. }
  29472. else
  29473. {
  29474. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29475. if (i != inputChannelOfIndexToIgnore
  29476. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29477. node->id, i) != 0)
  29478. return true;
  29479. }
  29480. inputChannelOfIndexToIgnore = -1;
  29481. ++stepIndexToSearchFrom;
  29482. }
  29483. return false;
  29484. }
  29485. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29486. {
  29487. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29488. {
  29489. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29490. midiNodeIds.set (bufferNum, nodeId);
  29491. }
  29492. else
  29493. {
  29494. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29495. nodeIds.set (bufferNum, nodeId);
  29496. channels.set (bufferNum, outputIndex);
  29497. }
  29498. }
  29499. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29500. };
  29501. }
  29502. void AudioProcessorGraph::clearRenderingSequence()
  29503. {
  29504. const ScopedLock sl (renderLock);
  29505. for (int i = renderingOps.size(); --i >= 0;)
  29506. {
  29507. GraphRenderingOps::AudioGraphRenderingOp* const r
  29508. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29509. renderingOps.remove (i);
  29510. delete r;
  29511. }
  29512. }
  29513. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29514. const uint32 possibleDestinationId,
  29515. const int recursionCheck) const
  29516. {
  29517. if (recursionCheck > 0)
  29518. {
  29519. for (int i = connections.size(); --i >= 0;)
  29520. {
  29521. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29522. if (c->destNodeId == possibleDestinationId
  29523. && (c->sourceNodeId == possibleInputId
  29524. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29525. return true;
  29526. }
  29527. }
  29528. return false;
  29529. }
  29530. void AudioProcessorGraph::buildRenderingSequence()
  29531. {
  29532. Array<void*> newRenderingOps;
  29533. int numRenderingBuffersNeeded = 2;
  29534. int numMidiBuffersNeeded = 1;
  29535. {
  29536. MessageManagerLock mml;
  29537. Array<void*> orderedNodes;
  29538. int i;
  29539. for (i = 0; i < nodes.size(); ++i)
  29540. {
  29541. Node* const node = nodes.getUnchecked(i);
  29542. node->prepare (getSampleRate(), getBlockSize(), this);
  29543. int j = 0;
  29544. for (; j < orderedNodes.size(); ++j)
  29545. if (isAnInputTo (node->id,
  29546. ((Node*) orderedNodes.getUnchecked (j))->id,
  29547. nodes.size() + 1))
  29548. break;
  29549. orderedNodes.insert (j, node);
  29550. }
  29551. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29552. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29553. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29554. }
  29555. Array<void*> oldRenderingOps (renderingOps);
  29556. {
  29557. // swap over to the new rendering sequence..
  29558. const ScopedLock sl (renderLock);
  29559. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29560. renderingBuffers.clear();
  29561. for (int i = midiBuffers.size(); --i >= 0;)
  29562. midiBuffers.getUnchecked(i)->clear();
  29563. while (midiBuffers.size() < numMidiBuffersNeeded)
  29564. midiBuffers.add (new MidiBuffer());
  29565. renderingOps = newRenderingOps;
  29566. }
  29567. for (int i = oldRenderingOps.size(); --i >= 0;)
  29568. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29569. }
  29570. void AudioProcessorGraph::handleAsyncUpdate()
  29571. {
  29572. buildRenderingSequence();
  29573. }
  29574. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29575. {
  29576. currentAudioInputBuffer = 0;
  29577. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29578. currentMidiInputBuffer = 0;
  29579. currentMidiOutputBuffer.clear();
  29580. clearRenderingSequence();
  29581. buildRenderingSequence();
  29582. }
  29583. void AudioProcessorGraph::releaseResources()
  29584. {
  29585. for (int i = 0; i < nodes.size(); ++i)
  29586. nodes.getUnchecked(i)->unprepare();
  29587. renderingBuffers.setSize (1, 1);
  29588. midiBuffers.clear();
  29589. currentAudioInputBuffer = 0;
  29590. currentAudioOutputBuffer.setSize (1, 1);
  29591. currentMidiInputBuffer = 0;
  29592. currentMidiOutputBuffer.clear();
  29593. }
  29594. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29595. {
  29596. const int numSamples = buffer.getNumSamples();
  29597. const ScopedLock sl (renderLock);
  29598. currentAudioInputBuffer = &buffer;
  29599. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29600. currentAudioOutputBuffer.clear();
  29601. currentMidiInputBuffer = &midiMessages;
  29602. currentMidiOutputBuffer.clear();
  29603. int i;
  29604. for (i = 0; i < renderingOps.size(); ++i)
  29605. {
  29606. GraphRenderingOps::AudioGraphRenderingOp* const op
  29607. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29608. op->perform (renderingBuffers, midiBuffers, numSamples);
  29609. }
  29610. for (i = 0; i < buffer.getNumChannels(); ++i)
  29611. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29612. midiMessages.clear();
  29613. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29614. }
  29615. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29616. {
  29617. return "Input " + String (channelIndex + 1);
  29618. }
  29619. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29620. {
  29621. return "Output " + String (channelIndex + 1);
  29622. }
  29623. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29624. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29625. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29626. bool AudioProcessorGraph::producesMidi() const { return true; }
  29627. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29628. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29629. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29630. : type (type_),
  29631. graph (0)
  29632. {
  29633. }
  29634. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29635. {
  29636. }
  29637. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29638. {
  29639. switch (type)
  29640. {
  29641. case audioOutputNode: return "Audio Output";
  29642. case audioInputNode: return "Audio Input";
  29643. case midiOutputNode: return "Midi Output";
  29644. case midiInputNode: return "Midi Input";
  29645. default: break;
  29646. }
  29647. return String::empty;
  29648. }
  29649. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29650. {
  29651. d.name = getName();
  29652. d.uid = d.name.hashCode();
  29653. d.category = "I/O devices";
  29654. d.pluginFormatName = "Internal";
  29655. d.manufacturerName = "Raw Material Software";
  29656. d.version = "1.0";
  29657. d.isInstrument = false;
  29658. d.numInputChannels = getNumInputChannels();
  29659. if (type == audioOutputNode && graph != 0)
  29660. d.numInputChannels = graph->getNumInputChannels();
  29661. d.numOutputChannels = getNumOutputChannels();
  29662. if (type == audioInputNode && graph != 0)
  29663. d.numOutputChannels = graph->getNumOutputChannels();
  29664. }
  29665. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29666. {
  29667. jassert (graph != 0);
  29668. }
  29669. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29670. {
  29671. }
  29672. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29673. MidiBuffer& midiMessages)
  29674. {
  29675. jassert (graph != 0);
  29676. switch (type)
  29677. {
  29678. case audioOutputNode:
  29679. {
  29680. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29681. buffer.getNumChannels()); --i >= 0;)
  29682. {
  29683. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29684. }
  29685. break;
  29686. }
  29687. case audioInputNode:
  29688. {
  29689. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29690. buffer.getNumChannels()); --i >= 0;)
  29691. {
  29692. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29693. }
  29694. break;
  29695. }
  29696. case midiOutputNode:
  29697. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29698. break;
  29699. case midiInputNode:
  29700. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29701. break;
  29702. default:
  29703. break;
  29704. }
  29705. }
  29706. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29707. {
  29708. return type == midiOutputNode;
  29709. }
  29710. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29711. {
  29712. return type == midiInputNode;
  29713. }
  29714. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29715. {
  29716. switch (type)
  29717. {
  29718. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29719. case midiOutputNode: return "Midi Output";
  29720. default: break;
  29721. }
  29722. return String::empty;
  29723. }
  29724. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29725. {
  29726. switch (type)
  29727. {
  29728. case audioInputNode: return "Input " + String (channelIndex + 1);
  29729. case midiInputNode: return "Midi Input";
  29730. default: break;
  29731. }
  29732. return String::empty;
  29733. }
  29734. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29735. {
  29736. return type == audioInputNode || type == audioOutputNode;
  29737. }
  29738. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29739. {
  29740. return isInputChannelStereoPair (index);
  29741. }
  29742. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29743. {
  29744. return type == audioInputNode || type == midiInputNode;
  29745. }
  29746. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29747. {
  29748. return type == audioOutputNode || type == midiOutputNode;
  29749. }
  29750. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29751. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29752. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29753. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29754. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29755. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29756. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29757. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29758. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29759. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29760. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29761. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29762. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29763. {
  29764. }
  29765. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29766. {
  29767. }
  29768. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29769. {
  29770. graph = newGraph;
  29771. if (graph != 0)
  29772. {
  29773. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29774. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29775. getSampleRate(),
  29776. getBlockSize());
  29777. updateHostDisplay();
  29778. }
  29779. }
  29780. END_JUCE_NAMESPACE
  29781. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29782. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29783. BEGIN_JUCE_NAMESPACE
  29784. AudioProcessorPlayer::AudioProcessorPlayer()
  29785. : processor (0),
  29786. sampleRate (0),
  29787. blockSize (0),
  29788. isPrepared (false),
  29789. numInputChans (0),
  29790. numOutputChans (0),
  29791. tempBuffer (1, 1)
  29792. {
  29793. }
  29794. AudioProcessorPlayer::~AudioProcessorPlayer()
  29795. {
  29796. setProcessor (0);
  29797. }
  29798. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29799. {
  29800. if (processor != processorToPlay)
  29801. {
  29802. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29803. {
  29804. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29805. sampleRate, blockSize);
  29806. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29807. }
  29808. AudioProcessor* oldOne;
  29809. {
  29810. const ScopedLock sl (lock);
  29811. oldOne = isPrepared ? processor : 0;
  29812. processor = processorToPlay;
  29813. isPrepared = true;
  29814. }
  29815. if (oldOne != 0)
  29816. oldOne->releaseResources();
  29817. }
  29818. }
  29819. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29820. const int numInputChannels,
  29821. float** const outputChannelData,
  29822. const int numOutputChannels,
  29823. const int numSamples)
  29824. {
  29825. // these should have been prepared by audioDeviceAboutToStart()...
  29826. jassert (sampleRate > 0 && blockSize > 0);
  29827. incomingMidi.clear();
  29828. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29829. int i, totalNumChans = 0;
  29830. if (numInputChannels > numOutputChannels)
  29831. {
  29832. // if there aren't enough output channels for the number of
  29833. // inputs, we need to create some temporary extra ones (can't
  29834. // use the input data in case it gets written to)
  29835. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29836. false, false, true);
  29837. for (i = 0; i < numOutputChannels; ++i)
  29838. {
  29839. channels[totalNumChans] = outputChannelData[i];
  29840. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29841. ++totalNumChans;
  29842. }
  29843. for (i = numOutputChannels; i < numInputChannels; ++i)
  29844. {
  29845. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29846. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29847. ++totalNumChans;
  29848. }
  29849. }
  29850. else
  29851. {
  29852. for (i = 0; i < numInputChannels; ++i)
  29853. {
  29854. channels[totalNumChans] = outputChannelData[i];
  29855. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29856. ++totalNumChans;
  29857. }
  29858. for (i = numInputChannels; i < numOutputChannels; ++i)
  29859. {
  29860. channels[totalNumChans] = outputChannelData[i];
  29861. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29862. ++totalNumChans;
  29863. }
  29864. }
  29865. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29866. const ScopedLock sl (lock);
  29867. if (processor != 0)
  29868. {
  29869. const ScopedLock sl2 (processor->getCallbackLock());
  29870. if (processor->isSuspended())
  29871. {
  29872. for (i = 0; i < numOutputChannels; ++i)
  29873. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29874. }
  29875. else
  29876. {
  29877. processor->processBlock (buffer, incomingMidi);
  29878. }
  29879. }
  29880. }
  29881. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29882. {
  29883. const ScopedLock sl (lock);
  29884. sampleRate = device->getCurrentSampleRate();
  29885. blockSize = device->getCurrentBufferSizeSamples();
  29886. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29887. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29888. messageCollector.reset (sampleRate);
  29889. zeromem (channels, sizeof (channels));
  29890. if (processor != 0)
  29891. {
  29892. if (isPrepared)
  29893. processor->releaseResources();
  29894. AudioProcessor* const oldProcessor = processor;
  29895. setProcessor (0);
  29896. setProcessor (oldProcessor);
  29897. }
  29898. }
  29899. void AudioProcessorPlayer::audioDeviceStopped()
  29900. {
  29901. const ScopedLock sl (lock);
  29902. if (processor != 0 && isPrepared)
  29903. processor->releaseResources();
  29904. sampleRate = 0.0;
  29905. blockSize = 0;
  29906. isPrepared = false;
  29907. tempBuffer.setSize (1, 1);
  29908. }
  29909. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29910. {
  29911. messageCollector.addMessageToQueue (message);
  29912. }
  29913. END_JUCE_NAMESPACE
  29914. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29915. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29916. BEGIN_JUCE_NAMESPACE
  29917. class ProcessorParameterPropertyComp : public PropertyComponent,
  29918. public AudioProcessorListener,
  29919. public Timer
  29920. {
  29921. public:
  29922. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  29923. : PropertyComponent (name),
  29924. owner (owner_),
  29925. index (index_),
  29926. paramHasChanged (false),
  29927. slider (owner_, index_)
  29928. {
  29929. startTimer (100);
  29930. addAndMakeVisible (&slider);
  29931. owner_.addListener (this);
  29932. }
  29933. ~ProcessorParameterPropertyComp()
  29934. {
  29935. owner.removeListener (this);
  29936. }
  29937. void refresh()
  29938. {
  29939. paramHasChanged = false;
  29940. slider.setValue (owner.getParameter (index), false);
  29941. }
  29942. void audioProcessorChanged (AudioProcessor*) {}
  29943. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29944. {
  29945. if (parameterIndex == index)
  29946. paramHasChanged = true;
  29947. }
  29948. void timerCallback()
  29949. {
  29950. if (paramHasChanged)
  29951. {
  29952. refresh();
  29953. startTimer (1000 / 50);
  29954. }
  29955. else
  29956. {
  29957. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  29958. }
  29959. }
  29960. private:
  29961. class ParamSlider : public Slider
  29962. {
  29963. public:
  29964. ParamSlider (AudioProcessor& owner_, const int index_)
  29965. : owner (owner_),
  29966. index (index_)
  29967. {
  29968. setRange (0.0, 1.0, 0.0);
  29969. setSliderStyle (Slider::LinearBar);
  29970. setTextBoxIsEditable (false);
  29971. setScrollWheelEnabled (false);
  29972. }
  29973. void valueChanged()
  29974. {
  29975. const float newVal = (float) getValue();
  29976. if (owner.getParameter (index) != newVal)
  29977. owner.setParameter (index, newVal);
  29978. }
  29979. const String getTextFromValue (double /*value*/)
  29980. {
  29981. return owner.getParameterText (index);
  29982. }
  29983. private:
  29984. AudioProcessor& owner;
  29985. const int index;
  29986. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  29987. };
  29988. AudioProcessor& owner;
  29989. const int index;
  29990. bool volatile paramHasChanged;
  29991. ParamSlider slider;
  29992. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  29993. };
  29994. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29995. : AudioProcessorEditor (owner_)
  29996. {
  29997. jassert (owner_ != 0);
  29998. setOpaque (true);
  29999. addAndMakeVisible (&panel);
  30000. Array <PropertyComponent*> params;
  30001. const int numParams = owner_->getNumParameters();
  30002. int totalHeight = 0;
  30003. for (int i = 0; i < numParams; ++i)
  30004. {
  30005. String name (owner_->getParameterName (i));
  30006. if (name.trim().isEmpty())
  30007. name = "Unnamed";
  30008. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30009. params.add (pc);
  30010. totalHeight += pc->getPreferredHeight();
  30011. }
  30012. panel.addProperties (params);
  30013. setSize (400, jlimit (25, 400, totalHeight));
  30014. }
  30015. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30016. {
  30017. }
  30018. void GenericAudioProcessorEditor::paint (Graphics& g)
  30019. {
  30020. g.fillAll (Colours::white);
  30021. }
  30022. void GenericAudioProcessorEditor::resized()
  30023. {
  30024. panel.setBounds (getLocalBounds());
  30025. }
  30026. END_JUCE_NAMESPACE
  30027. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30028. /*** Start of inlined file: juce_Sampler.cpp ***/
  30029. BEGIN_JUCE_NAMESPACE
  30030. SamplerSound::SamplerSound (const String& name_,
  30031. AudioFormatReader& source,
  30032. const BigInteger& midiNotes_,
  30033. const int midiNoteForNormalPitch,
  30034. const double attackTimeSecs,
  30035. const double releaseTimeSecs,
  30036. const double maxSampleLengthSeconds)
  30037. : name (name_),
  30038. midiNotes (midiNotes_),
  30039. midiRootNote (midiNoteForNormalPitch)
  30040. {
  30041. sourceSampleRate = source.sampleRate;
  30042. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30043. {
  30044. length = 0;
  30045. attackSamples = 0;
  30046. releaseSamples = 0;
  30047. }
  30048. else
  30049. {
  30050. length = jmin ((int) source.lengthInSamples,
  30051. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30052. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30053. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30054. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30055. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30056. }
  30057. }
  30058. SamplerSound::~SamplerSound()
  30059. {
  30060. }
  30061. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30062. {
  30063. return midiNotes [midiNoteNumber];
  30064. }
  30065. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30066. {
  30067. return true;
  30068. }
  30069. SamplerVoice::SamplerVoice()
  30070. : pitchRatio (0.0),
  30071. sourceSamplePosition (0.0),
  30072. lgain (0.0f),
  30073. rgain (0.0f),
  30074. isInAttack (false),
  30075. isInRelease (false)
  30076. {
  30077. }
  30078. SamplerVoice::~SamplerVoice()
  30079. {
  30080. }
  30081. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30082. {
  30083. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30084. }
  30085. void SamplerVoice::startNote (const int midiNoteNumber,
  30086. const float velocity,
  30087. SynthesiserSound* s,
  30088. const int /*currentPitchWheelPosition*/)
  30089. {
  30090. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30091. jassert (sound != 0); // this object can only play SamplerSounds!
  30092. if (sound != 0)
  30093. {
  30094. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30095. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30096. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30097. sourceSamplePosition = 0.0;
  30098. lgain = velocity;
  30099. rgain = velocity;
  30100. isInAttack = (sound->attackSamples > 0);
  30101. isInRelease = false;
  30102. if (isInAttack)
  30103. {
  30104. attackReleaseLevel = 0.0f;
  30105. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30106. }
  30107. else
  30108. {
  30109. attackReleaseLevel = 1.0f;
  30110. attackDelta = 0.0f;
  30111. }
  30112. if (sound->releaseSamples > 0)
  30113. {
  30114. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30115. }
  30116. else
  30117. {
  30118. releaseDelta = 0.0f;
  30119. }
  30120. }
  30121. }
  30122. void SamplerVoice::stopNote (const bool allowTailOff)
  30123. {
  30124. if (allowTailOff)
  30125. {
  30126. isInAttack = false;
  30127. isInRelease = true;
  30128. }
  30129. else
  30130. {
  30131. clearCurrentNote();
  30132. }
  30133. }
  30134. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30135. {
  30136. }
  30137. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30138. const int /*newValue*/)
  30139. {
  30140. }
  30141. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30142. {
  30143. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30144. if (playingSound != 0)
  30145. {
  30146. const float* const inL = playingSound->data->getSampleData (0, 0);
  30147. const float* const inR = playingSound->data->getNumChannels() > 1
  30148. ? playingSound->data->getSampleData (1, 0) : 0;
  30149. float* outL = outputBuffer.getSampleData (0, startSample);
  30150. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30151. while (--numSamples >= 0)
  30152. {
  30153. const int pos = (int) sourceSamplePosition;
  30154. const float alpha = (float) (sourceSamplePosition - pos);
  30155. const float invAlpha = 1.0f - alpha;
  30156. // just using a very simple linear interpolation here..
  30157. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30158. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30159. : l;
  30160. l *= lgain;
  30161. r *= rgain;
  30162. if (isInAttack)
  30163. {
  30164. l *= attackReleaseLevel;
  30165. r *= attackReleaseLevel;
  30166. attackReleaseLevel += attackDelta;
  30167. if (attackReleaseLevel >= 1.0f)
  30168. {
  30169. attackReleaseLevel = 1.0f;
  30170. isInAttack = false;
  30171. }
  30172. }
  30173. else if (isInRelease)
  30174. {
  30175. l *= attackReleaseLevel;
  30176. r *= attackReleaseLevel;
  30177. attackReleaseLevel += releaseDelta;
  30178. if (attackReleaseLevel <= 0.0f)
  30179. {
  30180. stopNote (false);
  30181. break;
  30182. }
  30183. }
  30184. if (outR != 0)
  30185. {
  30186. *outL++ += l;
  30187. *outR++ += r;
  30188. }
  30189. else
  30190. {
  30191. *outL++ += (l + r) * 0.5f;
  30192. }
  30193. sourceSamplePosition += pitchRatio;
  30194. if (sourceSamplePosition > playingSound->length)
  30195. {
  30196. stopNote (false);
  30197. break;
  30198. }
  30199. }
  30200. }
  30201. }
  30202. END_JUCE_NAMESPACE
  30203. /*** End of inlined file: juce_Sampler.cpp ***/
  30204. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30205. BEGIN_JUCE_NAMESPACE
  30206. SynthesiserSound::SynthesiserSound()
  30207. {
  30208. }
  30209. SynthesiserSound::~SynthesiserSound()
  30210. {
  30211. }
  30212. SynthesiserVoice::SynthesiserVoice()
  30213. : currentSampleRate (44100.0),
  30214. currentlyPlayingNote (-1),
  30215. noteOnTime (0),
  30216. currentlyPlayingSound (0)
  30217. {
  30218. }
  30219. SynthesiserVoice::~SynthesiserVoice()
  30220. {
  30221. }
  30222. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30223. {
  30224. return currentlyPlayingSound != 0
  30225. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30226. }
  30227. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30228. {
  30229. currentSampleRate = newRate;
  30230. }
  30231. void SynthesiserVoice::clearCurrentNote()
  30232. {
  30233. currentlyPlayingNote = -1;
  30234. currentlyPlayingSound = 0;
  30235. }
  30236. Synthesiser::Synthesiser()
  30237. : sampleRate (0),
  30238. lastNoteOnCounter (0),
  30239. shouldStealNotes (true)
  30240. {
  30241. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30242. lastPitchWheelValues[i] = 0x2000;
  30243. }
  30244. Synthesiser::~Synthesiser()
  30245. {
  30246. }
  30247. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30248. {
  30249. const ScopedLock sl (lock);
  30250. return voices [index];
  30251. }
  30252. void Synthesiser::clearVoices()
  30253. {
  30254. const ScopedLock sl (lock);
  30255. voices.clear();
  30256. }
  30257. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30258. {
  30259. const ScopedLock sl (lock);
  30260. voices.add (newVoice);
  30261. }
  30262. void Synthesiser::removeVoice (const int index)
  30263. {
  30264. const ScopedLock sl (lock);
  30265. voices.remove (index);
  30266. }
  30267. void Synthesiser::clearSounds()
  30268. {
  30269. const ScopedLock sl (lock);
  30270. sounds.clear();
  30271. }
  30272. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30273. {
  30274. const ScopedLock sl (lock);
  30275. sounds.add (newSound);
  30276. }
  30277. void Synthesiser::removeSound (const int index)
  30278. {
  30279. const ScopedLock sl (lock);
  30280. sounds.remove (index);
  30281. }
  30282. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30283. {
  30284. shouldStealNotes = shouldStealNotes_;
  30285. }
  30286. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30287. {
  30288. if (sampleRate != newRate)
  30289. {
  30290. const ScopedLock sl (lock);
  30291. allNotesOff (0, false);
  30292. sampleRate = newRate;
  30293. for (int i = voices.size(); --i >= 0;)
  30294. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30295. }
  30296. }
  30297. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30298. const MidiBuffer& midiData,
  30299. int startSample,
  30300. int numSamples)
  30301. {
  30302. // must set the sample rate before using this!
  30303. jassert (sampleRate != 0);
  30304. const ScopedLock sl (lock);
  30305. MidiBuffer::Iterator midiIterator (midiData);
  30306. midiIterator.setNextSamplePosition (startSample);
  30307. MidiMessage m (0xf4, 0.0);
  30308. while (numSamples > 0)
  30309. {
  30310. int midiEventPos;
  30311. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30312. && midiEventPos < startSample + numSamples;
  30313. const int numThisTime = useEvent ? midiEventPos - startSample
  30314. : numSamples;
  30315. if (numThisTime > 0)
  30316. {
  30317. for (int i = voices.size(); --i >= 0;)
  30318. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30319. }
  30320. if (useEvent)
  30321. {
  30322. if (m.isNoteOn())
  30323. {
  30324. const int channel = m.getChannel();
  30325. noteOn (channel,
  30326. m.getNoteNumber(),
  30327. m.getFloatVelocity());
  30328. }
  30329. else if (m.isNoteOff())
  30330. {
  30331. noteOff (m.getChannel(),
  30332. m.getNoteNumber(),
  30333. true);
  30334. }
  30335. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30336. {
  30337. allNotesOff (m.getChannel(), true);
  30338. }
  30339. else if (m.isPitchWheel())
  30340. {
  30341. const int channel = m.getChannel();
  30342. const int wheelPos = m.getPitchWheelValue();
  30343. lastPitchWheelValues [channel - 1] = wheelPos;
  30344. handlePitchWheel (channel, wheelPos);
  30345. }
  30346. else if (m.isController())
  30347. {
  30348. handleController (m.getChannel(),
  30349. m.getControllerNumber(),
  30350. m.getControllerValue());
  30351. }
  30352. }
  30353. startSample += numThisTime;
  30354. numSamples -= numThisTime;
  30355. }
  30356. }
  30357. void Synthesiser::noteOn (const int midiChannel,
  30358. const int midiNoteNumber,
  30359. const float velocity)
  30360. {
  30361. const ScopedLock sl (lock);
  30362. for (int i = sounds.size(); --i >= 0;)
  30363. {
  30364. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30365. if (sound->appliesToNote (midiNoteNumber)
  30366. && sound->appliesToChannel (midiChannel))
  30367. {
  30368. startVoice (findFreeVoice (sound, shouldStealNotes),
  30369. sound, midiChannel, midiNoteNumber, velocity);
  30370. }
  30371. }
  30372. }
  30373. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30374. SynthesiserSound* const sound,
  30375. const int midiChannel,
  30376. const int midiNoteNumber,
  30377. const float velocity)
  30378. {
  30379. if (voice != 0 && sound != 0)
  30380. {
  30381. if (voice->currentlyPlayingSound != 0)
  30382. voice->stopNote (false);
  30383. voice->startNote (midiNoteNumber,
  30384. velocity,
  30385. sound,
  30386. lastPitchWheelValues [midiChannel - 1]);
  30387. voice->currentlyPlayingNote = midiNoteNumber;
  30388. voice->noteOnTime = ++lastNoteOnCounter;
  30389. voice->currentlyPlayingSound = sound;
  30390. }
  30391. }
  30392. void Synthesiser::noteOff (const int midiChannel,
  30393. const int midiNoteNumber,
  30394. const bool allowTailOff)
  30395. {
  30396. const ScopedLock sl (lock);
  30397. for (int i = voices.size(); --i >= 0;)
  30398. {
  30399. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30400. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30401. {
  30402. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30403. if (sound != 0
  30404. && sound->appliesToNote (midiNoteNumber)
  30405. && sound->appliesToChannel (midiChannel))
  30406. {
  30407. voice->stopNote (allowTailOff);
  30408. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30409. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30410. }
  30411. }
  30412. }
  30413. }
  30414. void Synthesiser::allNotesOff (const int midiChannel,
  30415. const bool allowTailOff)
  30416. {
  30417. const ScopedLock sl (lock);
  30418. for (int i = voices.size(); --i >= 0;)
  30419. {
  30420. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30421. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30422. voice->stopNote (allowTailOff);
  30423. }
  30424. }
  30425. void Synthesiser::handlePitchWheel (const int midiChannel,
  30426. const int wheelValue)
  30427. {
  30428. const ScopedLock sl (lock);
  30429. for (int i = voices.size(); --i >= 0;)
  30430. {
  30431. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30432. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30433. {
  30434. voice->pitchWheelMoved (wheelValue);
  30435. }
  30436. }
  30437. }
  30438. void Synthesiser::handleController (const int midiChannel,
  30439. const int controllerNumber,
  30440. const int controllerValue)
  30441. {
  30442. const ScopedLock sl (lock);
  30443. for (int i = voices.size(); --i >= 0;)
  30444. {
  30445. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30446. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30447. voice->controllerMoved (controllerNumber, controllerValue);
  30448. }
  30449. }
  30450. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30451. const bool stealIfNoneAvailable) const
  30452. {
  30453. const ScopedLock sl (lock);
  30454. for (int i = voices.size(); --i >= 0;)
  30455. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30456. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30457. return voices.getUnchecked (i);
  30458. if (stealIfNoneAvailable)
  30459. {
  30460. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30461. SynthesiserVoice* oldest = 0;
  30462. for (int i = voices.size(); --i >= 0;)
  30463. {
  30464. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30465. if (voice->canPlaySound (soundToPlay)
  30466. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30467. oldest = voice;
  30468. }
  30469. jassert (oldest != 0);
  30470. return oldest;
  30471. }
  30472. return 0;
  30473. }
  30474. END_JUCE_NAMESPACE
  30475. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30476. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30477. BEGIN_JUCE_NAMESPACE
  30478. // special message of our own with a string in it
  30479. class ActionMessage : public Message
  30480. {
  30481. public:
  30482. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30483. : message (messageText)
  30484. {
  30485. pointerParameter = listener_;
  30486. }
  30487. const String message;
  30488. private:
  30489. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30490. };
  30491. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30492. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30493. {
  30494. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30495. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30496. if (owner->actionListeners.contains (target))
  30497. target->actionListenerCallback (am.message);
  30498. }
  30499. ActionBroadcaster::ActionBroadcaster()
  30500. {
  30501. // are you trying to create this object before or after juce has been intialised??
  30502. jassert (MessageManager::instance != 0);
  30503. callback.owner = this;
  30504. }
  30505. ActionBroadcaster::~ActionBroadcaster()
  30506. {
  30507. // all event-based objects must be deleted BEFORE juce is shut down!
  30508. jassert (MessageManager::instance != 0);
  30509. }
  30510. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30511. {
  30512. const ScopedLock sl (actionListenerLock);
  30513. if (listener != 0)
  30514. actionListeners.add (listener);
  30515. }
  30516. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30517. {
  30518. const ScopedLock sl (actionListenerLock);
  30519. actionListeners.removeValue (listener);
  30520. }
  30521. void ActionBroadcaster::removeAllActionListeners()
  30522. {
  30523. const ScopedLock sl (actionListenerLock);
  30524. actionListeners.clear();
  30525. }
  30526. void ActionBroadcaster::sendActionMessage (const String& message) const
  30527. {
  30528. const ScopedLock sl (actionListenerLock);
  30529. for (int i = actionListeners.size(); --i >= 0;)
  30530. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30531. }
  30532. END_JUCE_NAMESPACE
  30533. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30534. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30535. BEGIN_JUCE_NAMESPACE
  30536. class AsyncUpdaterMessage : public CallbackMessage
  30537. {
  30538. public:
  30539. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30540. : owner (owner_)
  30541. {
  30542. }
  30543. void messageCallback()
  30544. {
  30545. if (shouldDeliver.compareAndSetBool (0, 1))
  30546. owner.handleAsyncUpdate();
  30547. }
  30548. Atomic<int> shouldDeliver;
  30549. private:
  30550. AsyncUpdater& owner;
  30551. };
  30552. AsyncUpdater::AsyncUpdater()
  30553. {
  30554. message = new AsyncUpdaterMessage (*this);
  30555. }
  30556. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30557. {
  30558. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30559. }
  30560. AsyncUpdater::~AsyncUpdater()
  30561. {
  30562. // You're deleting this object with a background thread while there's an update
  30563. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30564. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30565. // deleting this object, or find some other way to avoid such a race condition.
  30566. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30567. getDeliveryFlag().set (0);
  30568. }
  30569. void AsyncUpdater::triggerAsyncUpdate()
  30570. {
  30571. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30572. message->post();
  30573. }
  30574. void AsyncUpdater::cancelPendingUpdate() throw()
  30575. {
  30576. getDeliveryFlag().set (0);
  30577. }
  30578. void AsyncUpdater::handleUpdateNowIfNeeded()
  30579. {
  30580. // This can only be called by the event thread.
  30581. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30582. if (getDeliveryFlag().exchange (0) != 0)
  30583. handleAsyncUpdate();
  30584. }
  30585. bool AsyncUpdater::isUpdatePending() const throw()
  30586. {
  30587. return getDeliveryFlag().value != 0;
  30588. }
  30589. END_JUCE_NAMESPACE
  30590. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30591. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30592. BEGIN_JUCE_NAMESPACE
  30593. ChangeBroadcaster::ChangeBroadcaster() throw()
  30594. {
  30595. // are you trying to create this object before or after juce has been intialised??
  30596. jassert (MessageManager::instance != 0);
  30597. callback.owner = this;
  30598. }
  30599. ChangeBroadcaster::~ChangeBroadcaster()
  30600. {
  30601. // all event-based objects must be deleted BEFORE juce is shut down!
  30602. jassert (MessageManager::instance != 0);
  30603. }
  30604. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30605. {
  30606. // Listeners can only be safely added when the event thread is locked
  30607. // You can use a MessageManagerLock if you need to call this from another thread.
  30608. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30609. changeListeners.add (listener);
  30610. }
  30611. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30612. {
  30613. // Listeners can only be safely added when the event thread is locked
  30614. // You can use a MessageManagerLock if you need to call this from another thread.
  30615. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30616. changeListeners.remove (listener);
  30617. }
  30618. void ChangeBroadcaster::removeAllChangeListeners()
  30619. {
  30620. // Listeners can only be safely added when the event thread is locked
  30621. // You can use a MessageManagerLock if you need to call this from another thread.
  30622. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30623. changeListeners.clear();
  30624. }
  30625. void ChangeBroadcaster::sendChangeMessage()
  30626. {
  30627. if (changeListeners.size() > 0)
  30628. callback.triggerAsyncUpdate();
  30629. }
  30630. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30631. {
  30632. // This can only be called by the event thread.
  30633. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30634. callback.cancelPendingUpdate();
  30635. callListeners();
  30636. }
  30637. void ChangeBroadcaster::dispatchPendingMessages()
  30638. {
  30639. callback.handleUpdateNowIfNeeded();
  30640. }
  30641. void ChangeBroadcaster::callListeners()
  30642. {
  30643. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30644. }
  30645. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30646. : owner (0)
  30647. {
  30648. }
  30649. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30650. {
  30651. jassert (owner != 0);
  30652. owner->callListeners();
  30653. }
  30654. END_JUCE_NAMESPACE
  30655. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30656. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30657. BEGIN_JUCE_NAMESPACE
  30658. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30659. const uint32 magicMessageHeaderNumber)
  30660. : Thread ("Juce IPC connection"),
  30661. callbackConnectionState (false),
  30662. useMessageThread (callbacksOnMessageThread),
  30663. magicMessageHeader (magicMessageHeaderNumber),
  30664. pipeReceiveMessageTimeout (-1)
  30665. {
  30666. }
  30667. InterprocessConnection::~InterprocessConnection()
  30668. {
  30669. callbackConnectionState = false;
  30670. disconnect();
  30671. }
  30672. bool InterprocessConnection::connectToSocket (const String& hostName,
  30673. const int portNumber,
  30674. const int timeOutMillisecs)
  30675. {
  30676. disconnect();
  30677. const ScopedLock sl (pipeAndSocketLock);
  30678. socket = new StreamingSocket();
  30679. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30680. {
  30681. connectionMadeInt();
  30682. startThread();
  30683. return true;
  30684. }
  30685. else
  30686. {
  30687. socket = 0;
  30688. return false;
  30689. }
  30690. }
  30691. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30692. const int pipeReceiveMessageTimeoutMs)
  30693. {
  30694. disconnect();
  30695. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30696. if (newPipe->openExisting (pipeName))
  30697. {
  30698. const ScopedLock sl (pipeAndSocketLock);
  30699. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30700. initialiseWithPipe (newPipe.release());
  30701. return true;
  30702. }
  30703. return false;
  30704. }
  30705. bool InterprocessConnection::createPipe (const String& pipeName,
  30706. const int pipeReceiveMessageTimeoutMs)
  30707. {
  30708. disconnect();
  30709. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30710. if (newPipe->createNewPipe (pipeName))
  30711. {
  30712. const ScopedLock sl (pipeAndSocketLock);
  30713. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30714. initialiseWithPipe (newPipe.release());
  30715. return true;
  30716. }
  30717. return false;
  30718. }
  30719. void InterprocessConnection::disconnect()
  30720. {
  30721. if (socket != 0)
  30722. socket->close();
  30723. if (pipe != 0)
  30724. {
  30725. pipe->cancelPendingReads();
  30726. pipe->close();
  30727. }
  30728. stopThread (4000);
  30729. {
  30730. const ScopedLock sl (pipeAndSocketLock);
  30731. socket = 0;
  30732. pipe = 0;
  30733. }
  30734. connectionLostInt();
  30735. }
  30736. bool InterprocessConnection::isConnected() const
  30737. {
  30738. const ScopedLock sl (pipeAndSocketLock);
  30739. return ((socket != 0 && socket->isConnected())
  30740. || (pipe != 0 && pipe->isOpen()))
  30741. && isThreadRunning();
  30742. }
  30743. const String InterprocessConnection::getConnectedHostName() const
  30744. {
  30745. if (pipe != 0)
  30746. {
  30747. return "localhost";
  30748. }
  30749. else if (socket != 0)
  30750. {
  30751. if (! socket->isLocal())
  30752. return socket->getHostName();
  30753. return "localhost";
  30754. }
  30755. return String::empty;
  30756. }
  30757. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30758. {
  30759. uint32 messageHeader[2];
  30760. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30761. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30762. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30763. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30764. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30765. int bytesWritten = 0;
  30766. const ScopedLock sl (pipeAndSocketLock);
  30767. if (socket != 0)
  30768. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30769. else if (pipe != 0)
  30770. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30771. return bytesWritten == (int) messageData.getSize();
  30772. }
  30773. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30774. {
  30775. jassert (socket == 0);
  30776. socket = socket_;
  30777. connectionMadeInt();
  30778. startThread();
  30779. }
  30780. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30781. {
  30782. jassert (pipe == 0);
  30783. pipe = pipe_;
  30784. connectionMadeInt();
  30785. startThread();
  30786. }
  30787. const int messageMagicNumber = 0xb734128b;
  30788. void InterprocessConnection::handleMessage (const Message& message)
  30789. {
  30790. if (message.intParameter1 == messageMagicNumber)
  30791. {
  30792. switch (message.intParameter2)
  30793. {
  30794. case 0:
  30795. {
  30796. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30797. messageReceived (*data);
  30798. break;
  30799. }
  30800. case 1:
  30801. connectionMade();
  30802. break;
  30803. case 2:
  30804. connectionLost();
  30805. break;
  30806. }
  30807. }
  30808. }
  30809. void InterprocessConnection::connectionMadeInt()
  30810. {
  30811. if (! callbackConnectionState)
  30812. {
  30813. callbackConnectionState = true;
  30814. if (useMessageThread)
  30815. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30816. else
  30817. connectionMade();
  30818. }
  30819. }
  30820. void InterprocessConnection::connectionLostInt()
  30821. {
  30822. if (callbackConnectionState)
  30823. {
  30824. callbackConnectionState = false;
  30825. if (useMessageThread)
  30826. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30827. else
  30828. connectionLost();
  30829. }
  30830. }
  30831. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30832. {
  30833. jassert (callbackConnectionState);
  30834. if (useMessageThread)
  30835. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30836. else
  30837. messageReceived (data);
  30838. }
  30839. bool InterprocessConnection::readNextMessageInt()
  30840. {
  30841. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30842. uint32 messageHeader[2];
  30843. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30844. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30845. if (bytes == sizeof (messageHeader)
  30846. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30847. {
  30848. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30849. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30850. {
  30851. MemoryBlock messageData (bytesInMessage, true);
  30852. int bytesRead = 0;
  30853. while (bytesInMessage > 0)
  30854. {
  30855. if (threadShouldExit())
  30856. return false;
  30857. const int numThisTime = jmin (bytesInMessage, 65536);
  30858. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30859. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30860. if (bytesIn <= 0)
  30861. break;
  30862. bytesRead += bytesIn;
  30863. bytesInMessage -= bytesIn;
  30864. }
  30865. if (bytesRead >= 0)
  30866. deliverDataInt (messageData);
  30867. }
  30868. }
  30869. else if (bytes < 0)
  30870. {
  30871. {
  30872. const ScopedLock sl (pipeAndSocketLock);
  30873. socket = 0;
  30874. }
  30875. connectionLostInt();
  30876. return false;
  30877. }
  30878. return true;
  30879. }
  30880. void InterprocessConnection::run()
  30881. {
  30882. while (! threadShouldExit())
  30883. {
  30884. if (socket != 0)
  30885. {
  30886. const int ready = socket->waitUntilReady (true, 0);
  30887. if (ready < 0)
  30888. {
  30889. {
  30890. const ScopedLock sl (pipeAndSocketLock);
  30891. socket = 0;
  30892. }
  30893. connectionLostInt();
  30894. break;
  30895. }
  30896. else if (ready > 0)
  30897. {
  30898. if (! readNextMessageInt())
  30899. break;
  30900. }
  30901. else
  30902. {
  30903. Thread::sleep (2);
  30904. }
  30905. }
  30906. else if (pipe != 0)
  30907. {
  30908. if (! pipe->isOpen())
  30909. {
  30910. {
  30911. const ScopedLock sl (pipeAndSocketLock);
  30912. pipe = 0;
  30913. }
  30914. connectionLostInt();
  30915. break;
  30916. }
  30917. else
  30918. {
  30919. if (! readNextMessageInt())
  30920. break;
  30921. }
  30922. }
  30923. else
  30924. {
  30925. break;
  30926. }
  30927. }
  30928. }
  30929. END_JUCE_NAMESPACE
  30930. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30931. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30932. BEGIN_JUCE_NAMESPACE
  30933. InterprocessConnectionServer::InterprocessConnectionServer()
  30934. : Thread ("Juce IPC server")
  30935. {
  30936. }
  30937. InterprocessConnectionServer::~InterprocessConnectionServer()
  30938. {
  30939. stop();
  30940. }
  30941. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30942. {
  30943. stop();
  30944. socket = new StreamingSocket();
  30945. if (socket->createListener (portNumber))
  30946. {
  30947. startThread();
  30948. return true;
  30949. }
  30950. socket = 0;
  30951. return false;
  30952. }
  30953. void InterprocessConnectionServer::stop()
  30954. {
  30955. signalThreadShouldExit();
  30956. if (socket != 0)
  30957. socket->close();
  30958. stopThread (4000);
  30959. socket = 0;
  30960. }
  30961. void InterprocessConnectionServer::run()
  30962. {
  30963. while ((! threadShouldExit()) && socket != 0)
  30964. {
  30965. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30966. if (clientSocket != 0)
  30967. {
  30968. InterprocessConnection* newConnection = createConnectionObject();
  30969. if (newConnection != 0)
  30970. newConnection->initialiseWithSocket (clientSocket.release());
  30971. }
  30972. }
  30973. }
  30974. END_JUCE_NAMESPACE
  30975. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30976. /*** Start of inlined file: juce_Message.cpp ***/
  30977. BEGIN_JUCE_NAMESPACE
  30978. Message::Message() throw()
  30979. : intParameter1 (0),
  30980. intParameter2 (0),
  30981. intParameter3 (0),
  30982. pointerParameter (0),
  30983. messageRecipient (0)
  30984. {
  30985. }
  30986. Message::Message (const int intParameter1_,
  30987. const int intParameter2_,
  30988. const int intParameter3_,
  30989. void* const pointerParameter_) throw()
  30990. : intParameter1 (intParameter1_),
  30991. intParameter2 (intParameter2_),
  30992. intParameter3 (intParameter3_),
  30993. pointerParameter (pointerParameter_),
  30994. messageRecipient (0)
  30995. {
  30996. }
  30997. Message::~Message()
  30998. {
  30999. }
  31000. END_JUCE_NAMESPACE
  31001. /*** End of inlined file: juce_Message.cpp ***/
  31002. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31003. BEGIN_JUCE_NAMESPACE
  31004. MessageListener::MessageListener() throw()
  31005. {
  31006. // are you trying to create a messagelistener before or after juce has been intialised??
  31007. jassert (MessageManager::instance != 0);
  31008. if (MessageManager::instance != 0)
  31009. MessageManager::instance->messageListeners.add (this);
  31010. }
  31011. MessageListener::~MessageListener()
  31012. {
  31013. if (MessageManager::instance != 0)
  31014. MessageManager::instance->messageListeners.removeValue (this);
  31015. }
  31016. void MessageListener::postMessage (Message* const message) const throw()
  31017. {
  31018. message->messageRecipient = const_cast <MessageListener*> (this);
  31019. if (MessageManager::instance == 0)
  31020. MessageManager::getInstance();
  31021. MessageManager::instance->postMessageToQueue (message);
  31022. }
  31023. bool MessageListener::isValidMessageListener() const throw()
  31024. {
  31025. return (MessageManager::instance != 0)
  31026. && MessageManager::instance->messageListeners.contains (this);
  31027. }
  31028. END_JUCE_NAMESPACE
  31029. /*** End of inlined file: juce_MessageListener.cpp ***/
  31030. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31031. BEGIN_JUCE_NAMESPACE
  31032. // platform-specific functions..
  31033. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31034. bool juce_postMessageToSystemQueue (Message* message);
  31035. MessageManager* MessageManager::instance = 0;
  31036. static const int quitMessageId = 0xfffff321;
  31037. MessageManager::MessageManager() throw()
  31038. : quitMessagePosted (false),
  31039. quitMessageReceived (false),
  31040. threadWithLock (0)
  31041. {
  31042. messageThreadId = Thread::getCurrentThreadId();
  31043. if (JUCEApplication::isStandaloneApp())
  31044. Thread::setCurrentThreadName ("Juce Message Thread");
  31045. }
  31046. MessageManager::~MessageManager() throw()
  31047. {
  31048. broadcaster = 0;
  31049. doPlatformSpecificShutdown();
  31050. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31051. jassert (messageListeners.size() == 0);
  31052. jassert (instance == this);
  31053. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31054. }
  31055. MessageManager* MessageManager::getInstance() throw()
  31056. {
  31057. if (instance == 0)
  31058. {
  31059. instance = new MessageManager();
  31060. doPlatformSpecificInitialisation();
  31061. }
  31062. return instance;
  31063. }
  31064. void MessageManager::postMessageToQueue (Message* const message)
  31065. {
  31066. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31067. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31068. }
  31069. CallbackMessage::CallbackMessage() throw() {}
  31070. CallbackMessage::~CallbackMessage() {}
  31071. void CallbackMessage::post()
  31072. {
  31073. if (MessageManager::instance != 0)
  31074. MessageManager::instance->postMessageToQueue (this);
  31075. }
  31076. // not for public use..
  31077. void MessageManager::deliverMessage (Message* const message)
  31078. {
  31079. JUCE_TRY
  31080. {
  31081. MessageListener* const recipient = message->messageRecipient;
  31082. if (recipient == 0)
  31083. {
  31084. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31085. if (callbackMessage != 0)
  31086. {
  31087. callbackMessage->messageCallback();
  31088. }
  31089. else if (message->intParameter1 == quitMessageId)
  31090. {
  31091. quitMessageReceived = true;
  31092. }
  31093. }
  31094. else if (messageListeners.contains (recipient))
  31095. {
  31096. recipient->handleMessage (*message);
  31097. }
  31098. }
  31099. JUCE_CATCH_EXCEPTION
  31100. }
  31101. #if ! (JUCE_MAC || JUCE_IOS)
  31102. void MessageManager::runDispatchLoop()
  31103. {
  31104. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31105. runDispatchLoopUntil (-1);
  31106. }
  31107. void MessageManager::stopDispatchLoop()
  31108. {
  31109. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31110. quitMessagePosted = true;
  31111. }
  31112. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31113. {
  31114. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31115. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31116. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31117. && ! quitMessageReceived)
  31118. {
  31119. JUCE_TRY
  31120. {
  31121. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31122. {
  31123. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31124. if (msToWait > 0)
  31125. Thread::sleep (jmin (5, msToWait));
  31126. }
  31127. }
  31128. JUCE_CATCH_EXCEPTION
  31129. }
  31130. return ! quitMessageReceived;
  31131. }
  31132. #endif
  31133. void MessageManager::deliverBroadcastMessage (const String& value)
  31134. {
  31135. if (broadcaster != 0)
  31136. broadcaster->sendActionMessage (value);
  31137. }
  31138. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31139. {
  31140. if (broadcaster == 0)
  31141. broadcaster = new ActionBroadcaster();
  31142. broadcaster->addActionListener (listener);
  31143. }
  31144. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31145. {
  31146. if (broadcaster != 0)
  31147. broadcaster->removeActionListener (listener);
  31148. }
  31149. bool MessageManager::isThisTheMessageThread() const throw()
  31150. {
  31151. return Thread::getCurrentThreadId() == messageThreadId;
  31152. }
  31153. void MessageManager::setCurrentThreadAsMessageThread()
  31154. {
  31155. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31156. if (messageThreadId != thisThread)
  31157. {
  31158. messageThreadId = thisThread;
  31159. // This is needed on windows to make sure the message window is created by this thread
  31160. doPlatformSpecificShutdown();
  31161. doPlatformSpecificInitialisation();
  31162. }
  31163. }
  31164. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31165. {
  31166. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31167. return thisThread == messageThreadId || thisThread == threadWithLock;
  31168. }
  31169. /* The only safe way to lock the message thread while another thread does
  31170. some work is by posting a special message, whose purpose is to tie up the event
  31171. loop until the other thread has finished its business.
  31172. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31173. get locked before making an event callback, because if the same OS lock gets indirectly
  31174. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31175. in Cocoa).
  31176. */
  31177. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31178. {
  31179. public:
  31180. BlockingMessage() {}
  31181. void messageCallback()
  31182. {
  31183. lockedEvent.signal();
  31184. releaseEvent.wait();
  31185. }
  31186. WaitableEvent lockedEvent, releaseEvent;
  31187. private:
  31188. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31189. };
  31190. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31191. : locked (false)
  31192. {
  31193. init (threadToCheck, 0);
  31194. }
  31195. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31196. : locked (false)
  31197. {
  31198. init (0, jobToCheckForExitSignal);
  31199. }
  31200. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31201. {
  31202. if (MessageManager::instance != 0)
  31203. {
  31204. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31205. {
  31206. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31207. }
  31208. else
  31209. {
  31210. if (threadToCheck == 0 && job == 0)
  31211. {
  31212. MessageManager::instance->lockingLock.enter();
  31213. }
  31214. else
  31215. {
  31216. while (! MessageManager::instance->lockingLock.tryEnter())
  31217. {
  31218. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31219. || (job != 0 && job->shouldExit()))
  31220. return;
  31221. Thread::sleep (1);
  31222. }
  31223. }
  31224. blockingMessage = new BlockingMessage();
  31225. blockingMessage->post();
  31226. while (! blockingMessage->lockedEvent.wait (20))
  31227. {
  31228. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31229. || (job != 0 && job->shouldExit()))
  31230. {
  31231. blockingMessage->releaseEvent.signal();
  31232. blockingMessage = 0;
  31233. MessageManager::instance->lockingLock.exit();
  31234. return;
  31235. }
  31236. }
  31237. jassert (MessageManager::instance->threadWithLock == 0);
  31238. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31239. locked = true;
  31240. }
  31241. }
  31242. }
  31243. MessageManagerLock::~MessageManagerLock() throw()
  31244. {
  31245. if (blockingMessage != 0)
  31246. {
  31247. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31248. blockingMessage->releaseEvent.signal();
  31249. blockingMessage = 0;
  31250. if (MessageManager::instance != 0)
  31251. {
  31252. MessageManager::instance->threadWithLock = 0;
  31253. MessageManager::instance->lockingLock.exit();
  31254. }
  31255. }
  31256. }
  31257. END_JUCE_NAMESPACE
  31258. /*** End of inlined file: juce_MessageManager.cpp ***/
  31259. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31260. BEGIN_JUCE_NAMESPACE
  31261. class MultiTimer::MultiTimerCallback : public Timer
  31262. {
  31263. public:
  31264. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31265. : timerId (timerId_),
  31266. owner (owner_)
  31267. {
  31268. }
  31269. ~MultiTimerCallback()
  31270. {
  31271. }
  31272. void timerCallback()
  31273. {
  31274. owner.timerCallback (timerId);
  31275. }
  31276. const int timerId;
  31277. private:
  31278. MultiTimer& owner;
  31279. };
  31280. MultiTimer::MultiTimer() throw()
  31281. {
  31282. }
  31283. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31284. {
  31285. }
  31286. MultiTimer::~MultiTimer()
  31287. {
  31288. const ScopedLock sl (timerListLock);
  31289. timers.clear();
  31290. }
  31291. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31292. {
  31293. const ScopedLock sl (timerListLock);
  31294. for (int i = timers.size(); --i >= 0;)
  31295. {
  31296. MultiTimerCallback* const t = timers.getUnchecked(i);
  31297. if (t->timerId == timerId)
  31298. {
  31299. t->startTimer (intervalInMilliseconds);
  31300. return;
  31301. }
  31302. }
  31303. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31304. timers.add (newTimer);
  31305. newTimer->startTimer (intervalInMilliseconds);
  31306. }
  31307. void MultiTimer::stopTimer (const int timerId) throw()
  31308. {
  31309. const ScopedLock sl (timerListLock);
  31310. for (int i = timers.size(); --i >= 0;)
  31311. {
  31312. MultiTimerCallback* const t = timers.getUnchecked(i);
  31313. if (t->timerId == timerId)
  31314. t->stopTimer();
  31315. }
  31316. }
  31317. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31318. {
  31319. const ScopedLock sl (timerListLock);
  31320. for (int i = timers.size(); --i >= 0;)
  31321. {
  31322. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31323. if (t->timerId == timerId)
  31324. return t->isTimerRunning();
  31325. }
  31326. return false;
  31327. }
  31328. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31329. {
  31330. const ScopedLock sl (timerListLock);
  31331. for (int i = timers.size(); --i >= 0;)
  31332. {
  31333. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31334. if (t->timerId == timerId)
  31335. return t->getTimerInterval();
  31336. }
  31337. return 0;
  31338. }
  31339. END_JUCE_NAMESPACE
  31340. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31341. /*** Start of inlined file: juce_Timer.cpp ***/
  31342. BEGIN_JUCE_NAMESPACE
  31343. class InternalTimerThread : private Thread,
  31344. private MessageListener,
  31345. private DeletedAtShutdown,
  31346. private AsyncUpdater
  31347. {
  31348. public:
  31349. InternalTimerThread()
  31350. : Thread ("Juce Timer"),
  31351. firstTimer (0),
  31352. callbackNeeded (0)
  31353. {
  31354. triggerAsyncUpdate();
  31355. }
  31356. ~InternalTimerThread() throw()
  31357. {
  31358. stopThread (4000);
  31359. jassert (instance == this || instance == 0);
  31360. if (instance == this)
  31361. instance = 0;
  31362. }
  31363. void run()
  31364. {
  31365. uint32 lastTime = Time::getMillisecondCounter();
  31366. Message::Ptr message (new Message());
  31367. while (! threadShouldExit())
  31368. {
  31369. const uint32 now = Time::getMillisecondCounter();
  31370. if (now <= lastTime)
  31371. {
  31372. wait (2);
  31373. continue;
  31374. }
  31375. const int elapsed = now - lastTime;
  31376. lastTime = now;
  31377. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31378. if (timeUntilFirstTimer <= 0)
  31379. {
  31380. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31381. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31382. but if it fails it means the message-thread changed the value from under us so at least
  31383. some processing is happenening and we can just loop around and try again
  31384. */
  31385. if (callbackNeeded.compareAndSetBool (1, 0))
  31386. {
  31387. postMessage (message);
  31388. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31389. when the app has a modal loop), so this is how long to wait before assuming the
  31390. message has been lost and trying again.
  31391. */
  31392. const uint32 messageDeliveryTimeout = now + 2000;
  31393. while (callbackNeeded.get() != 0)
  31394. {
  31395. wait (4);
  31396. if (threadShouldExit())
  31397. return;
  31398. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31399. break;
  31400. }
  31401. }
  31402. }
  31403. else
  31404. {
  31405. // don't wait for too long because running this loop also helps keep the
  31406. // Time::getApproximateMillisecondTimer value stay up-to-date
  31407. wait (jlimit (1, 50, timeUntilFirstTimer));
  31408. }
  31409. }
  31410. }
  31411. void callTimers()
  31412. {
  31413. const ScopedLock sl (lock);
  31414. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31415. {
  31416. Timer* const t = firstTimer;
  31417. t->countdownMs = t->periodMs;
  31418. removeTimer (t);
  31419. addTimer (t);
  31420. const ScopedUnlock ul (lock);
  31421. JUCE_TRY
  31422. {
  31423. t->timerCallback();
  31424. }
  31425. JUCE_CATCH_EXCEPTION
  31426. }
  31427. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31428. before the boolean is set. This set should never fail since if it was false in the first place,
  31429. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31430. get a message then the value is true and the other thread can only set it to true again and
  31431. we will get another callback to set it to false.
  31432. */
  31433. callbackNeeded.set (0);
  31434. }
  31435. void handleMessage (const Message&)
  31436. {
  31437. callTimers();
  31438. }
  31439. void callTimersSynchronously()
  31440. {
  31441. if (! isThreadRunning())
  31442. {
  31443. // (This is relied on by some plugins in cases where the MM has
  31444. // had to restart and the async callback never started)
  31445. cancelPendingUpdate();
  31446. triggerAsyncUpdate();
  31447. }
  31448. callTimers();
  31449. }
  31450. static void callAnyTimersSynchronously()
  31451. {
  31452. if (InternalTimerThread::instance != 0)
  31453. InternalTimerThread::instance->callTimersSynchronously();
  31454. }
  31455. static inline void add (Timer* const tim) throw()
  31456. {
  31457. if (instance == 0)
  31458. instance = new InternalTimerThread();
  31459. const ScopedLock sl (instance->lock);
  31460. instance->addTimer (tim);
  31461. }
  31462. static inline void remove (Timer* const tim) throw()
  31463. {
  31464. if (instance != 0)
  31465. {
  31466. const ScopedLock sl (instance->lock);
  31467. instance->removeTimer (tim);
  31468. }
  31469. }
  31470. static inline void resetCounter (Timer* const tim,
  31471. const int newCounter) throw()
  31472. {
  31473. if (instance != 0)
  31474. {
  31475. tim->countdownMs = newCounter;
  31476. tim->periodMs = newCounter;
  31477. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31478. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31479. {
  31480. const ScopedLock sl (instance->lock);
  31481. instance->removeTimer (tim);
  31482. instance->addTimer (tim);
  31483. }
  31484. }
  31485. }
  31486. private:
  31487. friend class Timer;
  31488. static InternalTimerThread* instance;
  31489. static CriticalSection lock;
  31490. Timer* volatile firstTimer;
  31491. Atomic <int> callbackNeeded;
  31492. void addTimer (Timer* const t) throw()
  31493. {
  31494. #if JUCE_DEBUG
  31495. Timer* tt = firstTimer;
  31496. while (tt != 0)
  31497. {
  31498. // trying to add a timer that's already here - shouldn't get to this point,
  31499. // so if you get this assertion, let me know!
  31500. jassert (tt != t);
  31501. tt = tt->next;
  31502. }
  31503. jassert (t->previous == 0 && t->next == 0);
  31504. #endif
  31505. Timer* i = firstTimer;
  31506. if (i == 0 || i->countdownMs > t->countdownMs)
  31507. {
  31508. t->next = firstTimer;
  31509. firstTimer = t;
  31510. }
  31511. else
  31512. {
  31513. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31514. i = i->next;
  31515. jassert (i != 0);
  31516. t->next = i->next;
  31517. t->previous = i;
  31518. i->next = t;
  31519. }
  31520. if (t->next != 0)
  31521. t->next->previous = t;
  31522. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31523. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31524. notify();
  31525. }
  31526. void removeTimer (Timer* const t) throw()
  31527. {
  31528. #if JUCE_DEBUG
  31529. Timer* tt = firstTimer;
  31530. bool found = false;
  31531. while (tt != 0)
  31532. {
  31533. if (tt == t)
  31534. {
  31535. found = true;
  31536. break;
  31537. }
  31538. tt = tt->next;
  31539. }
  31540. // trying to remove a timer that's not here - shouldn't get to this point,
  31541. // so if you get this assertion, let me know!
  31542. jassert (found);
  31543. #endif
  31544. if (t->previous != 0)
  31545. {
  31546. jassert (firstTimer != t);
  31547. t->previous->next = t->next;
  31548. }
  31549. else
  31550. {
  31551. jassert (firstTimer == t);
  31552. firstTimer = t->next;
  31553. }
  31554. if (t->next != 0)
  31555. t->next->previous = t->previous;
  31556. t->next = 0;
  31557. t->previous = 0;
  31558. }
  31559. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31560. {
  31561. const ScopedLock sl (lock);
  31562. for (Timer* t = firstTimer; t != 0; t = t->next)
  31563. t->countdownMs -= numMillisecsElapsed;
  31564. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31565. }
  31566. void handleAsyncUpdate()
  31567. {
  31568. startThread (7);
  31569. }
  31570. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31571. };
  31572. InternalTimerThread* InternalTimerThread::instance = 0;
  31573. CriticalSection InternalTimerThread::lock;
  31574. void juce_callAnyTimersSynchronously()
  31575. {
  31576. InternalTimerThread::callAnyTimersSynchronously();
  31577. }
  31578. #if JUCE_DEBUG
  31579. static SortedSet <Timer*> activeTimers;
  31580. #endif
  31581. Timer::Timer() throw()
  31582. : countdownMs (0),
  31583. periodMs (0),
  31584. previous (0),
  31585. next (0)
  31586. {
  31587. #if JUCE_DEBUG
  31588. activeTimers.add (this);
  31589. #endif
  31590. }
  31591. Timer::Timer (const Timer&) throw()
  31592. : countdownMs (0),
  31593. periodMs (0),
  31594. previous (0),
  31595. next (0)
  31596. {
  31597. #if JUCE_DEBUG
  31598. activeTimers.add (this);
  31599. #endif
  31600. }
  31601. Timer::~Timer()
  31602. {
  31603. stopTimer();
  31604. #if JUCE_DEBUG
  31605. activeTimers.removeValue (this);
  31606. #endif
  31607. }
  31608. void Timer::startTimer (const int interval) throw()
  31609. {
  31610. const ScopedLock sl (InternalTimerThread::lock);
  31611. #if JUCE_DEBUG
  31612. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31613. jassert (activeTimers.contains (this));
  31614. #endif
  31615. if (periodMs == 0)
  31616. {
  31617. countdownMs = interval;
  31618. periodMs = jmax (1, interval);
  31619. InternalTimerThread::add (this);
  31620. }
  31621. else
  31622. {
  31623. InternalTimerThread::resetCounter (this, interval);
  31624. }
  31625. }
  31626. void Timer::stopTimer() throw()
  31627. {
  31628. const ScopedLock sl (InternalTimerThread::lock);
  31629. #if JUCE_DEBUG
  31630. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31631. jassert (activeTimers.contains (this));
  31632. #endif
  31633. if (periodMs > 0)
  31634. {
  31635. InternalTimerThread::remove (this);
  31636. periodMs = 0;
  31637. }
  31638. }
  31639. END_JUCE_NAMESPACE
  31640. /*** End of inlined file: juce_Timer.cpp ***/
  31641. #endif
  31642. #if JUCE_BUILD_GUI
  31643. /*** Start of inlined file: juce_Component.cpp ***/
  31644. BEGIN_JUCE_NAMESPACE
  31645. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31646. Component* Component::currentlyFocusedComponent = 0;
  31647. class Component::MouseListenerList
  31648. {
  31649. public:
  31650. MouseListenerList()
  31651. : numDeepMouseListeners (0)
  31652. {
  31653. }
  31654. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31655. {
  31656. if (! listeners.contains (newListener))
  31657. {
  31658. if (wantsEventsForAllNestedChildComponents)
  31659. {
  31660. listeners.insert (0, newListener);
  31661. ++numDeepMouseListeners;
  31662. }
  31663. else
  31664. {
  31665. listeners.add (newListener);
  31666. }
  31667. }
  31668. }
  31669. void removeListener (MouseListener* const listenerToRemove)
  31670. {
  31671. const int index = listeners.indexOf (listenerToRemove);
  31672. if (index >= 0)
  31673. {
  31674. if (index < numDeepMouseListeners)
  31675. --numDeepMouseListeners;
  31676. listeners.remove (index);
  31677. }
  31678. }
  31679. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31680. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31681. {
  31682. if (checker.shouldBailOut())
  31683. return;
  31684. {
  31685. MouseListenerList* const list = comp.mouseListeners;
  31686. if (list != 0)
  31687. {
  31688. for (int i = list->listeners.size(); --i >= 0;)
  31689. {
  31690. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31691. if (checker.shouldBailOut())
  31692. return;
  31693. i = jmin (i, list->listeners.size());
  31694. }
  31695. }
  31696. }
  31697. Component* p = comp.parentComponent;
  31698. while (p != 0)
  31699. {
  31700. MouseListenerList* const list = p->mouseListeners;
  31701. if (list != 0 && list->numDeepMouseListeners > 0)
  31702. {
  31703. BailOutChecker2 checker2 (checker, p);
  31704. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31705. {
  31706. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31707. if (checker2.shouldBailOut())
  31708. return;
  31709. i = jmin (i, list->numDeepMouseListeners);
  31710. }
  31711. }
  31712. p = p->parentComponent;
  31713. }
  31714. }
  31715. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31716. const float wheelIncrementX, const float wheelIncrementY)
  31717. {
  31718. {
  31719. MouseListenerList* const list = comp.mouseListeners;
  31720. if (list != 0)
  31721. {
  31722. for (int i = list->listeners.size(); --i >= 0;)
  31723. {
  31724. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31725. if (checker.shouldBailOut())
  31726. return;
  31727. i = jmin (i, list->listeners.size());
  31728. }
  31729. }
  31730. }
  31731. Component* p = comp.parentComponent;
  31732. while (p != 0)
  31733. {
  31734. MouseListenerList* const list = p->mouseListeners;
  31735. if (list != 0 && list->numDeepMouseListeners > 0)
  31736. {
  31737. BailOutChecker2 checker2 (checker, p);
  31738. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31739. {
  31740. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31741. if (checker2.shouldBailOut())
  31742. return;
  31743. i = jmin (i, list->numDeepMouseListeners);
  31744. }
  31745. }
  31746. p = p->parentComponent;
  31747. }
  31748. }
  31749. private:
  31750. Array <MouseListener*> listeners;
  31751. int numDeepMouseListeners;
  31752. class BailOutChecker2
  31753. {
  31754. public:
  31755. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31756. : checker (checker_), safePointer (component)
  31757. {
  31758. }
  31759. bool shouldBailOut() const throw()
  31760. {
  31761. return checker.shouldBailOut() || safePointer == 0;
  31762. }
  31763. private:
  31764. BailOutChecker& checker;
  31765. const WeakReference<Component> safePointer;
  31766. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31767. };
  31768. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31769. };
  31770. class Component::ComponentHelpers
  31771. {
  31772. public:
  31773. static void* runModalLoopCallback (void* userData)
  31774. {
  31775. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31776. }
  31777. static const Identifier getColourPropertyId (const int colourId)
  31778. {
  31779. String s;
  31780. s.preallocateStorage (18);
  31781. s << "jcclr_" << String::toHexString (colourId);
  31782. return s;
  31783. }
  31784. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31785. {
  31786. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31787. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31788. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31789. }
  31790. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31791. {
  31792. if (comp.affineTransform == 0)
  31793. return pointInParentSpace - comp.getPosition();
  31794. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31795. }
  31796. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31797. {
  31798. if (comp.affineTransform == 0)
  31799. return areaInParentSpace - comp.getPosition();
  31800. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31801. }
  31802. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31803. {
  31804. if (comp.affineTransform == 0)
  31805. return pointInLocalSpace + comp.getPosition();
  31806. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31807. }
  31808. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31809. {
  31810. if (comp.affineTransform == 0)
  31811. return areaInLocalSpace + comp.getPosition();
  31812. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31813. }
  31814. template <typename Type>
  31815. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31816. {
  31817. const Component* const directParent = target.getParentComponent();
  31818. jassert (directParent != 0);
  31819. if (directParent == parent)
  31820. return convertFromParentSpace (target, coordInParent);
  31821. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31822. }
  31823. template <typename Type>
  31824. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31825. {
  31826. while (source != 0)
  31827. {
  31828. if (source == target)
  31829. return p;
  31830. if (source->isParentOf (target))
  31831. return convertFromDistantParentSpace (source, *target, p);
  31832. if (source->isOnDesktop())
  31833. {
  31834. p = source->getPeer()->localToGlobal (p);
  31835. source = 0;
  31836. }
  31837. else
  31838. {
  31839. p = convertToParentSpace (*source, p);
  31840. source = source->getParentComponent();
  31841. }
  31842. }
  31843. jassert (source == 0);
  31844. if (target == 0)
  31845. return p;
  31846. const Component* const topLevelComp = target->getTopLevelComponent();
  31847. if (topLevelComp->isOnDesktop())
  31848. p = topLevelComp->getPeer()->globalToLocal (p);
  31849. else
  31850. p = convertFromParentSpace (*topLevelComp, p);
  31851. if (topLevelComp == target)
  31852. return p;
  31853. return convertFromDistantParentSpace (topLevelComp, *target, p);
  31854. }
  31855. static const Rectangle<int> getUnclippedArea (const Component& comp)
  31856. {
  31857. Rectangle<int> r (comp.getLocalBounds());
  31858. Component* const p = comp.getParentComponent();
  31859. if (p != 0)
  31860. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  31861. return r;
  31862. }
  31863. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  31864. {
  31865. for (int i = comp.childComponentList.size(); --i >= 0;)
  31866. {
  31867. const Component& child = *comp.childComponentList.getUnchecked(i);
  31868. if (child.isVisible() && ! child.isTransformed())
  31869. {
  31870. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  31871. if (! newClip.isEmpty())
  31872. {
  31873. if (child.isOpaque())
  31874. {
  31875. g.excludeClipRegion (newClip + delta);
  31876. }
  31877. else
  31878. {
  31879. const Point<int> childPos (child.getPosition());
  31880. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  31881. }
  31882. }
  31883. }
  31884. }
  31885. }
  31886. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  31887. const Point<int>& delta,
  31888. const Rectangle<int>& clipRect,
  31889. const Component* const compToAvoid)
  31890. {
  31891. for (int i = comp.childComponentList.size(); --i >= 0;)
  31892. {
  31893. const Component* const c = comp.childComponentList.getUnchecked(i);
  31894. if (c != compToAvoid && c->isVisible())
  31895. {
  31896. if (c->isOpaque())
  31897. {
  31898. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  31899. childBounds.translate (delta.getX(), delta.getY());
  31900. result.subtract (childBounds);
  31901. }
  31902. else
  31903. {
  31904. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  31905. newClip.translate (-c->getX(), -c->getY());
  31906. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  31907. newClip, compToAvoid);
  31908. }
  31909. }
  31910. }
  31911. }
  31912. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  31913. {
  31914. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  31915. : Desktop::getInstance().getMainMonitorArea();
  31916. }
  31917. };
  31918. Component::Component()
  31919. : parentComponent (0),
  31920. lookAndFeel (0),
  31921. effect (0),
  31922. componentFlags (0),
  31923. componentTransparency (0)
  31924. {
  31925. }
  31926. Component::Component (const String& name)
  31927. : componentName (name),
  31928. parentComponent (0),
  31929. lookAndFeel (0),
  31930. effect (0),
  31931. componentFlags (0),
  31932. componentTransparency (0)
  31933. {
  31934. }
  31935. Component::~Component()
  31936. {
  31937. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  31938. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  31939. #endif
  31940. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31941. weakReferenceMaster.clear();
  31942. while (childComponentList.size() > 0)
  31943. removeChildComponent (childComponentList.size() - 1, false, true);
  31944. if (parentComponent != 0)
  31945. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  31946. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  31947. giveAwayFocus (currentlyFocusedComponent != this);
  31948. if (flags.hasHeavyweightPeerFlag)
  31949. removeFromDesktop();
  31950. // Something has added some children to this component during its destructor! Not a smart idea!
  31951. jassert (childComponentList.size() == 0);
  31952. }
  31953. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  31954. {
  31955. return weakReferenceMaster (this);
  31956. }
  31957. void Component::setName (const String& name)
  31958. {
  31959. // if component methods are being called from threads other than the message
  31960. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31961. CHECK_MESSAGE_MANAGER_IS_LOCKED
  31962. if (componentName != name)
  31963. {
  31964. componentName = name;
  31965. if (flags.hasHeavyweightPeerFlag)
  31966. {
  31967. ComponentPeer* const peer = getPeer();
  31968. jassert (peer != 0);
  31969. if (peer != 0)
  31970. peer->setTitle (name);
  31971. }
  31972. BailOutChecker checker (this);
  31973. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31974. }
  31975. }
  31976. void Component::setComponentID (const String& newID)
  31977. {
  31978. componentID = newID;
  31979. }
  31980. void Component::setVisible (bool shouldBeVisible)
  31981. {
  31982. if (flags.visibleFlag != shouldBeVisible)
  31983. {
  31984. // if component methods are being called from threads other than the message
  31985. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31986. CHECK_MESSAGE_MANAGER_IS_LOCKED
  31987. WeakReference<Component> safePointer (this);
  31988. flags.visibleFlag = shouldBeVisible;
  31989. internalRepaint (0, 0, getWidth(), getHeight());
  31990. sendFakeMouseMove();
  31991. if (! shouldBeVisible)
  31992. {
  31993. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  31994. {
  31995. if (parentComponent != 0)
  31996. parentComponent->grabKeyboardFocus();
  31997. else
  31998. giveAwayFocus (true);
  31999. }
  32000. }
  32001. if (safePointer != 0)
  32002. {
  32003. sendVisibilityChangeMessage();
  32004. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32005. {
  32006. ComponentPeer* const peer = getPeer();
  32007. jassert (peer != 0);
  32008. if (peer != 0)
  32009. {
  32010. peer->setVisible (shouldBeVisible);
  32011. internalHierarchyChanged();
  32012. }
  32013. }
  32014. }
  32015. }
  32016. }
  32017. void Component::visibilityChanged()
  32018. {
  32019. }
  32020. void Component::sendVisibilityChangeMessage()
  32021. {
  32022. BailOutChecker checker (this);
  32023. visibilityChanged();
  32024. if (! checker.shouldBailOut())
  32025. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32026. }
  32027. bool Component::isShowing() const
  32028. {
  32029. if (flags.visibleFlag)
  32030. {
  32031. if (parentComponent != 0)
  32032. {
  32033. return parentComponent->isShowing();
  32034. }
  32035. else
  32036. {
  32037. const ComponentPeer* const peer = getPeer();
  32038. return peer != 0 && ! peer->isMinimised();
  32039. }
  32040. }
  32041. return false;
  32042. }
  32043. void* Component::getWindowHandle() const
  32044. {
  32045. const ComponentPeer* const peer = getPeer();
  32046. if (peer != 0)
  32047. return peer->getNativeHandle();
  32048. return 0;
  32049. }
  32050. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32051. {
  32052. // if component methods are being called from threads other than the message
  32053. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32054. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32055. if (isOpaque())
  32056. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32057. else
  32058. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32059. int currentStyleFlags = 0;
  32060. // don't use getPeer(), so that we only get the peer that's specifically
  32061. // for this comp, and not for one of its parents.
  32062. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32063. if (peer != 0)
  32064. currentStyleFlags = peer->getStyleFlags();
  32065. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32066. {
  32067. WeakReference<Component> safePointer (this);
  32068. #if JUCE_LINUX
  32069. // it's wise to give the component a non-zero size before
  32070. // putting it on the desktop, as X windows get confused by this, and
  32071. // a (1, 1) minimum size is enforced here.
  32072. setSize (jmax (1, getWidth()),
  32073. jmax (1, getHeight()));
  32074. #endif
  32075. const Point<int> topLeft (getScreenPosition());
  32076. bool wasFullscreen = false;
  32077. bool wasMinimised = false;
  32078. ComponentBoundsConstrainer* currentConstainer = 0;
  32079. Rectangle<int> oldNonFullScreenBounds;
  32080. if (peer != 0)
  32081. {
  32082. wasFullscreen = peer->isFullScreen();
  32083. wasMinimised = peer->isMinimised();
  32084. currentConstainer = peer->getConstrainer();
  32085. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32086. removeFromDesktop();
  32087. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32088. }
  32089. if (parentComponent != 0)
  32090. parentComponent->removeChildComponent (this);
  32091. if (safePointer != 0)
  32092. {
  32093. flags.hasHeavyweightPeerFlag = true;
  32094. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32095. Desktop::getInstance().addDesktopComponent (this);
  32096. bounds.setPosition (topLeft);
  32097. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32098. peer->setVisible (isVisible());
  32099. if (wasFullscreen)
  32100. {
  32101. peer->setFullScreen (true);
  32102. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32103. }
  32104. if (wasMinimised)
  32105. peer->setMinimised (true);
  32106. if (isAlwaysOnTop())
  32107. peer->setAlwaysOnTop (true);
  32108. peer->setConstrainer (currentConstainer);
  32109. repaint();
  32110. }
  32111. internalHierarchyChanged();
  32112. }
  32113. }
  32114. void Component::removeFromDesktop()
  32115. {
  32116. // if component methods are being called from threads other than the message
  32117. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32118. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32119. if (flags.hasHeavyweightPeerFlag)
  32120. {
  32121. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32122. flags.hasHeavyweightPeerFlag = false;
  32123. jassert (peer != 0);
  32124. delete peer;
  32125. Desktop::getInstance().removeDesktopComponent (this);
  32126. }
  32127. }
  32128. bool Component::isOnDesktop() const throw()
  32129. {
  32130. return flags.hasHeavyweightPeerFlag;
  32131. }
  32132. void Component::userTriedToCloseWindow()
  32133. {
  32134. /* This means that the user's trying to get rid of your window with the 'close window' system
  32135. menu option (on windows) or possibly the task manager - you should really handle this
  32136. and delete or hide your component in an appropriate way.
  32137. If you want to ignore the event and don't want to trigger this assertion, just override
  32138. this method and do nothing.
  32139. */
  32140. jassertfalse;
  32141. }
  32142. void Component::minimisationStateChanged (bool)
  32143. {
  32144. }
  32145. void Component::setOpaque (const bool shouldBeOpaque)
  32146. {
  32147. if (shouldBeOpaque != flags.opaqueFlag)
  32148. {
  32149. flags.opaqueFlag = shouldBeOpaque;
  32150. if (flags.hasHeavyweightPeerFlag)
  32151. {
  32152. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32153. if (peer != 0)
  32154. {
  32155. // to make it recreate the heavyweight window
  32156. addToDesktop (peer->getStyleFlags());
  32157. }
  32158. }
  32159. repaint();
  32160. }
  32161. }
  32162. bool Component::isOpaque() const throw()
  32163. {
  32164. return flags.opaqueFlag;
  32165. }
  32166. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32167. {
  32168. if (shouldBeBuffered != flags.bufferToImageFlag)
  32169. {
  32170. bufferedImage = Image::null;
  32171. flags.bufferToImageFlag = shouldBeBuffered;
  32172. }
  32173. }
  32174. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32175. {
  32176. if (sourceIndex != destIndex)
  32177. {
  32178. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32179. jassert (c != 0);
  32180. c->repaintParent();
  32181. childComponentList.move (sourceIndex, destIndex);
  32182. sendFakeMouseMove();
  32183. internalChildrenChanged();
  32184. }
  32185. }
  32186. void Component::toFront (const bool setAsForeground)
  32187. {
  32188. // if component methods are being called from threads other than the message
  32189. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32190. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32191. if (flags.hasHeavyweightPeerFlag)
  32192. {
  32193. ComponentPeer* const peer = getPeer();
  32194. if (peer != 0)
  32195. {
  32196. peer->toFront (setAsForeground);
  32197. if (setAsForeground && ! hasKeyboardFocus (true))
  32198. grabKeyboardFocus();
  32199. }
  32200. }
  32201. else if (parentComponent != 0)
  32202. {
  32203. const Array<Component*>& childList = parentComponent->childComponentList;
  32204. if (childList.getLast() != this)
  32205. {
  32206. const int index = childList.indexOf (this);
  32207. if (index >= 0)
  32208. {
  32209. int insertIndex = -1;
  32210. if (! flags.alwaysOnTopFlag)
  32211. {
  32212. insertIndex = childList.size() - 1;
  32213. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32214. --insertIndex;
  32215. }
  32216. parentComponent->moveChildInternal (index, insertIndex);
  32217. }
  32218. }
  32219. if (setAsForeground)
  32220. {
  32221. internalBroughtToFront();
  32222. grabKeyboardFocus();
  32223. }
  32224. }
  32225. }
  32226. void Component::toBehind (Component* const other)
  32227. {
  32228. if (other != 0 && other != this)
  32229. {
  32230. // the two components must belong to the same parent..
  32231. jassert (parentComponent == other->parentComponent);
  32232. if (parentComponent != 0)
  32233. {
  32234. const Array<Component*>& childList = parentComponent->childComponentList;
  32235. const int index = childList.indexOf (this);
  32236. if (index >= 0 && childList [index + 1] != other)
  32237. {
  32238. int otherIndex = childList.indexOf (other);
  32239. if (otherIndex >= 0)
  32240. {
  32241. if (index < otherIndex)
  32242. --otherIndex;
  32243. parentComponent->moveChildInternal (index, otherIndex);
  32244. }
  32245. }
  32246. }
  32247. else if (isOnDesktop())
  32248. {
  32249. jassert (other->isOnDesktop());
  32250. if (other->isOnDesktop())
  32251. {
  32252. ComponentPeer* const us = getPeer();
  32253. ComponentPeer* const them = other->getPeer();
  32254. jassert (us != 0 && them != 0);
  32255. if (us != 0 && them != 0)
  32256. us->toBehind (them);
  32257. }
  32258. }
  32259. }
  32260. }
  32261. void Component::toBack()
  32262. {
  32263. if (isOnDesktop())
  32264. {
  32265. jassertfalse; //xxx need to add this to native window
  32266. }
  32267. else if (parentComponent != 0)
  32268. {
  32269. const Array<Component*>& childList = parentComponent->childComponentList;
  32270. if (childList.getFirst() != this)
  32271. {
  32272. const int index = childList.indexOf (this);
  32273. if (index > 0)
  32274. {
  32275. int insertIndex = 0;
  32276. if (flags.alwaysOnTopFlag)
  32277. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32278. ++insertIndex;
  32279. parentComponent->moveChildInternal (index, insertIndex);
  32280. }
  32281. }
  32282. }
  32283. }
  32284. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32285. {
  32286. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32287. {
  32288. flags.alwaysOnTopFlag = shouldStayOnTop;
  32289. if (isOnDesktop())
  32290. {
  32291. ComponentPeer* const peer = getPeer();
  32292. jassert (peer != 0);
  32293. if (peer != 0)
  32294. {
  32295. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32296. {
  32297. // some kinds of peer can't change their always-on-top status, so
  32298. // for these, we'll need to create a new window
  32299. const int oldFlags = peer->getStyleFlags();
  32300. removeFromDesktop();
  32301. addToDesktop (oldFlags);
  32302. }
  32303. }
  32304. }
  32305. if (shouldStayOnTop)
  32306. toFront (false);
  32307. internalHierarchyChanged();
  32308. }
  32309. }
  32310. bool Component::isAlwaysOnTop() const throw()
  32311. {
  32312. return flags.alwaysOnTopFlag;
  32313. }
  32314. int Component::proportionOfWidth (const float proportion) const throw()
  32315. {
  32316. return roundToInt (proportion * bounds.getWidth());
  32317. }
  32318. int Component::proportionOfHeight (const float proportion) const throw()
  32319. {
  32320. return roundToInt (proportion * bounds.getHeight());
  32321. }
  32322. int Component::getParentWidth() const throw()
  32323. {
  32324. return (parentComponent != 0) ? parentComponent->getWidth()
  32325. : getParentMonitorArea().getWidth();
  32326. }
  32327. int Component::getParentHeight() const throw()
  32328. {
  32329. return (parentComponent != 0) ? parentComponent->getHeight()
  32330. : getParentMonitorArea().getHeight();
  32331. }
  32332. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32333. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32334. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32335. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32336. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32337. {
  32338. return ComponentHelpers::convertCoordinate (this, source, point);
  32339. }
  32340. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32341. {
  32342. return ComponentHelpers::convertCoordinate (this, source, area);
  32343. }
  32344. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32345. {
  32346. return ComponentHelpers::convertCoordinate (0, this, point);
  32347. }
  32348. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32349. {
  32350. return ComponentHelpers::convertCoordinate (0, this, area);
  32351. }
  32352. /* Deprecated methods... */
  32353. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32354. {
  32355. return localPointToGlobal (relativePosition);
  32356. }
  32357. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32358. {
  32359. return getLocalPoint (0, screenPosition);
  32360. }
  32361. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32362. {
  32363. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32364. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32365. }
  32366. void Component::setBounds (const int x, const int y, int w, int h)
  32367. {
  32368. // if component methods are being called from threads other than the message
  32369. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32370. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32371. if (w < 0) w = 0;
  32372. if (h < 0) h = 0;
  32373. const bool wasResized = (getWidth() != w || getHeight() != h);
  32374. const bool wasMoved = (getX() != x || getY() != y);
  32375. #if JUCE_DEBUG
  32376. // It's a very bad idea to try to resize a window during its paint() method!
  32377. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32378. #endif
  32379. if (wasMoved || wasResized)
  32380. {
  32381. const bool showing = isShowing();
  32382. if (showing)
  32383. {
  32384. // send a fake mouse move to trigger enter/exit messages if needed..
  32385. sendFakeMouseMove();
  32386. if (! flags.hasHeavyweightPeerFlag)
  32387. repaintParent();
  32388. }
  32389. bounds.setBounds (x, y, w, h);
  32390. if (showing)
  32391. {
  32392. if (wasResized)
  32393. repaint();
  32394. else if (! flags.hasHeavyweightPeerFlag)
  32395. repaintParent();
  32396. }
  32397. if (flags.hasHeavyweightPeerFlag)
  32398. {
  32399. ComponentPeer* const peer = getPeer();
  32400. if (peer != 0)
  32401. {
  32402. if (wasMoved && wasResized)
  32403. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32404. else if (wasMoved)
  32405. peer->setPosition (getX(), getY());
  32406. else if (wasResized)
  32407. peer->setSize (getWidth(), getHeight());
  32408. }
  32409. }
  32410. sendMovedResizedMessages (wasMoved, wasResized);
  32411. }
  32412. }
  32413. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32414. {
  32415. BailOutChecker checker (this);
  32416. if (wasMoved)
  32417. {
  32418. moved();
  32419. if (checker.shouldBailOut())
  32420. return;
  32421. }
  32422. if (wasResized)
  32423. {
  32424. resized();
  32425. if (checker.shouldBailOut())
  32426. return;
  32427. for (int i = childComponentList.size(); --i >= 0;)
  32428. {
  32429. childComponentList.getUnchecked(i)->parentSizeChanged();
  32430. if (checker.shouldBailOut())
  32431. return;
  32432. i = jmin (i, childComponentList.size());
  32433. }
  32434. }
  32435. if (parentComponent != 0)
  32436. parentComponent->childBoundsChanged (this);
  32437. if (! checker.shouldBailOut())
  32438. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32439. *this, wasMoved, wasResized);
  32440. }
  32441. void Component::setSize (const int w, const int h)
  32442. {
  32443. setBounds (getX(), getY(), w, h);
  32444. }
  32445. void Component::setTopLeftPosition (const int x, const int y)
  32446. {
  32447. setBounds (x, y, getWidth(), getHeight());
  32448. }
  32449. void Component::setTopRightPosition (const int x, const int y)
  32450. {
  32451. setTopLeftPosition (x - getWidth(), y);
  32452. }
  32453. void Component::setBounds (const Rectangle<int>& r)
  32454. {
  32455. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32456. }
  32457. void Component::setBounds (const RelativeRectangle& newBounds)
  32458. {
  32459. newBounds.applyToComponent (*this);
  32460. }
  32461. void Component::setBoundsRelative (const float x, const float y,
  32462. const float w, const float h)
  32463. {
  32464. const int pw = getParentWidth();
  32465. const int ph = getParentHeight();
  32466. setBounds (roundToInt (x * pw),
  32467. roundToInt (y * ph),
  32468. roundToInt (w * pw),
  32469. roundToInt (h * ph));
  32470. }
  32471. void Component::setCentrePosition (const int x, const int y)
  32472. {
  32473. setTopLeftPosition (x - getWidth() / 2,
  32474. y - getHeight() / 2);
  32475. }
  32476. void Component::setCentreRelative (const float x, const float y)
  32477. {
  32478. setCentrePosition (roundToInt (getParentWidth() * x),
  32479. roundToInt (getParentHeight() * y));
  32480. }
  32481. void Component::centreWithSize (const int width, const int height)
  32482. {
  32483. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32484. setBounds (parentArea.getCentreX() - width / 2,
  32485. parentArea.getCentreY() - height / 2,
  32486. width, height);
  32487. }
  32488. void Component::setBoundsInset (const BorderSize<int>& borders)
  32489. {
  32490. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32491. }
  32492. void Component::setBoundsToFit (int x, int y, int width, int height,
  32493. const Justification& justification,
  32494. const bool onlyReduceInSize)
  32495. {
  32496. // it's no good calling this method unless both the component and
  32497. // target rectangle have a finite size.
  32498. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32499. if (getWidth() > 0 && getHeight() > 0
  32500. && width > 0 && height > 0)
  32501. {
  32502. int newW, newH;
  32503. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32504. {
  32505. newW = getWidth();
  32506. newH = getHeight();
  32507. }
  32508. else
  32509. {
  32510. const double imageRatio = getHeight() / (double) getWidth();
  32511. const double targetRatio = height / (double) width;
  32512. if (imageRatio <= targetRatio)
  32513. {
  32514. newW = width;
  32515. newH = jmin (height, roundToInt (newW * imageRatio));
  32516. }
  32517. else
  32518. {
  32519. newH = height;
  32520. newW = jmin (width, roundToInt (newH / imageRatio));
  32521. }
  32522. }
  32523. if (newW > 0 && newH > 0)
  32524. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32525. Rectangle<int> (x, y, width, height)));
  32526. }
  32527. }
  32528. bool Component::isTransformed() const throw()
  32529. {
  32530. return affineTransform != 0;
  32531. }
  32532. void Component::setTransform (const AffineTransform& newTransform)
  32533. {
  32534. // If you pass in a transform with no inverse, the component will have no dimensions,
  32535. // and there will be all sorts of maths errors when converting coordinates.
  32536. jassert (! newTransform.isSingularity());
  32537. if (newTransform.isIdentity())
  32538. {
  32539. if (affineTransform != 0)
  32540. {
  32541. repaint();
  32542. affineTransform = 0;
  32543. repaint();
  32544. sendMovedResizedMessages (false, false);
  32545. }
  32546. }
  32547. else if (affineTransform == 0)
  32548. {
  32549. repaint();
  32550. affineTransform = new AffineTransform (newTransform);
  32551. repaint();
  32552. sendMovedResizedMessages (false, false);
  32553. }
  32554. else if (*affineTransform != newTransform)
  32555. {
  32556. repaint();
  32557. *affineTransform = newTransform;
  32558. repaint();
  32559. sendMovedResizedMessages (false, false);
  32560. }
  32561. }
  32562. const AffineTransform Component::getTransform() const
  32563. {
  32564. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32565. }
  32566. bool Component::hitTest (int x, int y)
  32567. {
  32568. if (! flags.ignoresMouseClicksFlag)
  32569. return true;
  32570. if (flags.allowChildMouseClicksFlag)
  32571. {
  32572. for (int i = getNumChildComponents(); --i >= 0;)
  32573. {
  32574. Component& child = *getChildComponent (i);
  32575. if (child.isVisible()
  32576. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32577. return true;
  32578. }
  32579. }
  32580. return false;
  32581. }
  32582. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32583. const bool allowClicksOnChildComponents) throw()
  32584. {
  32585. flags.ignoresMouseClicksFlag = ! allowClicks;
  32586. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32587. }
  32588. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32589. bool& allowsClicksOnChildComponents) const throw()
  32590. {
  32591. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32592. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32593. }
  32594. bool Component::contains (const Point<int>& point)
  32595. {
  32596. if (ComponentHelpers::hitTest (*this, point))
  32597. {
  32598. if (parentComponent != 0)
  32599. {
  32600. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32601. }
  32602. else if (flags.hasHeavyweightPeerFlag)
  32603. {
  32604. const ComponentPeer* const peer = getPeer();
  32605. if (peer != 0)
  32606. return peer->contains (point, true);
  32607. }
  32608. }
  32609. return false;
  32610. }
  32611. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32612. {
  32613. if (! contains (point))
  32614. return false;
  32615. Component* const top = getTopLevelComponent();
  32616. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32617. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32618. }
  32619. Component* Component::getComponentAt (const Point<int>& position)
  32620. {
  32621. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32622. {
  32623. for (int i = childComponentList.size(); --i >= 0;)
  32624. {
  32625. Component* child = childComponentList.getUnchecked(i);
  32626. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32627. if (child != 0)
  32628. return child;
  32629. }
  32630. return this;
  32631. }
  32632. return 0;
  32633. }
  32634. Component* Component::getComponentAt (const int x, const int y)
  32635. {
  32636. return getComponentAt (Point<int> (x, y));
  32637. }
  32638. void Component::addChildComponent (Component* const child, int zOrder)
  32639. {
  32640. // if component methods are being called from threads other than the message
  32641. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32642. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32643. if (child != 0 && child->parentComponent != this)
  32644. {
  32645. if (child->parentComponent != 0)
  32646. child->parentComponent->removeChildComponent (child);
  32647. else
  32648. child->removeFromDesktop();
  32649. child->parentComponent = this;
  32650. if (child->isVisible())
  32651. child->repaintParent();
  32652. if (! child->isAlwaysOnTop())
  32653. {
  32654. if (zOrder < 0 || zOrder > childComponentList.size())
  32655. zOrder = childComponentList.size();
  32656. while (zOrder > 0)
  32657. {
  32658. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32659. break;
  32660. --zOrder;
  32661. }
  32662. }
  32663. childComponentList.insert (zOrder, child);
  32664. child->internalHierarchyChanged();
  32665. internalChildrenChanged();
  32666. }
  32667. }
  32668. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32669. {
  32670. if (child != 0)
  32671. {
  32672. child->setVisible (true);
  32673. addChildComponent (child, zOrder);
  32674. }
  32675. }
  32676. void Component::removeChildComponent (Component* const child)
  32677. {
  32678. removeChildComponent (childComponentList.indexOf (child), true, true);
  32679. }
  32680. Component* Component::removeChildComponent (const int index)
  32681. {
  32682. return removeChildComponent (index, true, true);
  32683. }
  32684. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32685. {
  32686. // if component methods are being called from threads other than the message
  32687. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32688. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32689. Component* const child = childComponentList [index];
  32690. if (child != 0)
  32691. {
  32692. sendParentEvents = sendParentEvents && child->isShowing();
  32693. if (sendParentEvents)
  32694. {
  32695. sendFakeMouseMove();
  32696. child->repaintParent();
  32697. }
  32698. childComponentList.remove (index);
  32699. child->parentComponent = 0;
  32700. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32701. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32702. {
  32703. if (sendParentEvents)
  32704. {
  32705. const WeakReference<Component> thisPointer (this);
  32706. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32707. if (thisPointer == 0)
  32708. return child;
  32709. grabKeyboardFocus();
  32710. }
  32711. else
  32712. {
  32713. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32714. }
  32715. }
  32716. if (sendChildEvents)
  32717. child->internalHierarchyChanged();
  32718. if (sendParentEvents)
  32719. internalChildrenChanged();
  32720. }
  32721. return child;
  32722. }
  32723. void Component::removeAllChildren()
  32724. {
  32725. while (childComponentList.size() > 0)
  32726. removeChildComponent (childComponentList.size() - 1);
  32727. }
  32728. void Component::deleteAllChildren()
  32729. {
  32730. while (childComponentList.size() > 0)
  32731. delete (removeChildComponent (childComponentList.size() - 1));
  32732. }
  32733. int Component::getNumChildComponents() const throw()
  32734. {
  32735. return childComponentList.size();
  32736. }
  32737. Component* Component::getChildComponent (const int index) const throw()
  32738. {
  32739. return childComponentList [index];
  32740. }
  32741. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32742. {
  32743. return childComponentList.indexOf (const_cast <Component*> (child));
  32744. }
  32745. Component* Component::getTopLevelComponent() const throw()
  32746. {
  32747. const Component* comp = this;
  32748. while (comp->parentComponent != 0)
  32749. comp = comp->parentComponent;
  32750. return const_cast <Component*> (comp);
  32751. }
  32752. bool Component::isParentOf (const Component* possibleChild) const throw()
  32753. {
  32754. while (possibleChild != 0)
  32755. {
  32756. possibleChild = possibleChild->parentComponent;
  32757. if (possibleChild == this)
  32758. return true;
  32759. }
  32760. return false;
  32761. }
  32762. void Component::parentHierarchyChanged()
  32763. {
  32764. }
  32765. void Component::childrenChanged()
  32766. {
  32767. }
  32768. void Component::internalChildrenChanged()
  32769. {
  32770. if (componentListeners.isEmpty())
  32771. {
  32772. childrenChanged();
  32773. }
  32774. else
  32775. {
  32776. BailOutChecker checker (this);
  32777. childrenChanged();
  32778. if (! checker.shouldBailOut())
  32779. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32780. }
  32781. }
  32782. void Component::internalHierarchyChanged()
  32783. {
  32784. BailOutChecker checker (this);
  32785. parentHierarchyChanged();
  32786. if (checker.shouldBailOut())
  32787. return;
  32788. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32789. if (checker.shouldBailOut())
  32790. return;
  32791. for (int i = childComponentList.size(); --i >= 0;)
  32792. {
  32793. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32794. if (checker.shouldBailOut())
  32795. {
  32796. // you really shouldn't delete the parent component during a callback telling you
  32797. // that it's changed..
  32798. jassertfalse;
  32799. return;
  32800. }
  32801. i = jmin (i, childComponentList.size());
  32802. }
  32803. }
  32804. int Component::runModalLoop()
  32805. {
  32806. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32807. {
  32808. // use a callback so this can be called from non-gui threads
  32809. return (int) (pointer_sized_int) MessageManager::getInstance()
  32810. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32811. }
  32812. if (! isCurrentlyModal())
  32813. enterModalState (true);
  32814. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32815. }
  32816. void Component::enterModalState (const bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* const callback)
  32817. {
  32818. // if component methods are being called from threads other than the message
  32819. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32820. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32821. // Check for an attempt to make a component modal when it already is!
  32822. // This can cause nasty problems..
  32823. jassert (! flags.currentlyModalFlag);
  32824. if (! isCurrentlyModal())
  32825. {
  32826. ModalComponentManager::getInstance()->startModal (this, callback);
  32827. flags.currentlyModalFlag = true;
  32828. setVisible (true);
  32829. if (shouldTakeKeyboardFocus)
  32830. grabKeyboardFocus();
  32831. }
  32832. }
  32833. void Component::exitModalState (const int returnValue)
  32834. {
  32835. if (flags.currentlyModalFlag)
  32836. {
  32837. if (MessageManager::getInstance()->isThisTheMessageThread())
  32838. {
  32839. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32840. flags.currentlyModalFlag = false;
  32841. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  32842. }
  32843. else
  32844. {
  32845. class ExitModalStateMessage : public CallbackMessage
  32846. {
  32847. public:
  32848. ExitModalStateMessage (Component* const target_, const int result_)
  32849. : target (target_), result (result_) {}
  32850. void messageCallback()
  32851. {
  32852. if (target.get() != 0) // (get() required for VS2003 bug)
  32853. target->exitModalState (result);
  32854. }
  32855. private:
  32856. WeakReference<Component> target;
  32857. int result;
  32858. };
  32859. (new ExitModalStateMessage (this, returnValue))->post();
  32860. }
  32861. }
  32862. }
  32863. bool Component::isCurrentlyModal() const throw()
  32864. {
  32865. return flags.currentlyModalFlag
  32866. && getCurrentlyModalComponent() == this;
  32867. }
  32868. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32869. {
  32870. Component* const mc = getCurrentlyModalComponent();
  32871. return mc != 0
  32872. && mc != this
  32873. && (! mc->isParentOf (this))
  32874. && ! mc->canModalEventBeSentToComponent (this);
  32875. }
  32876. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32877. {
  32878. return ModalComponentManager::getInstance()->getNumModalComponents();
  32879. }
  32880. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32881. {
  32882. return ModalComponentManager::getInstance()->getModalComponent (index);
  32883. }
  32884. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32885. {
  32886. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32887. }
  32888. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32889. {
  32890. return flags.bringToFrontOnClickFlag;
  32891. }
  32892. void Component::setMouseCursor (const MouseCursor& newCursor)
  32893. {
  32894. if (cursor != newCursor)
  32895. {
  32896. cursor = newCursor;
  32897. if (flags.visibleFlag)
  32898. updateMouseCursor();
  32899. }
  32900. }
  32901. const MouseCursor Component::getMouseCursor()
  32902. {
  32903. return cursor;
  32904. }
  32905. void Component::updateMouseCursor() const
  32906. {
  32907. sendFakeMouseMove();
  32908. }
  32909. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32910. {
  32911. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32912. }
  32913. void Component::setAlpha (const float newAlpha)
  32914. {
  32915. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  32916. if (componentTransparency != newIntAlpha)
  32917. {
  32918. componentTransparency = newIntAlpha;
  32919. if (flags.hasHeavyweightPeerFlag)
  32920. {
  32921. ComponentPeer* const peer = getPeer();
  32922. if (peer != 0)
  32923. peer->setAlpha (newAlpha);
  32924. }
  32925. else
  32926. {
  32927. repaint();
  32928. }
  32929. }
  32930. }
  32931. float Component::getAlpha() const
  32932. {
  32933. return (255 - componentTransparency) / 255.0f;
  32934. }
  32935. void Component::repaintParent()
  32936. {
  32937. if (flags.visibleFlag)
  32938. internalRepaint (0, 0, getWidth(), getHeight());
  32939. }
  32940. void Component::repaint()
  32941. {
  32942. repaint (0, 0, getWidth(), getHeight());
  32943. }
  32944. void Component::repaint (const int x, const int y,
  32945. const int w, const int h)
  32946. {
  32947. bufferedImage = Image::null;
  32948. if (flags.visibleFlag)
  32949. internalRepaint (x, y, w, h);
  32950. }
  32951. void Component::repaint (const Rectangle<int>& area)
  32952. {
  32953. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32954. }
  32955. void Component::internalRepaint (int x, int y, int w, int h)
  32956. {
  32957. // if component methods are being called from threads other than the message
  32958. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32959. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32960. if (x < 0)
  32961. {
  32962. w += x;
  32963. x = 0;
  32964. }
  32965. if (x + w > getWidth())
  32966. w = getWidth() - x;
  32967. if (w > 0)
  32968. {
  32969. if (y < 0)
  32970. {
  32971. h += y;
  32972. y = 0;
  32973. }
  32974. if (y + h > getHeight())
  32975. h = getHeight() - y;
  32976. if (h > 0)
  32977. {
  32978. if (parentComponent != 0)
  32979. {
  32980. if (parentComponent->flags.visibleFlag)
  32981. {
  32982. if (affineTransform == 0)
  32983. {
  32984. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  32985. }
  32986. else
  32987. {
  32988. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  32989. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32990. }
  32991. }
  32992. }
  32993. else if (flags.hasHeavyweightPeerFlag)
  32994. {
  32995. ComponentPeer* const peer = getPeer();
  32996. if (peer != 0)
  32997. peer->repaint (Rectangle<int> (x, y, w, h));
  32998. }
  32999. }
  33000. }
  33001. }
  33002. void Component::paintComponent (Graphics& g)
  33003. {
  33004. if (flags.bufferToImageFlag)
  33005. {
  33006. if (bufferedImage.isNull())
  33007. {
  33008. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33009. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33010. Graphics imG (bufferedImage);
  33011. paint (imG);
  33012. }
  33013. g.setColour (Colours::black.withAlpha (getAlpha()));
  33014. g.drawImageAt (bufferedImage, 0, 0);
  33015. }
  33016. else
  33017. {
  33018. paint (g);
  33019. }
  33020. }
  33021. void Component::paintWithinParentContext (Graphics& g)
  33022. {
  33023. g.setOrigin (getX(), getY());
  33024. paintEntireComponent (g, false);
  33025. }
  33026. void Component::paintComponentAndChildren (Graphics& g)
  33027. {
  33028. const Rectangle<int> clipBounds (g.getClipBounds());
  33029. if (flags.dontClipGraphicsFlag)
  33030. {
  33031. paintComponent (g);
  33032. }
  33033. else
  33034. {
  33035. g.saveState();
  33036. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33037. if (! g.isClipEmpty())
  33038. paintComponent (g);
  33039. g.restoreState();
  33040. }
  33041. for (int i = 0; i < childComponentList.size(); ++i)
  33042. {
  33043. Component& child = *childComponentList.getUnchecked (i);
  33044. if (child.isVisible())
  33045. {
  33046. if (child.affineTransform != 0)
  33047. {
  33048. g.saveState();
  33049. g.addTransform (*child.affineTransform);
  33050. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33051. child.paintWithinParentContext (g);
  33052. g.restoreState();
  33053. }
  33054. else if (clipBounds.intersects (child.getBounds()))
  33055. {
  33056. g.saveState();
  33057. if (child.flags.dontClipGraphicsFlag)
  33058. {
  33059. child.paintWithinParentContext (g);
  33060. }
  33061. else if (g.reduceClipRegion (child.getBounds()))
  33062. {
  33063. bool nothingClipped = true;
  33064. for (int j = i + 1; j < childComponentList.size(); ++j)
  33065. {
  33066. const Component& sibling = *childComponentList.getUnchecked (j);
  33067. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33068. {
  33069. nothingClipped = false;
  33070. g.excludeClipRegion (sibling.getBounds());
  33071. }
  33072. }
  33073. if (nothingClipped || ! g.isClipEmpty())
  33074. child.paintWithinParentContext (g);
  33075. }
  33076. g.restoreState();
  33077. }
  33078. }
  33079. }
  33080. g.saveState();
  33081. paintOverChildren (g);
  33082. g.restoreState();
  33083. }
  33084. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33085. {
  33086. jassert (! g.isClipEmpty());
  33087. #if JUCE_DEBUG
  33088. flags.isInsidePaintCall = true;
  33089. #endif
  33090. if (effect != 0)
  33091. {
  33092. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33093. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33094. {
  33095. Graphics g2 (effectImage);
  33096. paintComponentAndChildren (g2);
  33097. }
  33098. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33099. }
  33100. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33101. {
  33102. if (componentTransparency < 255)
  33103. {
  33104. g.beginTransparencyLayer (getAlpha());
  33105. paintComponentAndChildren (g);
  33106. g.endTransparencyLayer();
  33107. }
  33108. }
  33109. else
  33110. {
  33111. paintComponentAndChildren (g);
  33112. }
  33113. #if JUCE_DEBUG
  33114. flags.isInsidePaintCall = false;
  33115. #endif
  33116. }
  33117. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33118. {
  33119. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33120. }
  33121. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33122. const bool clipImageToComponentBounds)
  33123. {
  33124. Rectangle<int> r (areaToGrab);
  33125. if (clipImageToComponentBounds)
  33126. r = r.getIntersection (getLocalBounds());
  33127. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33128. jmax (1, r.getWidth()),
  33129. jmax (1, r.getHeight()),
  33130. true);
  33131. Graphics imageContext (componentImage);
  33132. imageContext.setOrigin (-r.getX(), -r.getY());
  33133. paintEntireComponent (imageContext, true);
  33134. return componentImage;
  33135. }
  33136. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33137. {
  33138. if (effect != newEffect)
  33139. {
  33140. effect = newEffect;
  33141. repaint();
  33142. }
  33143. }
  33144. LookAndFeel& Component::getLookAndFeel() const throw()
  33145. {
  33146. const Component* c = this;
  33147. do
  33148. {
  33149. if (c->lookAndFeel != 0)
  33150. return *(c->lookAndFeel);
  33151. c = c->parentComponent;
  33152. }
  33153. while (c != 0);
  33154. return LookAndFeel::getDefaultLookAndFeel();
  33155. }
  33156. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33157. {
  33158. if (lookAndFeel != newLookAndFeel)
  33159. {
  33160. lookAndFeel = newLookAndFeel;
  33161. sendLookAndFeelChange();
  33162. }
  33163. }
  33164. void Component::lookAndFeelChanged()
  33165. {
  33166. }
  33167. void Component::sendLookAndFeelChange()
  33168. {
  33169. repaint();
  33170. WeakReference<Component> safePointer (this);
  33171. lookAndFeelChanged();
  33172. if (safePointer != 0)
  33173. {
  33174. for (int i = childComponentList.size(); --i >= 0;)
  33175. {
  33176. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33177. if (safePointer == 0)
  33178. return;
  33179. i = jmin (i, childComponentList.size());
  33180. }
  33181. }
  33182. }
  33183. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33184. {
  33185. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33186. if (v != 0)
  33187. return Colour ((int) *v);
  33188. if (inheritFromParent && parentComponent != 0)
  33189. return parentComponent->findColour (colourId, true);
  33190. return getLookAndFeel().findColour (colourId);
  33191. }
  33192. bool Component::isColourSpecified (const int colourId) const
  33193. {
  33194. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33195. }
  33196. void Component::removeColour (const int colourId)
  33197. {
  33198. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33199. colourChanged();
  33200. }
  33201. void Component::setColour (const int colourId, const Colour& colour)
  33202. {
  33203. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33204. colourChanged();
  33205. }
  33206. void Component::copyAllExplicitColoursTo (Component& target) const
  33207. {
  33208. bool changed = false;
  33209. for (int i = properties.size(); --i >= 0;)
  33210. {
  33211. const Identifier name (properties.getName(i));
  33212. if (name.toString().startsWith ("jcclr_"))
  33213. if (target.properties.set (name, properties [name]))
  33214. changed = true;
  33215. }
  33216. if (changed)
  33217. target.colourChanged();
  33218. }
  33219. void Component::colourChanged()
  33220. {
  33221. }
  33222. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33223. {
  33224. return 0;
  33225. }
  33226. Component::Positioner::Positioner (Component& component_) throw()
  33227. : component (component_)
  33228. {
  33229. }
  33230. Component::Positioner* Component::getPositioner() const throw()
  33231. {
  33232. return positioner;
  33233. }
  33234. void Component::setPositioner (Positioner* newPositioner)
  33235. {
  33236. // You can only assign a positioner to the component that it was created for!
  33237. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33238. positioner = newPositioner;
  33239. }
  33240. const Rectangle<int> Component::getLocalBounds() const throw()
  33241. {
  33242. return Rectangle<int> (getWidth(), getHeight());
  33243. }
  33244. const Rectangle<int> Component::getBoundsInParent() const throw()
  33245. {
  33246. return affineTransform == 0 ? bounds
  33247. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33248. }
  33249. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33250. {
  33251. result.clear();
  33252. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33253. if (! unclipped.isEmpty())
  33254. {
  33255. result.add (unclipped);
  33256. if (includeSiblings)
  33257. {
  33258. const Component* const c = getTopLevelComponent();
  33259. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33260. c->getLocalBounds(), this);
  33261. }
  33262. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33263. result.consolidate();
  33264. }
  33265. }
  33266. void Component::mouseEnter (const MouseEvent&)
  33267. {
  33268. // base class does nothing
  33269. }
  33270. void Component::mouseExit (const MouseEvent&)
  33271. {
  33272. // base class does nothing
  33273. }
  33274. void Component::mouseDown (const MouseEvent&)
  33275. {
  33276. // base class does nothing
  33277. }
  33278. void Component::mouseUp (const MouseEvent&)
  33279. {
  33280. // base class does nothing
  33281. }
  33282. void Component::mouseDrag (const MouseEvent&)
  33283. {
  33284. // base class does nothing
  33285. }
  33286. void Component::mouseMove (const MouseEvent&)
  33287. {
  33288. // base class does nothing
  33289. }
  33290. void Component::mouseDoubleClick (const MouseEvent&)
  33291. {
  33292. // base class does nothing
  33293. }
  33294. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33295. {
  33296. // the base class just passes this event up to its parent..
  33297. if (parentComponent != 0)
  33298. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33299. wheelIncrementX, wheelIncrementY);
  33300. }
  33301. void Component::resized()
  33302. {
  33303. // base class does nothing
  33304. }
  33305. void Component::moved()
  33306. {
  33307. // base class does nothing
  33308. }
  33309. void Component::childBoundsChanged (Component*)
  33310. {
  33311. // base class does nothing
  33312. }
  33313. void Component::parentSizeChanged()
  33314. {
  33315. // base class does nothing
  33316. }
  33317. void Component::addComponentListener (ComponentListener* const newListener)
  33318. {
  33319. // if component methods are being called from threads other than the message
  33320. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33321. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33322. componentListeners.add (newListener);
  33323. }
  33324. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33325. {
  33326. componentListeners.remove (listenerToRemove);
  33327. }
  33328. void Component::inputAttemptWhenModal()
  33329. {
  33330. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33331. getLookAndFeel().playAlertSound();
  33332. }
  33333. bool Component::canModalEventBeSentToComponent (const Component*)
  33334. {
  33335. return false;
  33336. }
  33337. void Component::internalModalInputAttempt()
  33338. {
  33339. Component* const current = getCurrentlyModalComponent();
  33340. if (current != 0)
  33341. current->inputAttemptWhenModal();
  33342. }
  33343. void Component::paint (Graphics&)
  33344. {
  33345. // all painting is done in the subclasses
  33346. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33347. }
  33348. void Component::paintOverChildren (Graphics&)
  33349. {
  33350. // all painting is done in the subclasses
  33351. }
  33352. void Component::postCommandMessage (const int commandId)
  33353. {
  33354. class CustomCommandMessage : public CallbackMessage
  33355. {
  33356. public:
  33357. CustomCommandMessage (Component* const target_, const int commandId_)
  33358. : target (target_), commandId (commandId_) {}
  33359. void messageCallback()
  33360. {
  33361. if (target.get() != 0) // (get() required for VS2003 bug)
  33362. target->handleCommandMessage (commandId);
  33363. }
  33364. private:
  33365. WeakReference<Component> target;
  33366. int commandId;
  33367. };
  33368. (new CustomCommandMessage (this, commandId))->post();
  33369. }
  33370. void Component::handleCommandMessage (int)
  33371. {
  33372. // used by subclasses
  33373. }
  33374. void Component::addMouseListener (MouseListener* const newListener,
  33375. const bool wantsEventsForAllNestedChildComponents)
  33376. {
  33377. // if component methods are being called from threads other than the message
  33378. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33379. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33380. // If you register a component as a mouselistener for itself, it'll receive all the events
  33381. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33382. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33383. if (mouseListeners == 0)
  33384. mouseListeners = new MouseListenerList();
  33385. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33386. }
  33387. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33388. {
  33389. // if component methods are being called from threads other than the message
  33390. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33391. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33392. if (mouseListeners != 0)
  33393. mouseListeners->removeListener (listenerToRemove);
  33394. }
  33395. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33396. {
  33397. if (isCurrentlyBlockedByAnotherModalComponent())
  33398. {
  33399. // if something else is modal, always just show a normal mouse cursor
  33400. source.showMouseCursor (MouseCursor::NormalCursor);
  33401. return;
  33402. }
  33403. if (! flags.mouseInsideFlag)
  33404. {
  33405. flags.mouseInsideFlag = true;
  33406. flags.mouseOverFlag = true;
  33407. flags.mouseDownFlag = false;
  33408. BailOutChecker checker (this);
  33409. if (flags.repaintOnMouseActivityFlag)
  33410. repaint();
  33411. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33412. this, this, time, relativePos, time, 0, false);
  33413. mouseEnter (me);
  33414. if (checker.shouldBailOut())
  33415. return;
  33416. Desktop& desktop = Desktop::getInstance();
  33417. desktop.resetTimer();
  33418. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33419. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33420. }
  33421. }
  33422. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33423. {
  33424. BailOutChecker checker (this);
  33425. if (flags.mouseDownFlag)
  33426. {
  33427. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33428. if (checker.shouldBailOut())
  33429. return;
  33430. }
  33431. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33432. {
  33433. flags.mouseInsideFlag = false;
  33434. flags.mouseOverFlag = false;
  33435. flags.mouseDownFlag = false;
  33436. if (flags.repaintOnMouseActivityFlag)
  33437. repaint();
  33438. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33439. this, this, time, relativePos, time, 0, false);
  33440. mouseExit (me);
  33441. if (checker.shouldBailOut())
  33442. return;
  33443. Desktop& desktop = Desktop::getInstance();
  33444. desktop.resetTimer();
  33445. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33446. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33447. }
  33448. }
  33449. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33450. {
  33451. Desktop& desktop = Desktop::getInstance();
  33452. BailOutChecker checker (this);
  33453. if (isCurrentlyBlockedByAnotherModalComponent())
  33454. {
  33455. internalModalInputAttempt();
  33456. if (checker.shouldBailOut())
  33457. return;
  33458. // If processing the input attempt has exited the modal loop, we'll allow the event
  33459. // to be delivered..
  33460. if (isCurrentlyBlockedByAnotherModalComponent())
  33461. {
  33462. // allow blocked mouse-events to go to global listeners..
  33463. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33464. this, this, time, relativePos, time,
  33465. source.getNumberOfMultipleClicks(), false);
  33466. desktop.resetTimer();
  33467. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33468. return;
  33469. }
  33470. }
  33471. {
  33472. Component* c = this;
  33473. while (c != 0)
  33474. {
  33475. if (c->isBroughtToFrontOnMouseClick())
  33476. {
  33477. c->toFront (true);
  33478. if (checker.shouldBailOut())
  33479. return;
  33480. }
  33481. c = c->parentComponent;
  33482. }
  33483. }
  33484. if (! flags.dontFocusOnMouseClickFlag)
  33485. {
  33486. grabFocusInternal (focusChangedByMouseClick);
  33487. if (checker.shouldBailOut())
  33488. return;
  33489. }
  33490. flags.mouseDownFlag = true;
  33491. flags.mouseOverFlag = true;
  33492. if (flags.repaintOnMouseActivityFlag)
  33493. repaint();
  33494. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33495. this, this, time, relativePos, time,
  33496. source.getNumberOfMultipleClicks(), false);
  33497. mouseDown (me);
  33498. if (checker.shouldBailOut())
  33499. return;
  33500. desktop.resetTimer();
  33501. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33502. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33503. }
  33504. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33505. {
  33506. if (flags.mouseDownFlag)
  33507. {
  33508. flags.mouseDownFlag = false;
  33509. BailOutChecker checker (this);
  33510. if (flags.repaintOnMouseActivityFlag)
  33511. repaint();
  33512. const MouseEvent me (source, relativePos,
  33513. oldModifiers, this, this, time,
  33514. getLocalPoint (0, source.getLastMouseDownPosition()),
  33515. source.getLastMouseDownTime(),
  33516. source.getNumberOfMultipleClicks(),
  33517. source.hasMouseMovedSignificantlySincePressed());
  33518. mouseUp (me);
  33519. if (checker.shouldBailOut())
  33520. return;
  33521. Desktop& desktop = Desktop::getInstance();
  33522. desktop.resetTimer();
  33523. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33524. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33525. if (checker.shouldBailOut())
  33526. return;
  33527. // check for double-click
  33528. if (me.getNumberOfClicks() >= 2)
  33529. {
  33530. mouseDoubleClick (me);
  33531. if (checker.shouldBailOut())
  33532. return;
  33533. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33534. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33535. }
  33536. }
  33537. }
  33538. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33539. {
  33540. if (flags.mouseDownFlag)
  33541. {
  33542. flags.mouseOverFlag = reallyContains (relativePos, false);
  33543. BailOutChecker checker (this);
  33544. const MouseEvent me (source, relativePos,
  33545. source.getCurrentModifiers(), this, this, time,
  33546. getLocalPoint (0, source.getLastMouseDownPosition()),
  33547. source.getLastMouseDownTime(),
  33548. source.getNumberOfMultipleClicks(),
  33549. source.hasMouseMovedSignificantlySincePressed());
  33550. mouseDrag (me);
  33551. if (checker.shouldBailOut())
  33552. return;
  33553. Desktop& desktop = Desktop::getInstance();
  33554. desktop.resetTimer();
  33555. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33556. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33557. }
  33558. }
  33559. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33560. {
  33561. Desktop& desktop = Desktop::getInstance();
  33562. BailOutChecker checker (this);
  33563. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33564. this, this, time, relativePos, time, 0, false);
  33565. if (isCurrentlyBlockedByAnotherModalComponent())
  33566. {
  33567. // allow blocked mouse-events to go to global listeners..
  33568. desktop.sendMouseMove();
  33569. }
  33570. else
  33571. {
  33572. flags.mouseOverFlag = true;
  33573. mouseMove (me);
  33574. if (checker.shouldBailOut())
  33575. return;
  33576. desktop.resetTimer();
  33577. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33578. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33579. }
  33580. }
  33581. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33582. const Time& time, const float amountX, const float amountY)
  33583. {
  33584. Desktop& desktop = Desktop::getInstance();
  33585. BailOutChecker checker (this);
  33586. const float wheelIncrementX = amountX / 256.0f;
  33587. const float wheelIncrementY = amountY / 256.0f;
  33588. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33589. this, this, time, relativePos, time, 0, false);
  33590. if (isCurrentlyBlockedByAnotherModalComponent())
  33591. {
  33592. // allow blocked mouse-events to go to global listeners..
  33593. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33594. }
  33595. else
  33596. {
  33597. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33598. if (checker.shouldBailOut())
  33599. return;
  33600. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33601. if (! checker.shouldBailOut())
  33602. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33603. }
  33604. }
  33605. void Component::sendFakeMouseMove() const
  33606. {
  33607. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33608. if (! mainMouse.isDragging())
  33609. mainMouse.triggerFakeMove();
  33610. }
  33611. void Component::beginDragAutoRepeat (const int interval)
  33612. {
  33613. Desktop::getInstance().beginDragAutoRepeat (interval);
  33614. }
  33615. void Component::broughtToFront()
  33616. {
  33617. }
  33618. void Component::internalBroughtToFront()
  33619. {
  33620. if (flags.hasHeavyweightPeerFlag)
  33621. Desktop::getInstance().componentBroughtToFront (this);
  33622. BailOutChecker checker (this);
  33623. broughtToFront();
  33624. if (checker.shouldBailOut())
  33625. return;
  33626. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33627. if (checker.shouldBailOut())
  33628. return;
  33629. // When brought to the front and there's a modal component blocking this one,
  33630. // we need to bring the modal one to the front instead..
  33631. Component* const cm = getCurrentlyModalComponent();
  33632. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33633. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33634. }
  33635. void Component::focusGained (FocusChangeType)
  33636. {
  33637. // base class does nothing
  33638. }
  33639. void Component::internalFocusGain (const FocusChangeType cause)
  33640. {
  33641. internalFocusGain (cause, WeakReference<Component> (this));
  33642. }
  33643. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33644. {
  33645. focusGained (cause);
  33646. if (safePointer != 0)
  33647. internalChildFocusChange (cause, safePointer);
  33648. }
  33649. void Component::focusLost (FocusChangeType)
  33650. {
  33651. // base class does nothing
  33652. }
  33653. void Component::internalFocusLoss (const FocusChangeType cause)
  33654. {
  33655. WeakReference<Component> safePointer (this);
  33656. focusLost (focusChangedDirectly);
  33657. if (safePointer != 0)
  33658. internalChildFocusChange (cause, safePointer);
  33659. }
  33660. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33661. {
  33662. // base class does nothing
  33663. }
  33664. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33665. {
  33666. const bool childIsNowFocused = hasKeyboardFocus (true);
  33667. if (flags.childCompFocusedFlag != childIsNowFocused)
  33668. {
  33669. flags.childCompFocusedFlag = childIsNowFocused;
  33670. focusOfChildComponentChanged (cause);
  33671. if (safePointer == 0)
  33672. return;
  33673. }
  33674. if (parentComponent != 0)
  33675. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33676. }
  33677. bool Component::isEnabled() const throw()
  33678. {
  33679. return (! flags.isDisabledFlag)
  33680. && (parentComponent == 0 || parentComponent->isEnabled());
  33681. }
  33682. void Component::setEnabled (const bool shouldBeEnabled)
  33683. {
  33684. if (flags.isDisabledFlag == shouldBeEnabled)
  33685. {
  33686. flags.isDisabledFlag = ! shouldBeEnabled;
  33687. // if any parent components are disabled, setting our flag won't make a difference,
  33688. // so no need to send a change message
  33689. if (parentComponent == 0 || parentComponent->isEnabled())
  33690. sendEnablementChangeMessage();
  33691. }
  33692. }
  33693. void Component::sendEnablementChangeMessage()
  33694. {
  33695. WeakReference<Component> safePointer (this);
  33696. enablementChanged();
  33697. if (safePointer == 0)
  33698. return;
  33699. for (int i = getNumChildComponents(); --i >= 0;)
  33700. {
  33701. Component* const c = getChildComponent (i);
  33702. if (c != 0)
  33703. {
  33704. c->sendEnablementChangeMessage();
  33705. if (safePointer == 0)
  33706. return;
  33707. }
  33708. }
  33709. }
  33710. void Component::enablementChanged()
  33711. {
  33712. }
  33713. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33714. {
  33715. flags.wantsFocusFlag = wantsFocus;
  33716. }
  33717. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33718. {
  33719. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33720. }
  33721. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33722. {
  33723. return ! flags.dontFocusOnMouseClickFlag;
  33724. }
  33725. bool Component::getWantsKeyboardFocus() const throw()
  33726. {
  33727. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33728. }
  33729. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33730. {
  33731. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33732. }
  33733. bool Component::isFocusContainer() const throw()
  33734. {
  33735. return flags.isFocusContainerFlag;
  33736. }
  33737. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33738. int Component::getExplicitFocusOrder() const
  33739. {
  33740. return properties [juce_explicitFocusOrderId];
  33741. }
  33742. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33743. {
  33744. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33745. }
  33746. KeyboardFocusTraverser* Component::createFocusTraverser()
  33747. {
  33748. if (flags.isFocusContainerFlag || parentComponent == 0)
  33749. return new KeyboardFocusTraverser();
  33750. return parentComponent->createFocusTraverser();
  33751. }
  33752. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33753. {
  33754. // give the focus to this component
  33755. if (currentlyFocusedComponent != this)
  33756. {
  33757. // get the focus onto our desktop window
  33758. ComponentPeer* const peer = getPeer();
  33759. if (peer != 0)
  33760. {
  33761. WeakReference<Component> safePointer (this);
  33762. peer->grabFocus();
  33763. if (peer->isFocused() && currentlyFocusedComponent != this)
  33764. {
  33765. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33766. currentlyFocusedComponent = this;
  33767. Desktop::getInstance().triggerFocusCallback();
  33768. // call this after setting currentlyFocusedComponent so that the one that's
  33769. // losing it has a chance to see where focus is going
  33770. if (componentLosingFocus != 0)
  33771. componentLosingFocus->internalFocusLoss (cause);
  33772. if (currentlyFocusedComponent == this)
  33773. internalFocusGain (cause, safePointer);
  33774. }
  33775. }
  33776. }
  33777. }
  33778. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33779. {
  33780. if (isShowing())
  33781. {
  33782. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33783. {
  33784. takeKeyboardFocus (cause);
  33785. }
  33786. else
  33787. {
  33788. if (isParentOf (currentlyFocusedComponent)
  33789. && currentlyFocusedComponent->isShowing())
  33790. {
  33791. // do nothing if the focused component is actually a child of ours..
  33792. }
  33793. else
  33794. {
  33795. // find the default child component..
  33796. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33797. if (traverser != 0)
  33798. {
  33799. Component* const defaultComp = traverser->getDefaultComponent (this);
  33800. traverser = 0;
  33801. if (defaultComp != 0)
  33802. {
  33803. defaultComp->grabFocusInternal (cause, false);
  33804. return;
  33805. }
  33806. }
  33807. if (canTryParent && parentComponent != 0)
  33808. {
  33809. // if no children want it and we're allowed to try our parent comp,
  33810. // then pass up to parent, which will try our siblings.
  33811. parentComponent->grabFocusInternal (cause, true);
  33812. }
  33813. }
  33814. }
  33815. }
  33816. }
  33817. void Component::grabKeyboardFocus()
  33818. {
  33819. // if component methods are being called from threads other than the message
  33820. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33821. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33822. grabFocusInternal (focusChangedDirectly);
  33823. }
  33824. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33825. {
  33826. // if component methods are being called from threads other than the message
  33827. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33828. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33829. if (parentComponent != 0)
  33830. {
  33831. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33832. if (traverser != 0)
  33833. {
  33834. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33835. : traverser->getPreviousComponent (this);
  33836. traverser = 0;
  33837. if (nextComp != 0)
  33838. {
  33839. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33840. {
  33841. WeakReference<Component> nextCompPointer (nextComp);
  33842. internalModalInputAttempt();
  33843. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33844. return;
  33845. }
  33846. nextComp->grabFocusInternal (focusChangedByTabKey);
  33847. return;
  33848. }
  33849. }
  33850. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  33851. }
  33852. }
  33853. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33854. {
  33855. return (currentlyFocusedComponent == this)
  33856. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33857. }
  33858. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33859. {
  33860. return currentlyFocusedComponent;
  33861. }
  33862. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  33863. {
  33864. Component* const componentLosingFocus = currentlyFocusedComponent;
  33865. currentlyFocusedComponent = 0;
  33866. if (sendFocusLossEvent && componentLosingFocus != 0)
  33867. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33868. Desktop::getInstance().triggerFocusCallback();
  33869. }
  33870. bool Component::isMouseOver (const bool includeChildren) const
  33871. {
  33872. if (flags.mouseOverFlag)
  33873. return true;
  33874. if (includeChildren)
  33875. {
  33876. Desktop& desktop = Desktop::getInstance();
  33877. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33878. {
  33879. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  33880. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  33881. return true;
  33882. }
  33883. }
  33884. return false;
  33885. }
  33886. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  33887. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  33888. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33889. {
  33890. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33891. }
  33892. const Point<int> Component::getMouseXYRelative() const
  33893. {
  33894. return getLocalPoint (0, Desktop::getMousePosition());
  33895. }
  33896. const Rectangle<int> Component::getParentMonitorArea() const
  33897. {
  33898. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  33899. }
  33900. void Component::addKeyListener (KeyListener* const newListener)
  33901. {
  33902. if (keyListeners == 0)
  33903. keyListeners = new Array <KeyListener*>();
  33904. keyListeners->addIfNotAlreadyThere (newListener);
  33905. }
  33906. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33907. {
  33908. if (keyListeners != 0)
  33909. keyListeners->removeValue (listenerToRemove);
  33910. }
  33911. bool Component::keyPressed (const KeyPress&)
  33912. {
  33913. return false;
  33914. }
  33915. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33916. {
  33917. return false;
  33918. }
  33919. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33920. {
  33921. if (parentComponent != 0)
  33922. parentComponent->modifierKeysChanged (modifiers);
  33923. }
  33924. void Component::internalModifierKeysChanged()
  33925. {
  33926. sendFakeMouseMove();
  33927. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33928. }
  33929. ComponentPeer* Component::getPeer() const
  33930. {
  33931. if (flags.hasHeavyweightPeerFlag)
  33932. return ComponentPeer::getPeerFor (this);
  33933. else if (parentComponent == 0)
  33934. return 0;
  33935. return parentComponent->getPeer();
  33936. }
  33937. Component::BailOutChecker::BailOutChecker (Component* const component)
  33938. : safePointer (component)
  33939. {
  33940. jassert (component != 0);
  33941. }
  33942. bool Component::BailOutChecker::shouldBailOut() const throw()
  33943. {
  33944. return safePointer == 0;
  33945. }
  33946. END_JUCE_NAMESPACE
  33947. /*** End of inlined file: juce_Component.cpp ***/
  33948. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33949. BEGIN_JUCE_NAMESPACE
  33950. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33951. void ComponentListener::componentBroughtToFront (Component&) {}
  33952. void ComponentListener::componentVisibilityChanged (Component&) {}
  33953. void ComponentListener::componentChildrenChanged (Component&) {}
  33954. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33955. void ComponentListener::componentNameChanged (Component&) {}
  33956. void ComponentListener::componentBeingDeleted (Component&) {}
  33957. END_JUCE_NAMESPACE
  33958. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33959. /*** Start of inlined file: juce_Desktop.cpp ***/
  33960. BEGIN_JUCE_NAMESPACE
  33961. Desktop::Desktop()
  33962. : mouseClickCounter (0),
  33963. kioskModeComponent (0),
  33964. allowedOrientations (allOrientations)
  33965. {
  33966. createMouseInputSources();
  33967. refreshMonitorSizes();
  33968. }
  33969. Desktop::~Desktop()
  33970. {
  33971. jassert (instance == this);
  33972. instance = 0;
  33973. // doh! If you don't delete all your windows before exiting, you're going to
  33974. // be leaking memory!
  33975. jassert (desktopComponents.size() == 0);
  33976. }
  33977. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33978. {
  33979. if (instance == 0)
  33980. instance = new Desktop();
  33981. return *instance;
  33982. }
  33983. Desktop* Desktop::instance = 0;
  33984. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33985. const bool clipToWorkArea);
  33986. void Desktop::refreshMonitorSizes()
  33987. {
  33988. Array <Rectangle<int> > oldClipped, oldUnclipped;
  33989. oldClipped.swapWithArray (monitorCoordsClipped);
  33990. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  33991. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33992. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33993. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33994. if (oldClipped != monitorCoordsClipped
  33995. || oldUnclipped != monitorCoordsUnclipped)
  33996. {
  33997. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33998. {
  33999. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34000. if (p != 0)
  34001. p->handleScreenSizeChange();
  34002. }
  34003. }
  34004. }
  34005. int Desktop::getNumDisplayMonitors() const throw()
  34006. {
  34007. return monitorCoordsClipped.size();
  34008. }
  34009. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34010. {
  34011. return clippedToWorkArea ? monitorCoordsClipped [index]
  34012. : monitorCoordsUnclipped [index];
  34013. }
  34014. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34015. {
  34016. RectangleList rl;
  34017. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34018. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34019. return rl;
  34020. }
  34021. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34022. {
  34023. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34024. }
  34025. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34026. {
  34027. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34028. double bestDistance = 1.0e10;
  34029. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34030. {
  34031. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34032. if (rect.contains (position))
  34033. return rect;
  34034. const double distance = rect.getCentre().getDistanceFrom (position);
  34035. if (distance < bestDistance)
  34036. {
  34037. bestDistance = distance;
  34038. best = rect;
  34039. }
  34040. }
  34041. return best;
  34042. }
  34043. int Desktop::getNumComponents() const throw()
  34044. {
  34045. return desktopComponents.size();
  34046. }
  34047. Component* Desktop::getComponent (const int index) const throw()
  34048. {
  34049. return desktopComponents [index];
  34050. }
  34051. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34052. {
  34053. for (int i = desktopComponents.size(); --i >= 0;)
  34054. {
  34055. Component* const c = desktopComponents.getUnchecked(i);
  34056. if (c->isVisible())
  34057. {
  34058. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34059. if (c->contains (relative))
  34060. return c->getComponentAt (relative);
  34061. }
  34062. }
  34063. return 0;
  34064. }
  34065. void Desktop::addDesktopComponent (Component* const c)
  34066. {
  34067. jassert (c != 0);
  34068. jassert (! desktopComponents.contains (c));
  34069. desktopComponents.addIfNotAlreadyThere (c);
  34070. }
  34071. void Desktop::removeDesktopComponent (Component* const c)
  34072. {
  34073. desktopComponents.removeValue (c);
  34074. }
  34075. void Desktop::componentBroughtToFront (Component* const c)
  34076. {
  34077. const int index = desktopComponents.indexOf (c);
  34078. jassert (index >= 0);
  34079. if (index >= 0)
  34080. {
  34081. int newIndex = -1;
  34082. if (! c->isAlwaysOnTop())
  34083. {
  34084. newIndex = desktopComponents.size();
  34085. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34086. --newIndex;
  34087. --newIndex;
  34088. }
  34089. desktopComponents.move (index, newIndex);
  34090. }
  34091. }
  34092. const Point<int> Desktop::getMousePosition()
  34093. {
  34094. return getInstance().getMainMouseSource().getScreenPosition();
  34095. }
  34096. const Point<int> Desktop::getLastMouseDownPosition()
  34097. {
  34098. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34099. }
  34100. int Desktop::getMouseButtonClickCounter()
  34101. {
  34102. return getInstance().mouseClickCounter;
  34103. }
  34104. void Desktop::incrementMouseClickCounter() throw()
  34105. {
  34106. ++mouseClickCounter;
  34107. }
  34108. int Desktop::getNumDraggingMouseSources() const throw()
  34109. {
  34110. int num = 0;
  34111. for (int i = mouseSources.size(); --i >= 0;)
  34112. if (mouseSources.getUnchecked(i)->isDragging())
  34113. ++num;
  34114. return num;
  34115. }
  34116. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34117. {
  34118. int num = 0;
  34119. for (int i = mouseSources.size(); --i >= 0;)
  34120. {
  34121. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34122. if (mi->isDragging())
  34123. {
  34124. if (index == num)
  34125. return mi;
  34126. ++num;
  34127. }
  34128. }
  34129. return 0;
  34130. }
  34131. class MouseDragAutoRepeater : public Timer
  34132. {
  34133. public:
  34134. MouseDragAutoRepeater() {}
  34135. void timerCallback()
  34136. {
  34137. Desktop& desktop = Desktop::getInstance();
  34138. int numMiceDown = 0;
  34139. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34140. {
  34141. MouseInputSource* const source = desktop.getMouseSource(i);
  34142. if (source->isDragging())
  34143. {
  34144. source->triggerFakeMove();
  34145. ++numMiceDown;
  34146. }
  34147. }
  34148. if (numMiceDown == 0)
  34149. desktop.beginDragAutoRepeat (0);
  34150. }
  34151. private:
  34152. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34153. };
  34154. void Desktop::beginDragAutoRepeat (const int interval)
  34155. {
  34156. if (interval > 0)
  34157. {
  34158. if (dragRepeater == 0)
  34159. dragRepeater = new MouseDragAutoRepeater();
  34160. if (dragRepeater->getTimerInterval() != interval)
  34161. dragRepeater->startTimer (interval);
  34162. }
  34163. else
  34164. {
  34165. dragRepeater = 0;
  34166. }
  34167. }
  34168. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34169. {
  34170. focusListeners.add (listener);
  34171. }
  34172. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34173. {
  34174. focusListeners.remove (listener);
  34175. }
  34176. void Desktop::triggerFocusCallback()
  34177. {
  34178. triggerAsyncUpdate();
  34179. }
  34180. void Desktop::handleAsyncUpdate()
  34181. {
  34182. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34183. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34184. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34185. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34186. }
  34187. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34188. {
  34189. mouseListeners.add (listener);
  34190. resetTimer();
  34191. }
  34192. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34193. {
  34194. mouseListeners.remove (listener);
  34195. resetTimer();
  34196. }
  34197. void Desktop::timerCallback()
  34198. {
  34199. if (lastFakeMouseMove != getMousePosition())
  34200. sendMouseMove();
  34201. }
  34202. void Desktop::sendMouseMove()
  34203. {
  34204. if (! mouseListeners.isEmpty())
  34205. {
  34206. startTimer (20);
  34207. lastFakeMouseMove = getMousePosition();
  34208. Component* const target = findComponentAt (lastFakeMouseMove);
  34209. if (target != 0)
  34210. {
  34211. Component::BailOutChecker checker (target);
  34212. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34213. const Time now (Time::getCurrentTime());
  34214. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34215. target, target, now, pos, now, 0, false);
  34216. if (me.mods.isAnyMouseButtonDown())
  34217. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34218. else
  34219. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34220. }
  34221. }
  34222. }
  34223. void Desktop::resetTimer()
  34224. {
  34225. if (mouseListeners.size() == 0)
  34226. stopTimer();
  34227. else
  34228. startTimer (100);
  34229. lastFakeMouseMove = getMousePosition();
  34230. }
  34231. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34232. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34233. {
  34234. if (kioskModeComponent != componentToUse)
  34235. {
  34236. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34237. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34238. if (kioskModeComponent != 0)
  34239. {
  34240. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34241. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34242. }
  34243. kioskModeComponent = componentToUse;
  34244. if (kioskModeComponent != 0)
  34245. {
  34246. // Only components that are already on the desktop can be put into kiosk mode!
  34247. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34248. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34249. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34250. }
  34251. }
  34252. }
  34253. void Desktop::setOrientationsEnabled (const int newOrientations)
  34254. {
  34255. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34256. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34257. allowedOrientations = newOrientations;
  34258. }
  34259. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34260. {
  34261. // Make sure you only pass one valid flag in here...
  34262. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34263. return (allowedOrientations & orientation) != 0;
  34264. }
  34265. END_JUCE_NAMESPACE
  34266. /*** End of inlined file: juce_Desktop.cpp ***/
  34267. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34268. BEGIN_JUCE_NAMESPACE
  34269. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34270. {
  34271. public:
  34272. ModalItem (Component* const comp, Callback* const callback)
  34273. : ComponentMovementWatcher (comp),
  34274. component (comp), returnValue (0), isActive (true)
  34275. {
  34276. jassert (comp != 0);
  34277. if (callback != 0)
  34278. callbacks.add (callback);
  34279. }
  34280. void componentMovedOrResized (bool, bool) {}
  34281. void componentPeerChanged()
  34282. {
  34283. if (! component->isShowing())
  34284. cancel();
  34285. }
  34286. void componentVisibilityChanged()
  34287. {
  34288. if (! component->isShowing())
  34289. cancel();
  34290. }
  34291. void componentBeingDeleted (Component& comp)
  34292. {
  34293. ComponentMovementWatcher::componentBeingDeleted (comp);
  34294. if (component == &comp || comp.isParentOf (component))
  34295. cancel();
  34296. }
  34297. void cancel()
  34298. {
  34299. if (isActive)
  34300. {
  34301. isActive = false;
  34302. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34303. }
  34304. }
  34305. Component* component;
  34306. OwnedArray<Callback> callbacks;
  34307. int returnValue;
  34308. bool isActive;
  34309. private:
  34310. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34311. };
  34312. ModalComponentManager::ModalComponentManager()
  34313. {
  34314. }
  34315. ModalComponentManager::~ModalComponentManager()
  34316. {
  34317. clearSingletonInstance();
  34318. }
  34319. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34320. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34321. {
  34322. if (component != 0)
  34323. stack.add (new ModalItem (component, callback));
  34324. }
  34325. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34326. {
  34327. if (callback != 0)
  34328. {
  34329. ScopedPointer<Callback> callbackDeleter (callback);
  34330. for (int i = stack.size(); --i >= 0;)
  34331. {
  34332. ModalItem* const item = stack.getUnchecked(i);
  34333. if (item->component == component)
  34334. {
  34335. item->callbacks.add (callback);
  34336. callbackDeleter.release();
  34337. break;
  34338. }
  34339. }
  34340. }
  34341. }
  34342. void ModalComponentManager::endModal (Component* component)
  34343. {
  34344. for (int i = stack.size(); --i >= 0;)
  34345. {
  34346. ModalItem* const item = stack.getUnchecked(i);
  34347. if (item->component == component)
  34348. item->cancel();
  34349. }
  34350. }
  34351. void ModalComponentManager::endModal (Component* component, int returnValue)
  34352. {
  34353. for (int i = stack.size(); --i >= 0;)
  34354. {
  34355. ModalItem* const item = stack.getUnchecked(i);
  34356. if (item->component == component)
  34357. {
  34358. item->returnValue = returnValue;
  34359. item->cancel();
  34360. }
  34361. }
  34362. }
  34363. int ModalComponentManager::getNumModalComponents() const
  34364. {
  34365. int n = 0;
  34366. for (int i = 0; i < stack.size(); ++i)
  34367. if (stack.getUnchecked(i)->isActive)
  34368. ++n;
  34369. return n;
  34370. }
  34371. Component* ModalComponentManager::getModalComponent (const int index) const
  34372. {
  34373. int n = 0;
  34374. for (int i = stack.size(); --i >= 0;)
  34375. {
  34376. const ModalItem* const item = stack.getUnchecked(i);
  34377. if (item->isActive)
  34378. if (n++ == index)
  34379. return item->component;
  34380. }
  34381. return 0;
  34382. }
  34383. bool ModalComponentManager::isModal (Component* const comp) const
  34384. {
  34385. for (int i = stack.size(); --i >= 0;)
  34386. {
  34387. const ModalItem* const item = stack.getUnchecked(i);
  34388. if (item->isActive && item->component == comp)
  34389. return true;
  34390. }
  34391. return false;
  34392. }
  34393. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34394. {
  34395. return comp == getModalComponent (0);
  34396. }
  34397. void ModalComponentManager::handleAsyncUpdate()
  34398. {
  34399. for (int i = stack.size(); --i >= 0;)
  34400. {
  34401. const ModalItem* const item = stack.getUnchecked(i);
  34402. if (! item->isActive)
  34403. {
  34404. for (int j = item->callbacks.size(); --j >= 0;)
  34405. {
  34406. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34407. if (! stack.contains (item))
  34408. break;
  34409. }
  34410. stack.removeObject (item);
  34411. }
  34412. }
  34413. }
  34414. void ModalComponentManager::bringModalComponentsToFront()
  34415. {
  34416. ComponentPeer* lastOne = 0;
  34417. for (int i = 0; i < getNumModalComponents(); ++i)
  34418. {
  34419. Component* const c = getModalComponent (i);
  34420. if (c == 0)
  34421. break;
  34422. ComponentPeer* peer = c->getPeer();
  34423. if (peer != 0 && peer != lastOne)
  34424. {
  34425. if (lastOne == 0)
  34426. {
  34427. peer->toFront (true);
  34428. peer->grabFocus();
  34429. }
  34430. else
  34431. peer->toBehind (lastOne);
  34432. lastOne = peer;
  34433. }
  34434. }
  34435. }
  34436. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34437. {
  34438. public:
  34439. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34440. ~ReturnValueRetriever() {}
  34441. void modalStateFinished (int returnValue)
  34442. {
  34443. finished = true;
  34444. value = returnValue;
  34445. }
  34446. private:
  34447. int& value;
  34448. bool& finished;
  34449. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34450. };
  34451. int ModalComponentManager::runEventLoopForCurrentComponent()
  34452. {
  34453. // This can only be run from the message thread!
  34454. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34455. Component* currentlyModal = getModalComponent (0);
  34456. if (currentlyModal == 0)
  34457. return 0;
  34458. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34459. int returnValue = 0;
  34460. bool finished = false;
  34461. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34462. JUCE_TRY
  34463. {
  34464. while (! finished)
  34465. {
  34466. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34467. break;
  34468. }
  34469. }
  34470. JUCE_CATCH_EXCEPTION
  34471. if (prevFocused != 0)
  34472. prevFocused->grabKeyboardFocus();
  34473. return returnValue;
  34474. }
  34475. END_JUCE_NAMESPACE
  34476. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34477. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34478. BEGIN_JUCE_NAMESPACE
  34479. ArrowButton::ArrowButton (const String& name,
  34480. float arrowDirectionInRadians,
  34481. const Colour& arrowColour)
  34482. : Button (name),
  34483. colour (arrowColour)
  34484. {
  34485. path.lineTo (0.0f, 1.0f);
  34486. path.lineTo (1.0f, 0.5f);
  34487. path.closeSubPath();
  34488. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34489. 0.5f, 0.5f));
  34490. setComponentEffect (&shadow);
  34491. buttonStateChanged();
  34492. }
  34493. ArrowButton::~ArrowButton()
  34494. {
  34495. }
  34496. void ArrowButton::paintButton (Graphics& g,
  34497. bool /*isMouseOverButton*/,
  34498. bool /*isButtonDown*/)
  34499. {
  34500. g.setColour (colour);
  34501. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34502. (float) offset,
  34503. (float) (getWidth() - 3),
  34504. (float) (getHeight() - 3),
  34505. false));
  34506. }
  34507. void ArrowButton::buttonStateChanged()
  34508. {
  34509. offset = (isDown()) ? 1 : 0;
  34510. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34511. 0.3f, -1, 0);
  34512. }
  34513. END_JUCE_NAMESPACE
  34514. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34515. /*** Start of inlined file: juce_Button.cpp ***/
  34516. BEGIN_JUCE_NAMESPACE
  34517. class Button::RepeatTimer : public Timer
  34518. {
  34519. public:
  34520. RepeatTimer (Button& owner_) : owner (owner_) {}
  34521. void timerCallback() { owner.repeatTimerCallback(); }
  34522. private:
  34523. Button& owner;
  34524. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34525. };
  34526. Button::Button (const String& name)
  34527. : Component (name),
  34528. text (name),
  34529. buttonPressTime (0),
  34530. lastRepeatTime (0),
  34531. commandManagerToUse (0),
  34532. autoRepeatDelay (-1),
  34533. autoRepeatSpeed (0),
  34534. autoRepeatMinimumDelay (-1),
  34535. radioGroupId (0),
  34536. commandID (0),
  34537. connectedEdgeFlags (0),
  34538. buttonState (buttonNormal),
  34539. lastToggleState (false),
  34540. clickTogglesState (false),
  34541. needsToRelease (false),
  34542. needsRepainting (false),
  34543. isKeyDown (false),
  34544. triggerOnMouseDown (false),
  34545. generateTooltip (false)
  34546. {
  34547. setWantsKeyboardFocus (true);
  34548. isOn.addListener (this);
  34549. }
  34550. Button::~Button()
  34551. {
  34552. isOn.removeListener (this);
  34553. if (commandManagerToUse != 0)
  34554. commandManagerToUse->removeListener (this);
  34555. repeatTimer = 0;
  34556. clearShortcuts();
  34557. }
  34558. void Button::setButtonText (const String& newText)
  34559. {
  34560. if (text != newText)
  34561. {
  34562. text = newText;
  34563. repaint();
  34564. }
  34565. }
  34566. void Button::setTooltip (const String& newTooltip)
  34567. {
  34568. SettableTooltipClient::setTooltip (newTooltip);
  34569. generateTooltip = false;
  34570. }
  34571. const String Button::getTooltip()
  34572. {
  34573. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34574. {
  34575. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34576. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34577. for (int i = 0; i < keyPresses.size(); ++i)
  34578. {
  34579. const String key (keyPresses.getReference(i).getTextDescription());
  34580. tt << " [";
  34581. if (key.length() == 1)
  34582. tt << TRANS("shortcut") << ": '" << key << "']";
  34583. else
  34584. tt << key << ']';
  34585. }
  34586. return tt;
  34587. }
  34588. return SettableTooltipClient::getTooltip();
  34589. }
  34590. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34591. {
  34592. if (connectedEdgeFlags != connectedEdgeFlags_)
  34593. {
  34594. connectedEdgeFlags = connectedEdgeFlags_;
  34595. repaint();
  34596. }
  34597. }
  34598. void Button::setToggleState (const bool shouldBeOn,
  34599. const bool sendChangeNotification)
  34600. {
  34601. if (shouldBeOn != lastToggleState)
  34602. {
  34603. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34604. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34605. lastToggleState = shouldBeOn;
  34606. repaint();
  34607. WeakReference<Component> deletionWatcher (this);
  34608. if (sendChangeNotification)
  34609. {
  34610. sendClickMessage (ModifierKeys());
  34611. if (deletionWatcher == 0)
  34612. return;
  34613. }
  34614. if (lastToggleState)
  34615. {
  34616. turnOffOtherButtonsInGroup (sendChangeNotification);
  34617. if (deletionWatcher == 0)
  34618. return;
  34619. }
  34620. sendStateMessage();
  34621. }
  34622. }
  34623. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34624. {
  34625. clickTogglesState = shouldToggle;
  34626. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34627. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34628. // it is that this button represents, and the button will update its state to reflect this
  34629. // in the applicationCommandListChanged() method.
  34630. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34631. }
  34632. bool Button::getClickingTogglesState() const throw()
  34633. {
  34634. return clickTogglesState;
  34635. }
  34636. void Button::valueChanged (Value& value)
  34637. {
  34638. if (value.refersToSameSourceAs (isOn))
  34639. setToggleState (isOn.getValue(), true);
  34640. }
  34641. void Button::setRadioGroupId (const int newGroupId)
  34642. {
  34643. if (radioGroupId != newGroupId)
  34644. {
  34645. radioGroupId = newGroupId;
  34646. if (lastToggleState)
  34647. turnOffOtherButtonsInGroup (true);
  34648. }
  34649. }
  34650. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34651. {
  34652. Component* const p = getParentComponent();
  34653. if (p != 0 && radioGroupId != 0)
  34654. {
  34655. WeakReference<Component> deletionWatcher (this);
  34656. for (int i = p->getNumChildComponents(); --i >= 0;)
  34657. {
  34658. Component* const c = p->getChildComponent (i);
  34659. if (c != this)
  34660. {
  34661. Button* const b = dynamic_cast <Button*> (c);
  34662. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34663. {
  34664. b->setToggleState (false, sendChangeNotification);
  34665. if (deletionWatcher == 0)
  34666. return;
  34667. }
  34668. }
  34669. }
  34670. }
  34671. }
  34672. void Button::enablementChanged()
  34673. {
  34674. updateState();
  34675. repaint();
  34676. }
  34677. Button::ButtonState Button::updateState()
  34678. {
  34679. return updateState (isMouseOver (true), isMouseButtonDown());
  34680. }
  34681. Button::ButtonState Button::updateState (const bool over, const bool down)
  34682. {
  34683. ButtonState newState = buttonNormal;
  34684. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34685. {
  34686. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34687. newState = buttonDown;
  34688. else if (over)
  34689. newState = buttonOver;
  34690. }
  34691. setState (newState);
  34692. return newState;
  34693. }
  34694. void Button::setState (const ButtonState newState)
  34695. {
  34696. if (buttonState != newState)
  34697. {
  34698. buttonState = newState;
  34699. repaint();
  34700. if (buttonState == buttonDown)
  34701. {
  34702. buttonPressTime = Time::getApproximateMillisecondCounter();
  34703. lastRepeatTime = 0;
  34704. }
  34705. sendStateMessage();
  34706. }
  34707. }
  34708. bool Button::isDown() const throw()
  34709. {
  34710. return buttonState == buttonDown;
  34711. }
  34712. bool Button::isOver() const throw()
  34713. {
  34714. return buttonState != buttonNormal;
  34715. }
  34716. void Button::buttonStateChanged()
  34717. {
  34718. }
  34719. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34720. {
  34721. const uint32 now = Time::getApproximateMillisecondCounter();
  34722. return now > buttonPressTime ? now - buttonPressTime : 0;
  34723. }
  34724. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34725. {
  34726. triggerOnMouseDown = isTriggeredOnMouseDown;
  34727. }
  34728. void Button::clicked()
  34729. {
  34730. }
  34731. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34732. {
  34733. clicked();
  34734. }
  34735. static const int clickMessageId = 0x2f3f4f99;
  34736. void Button::triggerClick()
  34737. {
  34738. postCommandMessage (clickMessageId);
  34739. }
  34740. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34741. {
  34742. if (clickTogglesState)
  34743. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34744. sendClickMessage (modifiers);
  34745. }
  34746. void Button::flashButtonState()
  34747. {
  34748. if (isEnabled())
  34749. {
  34750. needsToRelease = true;
  34751. setState (buttonDown);
  34752. getRepeatTimer().startTimer (100);
  34753. }
  34754. }
  34755. void Button::handleCommandMessage (int commandId)
  34756. {
  34757. if (commandId == clickMessageId)
  34758. {
  34759. if (isEnabled())
  34760. {
  34761. flashButtonState();
  34762. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34763. }
  34764. }
  34765. else
  34766. {
  34767. Component::handleCommandMessage (commandId);
  34768. }
  34769. }
  34770. void Button::addListener (ButtonListener* const newListener)
  34771. {
  34772. buttonListeners.add (newListener);
  34773. }
  34774. void Button::removeListener (ButtonListener* const listener)
  34775. {
  34776. buttonListeners.remove (listener);
  34777. }
  34778. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34779. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34780. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34781. {
  34782. Component::BailOutChecker checker (this);
  34783. if (commandManagerToUse != 0 && commandID != 0)
  34784. {
  34785. ApplicationCommandTarget::InvocationInfo info (commandID);
  34786. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34787. info.originatingComponent = this;
  34788. commandManagerToUse->invoke (info, true);
  34789. }
  34790. clicked (modifiers);
  34791. if (! checker.shouldBailOut())
  34792. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34793. }
  34794. void Button::sendStateMessage()
  34795. {
  34796. Component::BailOutChecker checker (this);
  34797. buttonStateChanged();
  34798. if (! checker.shouldBailOut())
  34799. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34800. }
  34801. void Button::paint (Graphics& g)
  34802. {
  34803. if (needsToRelease && isEnabled())
  34804. {
  34805. needsToRelease = false;
  34806. needsRepainting = true;
  34807. }
  34808. paintButton (g, isOver(), isDown());
  34809. }
  34810. void Button::mouseEnter (const MouseEvent&)
  34811. {
  34812. updateState (true, false);
  34813. }
  34814. void Button::mouseExit (const MouseEvent&)
  34815. {
  34816. updateState (false, false);
  34817. }
  34818. void Button::mouseDown (const MouseEvent& e)
  34819. {
  34820. updateState (true, true);
  34821. if (isDown())
  34822. {
  34823. if (autoRepeatDelay >= 0)
  34824. getRepeatTimer().startTimer (autoRepeatDelay);
  34825. if (triggerOnMouseDown)
  34826. internalClickCallback (e.mods);
  34827. }
  34828. }
  34829. void Button::mouseUp (const MouseEvent& e)
  34830. {
  34831. const bool wasDown = isDown();
  34832. updateState (isMouseOver(), false);
  34833. if (wasDown && isOver() && ! triggerOnMouseDown)
  34834. internalClickCallback (e.mods);
  34835. }
  34836. void Button::mouseDrag (const MouseEvent&)
  34837. {
  34838. const ButtonState oldState = buttonState;
  34839. updateState (isMouseOver(), true);
  34840. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34841. getRepeatTimer().startTimer (autoRepeatSpeed);
  34842. }
  34843. void Button::focusGained (FocusChangeType)
  34844. {
  34845. updateState();
  34846. repaint();
  34847. }
  34848. void Button::focusLost (FocusChangeType)
  34849. {
  34850. updateState();
  34851. repaint();
  34852. }
  34853. void Button::visibilityChanged()
  34854. {
  34855. needsToRelease = false;
  34856. updateState();
  34857. }
  34858. void Button::parentHierarchyChanged()
  34859. {
  34860. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34861. if (newKeySource != keySource.get())
  34862. {
  34863. if (keySource != 0)
  34864. keySource->removeKeyListener (this);
  34865. keySource = newKeySource;
  34866. if (keySource != 0)
  34867. keySource->addKeyListener (this);
  34868. }
  34869. }
  34870. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34871. const int commandID_,
  34872. const bool generateTooltip_)
  34873. {
  34874. commandID = commandID_;
  34875. generateTooltip = generateTooltip_;
  34876. if (commandManagerToUse != commandManagerToUse_)
  34877. {
  34878. if (commandManagerToUse != 0)
  34879. commandManagerToUse->removeListener (this);
  34880. commandManagerToUse = commandManagerToUse_;
  34881. if (commandManagerToUse != 0)
  34882. commandManagerToUse->addListener (this);
  34883. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34884. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34885. // it is that this button represents, and the button will update its state to reflect this
  34886. // in the applicationCommandListChanged() method.
  34887. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34888. }
  34889. if (commandManagerToUse != 0)
  34890. applicationCommandListChanged();
  34891. else
  34892. setEnabled (true);
  34893. }
  34894. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34895. {
  34896. if (info.commandID == commandID
  34897. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34898. {
  34899. flashButtonState();
  34900. }
  34901. }
  34902. void Button::applicationCommandListChanged()
  34903. {
  34904. if (commandManagerToUse != 0)
  34905. {
  34906. ApplicationCommandInfo info (0);
  34907. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34908. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34909. if (target != 0)
  34910. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34911. }
  34912. }
  34913. void Button::addShortcut (const KeyPress& key)
  34914. {
  34915. if (key.isValid())
  34916. {
  34917. jassert (! isRegisteredForShortcut (key)); // already registered!
  34918. shortcuts.add (key);
  34919. parentHierarchyChanged();
  34920. }
  34921. }
  34922. void Button::clearShortcuts()
  34923. {
  34924. shortcuts.clear();
  34925. parentHierarchyChanged();
  34926. }
  34927. bool Button::isShortcutPressed() const
  34928. {
  34929. if (! isCurrentlyBlockedByAnotherModalComponent())
  34930. {
  34931. for (int i = shortcuts.size(); --i >= 0;)
  34932. if (shortcuts.getReference(i).isCurrentlyDown())
  34933. return true;
  34934. }
  34935. return false;
  34936. }
  34937. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34938. {
  34939. for (int i = shortcuts.size(); --i >= 0;)
  34940. if (key == shortcuts.getReference(i))
  34941. return true;
  34942. return false;
  34943. }
  34944. bool Button::keyStateChanged (const bool, Component*)
  34945. {
  34946. if (! isEnabled())
  34947. return false;
  34948. const bool wasDown = isKeyDown;
  34949. isKeyDown = isShortcutPressed();
  34950. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34951. getRepeatTimer().startTimer (autoRepeatDelay);
  34952. updateState();
  34953. if (isEnabled() && wasDown && ! isKeyDown)
  34954. {
  34955. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34956. // (return immediately - this button may now have been deleted)
  34957. return true;
  34958. }
  34959. return wasDown || isKeyDown;
  34960. }
  34961. bool Button::keyPressed (const KeyPress&, Component*)
  34962. {
  34963. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34964. return isShortcutPressed();
  34965. }
  34966. bool Button::keyPressed (const KeyPress& key)
  34967. {
  34968. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34969. {
  34970. triggerClick();
  34971. return true;
  34972. }
  34973. return false;
  34974. }
  34975. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34976. const int repeatMillisecs,
  34977. const int minimumDelayInMillisecs) throw()
  34978. {
  34979. autoRepeatDelay = initialDelayMillisecs;
  34980. autoRepeatSpeed = repeatMillisecs;
  34981. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34982. }
  34983. void Button::repeatTimerCallback()
  34984. {
  34985. if (needsRepainting)
  34986. {
  34987. getRepeatTimer().stopTimer();
  34988. updateState();
  34989. needsRepainting = false;
  34990. }
  34991. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  34992. {
  34993. int repeatSpeed = autoRepeatSpeed;
  34994. if (autoRepeatMinimumDelay >= 0)
  34995. {
  34996. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34997. timeHeldDown *= timeHeldDown;
  34998. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34999. }
  35000. repeatSpeed = jmax (1, repeatSpeed);
  35001. const uint32 now = Time::getMillisecondCounter();
  35002. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35003. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35004. repeatSpeed = jmax (1, repeatSpeed / 2);
  35005. lastRepeatTime = now;
  35006. getRepeatTimer().startTimer (repeatSpeed);
  35007. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35008. }
  35009. else if (! needsToRelease)
  35010. {
  35011. getRepeatTimer().stopTimer();
  35012. }
  35013. }
  35014. Button::RepeatTimer& Button::getRepeatTimer()
  35015. {
  35016. if (repeatTimer == 0)
  35017. repeatTimer = new RepeatTimer (*this);
  35018. return *repeatTimer;
  35019. }
  35020. END_JUCE_NAMESPACE
  35021. /*** End of inlined file: juce_Button.cpp ***/
  35022. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35023. BEGIN_JUCE_NAMESPACE
  35024. DrawableButton::DrawableButton (const String& name,
  35025. const DrawableButton::ButtonStyle buttonStyle)
  35026. : Button (name),
  35027. style (buttonStyle),
  35028. currentImage (0),
  35029. edgeIndent (3)
  35030. {
  35031. if (buttonStyle == ImageOnButtonBackground)
  35032. {
  35033. backgroundOff = Colour (0xffbbbbff);
  35034. backgroundOn = Colour (0xff3333ff);
  35035. }
  35036. else
  35037. {
  35038. backgroundOff = Colours::transparentBlack;
  35039. backgroundOn = Colour (0xaabbbbff);
  35040. }
  35041. }
  35042. DrawableButton::~DrawableButton()
  35043. {
  35044. }
  35045. void DrawableButton::setImages (const Drawable* normal,
  35046. const Drawable* over,
  35047. const Drawable* down,
  35048. const Drawable* disabled,
  35049. const Drawable* normalOn,
  35050. const Drawable* overOn,
  35051. const Drawable* downOn,
  35052. const Drawable* disabledOn)
  35053. {
  35054. jassert (normal != 0); // you really need to give it at least a normal image..
  35055. if (normal != 0) normalImage = normal->createCopy();
  35056. if (over != 0) overImage = over->createCopy();
  35057. if (down != 0) downImage = down->createCopy();
  35058. if (disabled != 0) disabledImage = disabled->createCopy();
  35059. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35060. if (overOn != 0) overImageOn = overOn->createCopy();
  35061. if (downOn != 0) downImageOn = downOn->createCopy();
  35062. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35063. buttonStateChanged();
  35064. }
  35065. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35066. {
  35067. if (style != newStyle)
  35068. {
  35069. style = newStyle;
  35070. buttonStateChanged();
  35071. }
  35072. }
  35073. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35074. const Colour& toggledOnColour)
  35075. {
  35076. if (backgroundOff != toggledOffColour
  35077. || backgroundOn != toggledOnColour)
  35078. {
  35079. backgroundOff = toggledOffColour;
  35080. backgroundOn = toggledOnColour;
  35081. repaint();
  35082. }
  35083. }
  35084. const Colour& DrawableButton::getBackgroundColour() const throw()
  35085. {
  35086. return getToggleState() ? backgroundOn
  35087. : backgroundOff;
  35088. }
  35089. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35090. {
  35091. edgeIndent = numPixelsIndent;
  35092. repaint();
  35093. resized();
  35094. }
  35095. void DrawableButton::resized()
  35096. {
  35097. Button::resized();
  35098. if (currentImage != 0)
  35099. {
  35100. if (style == ImageRaw)
  35101. {
  35102. currentImage->setOriginWithOriginalSize (Point<float>());
  35103. }
  35104. else
  35105. {
  35106. Rectangle<int> imageSpace;
  35107. if (style == ImageOnButtonBackground)
  35108. {
  35109. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35110. }
  35111. else
  35112. {
  35113. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35114. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35115. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35116. imageSpace.setBounds (indentX, indentY,
  35117. getWidth() - indentX * 2,
  35118. getHeight() - indentY * 2 - textH);
  35119. }
  35120. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35121. }
  35122. }
  35123. }
  35124. void DrawableButton::buttonStateChanged()
  35125. {
  35126. repaint();
  35127. Drawable* imageToDraw = 0;
  35128. float opacity = 1.0f;
  35129. if (isEnabled())
  35130. {
  35131. imageToDraw = getCurrentImage();
  35132. }
  35133. else
  35134. {
  35135. imageToDraw = getToggleState() ? disabledImageOn
  35136. : disabledImage;
  35137. if (imageToDraw == 0)
  35138. {
  35139. opacity = 0.4f;
  35140. imageToDraw = getNormalImage();
  35141. }
  35142. }
  35143. if (imageToDraw != currentImage)
  35144. {
  35145. removeChildComponent (currentImage);
  35146. currentImage = imageToDraw;
  35147. if (currentImage != 0)
  35148. {
  35149. currentImage->setInterceptsMouseClicks (false, false);
  35150. addAndMakeVisible (currentImage);
  35151. DrawableButton::resized();
  35152. }
  35153. }
  35154. if (currentImage != 0)
  35155. currentImage->setAlpha (opacity);
  35156. }
  35157. void DrawableButton::paintButton (Graphics& g,
  35158. bool isMouseOverButton,
  35159. bool isButtonDown)
  35160. {
  35161. if (style == ImageOnButtonBackground)
  35162. {
  35163. getLookAndFeel().drawButtonBackground (g, *this,
  35164. getBackgroundColour(),
  35165. isMouseOverButton,
  35166. isButtonDown);
  35167. }
  35168. else
  35169. {
  35170. g.fillAll (getBackgroundColour());
  35171. const int textH = (style == ImageAboveTextLabel)
  35172. ? jmin (16, proportionOfHeight (0.25f))
  35173. : 0;
  35174. if (textH > 0)
  35175. {
  35176. g.setFont ((float) textH);
  35177. g.setColour (findColour (DrawableButton::textColourId)
  35178. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35179. g.drawFittedText (getButtonText(),
  35180. 2, getHeight() - textH - 1,
  35181. getWidth() - 4, textH,
  35182. Justification::centred, 1);
  35183. }
  35184. }
  35185. }
  35186. Drawable* DrawableButton::getCurrentImage() const throw()
  35187. {
  35188. if (isDown())
  35189. return getDownImage();
  35190. if (isOver())
  35191. return getOverImage();
  35192. return getNormalImage();
  35193. }
  35194. Drawable* DrawableButton::getNormalImage() const throw()
  35195. {
  35196. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35197. : normalImage;
  35198. }
  35199. Drawable* DrawableButton::getOverImage() const throw()
  35200. {
  35201. Drawable* d = normalImage;
  35202. if (getToggleState())
  35203. {
  35204. if (overImageOn != 0)
  35205. d = overImageOn;
  35206. else if (normalImageOn != 0)
  35207. d = normalImageOn;
  35208. else if (overImage != 0)
  35209. d = overImage;
  35210. }
  35211. else
  35212. {
  35213. if (overImage != 0)
  35214. d = overImage;
  35215. }
  35216. return d;
  35217. }
  35218. Drawable* DrawableButton::getDownImage() const throw()
  35219. {
  35220. Drawable* d = normalImage;
  35221. if (getToggleState())
  35222. {
  35223. if (downImageOn != 0)
  35224. d = downImageOn;
  35225. else if (overImageOn != 0)
  35226. d = overImageOn;
  35227. else if (normalImageOn != 0)
  35228. d = normalImageOn;
  35229. else if (downImage != 0)
  35230. d = downImage;
  35231. else
  35232. d = getOverImage();
  35233. }
  35234. else
  35235. {
  35236. if (downImage != 0)
  35237. d = downImage;
  35238. else
  35239. d = getOverImage();
  35240. }
  35241. return d;
  35242. }
  35243. END_JUCE_NAMESPACE
  35244. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35245. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35246. BEGIN_JUCE_NAMESPACE
  35247. HyperlinkButton::HyperlinkButton (const String& linkText,
  35248. const URL& linkURL)
  35249. : Button (linkText),
  35250. url (linkURL),
  35251. font (14.0f, Font::underlined),
  35252. resizeFont (true),
  35253. justification (Justification::centred)
  35254. {
  35255. setMouseCursor (MouseCursor::PointingHandCursor);
  35256. setTooltip (linkURL.toString (false));
  35257. }
  35258. HyperlinkButton::~HyperlinkButton()
  35259. {
  35260. }
  35261. void HyperlinkButton::setFont (const Font& newFont,
  35262. const bool resizeToMatchComponentHeight,
  35263. const Justification& justificationType)
  35264. {
  35265. font = newFont;
  35266. resizeFont = resizeToMatchComponentHeight;
  35267. justification = justificationType;
  35268. repaint();
  35269. }
  35270. void HyperlinkButton::setURL (const URL& newURL) throw()
  35271. {
  35272. url = newURL;
  35273. setTooltip (newURL.toString (false));
  35274. }
  35275. const Font HyperlinkButton::getFontToUse() const
  35276. {
  35277. Font f (font);
  35278. if (resizeFont)
  35279. f.setHeight (getHeight() * 0.7f);
  35280. return f;
  35281. }
  35282. void HyperlinkButton::changeWidthToFitText()
  35283. {
  35284. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35285. }
  35286. void HyperlinkButton::colourChanged()
  35287. {
  35288. repaint();
  35289. }
  35290. void HyperlinkButton::clicked()
  35291. {
  35292. if (url.isWellFormed())
  35293. url.launchInDefaultBrowser();
  35294. }
  35295. void HyperlinkButton::paintButton (Graphics& g,
  35296. bool isMouseOverButton,
  35297. bool isButtonDown)
  35298. {
  35299. const Colour textColour (findColour (textColourId));
  35300. if (isEnabled())
  35301. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35302. : textColour);
  35303. else
  35304. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35305. g.setFont (getFontToUse());
  35306. g.drawText (getButtonText(),
  35307. 2, 0, getWidth() - 2, getHeight(),
  35308. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35309. true);
  35310. }
  35311. END_JUCE_NAMESPACE
  35312. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35313. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35314. BEGIN_JUCE_NAMESPACE
  35315. ImageButton::ImageButton (const String& text_)
  35316. : Button (text_),
  35317. scaleImageToFit (true),
  35318. preserveProportions (true),
  35319. alphaThreshold (0),
  35320. imageX (0),
  35321. imageY (0),
  35322. imageW (0),
  35323. imageH (0),
  35324. normalImage (0),
  35325. overImage (0),
  35326. downImage (0)
  35327. {
  35328. }
  35329. ImageButton::~ImageButton()
  35330. {
  35331. }
  35332. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35333. const bool rescaleImagesWhenButtonSizeChanges,
  35334. const bool preserveImageProportions,
  35335. const Image& normalImage_,
  35336. const float imageOpacityWhenNormal,
  35337. const Colour& overlayColourWhenNormal,
  35338. const Image& overImage_,
  35339. const float imageOpacityWhenOver,
  35340. const Colour& overlayColourWhenOver,
  35341. const Image& downImage_,
  35342. const float imageOpacityWhenDown,
  35343. const Colour& overlayColourWhenDown,
  35344. const float hitTestAlphaThreshold)
  35345. {
  35346. normalImage = normalImage_;
  35347. overImage = overImage_;
  35348. downImage = downImage_;
  35349. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35350. {
  35351. imageW = normalImage.getWidth();
  35352. imageH = normalImage.getHeight();
  35353. setSize (imageW, imageH);
  35354. }
  35355. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35356. preserveProportions = preserveImageProportions;
  35357. normalOpacity = imageOpacityWhenNormal;
  35358. normalOverlay = overlayColourWhenNormal;
  35359. overOpacity = imageOpacityWhenOver;
  35360. overOverlay = overlayColourWhenOver;
  35361. downOpacity = imageOpacityWhenDown;
  35362. downOverlay = overlayColourWhenDown;
  35363. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35364. repaint();
  35365. }
  35366. const Image ImageButton::getCurrentImage() const
  35367. {
  35368. if (isDown() || getToggleState())
  35369. return getDownImage();
  35370. if (isOver())
  35371. return getOverImage();
  35372. return getNormalImage();
  35373. }
  35374. const Image ImageButton::getNormalImage() const
  35375. {
  35376. return normalImage;
  35377. }
  35378. const Image ImageButton::getOverImage() const
  35379. {
  35380. return overImage.isValid() ? overImage
  35381. : normalImage;
  35382. }
  35383. const Image ImageButton::getDownImage() const
  35384. {
  35385. return downImage.isValid() ? downImage
  35386. : getOverImage();
  35387. }
  35388. void ImageButton::paintButton (Graphics& g,
  35389. bool isMouseOverButton,
  35390. bool isButtonDown)
  35391. {
  35392. if (! isEnabled())
  35393. {
  35394. isMouseOverButton = false;
  35395. isButtonDown = false;
  35396. }
  35397. Image im (getCurrentImage());
  35398. if (im.isValid())
  35399. {
  35400. const int iw = im.getWidth();
  35401. const int ih = im.getHeight();
  35402. imageW = getWidth();
  35403. imageH = getHeight();
  35404. imageX = (imageW - iw) >> 1;
  35405. imageY = (imageH - ih) >> 1;
  35406. if (scaleImageToFit)
  35407. {
  35408. if (preserveProportions)
  35409. {
  35410. int newW, newH;
  35411. const float imRatio = ih / (float)iw;
  35412. const float destRatio = imageH / (float)imageW;
  35413. if (imRatio > destRatio)
  35414. {
  35415. newW = roundToInt (imageH / imRatio);
  35416. newH = imageH;
  35417. }
  35418. else
  35419. {
  35420. newW = imageW;
  35421. newH = roundToInt (imageW * imRatio);
  35422. }
  35423. imageX = (imageW - newW) / 2;
  35424. imageY = (imageH - newH) / 2;
  35425. imageW = newW;
  35426. imageH = newH;
  35427. }
  35428. else
  35429. {
  35430. imageX = 0;
  35431. imageY = 0;
  35432. }
  35433. }
  35434. if (! scaleImageToFit)
  35435. {
  35436. imageW = iw;
  35437. imageH = ih;
  35438. }
  35439. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35440. isButtonDown ? downOverlay
  35441. : (isMouseOverButton ? overOverlay
  35442. : normalOverlay),
  35443. isButtonDown ? downOpacity
  35444. : (isMouseOverButton ? overOpacity
  35445. : normalOpacity),
  35446. *this);
  35447. }
  35448. }
  35449. bool ImageButton::hitTest (int x, int y)
  35450. {
  35451. if (alphaThreshold == 0)
  35452. return true;
  35453. Image im (getCurrentImage());
  35454. return im.isNull() || (imageW > 0 && imageH > 0
  35455. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35456. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35457. }
  35458. END_JUCE_NAMESPACE
  35459. /*** End of inlined file: juce_ImageButton.cpp ***/
  35460. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35461. BEGIN_JUCE_NAMESPACE
  35462. ShapeButton::ShapeButton (const String& text_,
  35463. const Colour& normalColour_,
  35464. const Colour& overColour_,
  35465. const Colour& downColour_)
  35466. : Button (text_),
  35467. normalColour (normalColour_),
  35468. overColour (overColour_),
  35469. downColour (downColour_),
  35470. maintainShapeProportions (false),
  35471. outlineWidth (0.0f)
  35472. {
  35473. }
  35474. ShapeButton::~ShapeButton()
  35475. {
  35476. }
  35477. void ShapeButton::setColours (const Colour& newNormalColour,
  35478. const Colour& newOverColour,
  35479. const Colour& newDownColour)
  35480. {
  35481. normalColour = newNormalColour;
  35482. overColour = newOverColour;
  35483. downColour = newDownColour;
  35484. }
  35485. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35486. const float newOutlineWidth)
  35487. {
  35488. outlineColour = newOutlineColour;
  35489. outlineWidth = newOutlineWidth;
  35490. }
  35491. void ShapeButton::setShape (const Path& newShape,
  35492. const bool resizeNowToFitThisShape,
  35493. const bool maintainShapeProportions_,
  35494. const bool hasShadow)
  35495. {
  35496. shape = newShape;
  35497. maintainShapeProportions = maintainShapeProportions_;
  35498. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35499. setComponentEffect ((hasShadow) ? &shadow : 0);
  35500. if (resizeNowToFitThisShape)
  35501. {
  35502. Rectangle<float> bounds (shape.getBounds());
  35503. if (hasShadow)
  35504. bounds.expand (4.0f, 4.0f);
  35505. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35506. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35507. 1 + (int) (bounds.getHeight() + outlineWidth));
  35508. }
  35509. }
  35510. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35511. {
  35512. if (! isEnabled())
  35513. {
  35514. isMouseOverButton = false;
  35515. isButtonDown = false;
  35516. }
  35517. g.setColour ((isButtonDown) ? downColour
  35518. : (isMouseOverButton) ? overColour
  35519. : normalColour);
  35520. int w = getWidth();
  35521. int h = getHeight();
  35522. if (getComponentEffect() != 0)
  35523. {
  35524. w -= 4;
  35525. h -= 4;
  35526. }
  35527. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35528. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35529. w - offset - outlineWidth,
  35530. h - offset - outlineWidth,
  35531. maintainShapeProportions));
  35532. g.fillPath (shape, trans);
  35533. if (outlineWidth > 0.0f)
  35534. {
  35535. g.setColour (outlineColour);
  35536. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35537. }
  35538. }
  35539. END_JUCE_NAMESPACE
  35540. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35541. /*** Start of inlined file: juce_TextButton.cpp ***/
  35542. BEGIN_JUCE_NAMESPACE
  35543. TextButton::TextButton (const String& name,
  35544. const String& toolTip)
  35545. : Button (name)
  35546. {
  35547. setTooltip (toolTip);
  35548. }
  35549. TextButton::~TextButton()
  35550. {
  35551. }
  35552. void TextButton::paintButton (Graphics& g,
  35553. bool isMouseOverButton,
  35554. bool isButtonDown)
  35555. {
  35556. getLookAndFeel().drawButtonBackground (g, *this,
  35557. findColour (getToggleState() ? buttonOnColourId
  35558. : buttonColourId),
  35559. isMouseOverButton,
  35560. isButtonDown);
  35561. getLookAndFeel().drawButtonText (g, *this,
  35562. isMouseOverButton,
  35563. isButtonDown);
  35564. }
  35565. void TextButton::colourChanged()
  35566. {
  35567. repaint();
  35568. }
  35569. const Font TextButton::getFont()
  35570. {
  35571. return Font (jmin (15.0f, getHeight() * 0.6f));
  35572. }
  35573. void TextButton::changeWidthToFitText (const int newHeight)
  35574. {
  35575. if (newHeight >= 0)
  35576. setSize (jmax (1, getWidth()), newHeight);
  35577. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35578. getHeight());
  35579. }
  35580. END_JUCE_NAMESPACE
  35581. /*** End of inlined file: juce_TextButton.cpp ***/
  35582. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35583. BEGIN_JUCE_NAMESPACE
  35584. ToggleButton::ToggleButton (const String& buttonText)
  35585. : Button (buttonText)
  35586. {
  35587. setClickingTogglesState (true);
  35588. }
  35589. ToggleButton::~ToggleButton()
  35590. {
  35591. }
  35592. void ToggleButton::paintButton (Graphics& g,
  35593. bool isMouseOverButton,
  35594. bool isButtonDown)
  35595. {
  35596. getLookAndFeel().drawToggleButton (g, *this,
  35597. isMouseOverButton,
  35598. isButtonDown);
  35599. }
  35600. void ToggleButton::changeWidthToFitText()
  35601. {
  35602. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35603. }
  35604. void ToggleButton::colourChanged()
  35605. {
  35606. repaint();
  35607. }
  35608. END_JUCE_NAMESPACE
  35609. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35610. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35611. BEGIN_JUCE_NAMESPACE
  35612. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35613. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35614. : ToolbarItemComponent (itemId_, buttonText, true),
  35615. normalImage (normalImage_),
  35616. toggledOnImage (toggledOnImage_),
  35617. currentImage (0)
  35618. {
  35619. jassert (normalImage_ != 0);
  35620. }
  35621. ToolbarButton::~ToolbarButton()
  35622. {
  35623. }
  35624. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35625. {
  35626. preferredSize = minSize = maxSize = toolbarDepth;
  35627. return true;
  35628. }
  35629. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35630. {
  35631. }
  35632. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35633. {
  35634. buttonStateChanged();
  35635. }
  35636. void ToolbarButton::updateDrawable()
  35637. {
  35638. if (currentImage != 0)
  35639. {
  35640. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35641. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35642. }
  35643. }
  35644. void ToolbarButton::resized()
  35645. {
  35646. ToolbarItemComponent::resized();
  35647. updateDrawable();
  35648. }
  35649. void ToolbarButton::enablementChanged()
  35650. {
  35651. ToolbarItemComponent::enablementChanged();
  35652. updateDrawable();
  35653. }
  35654. void ToolbarButton::buttonStateChanged()
  35655. {
  35656. Drawable* d = normalImage;
  35657. if (getToggleState() && toggledOnImage != 0)
  35658. d = toggledOnImage;
  35659. if (d != currentImage)
  35660. {
  35661. removeChildComponent (currentImage);
  35662. currentImage = d;
  35663. if (d != 0)
  35664. {
  35665. enablementChanged();
  35666. addAndMakeVisible (d);
  35667. updateDrawable();
  35668. }
  35669. }
  35670. }
  35671. END_JUCE_NAMESPACE
  35672. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35673. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35674. BEGIN_JUCE_NAMESPACE
  35675. class CodeDocumentLine
  35676. {
  35677. public:
  35678. CodeDocumentLine (const String::CharPointerType& line_,
  35679. const int lineLength_,
  35680. const int numNewLineChars,
  35681. const int lineStartInFile_)
  35682. : line (line_, lineLength_),
  35683. lineStartInFile (lineStartInFile_),
  35684. lineLength (lineLength_),
  35685. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35686. {
  35687. }
  35688. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35689. {
  35690. String::CharPointerType t (text.getCharPointer());
  35691. int charNumInFile = 0;
  35692. bool finished = t.isEmpty();
  35693. while (! finished)
  35694. {
  35695. String::CharPointerType startOfLine (t);
  35696. int startOfLineInFile = charNumInFile;
  35697. int lineLength = 0;
  35698. int numNewLineChars = 0;
  35699. for (;;)
  35700. {
  35701. const juce_wchar c = t.getAndAdvance();
  35702. if (c == 0)
  35703. {
  35704. finished = true;
  35705. break;
  35706. }
  35707. ++charNumInFile;
  35708. ++lineLength;
  35709. if (c == '\r')
  35710. {
  35711. ++numNewLineChars;
  35712. if (*t == '\n')
  35713. {
  35714. ++t;
  35715. ++charNumInFile;
  35716. ++lineLength;
  35717. ++numNewLineChars;
  35718. }
  35719. break;
  35720. }
  35721. if (c == '\n')
  35722. {
  35723. ++numNewLineChars;
  35724. break;
  35725. }
  35726. }
  35727. newLines.add (new CodeDocumentLine (startOfLine, lineLength,
  35728. numNewLineChars, startOfLineInFile));
  35729. }
  35730. jassert (charNumInFile == text.length());
  35731. }
  35732. bool endsWithLineBreak() const throw()
  35733. {
  35734. return lineLengthWithoutNewLines != lineLength;
  35735. }
  35736. void updateLength() throw()
  35737. {
  35738. lineLengthWithoutNewLines = lineLength = line.length();
  35739. while (lineLengthWithoutNewLines > 0
  35740. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35741. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35742. {
  35743. --lineLengthWithoutNewLines;
  35744. }
  35745. }
  35746. String line;
  35747. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35748. };
  35749. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35750. : document (document_),
  35751. currentLine (document_->lines[0]),
  35752. line (0),
  35753. position (0)
  35754. {
  35755. }
  35756. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35757. : document (other.document),
  35758. currentLine (other.currentLine),
  35759. line (other.line),
  35760. position (other.position)
  35761. {
  35762. }
  35763. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35764. {
  35765. document = other.document;
  35766. currentLine = other.currentLine;
  35767. line = other.line;
  35768. position = other.position;
  35769. return *this;
  35770. }
  35771. CodeDocument::Iterator::~Iterator() throw()
  35772. {
  35773. }
  35774. juce_wchar CodeDocument::Iterator::nextChar()
  35775. {
  35776. if (currentLine == 0)
  35777. return 0;
  35778. jassert (currentLine == document->lines.getUnchecked (line));
  35779. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35780. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35781. {
  35782. ++line;
  35783. currentLine = document->lines [line];
  35784. }
  35785. return result;
  35786. }
  35787. void CodeDocument::Iterator::skip()
  35788. {
  35789. if (currentLine != 0)
  35790. {
  35791. jassert (currentLine == document->lines.getUnchecked (line));
  35792. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35793. {
  35794. ++line;
  35795. currentLine = document->lines [line];
  35796. }
  35797. }
  35798. }
  35799. void CodeDocument::Iterator::skipToEndOfLine()
  35800. {
  35801. if (currentLine != 0)
  35802. {
  35803. jassert (currentLine == document->lines.getUnchecked (line));
  35804. ++line;
  35805. currentLine = document->lines [line];
  35806. if (currentLine != 0)
  35807. position = currentLine->lineStartInFile;
  35808. else
  35809. position = document->getNumCharacters();
  35810. }
  35811. }
  35812. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35813. {
  35814. if (currentLine == 0)
  35815. return 0;
  35816. jassert (currentLine == document->lines.getUnchecked (line));
  35817. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35818. }
  35819. void CodeDocument::Iterator::skipWhitespace()
  35820. {
  35821. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35822. skip();
  35823. }
  35824. bool CodeDocument::Iterator::isEOF() const throw()
  35825. {
  35826. return currentLine == 0;
  35827. }
  35828. CodeDocument::Position::Position() throw()
  35829. : owner (0), characterPos (0), line (0),
  35830. indexInLine (0), positionMaintained (false)
  35831. {
  35832. }
  35833. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35834. const int line_, const int indexInLine_) throw()
  35835. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35836. characterPos (0), line (line_),
  35837. indexInLine (indexInLine_), positionMaintained (false)
  35838. {
  35839. setLineAndIndex (line_, indexInLine_);
  35840. }
  35841. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35842. const int characterPos_) throw()
  35843. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35844. positionMaintained (false)
  35845. {
  35846. setPosition (characterPos_);
  35847. }
  35848. CodeDocument::Position::Position (const Position& other) throw()
  35849. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35850. indexInLine (other.indexInLine), positionMaintained (false)
  35851. {
  35852. jassert (*this == other);
  35853. }
  35854. CodeDocument::Position::~Position()
  35855. {
  35856. setPositionMaintained (false);
  35857. }
  35858. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  35859. {
  35860. if (this != &other)
  35861. {
  35862. const bool wasPositionMaintained = positionMaintained;
  35863. if (owner != other.owner)
  35864. setPositionMaintained (false);
  35865. owner = other.owner;
  35866. line = other.line;
  35867. indexInLine = other.indexInLine;
  35868. characterPos = other.characterPos;
  35869. setPositionMaintained (wasPositionMaintained);
  35870. jassert (*this == other);
  35871. }
  35872. return *this;
  35873. }
  35874. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35875. {
  35876. jassert ((characterPos == other.characterPos)
  35877. == (line == other.line && indexInLine == other.indexInLine));
  35878. return characterPos == other.characterPos
  35879. && line == other.line
  35880. && indexInLine == other.indexInLine
  35881. && owner == other.owner;
  35882. }
  35883. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35884. {
  35885. return ! operator== (other);
  35886. }
  35887. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  35888. {
  35889. jassert (owner != 0);
  35890. if (owner->lines.size() == 0)
  35891. {
  35892. line = 0;
  35893. indexInLine = 0;
  35894. characterPos = 0;
  35895. }
  35896. else
  35897. {
  35898. if (newLineNum >= owner->lines.size())
  35899. {
  35900. line = owner->lines.size() - 1;
  35901. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35902. jassert (l != 0);
  35903. indexInLine = l->lineLengthWithoutNewLines;
  35904. characterPos = l->lineStartInFile + indexInLine;
  35905. }
  35906. else
  35907. {
  35908. line = jmax (0, newLineNum);
  35909. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35910. jassert (l != 0);
  35911. if (l->lineLengthWithoutNewLines > 0)
  35912. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35913. else
  35914. indexInLine = 0;
  35915. characterPos = l->lineStartInFile + indexInLine;
  35916. }
  35917. }
  35918. }
  35919. void CodeDocument::Position::setPosition (const int newPosition)
  35920. {
  35921. jassert (owner != 0);
  35922. line = 0;
  35923. indexInLine = 0;
  35924. characterPos = 0;
  35925. if (newPosition > 0)
  35926. {
  35927. int lineStart = 0;
  35928. int lineEnd = owner->lines.size();
  35929. for (;;)
  35930. {
  35931. if (lineEnd - lineStart < 4)
  35932. {
  35933. for (int i = lineStart; i < lineEnd; ++i)
  35934. {
  35935. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35936. int index = newPosition - l->lineStartInFile;
  35937. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35938. {
  35939. line = i;
  35940. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35941. characterPos = l->lineStartInFile + indexInLine;
  35942. }
  35943. }
  35944. break;
  35945. }
  35946. else
  35947. {
  35948. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35949. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35950. if (newPosition >= mid->lineStartInFile)
  35951. lineStart = midIndex;
  35952. else
  35953. lineEnd = midIndex;
  35954. }
  35955. }
  35956. }
  35957. }
  35958. void CodeDocument::Position::moveBy (int characterDelta)
  35959. {
  35960. jassert (owner != 0);
  35961. if (characterDelta == 1)
  35962. {
  35963. setPosition (getPosition());
  35964. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35965. if (line < owner->lines.size())
  35966. {
  35967. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35968. if (indexInLine + characterDelta < l->lineLength
  35969. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35970. ++characterDelta;
  35971. }
  35972. }
  35973. setPosition (characterPos + characterDelta);
  35974. }
  35975. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  35976. {
  35977. CodeDocument::Position p (*this);
  35978. p.moveBy (characterDelta);
  35979. return p;
  35980. }
  35981. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  35982. {
  35983. CodeDocument::Position p (*this);
  35984. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35985. return p;
  35986. }
  35987. const juce_wchar CodeDocument::Position::getCharacter() const
  35988. {
  35989. const CodeDocumentLine* const l = owner->lines [line];
  35990. return l == 0 ? 0 : l->line [getIndexInLine()];
  35991. }
  35992. const String CodeDocument::Position::getLineText() const
  35993. {
  35994. const CodeDocumentLine* const l = owner->lines [line];
  35995. return l == 0 ? String::empty : l->line;
  35996. }
  35997. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  35998. {
  35999. if (isMaintained != positionMaintained)
  36000. {
  36001. positionMaintained = isMaintained;
  36002. if (owner != 0)
  36003. {
  36004. if (isMaintained)
  36005. {
  36006. jassert (! owner->positionsToMaintain.contains (this));
  36007. owner->positionsToMaintain.add (this);
  36008. }
  36009. else
  36010. {
  36011. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36012. jassert (owner->positionsToMaintain.contains (this));
  36013. owner->positionsToMaintain.removeValue (this);
  36014. }
  36015. }
  36016. }
  36017. }
  36018. CodeDocument::CodeDocument()
  36019. : undoManager (std::numeric_limits<int>::max(), 10000),
  36020. currentActionIndex (0),
  36021. indexOfSavedState (-1),
  36022. maximumLineLength (-1),
  36023. newLineChars ("\r\n")
  36024. {
  36025. }
  36026. CodeDocument::~CodeDocument()
  36027. {
  36028. }
  36029. const String CodeDocument::getAllContent() const
  36030. {
  36031. return getTextBetween (Position (this, 0),
  36032. Position (this, lines.size(), 0));
  36033. }
  36034. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36035. {
  36036. if (end.getPosition() <= start.getPosition())
  36037. return String::empty;
  36038. const int startLine = start.getLineNumber();
  36039. const int endLine = end.getLineNumber();
  36040. if (startLine == endLine)
  36041. {
  36042. CodeDocumentLine* const line = lines [startLine];
  36043. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36044. }
  36045. String result;
  36046. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36047. String::Concatenator concatenator (result);
  36048. const int maxLine = jmin (lines.size() - 1, endLine);
  36049. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36050. {
  36051. const CodeDocumentLine* line = lines.getUnchecked(i);
  36052. int len = line->lineLength;
  36053. if (i == startLine)
  36054. {
  36055. const int index = start.getIndexInLine();
  36056. concatenator.append (line->line.substring (index, len));
  36057. }
  36058. else if (i == endLine)
  36059. {
  36060. len = end.getIndexInLine();
  36061. concatenator.append (line->line.substring (0, len));
  36062. }
  36063. else
  36064. {
  36065. concatenator.append (line->line);
  36066. }
  36067. }
  36068. return result;
  36069. }
  36070. int CodeDocument::getNumCharacters() const throw()
  36071. {
  36072. const CodeDocumentLine* const lastLine = lines.getLast();
  36073. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36074. }
  36075. const String CodeDocument::getLine (const int lineIndex) const throw()
  36076. {
  36077. const CodeDocumentLine* const line = lines [lineIndex];
  36078. return (line == 0) ? String::empty : line->line;
  36079. }
  36080. int CodeDocument::getMaximumLineLength() throw()
  36081. {
  36082. if (maximumLineLength < 0)
  36083. {
  36084. maximumLineLength = 0;
  36085. for (int i = lines.size(); --i >= 0;)
  36086. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36087. }
  36088. return maximumLineLength;
  36089. }
  36090. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36091. {
  36092. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36093. }
  36094. void CodeDocument::insertText (const Position& position, const String& text)
  36095. {
  36096. insert (text, position.getPosition(), true);
  36097. }
  36098. void CodeDocument::replaceAllContent (const String& newContent)
  36099. {
  36100. remove (0, getNumCharacters(), true);
  36101. insert (newContent, 0, true);
  36102. }
  36103. bool CodeDocument::loadFromStream (InputStream& stream)
  36104. {
  36105. replaceAllContent (stream.readEntireStreamAsString());
  36106. setSavePoint();
  36107. clearUndoHistory();
  36108. return true;
  36109. }
  36110. bool CodeDocument::writeToStream (OutputStream& stream)
  36111. {
  36112. for (int i = 0; i < lines.size(); ++i)
  36113. {
  36114. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36115. const char* utf8 = temp.toUTF8();
  36116. if (! stream.write (utf8, (int) strlen (utf8)))
  36117. return false;
  36118. }
  36119. return true;
  36120. }
  36121. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36122. {
  36123. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36124. newLineChars = newLineChars_;
  36125. }
  36126. void CodeDocument::newTransaction()
  36127. {
  36128. undoManager.beginNewTransaction (String::empty);
  36129. }
  36130. void CodeDocument::undo()
  36131. {
  36132. newTransaction();
  36133. undoManager.undo();
  36134. }
  36135. void CodeDocument::redo()
  36136. {
  36137. undoManager.redo();
  36138. }
  36139. void CodeDocument::clearUndoHistory()
  36140. {
  36141. undoManager.clearUndoHistory();
  36142. }
  36143. void CodeDocument::setSavePoint() throw()
  36144. {
  36145. indexOfSavedState = currentActionIndex;
  36146. }
  36147. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36148. {
  36149. return currentActionIndex != indexOfSavedState;
  36150. }
  36151. namespace CodeDocumentHelpers
  36152. {
  36153. int getCharacterType (const juce_wchar character) throw()
  36154. {
  36155. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36156. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36157. }
  36158. }
  36159. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36160. {
  36161. Position p (position);
  36162. const int maxDistance = 256;
  36163. int i = 0;
  36164. while (i < maxDistance
  36165. && CharacterFunctions::isWhitespace (p.getCharacter())
  36166. && (i == 0 || (p.getCharacter() != '\n'
  36167. && p.getCharacter() != '\r')))
  36168. {
  36169. ++i;
  36170. p.moveBy (1);
  36171. }
  36172. if (i == 0)
  36173. {
  36174. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36175. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36176. {
  36177. ++i;
  36178. p.moveBy (1);
  36179. }
  36180. while (i < maxDistance
  36181. && CharacterFunctions::isWhitespace (p.getCharacter())
  36182. && (i == 0 || (p.getCharacter() != '\n'
  36183. && p.getCharacter() != '\r')))
  36184. {
  36185. ++i;
  36186. p.moveBy (1);
  36187. }
  36188. }
  36189. return p;
  36190. }
  36191. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36192. {
  36193. Position p (position);
  36194. const int maxDistance = 256;
  36195. int i = 0;
  36196. bool stoppedAtLineStart = false;
  36197. while (i < maxDistance)
  36198. {
  36199. const juce_wchar c = p.movedBy (-1).getCharacter();
  36200. if (c == '\r' || c == '\n')
  36201. {
  36202. stoppedAtLineStart = true;
  36203. if (i > 0)
  36204. break;
  36205. }
  36206. if (! CharacterFunctions::isWhitespace (c))
  36207. break;
  36208. p.moveBy (-1);
  36209. ++i;
  36210. }
  36211. if (i < maxDistance && ! stoppedAtLineStart)
  36212. {
  36213. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36214. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36215. {
  36216. p.moveBy (-1);
  36217. ++i;
  36218. }
  36219. }
  36220. return p;
  36221. }
  36222. void CodeDocument::checkLastLineStatus()
  36223. {
  36224. while (lines.size() > 0
  36225. && lines.getLast()->lineLength == 0
  36226. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36227. {
  36228. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36229. lines.removeLast();
  36230. }
  36231. const CodeDocumentLine* const lastLine = lines.getLast();
  36232. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36233. {
  36234. // check that there's an empty line at the end if the preceding one ends in a newline..
  36235. lines.add (new CodeDocumentLine (String::empty.getCharPointer(), 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36236. }
  36237. }
  36238. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36239. {
  36240. listeners.add (listener);
  36241. }
  36242. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36243. {
  36244. listeners.remove (listener);
  36245. }
  36246. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36247. {
  36248. Position startPos (this, startLine, 0);
  36249. Position endPos (this, endLine, 0);
  36250. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36251. }
  36252. class CodeDocumentInsertAction : public UndoableAction
  36253. {
  36254. public:
  36255. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36256. : owner (owner_),
  36257. text (text_),
  36258. insertPos (insertPos_)
  36259. {
  36260. }
  36261. bool perform()
  36262. {
  36263. owner.currentActionIndex++;
  36264. owner.insert (text, insertPos, false);
  36265. return true;
  36266. }
  36267. bool undo()
  36268. {
  36269. owner.currentActionIndex--;
  36270. owner.remove (insertPos, insertPos + text.length(), false);
  36271. return true;
  36272. }
  36273. int getSizeInUnits() { return text.length() + 32; }
  36274. private:
  36275. CodeDocument& owner;
  36276. const String text;
  36277. int insertPos;
  36278. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36279. };
  36280. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36281. {
  36282. if (text.isEmpty())
  36283. return;
  36284. if (undoable)
  36285. {
  36286. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36287. }
  36288. else
  36289. {
  36290. Position pos (this, insertPos);
  36291. const int firstAffectedLine = pos.getLineNumber();
  36292. int lastAffectedLine = firstAffectedLine + 1;
  36293. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36294. String textInsideOriginalLine (text);
  36295. if (firstLine != 0)
  36296. {
  36297. const int index = pos.getIndexInLine();
  36298. textInsideOriginalLine = firstLine->line.substring (0, index)
  36299. + textInsideOriginalLine
  36300. + firstLine->line.substring (index);
  36301. }
  36302. maximumLineLength = -1;
  36303. Array <CodeDocumentLine*> newLines;
  36304. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36305. jassert (newLines.size() > 0);
  36306. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36307. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36308. lines.set (firstAffectedLine, newFirstLine);
  36309. if (newLines.size() > 1)
  36310. {
  36311. for (int i = 1; i < newLines.size(); ++i)
  36312. {
  36313. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36314. lines.insert (firstAffectedLine + i, l);
  36315. }
  36316. lastAffectedLine = lines.size();
  36317. }
  36318. int i, lineStart = newFirstLine->lineStartInFile;
  36319. for (i = firstAffectedLine; i < lines.size(); ++i)
  36320. {
  36321. CodeDocumentLine* const l = lines.getUnchecked (i);
  36322. l->lineStartInFile = lineStart;
  36323. lineStart += l->lineLength;
  36324. }
  36325. checkLastLineStatus();
  36326. const int newTextLength = text.length();
  36327. for (i = 0; i < positionsToMaintain.size(); ++i)
  36328. {
  36329. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36330. if (p->getPosition() >= insertPos)
  36331. p->setPosition (p->getPosition() + newTextLength);
  36332. }
  36333. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36334. }
  36335. }
  36336. class CodeDocumentDeleteAction : public UndoableAction
  36337. {
  36338. public:
  36339. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36340. : owner (owner_),
  36341. startPos (startPos_),
  36342. endPos (endPos_)
  36343. {
  36344. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36345. CodeDocument::Position (&owner, endPos));
  36346. }
  36347. bool perform()
  36348. {
  36349. owner.currentActionIndex++;
  36350. owner.remove (startPos, endPos, false);
  36351. return true;
  36352. }
  36353. bool undo()
  36354. {
  36355. owner.currentActionIndex--;
  36356. owner.insert (removedText, startPos, false);
  36357. return true;
  36358. }
  36359. int getSizeInUnits() { return removedText.length() + 32; }
  36360. private:
  36361. CodeDocument& owner;
  36362. int startPos, endPos;
  36363. String removedText;
  36364. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36365. };
  36366. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36367. {
  36368. if (endPos <= startPos)
  36369. return;
  36370. if (undoable)
  36371. {
  36372. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36373. }
  36374. else
  36375. {
  36376. Position startPosition (this, startPos);
  36377. Position endPosition (this, endPos);
  36378. maximumLineLength = -1;
  36379. const int firstAffectedLine = startPosition.getLineNumber();
  36380. const int endLine = endPosition.getLineNumber();
  36381. int lastAffectedLine = firstAffectedLine + 1;
  36382. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36383. if (firstAffectedLine == endLine)
  36384. {
  36385. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36386. + firstLine->line.substring (endPosition.getIndexInLine());
  36387. firstLine->updateLength();
  36388. }
  36389. else
  36390. {
  36391. lastAffectedLine = lines.size();
  36392. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36393. jassert (lastLine != 0);
  36394. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36395. + lastLine->line.substring (endPosition.getIndexInLine());
  36396. firstLine->updateLength();
  36397. int numLinesToRemove = endLine - firstAffectedLine;
  36398. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36399. }
  36400. int i;
  36401. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36402. {
  36403. CodeDocumentLine* const l = lines.getUnchecked (i);
  36404. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36405. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36406. }
  36407. checkLastLineStatus();
  36408. const int totalChars = getNumCharacters();
  36409. for (i = 0; i < positionsToMaintain.size(); ++i)
  36410. {
  36411. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36412. if (p->getPosition() > startPosition.getPosition())
  36413. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36414. if (p->getPosition() > totalChars)
  36415. p->setPosition (totalChars);
  36416. }
  36417. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36418. }
  36419. }
  36420. END_JUCE_NAMESPACE
  36421. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36422. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36423. BEGIN_JUCE_NAMESPACE
  36424. class CodeEditorComponent::CaretComponent : public Component,
  36425. public Timer
  36426. {
  36427. public:
  36428. CaretComponent (CodeEditorComponent& owner_)
  36429. : owner (owner_)
  36430. {
  36431. setAlwaysOnTop (true);
  36432. setInterceptsMouseClicks (false, false);
  36433. }
  36434. void paint (Graphics& g)
  36435. {
  36436. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36437. }
  36438. void timerCallback()
  36439. {
  36440. setVisible (shouldBeShown() && ! isVisible());
  36441. }
  36442. void updatePosition()
  36443. {
  36444. startTimer (400);
  36445. setVisible (shouldBeShown());
  36446. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36447. }
  36448. private:
  36449. CodeEditorComponent& owner;
  36450. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36451. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36452. };
  36453. class CodeEditorComponent::CodeEditorLine
  36454. {
  36455. public:
  36456. CodeEditorLine() throw()
  36457. : highlightColumnStart (0), highlightColumnEnd (0)
  36458. {
  36459. }
  36460. bool update (CodeDocument& document, int lineNum,
  36461. CodeDocument::Iterator& source,
  36462. CodeTokeniser* analyser, const int spacesPerTab,
  36463. const CodeDocument::Position& selectionStart,
  36464. const CodeDocument::Position& selectionEnd)
  36465. {
  36466. Array <SyntaxToken> newTokens;
  36467. newTokens.ensureStorageAllocated (8);
  36468. if (analyser == 0)
  36469. {
  36470. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36471. }
  36472. else if (lineNum < document.getNumLines())
  36473. {
  36474. const CodeDocument::Position pos (&document, lineNum, 0);
  36475. createTokens (pos.getPosition(), pos.getLineText(),
  36476. source, analyser, newTokens);
  36477. }
  36478. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36479. int newHighlightStart = 0;
  36480. int newHighlightEnd = 0;
  36481. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36482. {
  36483. const String line (document.getLine (lineNum));
  36484. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36485. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36486. line, spacesPerTab);
  36487. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36488. line, spacesPerTab);
  36489. }
  36490. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36491. {
  36492. highlightColumnStart = newHighlightStart;
  36493. highlightColumnEnd = newHighlightEnd;
  36494. }
  36495. else
  36496. {
  36497. if (tokens.size() == newTokens.size())
  36498. {
  36499. bool allTheSame = true;
  36500. for (int i = newTokens.size(); --i >= 0;)
  36501. {
  36502. if (tokens.getReference(i) != newTokens.getReference(i))
  36503. {
  36504. allTheSame = false;
  36505. break;
  36506. }
  36507. }
  36508. if (allTheSame)
  36509. return false;
  36510. }
  36511. }
  36512. tokens.swapWithArray (newTokens);
  36513. return true;
  36514. }
  36515. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36516. float x, const int y, const int baselineOffset, const int lineHeight,
  36517. const Colour& highlightColour) const
  36518. {
  36519. if (highlightColumnStart < highlightColumnEnd)
  36520. {
  36521. g.setColour (highlightColour);
  36522. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36523. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36524. }
  36525. int lastType = std::numeric_limits<int>::min();
  36526. for (int i = 0; i < tokens.size(); ++i)
  36527. {
  36528. SyntaxToken& token = tokens.getReference(i);
  36529. if (lastType != token.tokenType)
  36530. {
  36531. lastType = token.tokenType;
  36532. g.setColour (owner.getColourForTokenType (lastType));
  36533. }
  36534. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36535. if (i < tokens.size() - 1)
  36536. {
  36537. if (token.width < 0)
  36538. token.width = font.getStringWidthFloat (token.text);
  36539. x += token.width;
  36540. }
  36541. }
  36542. }
  36543. private:
  36544. struct SyntaxToken
  36545. {
  36546. SyntaxToken (const String& text_, const int type) throw()
  36547. : text (text_), tokenType (type), width (-1.0f)
  36548. {
  36549. }
  36550. bool operator!= (const SyntaxToken& other) const throw()
  36551. {
  36552. return text != other.text || tokenType != other.tokenType;
  36553. }
  36554. String text;
  36555. int tokenType;
  36556. float width;
  36557. };
  36558. Array <SyntaxToken> tokens;
  36559. int highlightColumnStart, highlightColumnEnd;
  36560. static void createTokens (int startPosition, const String& lineText,
  36561. CodeDocument::Iterator& source,
  36562. CodeTokeniser* analyser,
  36563. Array <SyntaxToken>& newTokens)
  36564. {
  36565. CodeDocument::Iterator lastIterator (source);
  36566. const int lineLength = lineText.length();
  36567. for (;;)
  36568. {
  36569. int tokenType = analyser->readNextToken (source);
  36570. int tokenStart = lastIterator.getPosition();
  36571. int tokenEnd = source.getPosition();
  36572. if (tokenEnd <= tokenStart)
  36573. break;
  36574. tokenEnd -= startPosition;
  36575. if (tokenEnd > 0)
  36576. {
  36577. tokenStart -= startPosition;
  36578. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36579. tokenType));
  36580. if (tokenEnd >= lineLength)
  36581. break;
  36582. }
  36583. lastIterator = source;
  36584. }
  36585. source = lastIterator;
  36586. }
  36587. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36588. {
  36589. int x = 0;
  36590. for (int i = 0; i < tokens.size(); ++i)
  36591. {
  36592. SyntaxToken& t = tokens.getReference(i);
  36593. for (;;)
  36594. {
  36595. int tabPos = t.text.indexOfChar ('\t');
  36596. if (tabPos < 0)
  36597. break;
  36598. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36599. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36600. }
  36601. x += t.text.length();
  36602. }
  36603. }
  36604. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36605. {
  36606. jassert (index <= line.length());
  36607. int col = 0;
  36608. for (int i = 0; i < index; ++i)
  36609. {
  36610. if (line[i] != '\t')
  36611. ++col;
  36612. else
  36613. col += spacesPerTab - (col % spacesPerTab);
  36614. }
  36615. return col;
  36616. }
  36617. };
  36618. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36619. CodeTokeniser* const codeTokeniser_)
  36620. : document (document_),
  36621. firstLineOnScreen (0),
  36622. gutter (5),
  36623. spacesPerTab (4),
  36624. lineHeight (0),
  36625. linesOnScreen (0),
  36626. columnsOnScreen (0),
  36627. scrollbarThickness (16),
  36628. columnToTryToMaintain (-1),
  36629. useSpacesForTabs (false),
  36630. xOffset (0),
  36631. verticalScrollBar (true),
  36632. horizontalScrollBar (false),
  36633. codeTokeniser (codeTokeniser_)
  36634. {
  36635. caretPos = CodeDocument::Position (&document_, 0, 0);
  36636. caretPos.setPositionMaintained (true);
  36637. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36638. selectionStart.setPositionMaintained (true);
  36639. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36640. selectionEnd.setPositionMaintained (true);
  36641. setOpaque (true);
  36642. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36643. setWantsKeyboardFocus (true);
  36644. addAndMakeVisible (&verticalScrollBar);
  36645. verticalScrollBar.setSingleStepSize (1.0);
  36646. addAndMakeVisible (&horizontalScrollBar);
  36647. horizontalScrollBar.setSingleStepSize (1.0);
  36648. addAndMakeVisible (caret = new CaretComponent (*this));
  36649. Font f (12.0f);
  36650. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36651. setFont (f);
  36652. resetToDefaultColours();
  36653. verticalScrollBar.addListener (this);
  36654. horizontalScrollBar.addListener (this);
  36655. document.addListener (this);
  36656. }
  36657. CodeEditorComponent::~CodeEditorComponent()
  36658. {
  36659. document.removeListener (this);
  36660. }
  36661. void CodeEditorComponent::loadContent (const String& newContent)
  36662. {
  36663. clearCachedIterators (0);
  36664. document.replaceAllContent (newContent);
  36665. document.clearUndoHistory();
  36666. document.setSavePoint();
  36667. caretPos.setPosition (0);
  36668. selectionStart.setPosition (0);
  36669. selectionEnd.setPosition (0);
  36670. scrollToLine (0);
  36671. }
  36672. bool CodeEditorComponent::isTextInputActive() const
  36673. {
  36674. return true;
  36675. }
  36676. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36677. const CodeDocument::Position& affectedTextEnd)
  36678. {
  36679. clearCachedIterators (affectedTextStart.getLineNumber());
  36680. triggerAsyncUpdate();
  36681. caret->updatePosition();
  36682. columnToTryToMaintain = -1;
  36683. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36684. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36685. deselectAll();
  36686. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36687. || caretPos.getPosition() < affectedTextStart.getPosition())
  36688. moveCaretTo (affectedTextStart, false);
  36689. updateScrollBars();
  36690. }
  36691. void CodeEditorComponent::resized()
  36692. {
  36693. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36694. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36695. lines.clear();
  36696. rebuildLineTokens();
  36697. caret->updatePosition();
  36698. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36699. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36700. updateScrollBars();
  36701. }
  36702. void CodeEditorComponent::paint (Graphics& g)
  36703. {
  36704. handleUpdateNowIfNeeded();
  36705. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36706. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36707. g.setFont (font);
  36708. const int baselineOffset = (int) font.getAscent();
  36709. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36710. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36711. const Rectangle<int> clip (g.getClipBounds());
  36712. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36713. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36714. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36715. {
  36716. lines.getUnchecked(j)->draw (*this, g, font,
  36717. (float) (gutter - xOffset * charWidth),
  36718. lineHeight * j, baselineOffset, lineHeight,
  36719. highlightColour);
  36720. }
  36721. }
  36722. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36723. {
  36724. if (scrollbarThickness != thickness)
  36725. {
  36726. scrollbarThickness = thickness;
  36727. resized();
  36728. }
  36729. }
  36730. void CodeEditorComponent::handleAsyncUpdate()
  36731. {
  36732. rebuildLineTokens();
  36733. }
  36734. void CodeEditorComponent::rebuildLineTokens()
  36735. {
  36736. cancelPendingUpdate();
  36737. const int numNeeded = linesOnScreen + 1;
  36738. int minLineToRepaint = numNeeded;
  36739. int maxLineToRepaint = 0;
  36740. if (numNeeded != lines.size())
  36741. {
  36742. lines.clear();
  36743. for (int i = numNeeded; --i >= 0;)
  36744. lines.add (new CodeEditorLine());
  36745. minLineToRepaint = 0;
  36746. maxLineToRepaint = numNeeded;
  36747. }
  36748. jassert (numNeeded == lines.size());
  36749. CodeDocument::Iterator source (&document);
  36750. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36751. for (int i = 0; i < numNeeded; ++i)
  36752. {
  36753. CodeEditorLine* const line = lines.getUnchecked(i);
  36754. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36755. selectionStart, selectionEnd))
  36756. {
  36757. minLineToRepaint = jmin (minLineToRepaint, i);
  36758. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36759. }
  36760. }
  36761. if (minLineToRepaint <= maxLineToRepaint)
  36762. {
  36763. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36764. verticalScrollBar.getX() - gutter,
  36765. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36766. }
  36767. }
  36768. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36769. {
  36770. caretPos = newPos;
  36771. columnToTryToMaintain = -1;
  36772. if (highlighting)
  36773. {
  36774. if (dragType == notDragging)
  36775. {
  36776. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36777. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36778. dragType = draggingSelectionStart;
  36779. else
  36780. dragType = draggingSelectionEnd;
  36781. }
  36782. if (dragType == draggingSelectionStart)
  36783. {
  36784. selectionStart = caretPos;
  36785. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36786. {
  36787. const CodeDocument::Position temp (selectionStart);
  36788. selectionStart = selectionEnd;
  36789. selectionEnd = temp;
  36790. dragType = draggingSelectionEnd;
  36791. }
  36792. }
  36793. else
  36794. {
  36795. selectionEnd = caretPos;
  36796. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36797. {
  36798. const CodeDocument::Position temp (selectionStart);
  36799. selectionStart = selectionEnd;
  36800. selectionEnd = temp;
  36801. dragType = draggingSelectionStart;
  36802. }
  36803. }
  36804. triggerAsyncUpdate();
  36805. }
  36806. else
  36807. {
  36808. deselectAll();
  36809. }
  36810. caret->updatePosition();
  36811. scrollToKeepCaretOnScreen();
  36812. updateScrollBars();
  36813. }
  36814. void CodeEditorComponent::deselectAll()
  36815. {
  36816. if (selectionStart != selectionEnd)
  36817. triggerAsyncUpdate();
  36818. selectionStart = caretPos;
  36819. selectionEnd = caretPos;
  36820. }
  36821. void CodeEditorComponent::updateScrollBars()
  36822. {
  36823. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36824. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36825. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36826. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36827. }
  36828. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36829. {
  36830. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36831. newFirstLineOnScreen);
  36832. if (newFirstLineOnScreen != firstLineOnScreen)
  36833. {
  36834. firstLineOnScreen = newFirstLineOnScreen;
  36835. caret->updatePosition();
  36836. updateCachedIterators (firstLineOnScreen);
  36837. triggerAsyncUpdate();
  36838. }
  36839. }
  36840. void CodeEditorComponent::scrollToColumnInternal (double column)
  36841. {
  36842. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36843. if (xOffset != newOffset)
  36844. {
  36845. xOffset = newOffset;
  36846. caret->updatePosition();
  36847. repaint();
  36848. }
  36849. }
  36850. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36851. {
  36852. scrollToLineInternal (newFirstLineOnScreen);
  36853. updateScrollBars();
  36854. }
  36855. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36856. {
  36857. scrollToColumnInternal (newFirstColumnOnScreen);
  36858. updateScrollBars();
  36859. }
  36860. void CodeEditorComponent::scrollBy (int deltaLines)
  36861. {
  36862. scrollToLine (firstLineOnScreen + deltaLines);
  36863. }
  36864. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36865. {
  36866. if (caretPos.getLineNumber() < firstLineOnScreen)
  36867. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36868. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36869. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36870. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36871. if (column >= xOffset + columnsOnScreen - 1)
  36872. scrollToColumn (column + 1 - columnsOnScreen);
  36873. else if (column < xOffset)
  36874. scrollToColumn (column);
  36875. }
  36876. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  36877. {
  36878. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36879. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36880. roundToInt (charWidth),
  36881. lineHeight);
  36882. }
  36883. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36884. {
  36885. const int line = y / lineHeight + firstLineOnScreen;
  36886. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36887. const int index = columnToIndex (line, column);
  36888. return CodeDocument::Position (&document, line, index);
  36889. }
  36890. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36891. {
  36892. document.deleteSection (selectionStart, selectionEnd);
  36893. if (newText.isNotEmpty())
  36894. document.insertText (caretPos, newText);
  36895. scrollToKeepCaretOnScreen();
  36896. }
  36897. void CodeEditorComponent::insertTabAtCaret()
  36898. {
  36899. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36900. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36901. {
  36902. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36903. }
  36904. if (useSpacesForTabs)
  36905. {
  36906. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36907. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36908. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36909. }
  36910. else
  36911. {
  36912. insertTextAtCaret ("\t");
  36913. }
  36914. }
  36915. void CodeEditorComponent::cut()
  36916. {
  36917. insertTextAtCaret (String::empty);
  36918. }
  36919. void CodeEditorComponent::copy()
  36920. {
  36921. newTransaction();
  36922. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36923. if (selection.isNotEmpty())
  36924. SystemClipboard::copyTextToClipboard (selection);
  36925. }
  36926. void CodeEditorComponent::copyThenCut()
  36927. {
  36928. copy();
  36929. cut();
  36930. newTransaction();
  36931. }
  36932. void CodeEditorComponent::paste()
  36933. {
  36934. newTransaction();
  36935. const String clip (SystemClipboard::getTextFromClipboard());
  36936. if (clip.isNotEmpty())
  36937. insertTextAtCaret (clip);
  36938. newTransaction();
  36939. }
  36940. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36941. {
  36942. newTransaction();
  36943. if (moveInWholeWordSteps)
  36944. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36945. else
  36946. moveCaretTo (caretPos.movedBy (-1), selecting);
  36947. }
  36948. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36949. {
  36950. newTransaction();
  36951. if (moveInWholeWordSteps)
  36952. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36953. else
  36954. moveCaretTo (caretPos.movedBy (1), selecting);
  36955. }
  36956. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36957. {
  36958. CodeDocument::Position pos (caretPos);
  36959. const int newLineNum = pos.getLineNumber() + delta;
  36960. if (columnToTryToMaintain < 0)
  36961. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36962. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36963. const int colToMaintain = columnToTryToMaintain;
  36964. moveCaretTo (pos, selecting);
  36965. columnToTryToMaintain = colToMaintain;
  36966. }
  36967. void CodeEditorComponent::cursorDown (const bool selecting)
  36968. {
  36969. newTransaction();
  36970. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36971. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36972. else
  36973. moveLineDelta (1, selecting);
  36974. }
  36975. void CodeEditorComponent::cursorUp (const bool selecting)
  36976. {
  36977. newTransaction();
  36978. if (caretPos.getLineNumber() == 0)
  36979. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36980. else
  36981. moveLineDelta (-1, selecting);
  36982. }
  36983. void CodeEditorComponent::pageDown (const bool selecting)
  36984. {
  36985. newTransaction();
  36986. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36987. moveLineDelta (linesOnScreen, selecting);
  36988. }
  36989. void CodeEditorComponent::pageUp (const bool selecting)
  36990. {
  36991. newTransaction();
  36992. scrollBy (-linesOnScreen);
  36993. moveLineDelta (-linesOnScreen, selecting);
  36994. }
  36995. void CodeEditorComponent::scrollUp()
  36996. {
  36997. newTransaction();
  36998. scrollBy (1);
  36999. if (caretPos.getLineNumber() < firstLineOnScreen)
  37000. moveLineDelta (1, false);
  37001. }
  37002. void CodeEditorComponent::scrollDown()
  37003. {
  37004. newTransaction();
  37005. scrollBy (-1);
  37006. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37007. moveLineDelta (-1, false);
  37008. }
  37009. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37010. {
  37011. newTransaction();
  37012. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37013. }
  37014. namespace CodeEditorHelpers
  37015. {
  37016. int findFirstNonWhitespaceChar (const String& line) throw()
  37017. {
  37018. const int len = line.length();
  37019. for (int i = 0; i < len; ++i)
  37020. if (! CharacterFunctions::isWhitespace (line [i]))
  37021. return i;
  37022. return 0;
  37023. }
  37024. }
  37025. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37026. {
  37027. newTransaction();
  37028. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37029. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37030. index = 0;
  37031. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37032. }
  37033. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37034. {
  37035. newTransaction();
  37036. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37037. }
  37038. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37039. {
  37040. newTransaction();
  37041. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37042. }
  37043. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37044. {
  37045. if (moveInWholeWordSteps)
  37046. {
  37047. cut(); // in case something is already highlighted
  37048. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37049. }
  37050. else
  37051. {
  37052. if (selectionStart == selectionEnd)
  37053. selectionStart.moveBy (-1);
  37054. }
  37055. cut();
  37056. }
  37057. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37058. {
  37059. if (moveInWholeWordSteps)
  37060. {
  37061. cut(); // in case something is already highlighted
  37062. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37063. }
  37064. else
  37065. {
  37066. if (selectionStart == selectionEnd)
  37067. selectionEnd.moveBy (1);
  37068. else
  37069. newTransaction();
  37070. }
  37071. cut();
  37072. }
  37073. void CodeEditorComponent::selectAll()
  37074. {
  37075. newTransaction();
  37076. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37077. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37078. }
  37079. void CodeEditorComponent::undo()
  37080. {
  37081. document.undo();
  37082. scrollToKeepCaretOnScreen();
  37083. }
  37084. void CodeEditorComponent::redo()
  37085. {
  37086. document.redo();
  37087. scrollToKeepCaretOnScreen();
  37088. }
  37089. void CodeEditorComponent::newTransaction()
  37090. {
  37091. document.newTransaction();
  37092. startTimer (600);
  37093. }
  37094. void CodeEditorComponent::timerCallback()
  37095. {
  37096. newTransaction();
  37097. }
  37098. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37099. {
  37100. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37101. }
  37102. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37103. {
  37104. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37105. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37106. }
  37107. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37108. {
  37109. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37110. CodeDocument::Position (&document, range.getEnd()));
  37111. }
  37112. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37113. {
  37114. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37115. const bool shiftDown = key.getModifiers().isShiftDown();
  37116. if (key.isKeyCode (KeyPress::leftKey))
  37117. {
  37118. cursorLeft (moveInWholeWordSteps, shiftDown);
  37119. }
  37120. else if (key.isKeyCode (KeyPress::rightKey))
  37121. {
  37122. cursorRight (moveInWholeWordSteps, shiftDown);
  37123. }
  37124. else if (key.isKeyCode (KeyPress::upKey))
  37125. {
  37126. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37127. scrollDown();
  37128. #if JUCE_MAC
  37129. else if (key.getModifiers().isCommandDown())
  37130. goToStartOfDocument (shiftDown);
  37131. #endif
  37132. else
  37133. cursorUp (shiftDown);
  37134. }
  37135. else if (key.isKeyCode (KeyPress::downKey))
  37136. {
  37137. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37138. scrollUp();
  37139. #if JUCE_MAC
  37140. else if (key.getModifiers().isCommandDown())
  37141. goToEndOfDocument (shiftDown);
  37142. #endif
  37143. else
  37144. cursorDown (shiftDown);
  37145. }
  37146. else if (key.isKeyCode (KeyPress::pageDownKey))
  37147. {
  37148. pageDown (shiftDown);
  37149. }
  37150. else if (key.isKeyCode (KeyPress::pageUpKey))
  37151. {
  37152. pageUp (shiftDown);
  37153. }
  37154. else if (key.isKeyCode (KeyPress::homeKey))
  37155. {
  37156. if (moveInWholeWordSteps)
  37157. goToStartOfDocument (shiftDown);
  37158. else
  37159. goToStartOfLine (shiftDown);
  37160. }
  37161. else if (key.isKeyCode (KeyPress::endKey))
  37162. {
  37163. if (moveInWholeWordSteps)
  37164. goToEndOfDocument (shiftDown);
  37165. else
  37166. goToEndOfLine (shiftDown);
  37167. }
  37168. else if (key.isKeyCode (KeyPress::backspaceKey))
  37169. {
  37170. backspace (moveInWholeWordSteps);
  37171. }
  37172. else if (key.isKeyCode (KeyPress::deleteKey))
  37173. {
  37174. deleteForward (moveInWholeWordSteps);
  37175. }
  37176. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37177. {
  37178. copy();
  37179. }
  37180. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37181. {
  37182. copyThenCut();
  37183. }
  37184. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37185. {
  37186. paste();
  37187. }
  37188. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37189. {
  37190. undo();
  37191. }
  37192. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37193. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37194. {
  37195. redo();
  37196. }
  37197. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37198. {
  37199. selectAll();
  37200. }
  37201. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37202. {
  37203. insertTabAtCaret();
  37204. }
  37205. else if (key == KeyPress::returnKey)
  37206. {
  37207. newTransaction();
  37208. insertTextAtCaret (document.getNewLineCharacters());
  37209. }
  37210. else if (key.isKeyCode (KeyPress::escapeKey))
  37211. {
  37212. newTransaction();
  37213. }
  37214. else if (key.getTextCharacter() >= ' ')
  37215. {
  37216. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37217. }
  37218. else
  37219. {
  37220. return false;
  37221. }
  37222. return true;
  37223. }
  37224. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37225. {
  37226. newTransaction();
  37227. dragType = notDragging;
  37228. if (! e.mods.isPopupMenu())
  37229. {
  37230. beginDragAutoRepeat (100);
  37231. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37232. }
  37233. else
  37234. {
  37235. /*PopupMenu m;
  37236. addPopupMenuItems (m, &e);
  37237. const int result = m.show();
  37238. if (result != 0)
  37239. performPopupMenuAction (result);
  37240. */
  37241. }
  37242. }
  37243. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37244. {
  37245. if (! e.mods.isPopupMenu())
  37246. moveCaretTo (getPositionAt (e.x, e.y), true);
  37247. }
  37248. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37249. {
  37250. newTransaction();
  37251. beginDragAutoRepeat (0);
  37252. dragType = notDragging;
  37253. }
  37254. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37255. {
  37256. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37257. CodeDocument::Position tokenEnd (tokenStart);
  37258. if (e.getNumberOfClicks() > 2)
  37259. {
  37260. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37261. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37262. }
  37263. else
  37264. {
  37265. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37266. tokenEnd.moveBy (1);
  37267. tokenStart = tokenEnd;
  37268. while (tokenStart.getIndexInLine() > 0
  37269. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37270. tokenStart.moveBy (-1);
  37271. }
  37272. moveCaretTo (tokenEnd, false);
  37273. moveCaretTo (tokenStart, true);
  37274. }
  37275. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37276. {
  37277. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37278. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37279. {
  37280. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37281. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37282. }
  37283. else
  37284. {
  37285. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37286. }
  37287. }
  37288. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37289. {
  37290. if (scrollBarThatHasMoved == &verticalScrollBar)
  37291. scrollToLineInternal ((int) newRangeStart);
  37292. else
  37293. scrollToColumnInternal (newRangeStart);
  37294. }
  37295. void CodeEditorComponent::focusGained (FocusChangeType)
  37296. {
  37297. caret->updatePosition();
  37298. }
  37299. void CodeEditorComponent::focusLost (FocusChangeType)
  37300. {
  37301. caret->updatePosition();
  37302. }
  37303. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37304. {
  37305. useSpacesForTabs = insertSpaces;
  37306. if (spacesPerTab != numSpaces)
  37307. {
  37308. spacesPerTab = numSpaces;
  37309. triggerAsyncUpdate();
  37310. }
  37311. }
  37312. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37313. {
  37314. const String line (document.getLine (lineNum));
  37315. jassert (index <= line.length());
  37316. int col = 0;
  37317. for (int i = 0; i < index; ++i)
  37318. {
  37319. if (line[i] != '\t')
  37320. ++col;
  37321. else
  37322. col += getTabSize() - (col % getTabSize());
  37323. }
  37324. return col;
  37325. }
  37326. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37327. {
  37328. const String line (document.getLine (lineNum));
  37329. const int lineLength = line.length();
  37330. int i, col = 0;
  37331. for (i = 0; i < lineLength; ++i)
  37332. {
  37333. if (line[i] != '\t')
  37334. ++col;
  37335. else
  37336. col += getTabSize() - (col % getTabSize());
  37337. if (col > column)
  37338. break;
  37339. }
  37340. return i;
  37341. }
  37342. void CodeEditorComponent::setFont (const Font& newFont)
  37343. {
  37344. font = newFont;
  37345. charWidth = font.getStringWidthFloat ("0");
  37346. lineHeight = roundToInt (font.getHeight());
  37347. resized();
  37348. }
  37349. void CodeEditorComponent::resetToDefaultColours()
  37350. {
  37351. coloursForTokenCategories.clear();
  37352. if (codeTokeniser != 0)
  37353. {
  37354. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37355. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37356. }
  37357. }
  37358. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37359. {
  37360. jassert (tokenType < 256);
  37361. while (coloursForTokenCategories.size() < tokenType)
  37362. coloursForTokenCategories.add (Colours::black);
  37363. coloursForTokenCategories.set (tokenType, colour);
  37364. repaint();
  37365. }
  37366. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37367. {
  37368. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37369. return findColour (CodeEditorComponent::defaultTextColourId);
  37370. return coloursForTokenCategories.getReference (tokenType);
  37371. }
  37372. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37373. {
  37374. int i;
  37375. for (i = cachedIterators.size(); --i >= 0;)
  37376. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37377. break;
  37378. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37379. }
  37380. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37381. {
  37382. const int maxNumCachedPositions = 5000;
  37383. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37384. if (cachedIterators.size() == 0)
  37385. cachedIterators.add (new CodeDocument::Iterator (&document));
  37386. if (codeTokeniser == 0)
  37387. return;
  37388. for (;;)
  37389. {
  37390. CodeDocument::Iterator* last = cachedIterators.getLast();
  37391. if (last->getLine() >= maxLineNum)
  37392. break;
  37393. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37394. cachedIterators.add (t);
  37395. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37396. for (;;)
  37397. {
  37398. codeTokeniser->readNextToken (*t);
  37399. if (t->getLine() >= targetLine)
  37400. break;
  37401. if (t->isEOF())
  37402. return;
  37403. }
  37404. }
  37405. }
  37406. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37407. {
  37408. if (codeTokeniser == 0)
  37409. return;
  37410. for (int i = cachedIterators.size(); --i >= 0;)
  37411. {
  37412. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37413. if (t->getPosition() <= position)
  37414. {
  37415. source = *t;
  37416. break;
  37417. }
  37418. }
  37419. while (source.getPosition() < position)
  37420. {
  37421. const CodeDocument::Iterator original (source);
  37422. codeTokeniser->readNextToken (source);
  37423. if (source.getPosition() > position || source.isEOF())
  37424. {
  37425. source = original;
  37426. break;
  37427. }
  37428. }
  37429. }
  37430. END_JUCE_NAMESPACE
  37431. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37432. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37433. BEGIN_JUCE_NAMESPACE
  37434. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37435. {
  37436. }
  37437. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37438. {
  37439. }
  37440. namespace CppTokeniser
  37441. {
  37442. bool isIdentifierStart (const juce_wchar c) throw()
  37443. {
  37444. return CharacterFunctions::isLetter (c)
  37445. || c == '_' || c == '@';
  37446. }
  37447. bool isIdentifierBody (const juce_wchar c) throw()
  37448. {
  37449. return CharacterFunctions::isLetterOrDigit (c)
  37450. || c == '_' || c == '@';
  37451. }
  37452. bool isReservedKeyword (String::CharPointerType token, const int tokenLength) throw()
  37453. {
  37454. static const char* const keywords2Char[] =
  37455. { "if", "do", "or", "id", 0 };
  37456. static const char* const keywords3Char[] =
  37457. { "for", "int", "new", "try", "xor", "and", "asm", "not", 0 };
  37458. static const char* const keywords4Char[] =
  37459. { "bool", "void", "this", "true", "long", "else", "char",
  37460. "enum", "case", "goto", "auto", 0 };
  37461. static const char* const keywords5Char[] =
  37462. { "while", "bitor", "break", "catch", "class", "compl", "const", "false",
  37463. "float", "short", "throw", "union", "using", "or_eq", 0 };
  37464. static const char* const keywords6Char[] =
  37465. { "return", "struct", "and_eq", "bitand", "delete", "double", "extern",
  37466. "friend", "inline", "not_eq", "public", "sizeof", "static", "signed",
  37467. "switch", "typeid", "wchar_t", "xor_eq", 0};
  37468. static const char* const keywordsOther[] =
  37469. { "const_cast", "continue", "default", "explicit", "mutable", "namespace",
  37470. "operator", "private", "protected", "register", "reinterpret_cast", "static_cast",
  37471. "template", "typedef", "typename", "unsigned", "virtual", "volatile",
  37472. "@implementation", "@interface", "@end", "@synthesize", "@dynamic", "@public",
  37473. "@private", "@property", "@protected", "@class", 0 };
  37474. const char* const* k;
  37475. switch (tokenLength)
  37476. {
  37477. case 2: k = keywords2Char; break;
  37478. case 3: k = keywords3Char; break;
  37479. case 4: k = keywords4Char; break;
  37480. case 5: k = keywords5Char; break;
  37481. case 6: k = keywords6Char; break;
  37482. default:
  37483. if (tokenLength < 2 || tokenLength > 16)
  37484. return false;
  37485. k = keywordsOther;
  37486. break;
  37487. }
  37488. int i = 0;
  37489. while (k[i] != 0)
  37490. {
  37491. if (token.compare (CharPointer_ASCII (k[i])) == 0)
  37492. return true;
  37493. ++i;
  37494. }
  37495. return false;
  37496. }
  37497. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37498. {
  37499. int tokenLength = 0;
  37500. juce_wchar possibleIdentifier [19];
  37501. while (isIdentifierBody (source.peekNextChar()))
  37502. {
  37503. const juce_wchar c = source.nextChar();
  37504. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37505. possibleIdentifier [tokenLength] = c;
  37506. ++tokenLength;
  37507. }
  37508. if (tokenLength > 1 && tokenLength <= 16)
  37509. {
  37510. possibleIdentifier [tokenLength] = 0;
  37511. if (isReservedKeyword (CharPointer_UTF32 (possibleIdentifier), tokenLength))
  37512. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37513. }
  37514. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37515. }
  37516. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37517. {
  37518. const juce_wchar c = source.peekNextChar();
  37519. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37520. source.skip();
  37521. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37522. return false;
  37523. return true;
  37524. }
  37525. bool isHexDigit (const juce_wchar c) throw()
  37526. {
  37527. return (c >= '0' && c <= '9')
  37528. || (c >= 'a' && c <= 'f')
  37529. || (c >= 'A' && c <= 'F');
  37530. }
  37531. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37532. {
  37533. if (source.nextChar() != '0')
  37534. return false;
  37535. juce_wchar c = source.nextChar();
  37536. if (c != 'x' && c != 'X')
  37537. return false;
  37538. int numDigits = 0;
  37539. while (isHexDigit (source.peekNextChar()))
  37540. {
  37541. ++numDigits;
  37542. source.skip();
  37543. }
  37544. if (numDigits == 0)
  37545. return false;
  37546. return skipNumberSuffix (source);
  37547. }
  37548. bool isOctalDigit (const juce_wchar c) throw()
  37549. {
  37550. return c >= '0' && c <= '7';
  37551. }
  37552. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37553. {
  37554. if (source.nextChar() != '0')
  37555. return false;
  37556. if (! isOctalDigit (source.nextChar()))
  37557. return false;
  37558. while (isOctalDigit (source.peekNextChar()))
  37559. source.skip();
  37560. return skipNumberSuffix (source);
  37561. }
  37562. bool isDecimalDigit (const juce_wchar c) throw()
  37563. {
  37564. return c >= '0' && c <= '9';
  37565. }
  37566. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37567. {
  37568. int numChars = 0;
  37569. while (isDecimalDigit (source.peekNextChar()))
  37570. {
  37571. ++numChars;
  37572. source.skip();
  37573. }
  37574. if (numChars == 0)
  37575. return false;
  37576. return skipNumberSuffix (source);
  37577. }
  37578. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37579. {
  37580. int numDigits = 0;
  37581. while (isDecimalDigit (source.peekNextChar()))
  37582. {
  37583. source.skip();
  37584. ++numDigits;
  37585. }
  37586. const bool hasPoint = (source.peekNextChar() == '.');
  37587. if (hasPoint)
  37588. {
  37589. source.skip();
  37590. while (isDecimalDigit (source.peekNextChar()))
  37591. {
  37592. source.skip();
  37593. ++numDigits;
  37594. }
  37595. }
  37596. if (numDigits == 0)
  37597. return false;
  37598. juce_wchar c = source.peekNextChar();
  37599. const bool hasExponent = (c == 'e' || c == 'E');
  37600. if (hasExponent)
  37601. {
  37602. source.skip();
  37603. c = source.peekNextChar();
  37604. if (c == '+' || c == '-')
  37605. source.skip();
  37606. int numExpDigits = 0;
  37607. while (isDecimalDigit (source.peekNextChar()))
  37608. {
  37609. source.skip();
  37610. ++numExpDigits;
  37611. }
  37612. if (numExpDigits == 0)
  37613. return false;
  37614. }
  37615. c = source.peekNextChar();
  37616. if (c == 'f' || c == 'F')
  37617. source.skip();
  37618. else if (! (hasExponent || hasPoint))
  37619. return false;
  37620. return true;
  37621. }
  37622. int parseNumber (CodeDocument::Iterator& source)
  37623. {
  37624. const CodeDocument::Iterator original (source);
  37625. if (parseFloatLiteral (source))
  37626. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37627. source = original;
  37628. if (parseHexLiteral (source))
  37629. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37630. source = original;
  37631. if (parseOctalLiteral (source))
  37632. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37633. source = original;
  37634. if (parseDecimalLiteral (source))
  37635. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37636. source = original;
  37637. source.skip();
  37638. return CPlusPlusCodeTokeniser::tokenType_error;
  37639. }
  37640. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37641. {
  37642. const juce_wchar quote = source.nextChar();
  37643. for (;;)
  37644. {
  37645. const juce_wchar c = source.nextChar();
  37646. if (c == quote || c == 0)
  37647. break;
  37648. if (c == '\\')
  37649. source.skip();
  37650. }
  37651. }
  37652. void skipComment (CodeDocument::Iterator& source) throw()
  37653. {
  37654. bool lastWasStar = false;
  37655. for (;;)
  37656. {
  37657. const juce_wchar c = source.nextChar();
  37658. if (c == 0 || (c == '/' && lastWasStar))
  37659. break;
  37660. lastWasStar = (c == '*');
  37661. }
  37662. }
  37663. }
  37664. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37665. {
  37666. int result = tokenType_error;
  37667. source.skipWhitespace();
  37668. juce_wchar firstChar = source.peekNextChar();
  37669. switch (firstChar)
  37670. {
  37671. case 0:
  37672. source.skip();
  37673. break;
  37674. case '0':
  37675. case '1':
  37676. case '2':
  37677. case '3':
  37678. case '4':
  37679. case '5':
  37680. case '6':
  37681. case '7':
  37682. case '8':
  37683. case '9':
  37684. result = CppTokeniser::parseNumber (source);
  37685. break;
  37686. case '.':
  37687. result = CppTokeniser::parseNumber (source);
  37688. if (result == tokenType_error)
  37689. result = tokenType_punctuation;
  37690. break;
  37691. case ',':
  37692. case ';':
  37693. case ':':
  37694. source.skip();
  37695. result = tokenType_punctuation;
  37696. break;
  37697. case '(':
  37698. case ')':
  37699. case '{':
  37700. case '}':
  37701. case '[':
  37702. case ']':
  37703. source.skip();
  37704. result = tokenType_bracket;
  37705. break;
  37706. case '"':
  37707. case '\'':
  37708. CppTokeniser::skipQuotedString (source);
  37709. result = tokenType_stringLiteral;
  37710. break;
  37711. case '+':
  37712. result = tokenType_operator;
  37713. source.skip();
  37714. if (source.peekNextChar() == '+')
  37715. source.skip();
  37716. else if (source.peekNextChar() == '=')
  37717. source.skip();
  37718. break;
  37719. case '-':
  37720. source.skip();
  37721. result = CppTokeniser::parseNumber (source);
  37722. if (result == tokenType_error)
  37723. {
  37724. result = tokenType_operator;
  37725. if (source.peekNextChar() == '-')
  37726. source.skip();
  37727. else if (source.peekNextChar() == '=')
  37728. source.skip();
  37729. }
  37730. break;
  37731. case '*':
  37732. case '%':
  37733. case '=':
  37734. case '!':
  37735. result = tokenType_operator;
  37736. source.skip();
  37737. if (source.peekNextChar() == '=')
  37738. source.skip();
  37739. break;
  37740. case '/':
  37741. result = tokenType_operator;
  37742. source.skip();
  37743. if (source.peekNextChar() == '=')
  37744. {
  37745. source.skip();
  37746. }
  37747. else if (source.peekNextChar() == '/')
  37748. {
  37749. result = tokenType_comment;
  37750. source.skipToEndOfLine();
  37751. }
  37752. else if (source.peekNextChar() == '*')
  37753. {
  37754. source.skip();
  37755. result = tokenType_comment;
  37756. CppTokeniser::skipComment (source);
  37757. }
  37758. break;
  37759. case '?':
  37760. case '~':
  37761. source.skip();
  37762. result = tokenType_operator;
  37763. break;
  37764. case '<':
  37765. source.skip();
  37766. result = tokenType_operator;
  37767. if (source.peekNextChar() == '=')
  37768. {
  37769. source.skip();
  37770. }
  37771. else if (source.peekNextChar() == '<')
  37772. {
  37773. source.skip();
  37774. if (source.peekNextChar() == '=')
  37775. source.skip();
  37776. }
  37777. break;
  37778. case '>':
  37779. source.skip();
  37780. result = tokenType_operator;
  37781. if (source.peekNextChar() == '=')
  37782. {
  37783. source.skip();
  37784. }
  37785. else if (source.peekNextChar() == '<')
  37786. {
  37787. source.skip();
  37788. if (source.peekNextChar() == '=')
  37789. source.skip();
  37790. }
  37791. break;
  37792. case '|':
  37793. source.skip();
  37794. result = tokenType_operator;
  37795. if (source.peekNextChar() == '=')
  37796. {
  37797. source.skip();
  37798. }
  37799. else if (source.peekNextChar() == '|')
  37800. {
  37801. source.skip();
  37802. if (source.peekNextChar() == '=')
  37803. source.skip();
  37804. }
  37805. break;
  37806. case '&':
  37807. source.skip();
  37808. result = tokenType_operator;
  37809. if (source.peekNextChar() == '=')
  37810. {
  37811. source.skip();
  37812. }
  37813. else if (source.peekNextChar() == '&')
  37814. {
  37815. source.skip();
  37816. if (source.peekNextChar() == '=')
  37817. source.skip();
  37818. }
  37819. break;
  37820. case '^':
  37821. source.skip();
  37822. result = tokenType_operator;
  37823. if (source.peekNextChar() == '=')
  37824. {
  37825. source.skip();
  37826. }
  37827. else if (source.peekNextChar() == '^')
  37828. {
  37829. source.skip();
  37830. if (source.peekNextChar() == '=')
  37831. source.skip();
  37832. }
  37833. break;
  37834. case '#':
  37835. result = tokenType_preprocessor;
  37836. source.skipToEndOfLine();
  37837. break;
  37838. default:
  37839. if (CppTokeniser::isIdentifierStart (firstChar))
  37840. result = CppTokeniser::parseIdentifier (source);
  37841. else
  37842. source.skip();
  37843. break;
  37844. }
  37845. return result;
  37846. }
  37847. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37848. {
  37849. const char* const types[] =
  37850. {
  37851. "Error",
  37852. "Comment",
  37853. "C++ keyword",
  37854. "Identifier",
  37855. "Integer literal",
  37856. "Float literal",
  37857. "String literal",
  37858. "Operator",
  37859. "Bracket",
  37860. "Punctuation",
  37861. "Preprocessor line",
  37862. 0
  37863. };
  37864. return StringArray (types);
  37865. }
  37866. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37867. {
  37868. const uint32 colours[] =
  37869. {
  37870. 0xffcc0000, // error
  37871. 0xff00aa00, // comment
  37872. 0xff0000cc, // keyword
  37873. 0xff000000, // identifier
  37874. 0xff880000, // int literal
  37875. 0xff885500, // float literal
  37876. 0xff990099, // string literal
  37877. 0xff225500, // operator
  37878. 0xff000055, // bracket
  37879. 0xff004400, // punctuation
  37880. 0xff660000 // preprocessor
  37881. };
  37882. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37883. return Colour (colours [tokenType]);
  37884. return Colours::black;
  37885. }
  37886. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37887. {
  37888. return CppTokeniser::isReservedKeyword (token.getCharPointer(), token.length());
  37889. }
  37890. END_JUCE_NAMESPACE
  37891. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37892. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37893. BEGIN_JUCE_NAMESPACE
  37894. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  37895. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  37896. {
  37897. }
  37898. bool ComboBox::ItemInfo::isSeparator() const throw()
  37899. {
  37900. return name.isEmpty();
  37901. }
  37902. bool ComboBox::ItemInfo::isRealItem() const throw()
  37903. {
  37904. return ! (isHeading || name.isEmpty());
  37905. }
  37906. ComboBox::ComboBox (const String& name)
  37907. : Component (name),
  37908. lastCurrentId (0),
  37909. isButtonDown (false),
  37910. separatorPending (false),
  37911. menuActive (false),
  37912. noChoicesMessage (TRANS("(no choices)"))
  37913. {
  37914. setRepaintsOnMouseActivity (true);
  37915. lookAndFeelChanged();
  37916. currentId.addListener (this);
  37917. }
  37918. ComboBox::~ComboBox()
  37919. {
  37920. currentId.removeListener (this);
  37921. if (menuActive)
  37922. PopupMenu::dismissAllActiveMenus();
  37923. label = 0;
  37924. }
  37925. void ComboBox::setEditableText (const bool isEditable)
  37926. {
  37927. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37928. {
  37929. label->setEditable (isEditable, isEditable, false);
  37930. setWantsKeyboardFocus (! isEditable);
  37931. resized();
  37932. }
  37933. }
  37934. bool ComboBox::isTextEditable() const throw()
  37935. {
  37936. return label->isEditable();
  37937. }
  37938. void ComboBox::setJustificationType (const Justification& justification)
  37939. {
  37940. label->setJustificationType (justification);
  37941. }
  37942. const Justification ComboBox::getJustificationType() const throw()
  37943. {
  37944. return label->getJustificationType();
  37945. }
  37946. void ComboBox::setTooltip (const String& newTooltip)
  37947. {
  37948. SettableTooltipClient::setTooltip (newTooltip);
  37949. label->setTooltip (newTooltip);
  37950. }
  37951. void ComboBox::addItem (const String& newItemText, const int newItemId)
  37952. {
  37953. // you can't add empty strings to the list..
  37954. jassert (newItemText.isNotEmpty());
  37955. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37956. jassert (newItemId != 0);
  37957. // you shouldn't use duplicate item IDs!
  37958. jassert (getItemForId (newItemId) == 0);
  37959. if (newItemText.isNotEmpty() && newItemId != 0)
  37960. {
  37961. if (separatorPending)
  37962. {
  37963. separatorPending = false;
  37964. items.add (new ItemInfo (String::empty, 0, false, false));
  37965. }
  37966. items.add (new ItemInfo (newItemText, newItemId, true, false));
  37967. }
  37968. }
  37969. void ComboBox::addSeparator()
  37970. {
  37971. separatorPending = (items.size() > 0);
  37972. }
  37973. void ComboBox::addSectionHeading (const String& headingName)
  37974. {
  37975. // you can't add empty strings to the list..
  37976. jassert (headingName.isNotEmpty());
  37977. if (headingName.isNotEmpty())
  37978. {
  37979. if (separatorPending)
  37980. {
  37981. separatorPending = false;
  37982. items.add (new ItemInfo (String::empty, 0, false, false));
  37983. }
  37984. items.add (new ItemInfo (headingName, 0, true, true));
  37985. }
  37986. }
  37987. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  37988. {
  37989. ItemInfo* const item = getItemForId (itemId);
  37990. if (item != 0)
  37991. item->isEnabled = shouldBeEnabled;
  37992. }
  37993. bool ComboBox::isItemEnabled (int itemId) const throw()
  37994. {
  37995. const ItemInfo* const item = getItemForId (itemId);
  37996. return item != 0 && item->isEnabled;
  37997. }
  37998. void ComboBox::changeItemText (const int itemId, const String& newText)
  37999. {
  38000. ItemInfo* const item = getItemForId (itemId);
  38001. jassert (item != 0);
  38002. if (item != 0)
  38003. item->name = newText;
  38004. }
  38005. void ComboBox::clear (const bool dontSendChangeMessage)
  38006. {
  38007. items.clear();
  38008. separatorPending = false;
  38009. if (! label->isEditable())
  38010. setSelectedItemIndex (-1, dontSendChangeMessage);
  38011. }
  38012. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38013. {
  38014. if (itemId != 0)
  38015. {
  38016. for (int i = items.size(); --i >= 0;)
  38017. if (items.getUnchecked(i)->itemId == itemId)
  38018. return items.getUnchecked(i);
  38019. }
  38020. return 0;
  38021. }
  38022. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38023. {
  38024. for (int n = 0, i = 0; i < items.size(); ++i)
  38025. {
  38026. ItemInfo* const item = items.getUnchecked(i);
  38027. if (item->isRealItem())
  38028. if (n++ == index)
  38029. return item;
  38030. }
  38031. return 0;
  38032. }
  38033. int ComboBox::getNumItems() const throw()
  38034. {
  38035. int n = 0;
  38036. for (int i = items.size(); --i >= 0;)
  38037. if (items.getUnchecked(i)->isRealItem())
  38038. ++n;
  38039. return n;
  38040. }
  38041. const String ComboBox::getItemText (const int index) const
  38042. {
  38043. const ItemInfo* const item = getItemForIndex (index);
  38044. return item != 0 ? item->name : String::empty;
  38045. }
  38046. int ComboBox::getItemId (const int index) const throw()
  38047. {
  38048. const ItemInfo* const item = getItemForIndex (index);
  38049. return item != 0 ? item->itemId : 0;
  38050. }
  38051. int ComboBox::indexOfItemId (const int itemId) const throw()
  38052. {
  38053. for (int n = 0, i = 0; i < items.size(); ++i)
  38054. {
  38055. const ItemInfo* const item = items.getUnchecked(i);
  38056. if (item->isRealItem())
  38057. {
  38058. if (item->itemId == itemId)
  38059. return n;
  38060. ++n;
  38061. }
  38062. }
  38063. return -1;
  38064. }
  38065. int ComboBox::getSelectedItemIndex() const
  38066. {
  38067. int index = indexOfItemId (currentId.getValue());
  38068. if (getText() != getItemText (index))
  38069. index = -1;
  38070. return index;
  38071. }
  38072. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38073. {
  38074. setSelectedId (getItemId (index), dontSendChangeMessage);
  38075. }
  38076. int ComboBox::getSelectedId() const throw()
  38077. {
  38078. const ItemInfo* const item = getItemForId (currentId.getValue());
  38079. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38080. }
  38081. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38082. {
  38083. const ItemInfo* const item = getItemForId (newItemId);
  38084. const String newItemText (item != 0 ? item->name : String::empty);
  38085. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38086. {
  38087. if (! dontSendChangeMessage)
  38088. triggerAsyncUpdate();
  38089. label->setText (newItemText, false);
  38090. lastCurrentId = newItemId;
  38091. currentId = newItemId;
  38092. repaint(); // for the benefit of the 'none selected' text
  38093. }
  38094. }
  38095. bool ComboBox::selectIfEnabled (const int index)
  38096. {
  38097. const ItemInfo* const item = getItemForIndex (index);
  38098. if (item != 0 && item->isEnabled)
  38099. {
  38100. setSelectedItemIndex (index);
  38101. return true;
  38102. }
  38103. return false;
  38104. }
  38105. void ComboBox::valueChanged (Value&)
  38106. {
  38107. if (lastCurrentId != (int) currentId.getValue())
  38108. setSelectedId (currentId.getValue(), false);
  38109. }
  38110. const String ComboBox::getText() const
  38111. {
  38112. return label->getText();
  38113. }
  38114. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38115. {
  38116. for (int i = items.size(); --i >= 0;)
  38117. {
  38118. const ItemInfo* const item = items.getUnchecked(i);
  38119. if (item->isRealItem()
  38120. && item->name == newText)
  38121. {
  38122. setSelectedId (item->itemId, dontSendChangeMessage);
  38123. return;
  38124. }
  38125. }
  38126. lastCurrentId = 0;
  38127. currentId = 0;
  38128. if (label->getText() != newText)
  38129. {
  38130. label->setText (newText, false);
  38131. if (! dontSendChangeMessage)
  38132. triggerAsyncUpdate();
  38133. }
  38134. repaint();
  38135. }
  38136. void ComboBox::showEditor()
  38137. {
  38138. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38139. label->showEditor();
  38140. }
  38141. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38142. {
  38143. if (textWhenNothingSelected != newMessage)
  38144. {
  38145. textWhenNothingSelected = newMessage;
  38146. repaint();
  38147. }
  38148. }
  38149. const String ComboBox::getTextWhenNothingSelected() const
  38150. {
  38151. return textWhenNothingSelected;
  38152. }
  38153. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38154. {
  38155. noChoicesMessage = newMessage;
  38156. }
  38157. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38158. {
  38159. return noChoicesMessage;
  38160. }
  38161. void ComboBox::paint (Graphics& g)
  38162. {
  38163. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38164. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38165. *this);
  38166. if (textWhenNothingSelected.isNotEmpty()
  38167. && label->getText().isEmpty()
  38168. && ! label->isBeingEdited())
  38169. {
  38170. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38171. g.setFont (label->getFont());
  38172. g.drawFittedText (textWhenNothingSelected,
  38173. label->getX() + 2, label->getY() + 1,
  38174. label->getWidth() - 4, label->getHeight() - 2,
  38175. label->getJustificationType(),
  38176. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38177. }
  38178. }
  38179. void ComboBox::resized()
  38180. {
  38181. if (getHeight() > 0 && getWidth() > 0)
  38182. getLookAndFeel().positionComboBoxText (*this, *label);
  38183. }
  38184. void ComboBox::enablementChanged()
  38185. {
  38186. repaint();
  38187. }
  38188. void ComboBox::lookAndFeelChanged()
  38189. {
  38190. repaint();
  38191. {
  38192. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38193. jassert (newLabel != 0);
  38194. if (label != 0)
  38195. {
  38196. newLabel->setEditable (label->isEditable());
  38197. newLabel->setJustificationType (label->getJustificationType());
  38198. newLabel->setTooltip (label->getTooltip());
  38199. newLabel->setText (label->getText(), false);
  38200. }
  38201. label = newLabel;
  38202. }
  38203. addAndMakeVisible (label);
  38204. label->addListener (this);
  38205. label->addMouseListener (this, false);
  38206. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38207. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38208. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38209. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38210. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38211. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38212. resized();
  38213. }
  38214. void ComboBox::colourChanged()
  38215. {
  38216. lookAndFeelChanged();
  38217. }
  38218. bool ComboBox::keyPressed (const KeyPress& key)
  38219. {
  38220. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38221. {
  38222. int index = getSelectedItemIndex() - 1;
  38223. while (index >= 0 && ! selectIfEnabled (index))
  38224. --index;
  38225. return true;
  38226. }
  38227. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38228. {
  38229. int index = getSelectedItemIndex() + 1;
  38230. while (index < getNumItems() && ! selectIfEnabled (index))
  38231. ++index;
  38232. return true;
  38233. }
  38234. else if (key.isKeyCode (KeyPress::returnKey))
  38235. {
  38236. showPopup();
  38237. return true;
  38238. }
  38239. return false;
  38240. }
  38241. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38242. {
  38243. // only forward key events that aren't used by this component
  38244. return isKeyDown
  38245. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38246. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38247. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38248. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38249. }
  38250. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38251. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38252. void ComboBox::labelTextChanged (Label*)
  38253. {
  38254. triggerAsyncUpdate();
  38255. }
  38256. class ComboBox::Callback : public ModalComponentManager::Callback
  38257. {
  38258. public:
  38259. Callback (ComboBox* const box_)
  38260. : box (box_)
  38261. {
  38262. }
  38263. void modalStateFinished (int returnValue)
  38264. {
  38265. if (box != 0)
  38266. {
  38267. box->menuActive = false;
  38268. if (returnValue != 0)
  38269. box->setSelectedId (returnValue);
  38270. }
  38271. }
  38272. private:
  38273. Component::SafePointer<ComboBox> box;
  38274. JUCE_DECLARE_NON_COPYABLE (Callback);
  38275. };
  38276. void ComboBox::showPopup()
  38277. {
  38278. if (! menuActive)
  38279. {
  38280. const int selectedId = getSelectedId();
  38281. PopupMenu menu;
  38282. menu.setLookAndFeel (&getLookAndFeel());
  38283. for (int i = 0; i < items.size(); ++i)
  38284. {
  38285. const ItemInfo* const item = items.getUnchecked(i);
  38286. if (item->isSeparator())
  38287. menu.addSeparator();
  38288. else if (item->isHeading)
  38289. menu.addSectionHeader (item->name);
  38290. else
  38291. menu.addItem (item->itemId, item->name,
  38292. item->isEnabled, item->itemId == selectedId);
  38293. }
  38294. if (items.size() == 0)
  38295. menu.addItem (1, noChoicesMessage, false);
  38296. menuActive = true;
  38297. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38298. new Callback (this));
  38299. }
  38300. }
  38301. void ComboBox::mouseDown (const MouseEvent& e)
  38302. {
  38303. beginDragAutoRepeat (300);
  38304. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38305. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38306. showPopup();
  38307. }
  38308. void ComboBox::mouseDrag (const MouseEvent& e)
  38309. {
  38310. beginDragAutoRepeat (50);
  38311. if (isButtonDown && ! e.mouseWasClicked())
  38312. showPopup();
  38313. }
  38314. void ComboBox::mouseUp (const MouseEvent& e2)
  38315. {
  38316. if (isButtonDown)
  38317. {
  38318. isButtonDown = false;
  38319. repaint();
  38320. const MouseEvent e (e2.getEventRelativeTo (this));
  38321. if (reallyContains (e.getPosition(), true)
  38322. && (e2.eventComponent == this || ! label->isEditable()))
  38323. {
  38324. showPopup();
  38325. }
  38326. }
  38327. }
  38328. void ComboBox::addListener (ComboBoxListener* const listener)
  38329. {
  38330. listeners.add (listener);
  38331. }
  38332. void ComboBox::removeListener (ComboBoxListener* const listener)
  38333. {
  38334. listeners.remove (listener);
  38335. }
  38336. void ComboBox::handleAsyncUpdate()
  38337. {
  38338. Component::BailOutChecker checker (this);
  38339. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38340. }
  38341. END_JUCE_NAMESPACE
  38342. /*** End of inlined file: juce_ComboBox.cpp ***/
  38343. /*** Start of inlined file: juce_Label.cpp ***/
  38344. BEGIN_JUCE_NAMESPACE
  38345. Label::Label (const String& componentName,
  38346. const String& labelText)
  38347. : Component (componentName),
  38348. textValue (labelText),
  38349. lastTextValue (labelText),
  38350. font (15.0f),
  38351. justification (Justification::centredLeft),
  38352. ownerComponent (0),
  38353. horizontalBorderSize (5),
  38354. verticalBorderSize (1),
  38355. minimumHorizontalScale (0.7f),
  38356. editSingleClick (false),
  38357. editDoubleClick (false),
  38358. lossOfFocusDiscardsChanges (false)
  38359. {
  38360. setColour (TextEditor::textColourId, Colours::black);
  38361. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38362. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38363. textValue.addListener (this);
  38364. }
  38365. Label::~Label()
  38366. {
  38367. textValue.removeListener (this);
  38368. if (ownerComponent != 0)
  38369. ownerComponent->removeComponentListener (this);
  38370. editor = 0;
  38371. }
  38372. void Label::setText (const String& newText,
  38373. const bool broadcastChangeMessage)
  38374. {
  38375. hideEditor (true);
  38376. if (lastTextValue != newText)
  38377. {
  38378. lastTextValue = newText;
  38379. textValue = newText;
  38380. repaint();
  38381. textWasChanged();
  38382. if (ownerComponent != 0)
  38383. componentMovedOrResized (*ownerComponent, true, true);
  38384. if (broadcastChangeMessage)
  38385. callChangeListeners();
  38386. }
  38387. }
  38388. const String Label::getText (const bool returnActiveEditorContents) const
  38389. {
  38390. return (returnActiveEditorContents && isBeingEdited())
  38391. ? editor->getText()
  38392. : textValue.toString();
  38393. }
  38394. void Label::valueChanged (Value&)
  38395. {
  38396. if (lastTextValue != textValue.toString())
  38397. setText (textValue.toString(), true);
  38398. }
  38399. void Label::setFont (const Font& newFont)
  38400. {
  38401. if (font != newFont)
  38402. {
  38403. font = newFont;
  38404. repaint();
  38405. }
  38406. }
  38407. const Font& Label::getFont() const throw()
  38408. {
  38409. return font;
  38410. }
  38411. void Label::setEditable (const bool editOnSingleClick,
  38412. const bool editOnDoubleClick,
  38413. const bool lossOfFocusDiscardsChanges_)
  38414. {
  38415. editSingleClick = editOnSingleClick;
  38416. editDoubleClick = editOnDoubleClick;
  38417. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38418. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38419. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38420. }
  38421. void Label::setJustificationType (const Justification& newJustification)
  38422. {
  38423. if (justification != newJustification)
  38424. {
  38425. justification = newJustification;
  38426. repaint();
  38427. }
  38428. }
  38429. void Label::setBorderSize (int h, int v)
  38430. {
  38431. if (horizontalBorderSize != h || verticalBorderSize != v)
  38432. {
  38433. horizontalBorderSize = h;
  38434. verticalBorderSize = v;
  38435. repaint();
  38436. }
  38437. }
  38438. Component* Label::getAttachedComponent() const
  38439. {
  38440. return static_cast<Component*> (ownerComponent);
  38441. }
  38442. void Label::attachToComponent (Component* owner,
  38443. const bool onLeft)
  38444. {
  38445. if (ownerComponent != 0)
  38446. ownerComponent->removeComponentListener (this);
  38447. ownerComponent = owner;
  38448. leftOfOwnerComp = onLeft;
  38449. if (ownerComponent != 0)
  38450. {
  38451. setVisible (owner->isVisible());
  38452. ownerComponent->addComponentListener (this);
  38453. componentParentHierarchyChanged (*ownerComponent);
  38454. componentMovedOrResized (*ownerComponent, true, true);
  38455. }
  38456. }
  38457. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38458. {
  38459. if (leftOfOwnerComp)
  38460. {
  38461. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38462. component.getHeight());
  38463. setTopRightPosition (component.getX(), component.getY());
  38464. }
  38465. else
  38466. {
  38467. setSize (component.getWidth(),
  38468. 8 + roundToInt (getFont().getHeight()));
  38469. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38470. }
  38471. }
  38472. void Label::componentParentHierarchyChanged (Component& component)
  38473. {
  38474. if (component.getParentComponent() != 0)
  38475. component.getParentComponent()->addChildComponent (this);
  38476. }
  38477. void Label::componentVisibilityChanged (Component& component)
  38478. {
  38479. setVisible (component.isVisible());
  38480. }
  38481. void Label::textWasEdited()
  38482. {
  38483. }
  38484. void Label::textWasChanged()
  38485. {
  38486. }
  38487. void Label::showEditor()
  38488. {
  38489. if (editor == 0)
  38490. {
  38491. addAndMakeVisible (editor = createEditorComponent());
  38492. editor->setText (getText(), false);
  38493. editor->addListener (this);
  38494. editor->grabKeyboardFocus();
  38495. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38496. editor->addListener (this);
  38497. resized();
  38498. repaint();
  38499. editorShown (editor);
  38500. enterModalState (false);
  38501. editor->grabKeyboardFocus();
  38502. }
  38503. }
  38504. void Label::editorShown (TextEditor*)
  38505. {
  38506. }
  38507. void Label::editorAboutToBeHidden (TextEditor*)
  38508. {
  38509. }
  38510. bool Label::updateFromTextEditorContents (TextEditor& ed)
  38511. {
  38512. const String newText (ed.getText());
  38513. if (textValue.toString() != newText)
  38514. {
  38515. lastTextValue = newText;
  38516. textValue = newText;
  38517. repaint();
  38518. textWasChanged();
  38519. if (ownerComponent != 0)
  38520. componentMovedOrResized (*ownerComponent, true, true);
  38521. return true;
  38522. }
  38523. return false;
  38524. }
  38525. void Label::hideEditor (const bool discardCurrentEditorContents)
  38526. {
  38527. if (editor != 0)
  38528. {
  38529. WeakReference<Component> deletionChecker (this);
  38530. ScopedPointer<TextEditor> outgoingEditor (editor);
  38531. editorAboutToBeHidden (outgoingEditor);
  38532. const bool changed = (! discardCurrentEditorContents)
  38533. && updateFromTextEditorContents (*outgoingEditor);
  38534. outgoingEditor = 0;
  38535. repaint();
  38536. if (changed)
  38537. textWasEdited();
  38538. if (deletionChecker != 0)
  38539. exitModalState (0);
  38540. if (changed && deletionChecker != 0)
  38541. callChangeListeners();
  38542. }
  38543. }
  38544. void Label::inputAttemptWhenModal()
  38545. {
  38546. if (editor != 0)
  38547. {
  38548. if (lossOfFocusDiscardsChanges)
  38549. textEditorEscapeKeyPressed (*editor);
  38550. else
  38551. textEditorReturnKeyPressed (*editor);
  38552. }
  38553. }
  38554. bool Label::isBeingEdited() const throw()
  38555. {
  38556. return editor != 0;
  38557. }
  38558. TextEditor* Label::createEditorComponent()
  38559. {
  38560. TextEditor* const ed = new TextEditor (getName());
  38561. ed->setFont (font);
  38562. // copy these colours from our own settings..
  38563. const int cols[] = { TextEditor::backgroundColourId,
  38564. TextEditor::textColourId,
  38565. TextEditor::highlightColourId,
  38566. TextEditor::highlightedTextColourId,
  38567. TextEditor::caretColourId,
  38568. TextEditor::outlineColourId,
  38569. TextEditor::focusedOutlineColourId,
  38570. TextEditor::shadowColourId };
  38571. for (int i = 0; i < numElementsInArray (cols); ++i)
  38572. ed->setColour (cols[i], findColour (cols[i]));
  38573. return ed;
  38574. }
  38575. void Label::paint (Graphics& g)
  38576. {
  38577. getLookAndFeel().drawLabel (g, *this);
  38578. }
  38579. void Label::mouseUp (const MouseEvent& e)
  38580. {
  38581. if (editSingleClick
  38582. && e.mouseWasClicked()
  38583. && contains (e.getPosition())
  38584. && ! e.mods.isPopupMenu())
  38585. {
  38586. showEditor();
  38587. }
  38588. }
  38589. void Label::mouseDoubleClick (const MouseEvent& e)
  38590. {
  38591. if (editDoubleClick && ! e.mods.isPopupMenu())
  38592. showEditor();
  38593. }
  38594. void Label::resized()
  38595. {
  38596. if (editor != 0)
  38597. editor->setBoundsInset (BorderSize<int> (0));
  38598. }
  38599. void Label::focusGained (FocusChangeType cause)
  38600. {
  38601. if (editSingleClick && cause == focusChangedByTabKey)
  38602. showEditor();
  38603. }
  38604. void Label::enablementChanged()
  38605. {
  38606. repaint();
  38607. }
  38608. void Label::colourChanged()
  38609. {
  38610. repaint();
  38611. }
  38612. void Label::setMinimumHorizontalScale (const float newScale)
  38613. {
  38614. if (minimumHorizontalScale != newScale)
  38615. {
  38616. minimumHorizontalScale = newScale;
  38617. repaint();
  38618. }
  38619. }
  38620. // We'll use a custom focus traverser here to make sure focus goes from the
  38621. // text editor to another component rather than back to the label itself.
  38622. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38623. {
  38624. public:
  38625. LabelKeyboardFocusTraverser() {}
  38626. Component* getNextComponent (Component* current)
  38627. {
  38628. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38629. ? current->getParentComponent() : current);
  38630. }
  38631. Component* getPreviousComponent (Component* current)
  38632. {
  38633. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38634. ? current->getParentComponent() : current);
  38635. }
  38636. };
  38637. KeyboardFocusTraverser* Label::createFocusTraverser()
  38638. {
  38639. return new LabelKeyboardFocusTraverser();
  38640. }
  38641. void Label::addListener (LabelListener* const listener)
  38642. {
  38643. listeners.add (listener);
  38644. }
  38645. void Label::removeListener (LabelListener* const listener)
  38646. {
  38647. listeners.remove (listener);
  38648. }
  38649. void Label::callChangeListeners()
  38650. {
  38651. Component::BailOutChecker checker (this);
  38652. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38653. }
  38654. void Label::textEditorTextChanged (TextEditor& ed)
  38655. {
  38656. if (editor != 0)
  38657. {
  38658. jassert (&ed == editor);
  38659. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38660. {
  38661. if (lossOfFocusDiscardsChanges)
  38662. textEditorEscapeKeyPressed (ed);
  38663. else
  38664. textEditorReturnKeyPressed (ed);
  38665. }
  38666. }
  38667. }
  38668. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38669. {
  38670. if (editor != 0)
  38671. {
  38672. jassert (&ed == editor);
  38673. const bool changed = updateFromTextEditorContents (ed);
  38674. hideEditor (true);
  38675. if (changed)
  38676. {
  38677. WeakReference<Component> deletionChecker (this);
  38678. textWasEdited();
  38679. if (deletionChecker != 0)
  38680. callChangeListeners();
  38681. }
  38682. }
  38683. }
  38684. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38685. {
  38686. if (editor != 0)
  38687. {
  38688. jassert (&ed == editor);
  38689. (void) ed;
  38690. editor->setText (textValue.toString(), false);
  38691. hideEditor (true);
  38692. }
  38693. }
  38694. void Label::textEditorFocusLost (TextEditor& ed)
  38695. {
  38696. textEditorTextChanged (ed);
  38697. }
  38698. END_JUCE_NAMESPACE
  38699. /*** End of inlined file: juce_Label.cpp ***/
  38700. /*** Start of inlined file: juce_ListBox.cpp ***/
  38701. BEGIN_JUCE_NAMESPACE
  38702. class ListBoxRowComponent : public Component,
  38703. public TooltipClient
  38704. {
  38705. public:
  38706. ListBoxRowComponent (ListBox& owner_)
  38707. : owner (owner_), row (-1),
  38708. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38709. {
  38710. }
  38711. void paint (Graphics& g)
  38712. {
  38713. if (owner.getModel() != 0)
  38714. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38715. }
  38716. void update (const int row_, const bool selected_)
  38717. {
  38718. if (row != row_ || selected != selected_)
  38719. {
  38720. repaint();
  38721. row = row_;
  38722. selected = selected_;
  38723. }
  38724. if (owner.getModel() != 0)
  38725. {
  38726. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38727. if (customComponent != 0)
  38728. {
  38729. addAndMakeVisible (customComponent);
  38730. customComponent->setBounds (getLocalBounds());
  38731. }
  38732. }
  38733. }
  38734. void mouseDown (const MouseEvent& e)
  38735. {
  38736. isDragging = false;
  38737. selectRowOnMouseUp = false;
  38738. if (isEnabled())
  38739. {
  38740. if (! selected)
  38741. {
  38742. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38743. if (owner.getModel() != 0)
  38744. owner.getModel()->listBoxItemClicked (row, e);
  38745. }
  38746. else
  38747. {
  38748. selectRowOnMouseUp = true;
  38749. }
  38750. }
  38751. }
  38752. void mouseUp (const MouseEvent& e)
  38753. {
  38754. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38755. {
  38756. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38757. if (owner.getModel() != 0)
  38758. owner.getModel()->listBoxItemClicked (row, e);
  38759. }
  38760. }
  38761. void mouseDoubleClick (const MouseEvent& e)
  38762. {
  38763. if (owner.getModel() != 0 && isEnabled())
  38764. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38765. }
  38766. void mouseDrag (const MouseEvent& e)
  38767. {
  38768. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38769. {
  38770. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38771. if (selectedRows.size() > 0)
  38772. {
  38773. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38774. if (dragDescription.isNotEmpty())
  38775. {
  38776. isDragging = true;
  38777. owner.startDragAndDrop (e, dragDescription);
  38778. }
  38779. }
  38780. }
  38781. }
  38782. void resized()
  38783. {
  38784. if (customComponent != 0)
  38785. customComponent->setBounds (getLocalBounds());
  38786. }
  38787. const String getTooltip()
  38788. {
  38789. if (owner.getModel() != 0)
  38790. return owner.getModel()->getTooltipForRow (row);
  38791. return String::empty;
  38792. }
  38793. ScopedPointer<Component> customComponent;
  38794. private:
  38795. ListBox& owner;
  38796. int row;
  38797. bool selected, isDragging, selectRowOnMouseUp;
  38798. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38799. };
  38800. class ListViewport : public Viewport
  38801. {
  38802. public:
  38803. ListViewport (ListBox& owner_)
  38804. : owner (owner_)
  38805. {
  38806. setWantsKeyboardFocus (false);
  38807. Component* const content = new Component();
  38808. setViewedComponent (content);
  38809. content->addMouseListener (this, false);
  38810. content->setWantsKeyboardFocus (false);
  38811. }
  38812. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38813. {
  38814. return rows [row % jmax (1, rows.size())];
  38815. }
  38816. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38817. {
  38818. return (row >= firstIndex && row < firstIndex + rows.size())
  38819. ? getComponentForRow (row) : 0;
  38820. }
  38821. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38822. {
  38823. const int index = getIndexOfChildComponent (rowComponent);
  38824. const int num = rows.size();
  38825. for (int i = num; --i >= 0;)
  38826. if (((firstIndex + i) % jmax (1, num)) == index)
  38827. return firstIndex + i;
  38828. return -1;
  38829. }
  38830. void visibleAreaChanged (const Rectangle<int>&)
  38831. {
  38832. updateVisibleArea (true);
  38833. if (owner.getModel() != 0)
  38834. owner.getModel()->listWasScrolled();
  38835. }
  38836. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38837. {
  38838. hasUpdated = false;
  38839. const int newX = getViewedComponent()->getX();
  38840. int newY = getViewedComponent()->getY();
  38841. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38842. const int newH = owner.totalItems * owner.getRowHeight();
  38843. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38844. newY = getMaximumVisibleHeight() - newH;
  38845. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38846. if (makeSureItUpdatesContent && ! hasUpdated)
  38847. updateContents();
  38848. }
  38849. void updateContents()
  38850. {
  38851. hasUpdated = true;
  38852. const int rowHeight = owner.getRowHeight();
  38853. if (rowHeight > 0)
  38854. {
  38855. const int y = getViewPositionY();
  38856. const int w = getViewedComponent()->getWidth();
  38857. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38858. rows.removeRange (numNeeded, rows.size());
  38859. while (numNeeded > rows.size())
  38860. {
  38861. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  38862. rows.add (newRow);
  38863. getViewedComponent()->addAndMakeVisible (newRow);
  38864. }
  38865. firstIndex = y / rowHeight;
  38866. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38867. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38868. for (int i = 0; i < numNeeded; ++i)
  38869. {
  38870. const int row = i + firstIndex;
  38871. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38872. if (rowComp != 0)
  38873. {
  38874. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38875. rowComp->update (row, owner.isRowSelected (row));
  38876. }
  38877. }
  38878. }
  38879. if (owner.headerComponent != 0)
  38880. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38881. owner.outlineThickness,
  38882. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38883. getViewedComponent()->getWidth()),
  38884. owner.headerComponent->getHeight());
  38885. }
  38886. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  38887. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  38888. {
  38889. hasUpdated = false;
  38890. if (row < firstWholeIndex && ! dontScroll)
  38891. {
  38892. setViewPosition (getViewPositionX(), row * rowHeight);
  38893. }
  38894. else if (row >= lastWholeIndex && ! dontScroll)
  38895. {
  38896. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  38897. if (row >= lastRowSelected + rowsOnScreen
  38898. && rowsOnScreen < totalItems - 1
  38899. && ! isMouseClick)
  38900. {
  38901. setViewPosition (getViewPositionX(),
  38902. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  38903. }
  38904. else
  38905. {
  38906. setViewPosition (getViewPositionX(),
  38907. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38908. }
  38909. }
  38910. if (! hasUpdated)
  38911. updateContents();
  38912. }
  38913. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  38914. {
  38915. if (row < firstWholeIndex)
  38916. {
  38917. setViewPosition (getViewPositionX(), row * rowHeight);
  38918. }
  38919. else if (row >= lastWholeIndex)
  38920. {
  38921. setViewPosition (getViewPositionX(),
  38922. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38923. }
  38924. }
  38925. void paint (Graphics& g)
  38926. {
  38927. if (isOpaque())
  38928. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38929. }
  38930. bool keyPressed (const KeyPress& key)
  38931. {
  38932. if (key.isKeyCode (KeyPress::upKey)
  38933. || key.isKeyCode (KeyPress::downKey)
  38934. || key.isKeyCode (KeyPress::pageUpKey)
  38935. || key.isKeyCode (KeyPress::pageDownKey)
  38936. || key.isKeyCode (KeyPress::homeKey)
  38937. || key.isKeyCode (KeyPress::endKey))
  38938. {
  38939. // we want to avoid these keypresses going to the viewport, and instead allow
  38940. // them to pass up to our listbox..
  38941. return false;
  38942. }
  38943. return Viewport::keyPressed (key);
  38944. }
  38945. private:
  38946. ListBox& owner;
  38947. OwnedArray<ListBoxRowComponent> rows;
  38948. int firstIndex, firstWholeIndex, lastWholeIndex;
  38949. bool hasUpdated;
  38950. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  38951. };
  38952. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38953. : Component (name),
  38954. model (model_),
  38955. totalItems (0),
  38956. rowHeight (22),
  38957. minimumRowWidth (0),
  38958. outlineThickness (0),
  38959. lastRowSelected (-1),
  38960. mouseMoveSelects (false),
  38961. multipleSelection (false),
  38962. hasDoneInitialUpdate (false)
  38963. {
  38964. addAndMakeVisible (viewport = new ListViewport (*this));
  38965. setWantsKeyboardFocus (true);
  38966. colourChanged();
  38967. }
  38968. ListBox::~ListBox()
  38969. {
  38970. headerComponent = 0;
  38971. viewport = 0;
  38972. }
  38973. void ListBox::setModel (ListBoxModel* const newModel)
  38974. {
  38975. if (model != newModel)
  38976. {
  38977. model = newModel;
  38978. repaint();
  38979. updateContent();
  38980. }
  38981. }
  38982. void ListBox::setMultipleSelectionEnabled (bool b)
  38983. {
  38984. multipleSelection = b;
  38985. }
  38986. void ListBox::setMouseMoveSelectsRows (bool b)
  38987. {
  38988. mouseMoveSelects = b;
  38989. if (b)
  38990. addMouseListener (this, true);
  38991. }
  38992. void ListBox::paint (Graphics& g)
  38993. {
  38994. if (! hasDoneInitialUpdate)
  38995. updateContent();
  38996. g.fillAll (findColour (backgroundColourId));
  38997. }
  38998. void ListBox::paintOverChildren (Graphics& g)
  38999. {
  39000. if (outlineThickness > 0)
  39001. {
  39002. g.setColour (findColour (outlineColourId));
  39003. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39004. }
  39005. }
  39006. void ListBox::resized()
  39007. {
  39008. viewport->setBoundsInset (BorderSize<int> (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39009. outlineThickness, outlineThickness, outlineThickness));
  39010. viewport->setSingleStepSizes (20, getRowHeight());
  39011. viewport->updateVisibleArea (false);
  39012. }
  39013. void ListBox::visibilityChanged()
  39014. {
  39015. viewport->updateVisibleArea (true);
  39016. }
  39017. Viewport* ListBox::getViewport() const throw()
  39018. {
  39019. return viewport;
  39020. }
  39021. void ListBox::updateContent()
  39022. {
  39023. hasDoneInitialUpdate = true;
  39024. totalItems = (model != 0) ? model->getNumRows() : 0;
  39025. bool selectionChanged = false;
  39026. if (selected.size() > 0 && selected [selected.size() - 1] >= totalItems)
  39027. {
  39028. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39029. lastRowSelected = getSelectedRow (0);
  39030. selectionChanged = true;
  39031. }
  39032. viewport->updateVisibleArea (isVisible());
  39033. viewport->resized();
  39034. if (selectionChanged && model != 0)
  39035. model->selectedRowsChanged (lastRowSelected);
  39036. }
  39037. void ListBox::selectRow (const int row,
  39038. bool dontScroll,
  39039. bool deselectOthersFirst)
  39040. {
  39041. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39042. }
  39043. void ListBox::selectRowInternal (const int row,
  39044. bool dontScroll,
  39045. bool deselectOthersFirst,
  39046. bool isMouseClick)
  39047. {
  39048. if (! multipleSelection)
  39049. deselectOthersFirst = true;
  39050. if ((! isRowSelected (row))
  39051. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39052. {
  39053. if (isPositiveAndBelow (row, totalItems))
  39054. {
  39055. if (deselectOthersFirst)
  39056. selected.clear();
  39057. selected.addRange (Range<int> (row, row + 1));
  39058. if (getHeight() == 0 || getWidth() == 0)
  39059. dontScroll = true;
  39060. viewport->selectRow (row, getRowHeight(), dontScroll,
  39061. lastRowSelected, totalItems, isMouseClick);
  39062. lastRowSelected = row;
  39063. model->selectedRowsChanged (row);
  39064. }
  39065. else
  39066. {
  39067. if (deselectOthersFirst)
  39068. deselectAllRows();
  39069. }
  39070. }
  39071. }
  39072. void ListBox::deselectRow (const int row)
  39073. {
  39074. if (selected.contains (row))
  39075. {
  39076. selected.removeRange (Range <int> (row, row + 1));
  39077. if (row == lastRowSelected)
  39078. lastRowSelected = getSelectedRow (0);
  39079. viewport->updateContents();
  39080. model->selectedRowsChanged (lastRowSelected);
  39081. }
  39082. }
  39083. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39084. const bool sendNotificationEventToModel)
  39085. {
  39086. selected = setOfRowsToBeSelected;
  39087. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39088. if (! isRowSelected (lastRowSelected))
  39089. lastRowSelected = getSelectedRow (0);
  39090. viewport->updateContents();
  39091. if ((model != 0) && sendNotificationEventToModel)
  39092. model->selectedRowsChanged (lastRowSelected);
  39093. }
  39094. const SparseSet<int> ListBox::getSelectedRows() const
  39095. {
  39096. return selected;
  39097. }
  39098. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39099. {
  39100. if (multipleSelection && (firstRow != lastRow))
  39101. {
  39102. const int numRows = totalItems - 1;
  39103. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39104. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39105. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39106. jmax (firstRow, lastRow) + 1));
  39107. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39108. }
  39109. selectRowInternal (lastRow, false, false, true);
  39110. }
  39111. void ListBox::flipRowSelection (const int row)
  39112. {
  39113. if (isRowSelected (row))
  39114. deselectRow (row);
  39115. else
  39116. selectRowInternal (row, false, false, true);
  39117. }
  39118. void ListBox::deselectAllRows()
  39119. {
  39120. if (! selected.isEmpty())
  39121. {
  39122. selected.clear();
  39123. lastRowSelected = -1;
  39124. viewport->updateContents();
  39125. if (model != 0)
  39126. model->selectedRowsChanged (lastRowSelected);
  39127. }
  39128. }
  39129. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39130. const ModifierKeys& mods,
  39131. const bool isMouseUpEvent)
  39132. {
  39133. if (multipleSelection && mods.isCommandDown())
  39134. {
  39135. flipRowSelection (row);
  39136. }
  39137. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39138. {
  39139. selectRangeOfRows (lastRowSelected, row);
  39140. }
  39141. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39142. {
  39143. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39144. }
  39145. }
  39146. int ListBox::getNumSelectedRows() const
  39147. {
  39148. return selected.size();
  39149. }
  39150. int ListBox::getSelectedRow (const int index) const
  39151. {
  39152. return (isPositiveAndBelow (index, selected.size()))
  39153. ? selected [index] : -1;
  39154. }
  39155. bool ListBox::isRowSelected (const int row) const
  39156. {
  39157. return selected.contains (row);
  39158. }
  39159. int ListBox::getLastRowSelected() const
  39160. {
  39161. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39162. }
  39163. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39164. {
  39165. if (isPositiveAndBelow (x, getWidth()))
  39166. {
  39167. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39168. if (isPositiveAndBelow (row, totalItems))
  39169. return row;
  39170. }
  39171. return -1;
  39172. }
  39173. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39174. {
  39175. if (isPositiveAndBelow (x, getWidth()))
  39176. {
  39177. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39178. return jlimit (0, totalItems, row);
  39179. }
  39180. return -1;
  39181. }
  39182. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39183. {
  39184. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39185. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39186. }
  39187. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39188. {
  39189. return viewport->getRowNumberOfComponent (rowComponent);
  39190. }
  39191. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39192. const bool relativeToComponentTopLeft) const throw()
  39193. {
  39194. int y = viewport->getY() + rowHeight * rowNumber;
  39195. if (relativeToComponentTopLeft)
  39196. y -= viewport->getViewPositionY();
  39197. return Rectangle<int> (viewport->getX(), y,
  39198. viewport->getViewedComponent()->getWidth(), rowHeight);
  39199. }
  39200. void ListBox::setVerticalPosition (const double proportion)
  39201. {
  39202. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39203. viewport->setViewPosition (viewport->getViewPositionX(),
  39204. jmax (0, roundToInt (proportion * offscreen)));
  39205. }
  39206. double ListBox::getVerticalPosition() const
  39207. {
  39208. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39209. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39210. : 0;
  39211. }
  39212. int ListBox::getVisibleRowWidth() const throw()
  39213. {
  39214. return viewport->getViewWidth();
  39215. }
  39216. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39217. {
  39218. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39219. }
  39220. bool ListBox::keyPressed (const KeyPress& key)
  39221. {
  39222. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39223. const bool multiple = multipleSelection
  39224. && (lastRowSelected >= 0)
  39225. && (key.getModifiers().isShiftDown()
  39226. || key.getModifiers().isCtrlDown()
  39227. || key.getModifiers().isCommandDown());
  39228. if (key.isKeyCode (KeyPress::upKey))
  39229. {
  39230. if (multiple)
  39231. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39232. else
  39233. selectRow (jmax (0, lastRowSelected - 1));
  39234. }
  39235. else if (key.isKeyCode (KeyPress::returnKey)
  39236. && isRowSelected (lastRowSelected))
  39237. {
  39238. if (model != 0)
  39239. model->returnKeyPressed (lastRowSelected);
  39240. }
  39241. else if (key.isKeyCode (KeyPress::pageUpKey))
  39242. {
  39243. if (multiple)
  39244. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39245. else
  39246. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39247. }
  39248. else if (key.isKeyCode (KeyPress::pageDownKey))
  39249. {
  39250. if (multiple)
  39251. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39252. else
  39253. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39254. }
  39255. else if (key.isKeyCode (KeyPress::homeKey))
  39256. {
  39257. if (multiple && key.getModifiers().isShiftDown())
  39258. selectRangeOfRows (lastRowSelected, 0);
  39259. else
  39260. selectRow (0);
  39261. }
  39262. else if (key.isKeyCode (KeyPress::endKey))
  39263. {
  39264. if (multiple && key.getModifiers().isShiftDown())
  39265. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39266. else
  39267. selectRow (totalItems - 1);
  39268. }
  39269. else if (key.isKeyCode (KeyPress::downKey))
  39270. {
  39271. if (multiple)
  39272. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39273. else
  39274. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39275. }
  39276. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39277. && isRowSelected (lastRowSelected))
  39278. {
  39279. if (model != 0)
  39280. model->deleteKeyPressed (lastRowSelected);
  39281. }
  39282. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39283. {
  39284. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39285. }
  39286. else
  39287. {
  39288. return false;
  39289. }
  39290. return true;
  39291. }
  39292. bool ListBox::keyStateChanged (const bool isKeyDown)
  39293. {
  39294. return isKeyDown
  39295. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39296. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39297. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39298. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39299. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39300. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39301. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39302. }
  39303. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39304. {
  39305. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39306. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39307. }
  39308. void ListBox::mouseMove (const MouseEvent& e)
  39309. {
  39310. if (mouseMoveSelects)
  39311. {
  39312. const MouseEvent e2 (e.getEventRelativeTo (this));
  39313. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39314. }
  39315. }
  39316. void ListBox::mouseExit (const MouseEvent& e)
  39317. {
  39318. mouseMove (e);
  39319. }
  39320. void ListBox::mouseUp (const MouseEvent& e)
  39321. {
  39322. if (e.mouseWasClicked() && model != 0)
  39323. model->backgroundClicked();
  39324. }
  39325. void ListBox::setRowHeight (const int newHeight)
  39326. {
  39327. rowHeight = jmax (1, newHeight);
  39328. viewport->setSingleStepSizes (20, rowHeight);
  39329. updateContent();
  39330. }
  39331. int ListBox::getNumRowsOnScreen() const throw()
  39332. {
  39333. return viewport->getMaximumVisibleHeight() / rowHeight;
  39334. }
  39335. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39336. {
  39337. minimumRowWidth = newMinimumWidth;
  39338. updateContent();
  39339. }
  39340. int ListBox::getVisibleContentWidth() const throw()
  39341. {
  39342. return viewport->getMaximumVisibleWidth();
  39343. }
  39344. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39345. {
  39346. return viewport->getVerticalScrollBar();
  39347. }
  39348. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39349. {
  39350. return viewport->getHorizontalScrollBar();
  39351. }
  39352. void ListBox::colourChanged()
  39353. {
  39354. setOpaque (findColour (backgroundColourId).isOpaque());
  39355. viewport->setOpaque (isOpaque());
  39356. repaint();
  39357. }
  39358. void ListBox::setOutlineThickness (const int outlineThickness_)
  39359. {
  39360. outlineThickness = outlineThickness_;
  39361. resized();
  39362. }
  39363. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39364. {
  39365. if (headerComponent != newHeaderComponent)
  39366. {
  39367. headerComponent = newHeaderComponent;
  39368. addAndMakeVisible (newHeaderComponent);
  39369. ListBox::resized();
  39370. }
  39371. }
  39372. void ListBox::repaintRow (const int rowNumber) throw()
  39373. {
  39374. repaint (getRowPosition (rowNumber, true));
  39375. }
  39376. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39377. {
  39378. Rectangle<int> imageArea;
  39379. const int firstRow = getRowContainingPosition (0, 0);
  39380. int i;
  39381. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39382. {
  39383. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39384. if (rowComp != 0 && isRowSelected (firstRow + i))
  39385. {
  39386. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39387. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39388. imageArea = imageArea.getUnion (rowRect);
  39389. }
  39390. }
  39391. imageArea = imageArea.getIntersection (getLocalBounds());
  39392. imageX = imageArea.getX();
  39393. imageY = imageArea.getY();
  39394. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39395. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39396. {
  39397. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39398. if (rowComp != 0 && isRowSelected (firstRow + i))
  39399. {
  39400. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39401. Graphics g (snapshot);
  39402. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39403. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39404. {
  39405. g.beginTransparencyLayer (0.6f);
  39406. rowComp->paintEntireComponent (g, false);
  39407. g.endTransparencyLayer();
  39408. }
  39409. }
  39410. }
  39411. return snapshot;
  39412. }
  39413. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39414. {
  39415. DragAndDropContainer* const dragContainer
  39416. = DragAndDropContainer::findParentDragContainerFor (this);
  39417. if (dragContainer != 0)
  39418. {
  39419. int x, y;
  39420. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39421. MouseEvent e2 (e.getEventRelativeTo (this));
  39422. const Point<int> p (x - e2.x, y - e2.y);
  39423. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39424. }
  39425. else
  39426. {
  39427. // to be able to do a drag-and-drop operation, the listbox needs to
  39428. // be inside a component which is also a DragAndDropContainer.
  39429. jassertfalse;
  39430. }
  39431. }
  39432. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39433. {
  39434. (void) existingComponentToUpdate;
  39435. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39436. return 0;
  39437. }
  39438. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39439. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39440. void ListBoxModel::backgroundClicked() {}
  39441. void ListBoxModel::selectedRowsChanged (int) {}
  39442. void ListBoxModel::deleteKeyPressed (int) {}
  39443. void ListBoxModel::returnKeyPressed (int) {}
  39444. void ListBoxModel::listWasScrolled() {}
  39445. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39446. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39447. END_JUCE_NAMESPACE
  39448. /*** End of inlined file: juce_ListBox.cpp ***/
  39449. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39450. BEGIN_JUCE_NAMESPACE
  39451. ProgressBar::ProgressBar (double& progress_)
  39452. : progress (progress_),
  39453. displayPercentage (true),
  39454. lastCallbackTime (0)
  39455. {
  39456. currentValue = jlimit (0.0, 1.0, progress);
  39457. }
  39458. ProgressBar::~ProgressBar()
  39459. {
  39460. }
  39461. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39462. {
  39463. displayPercentage = shouldDisplayPercentage;
  39464. repaint();
  39465. }
  39466. void ProgressBar::setTextToDisplay (const String& text)
  39467. {
  39468. displayPercentage = false;
  39469. displayedMessage = text;
  39470. }
  39471. void ProgressBar::lookAndFeelChanged()
  39472. {
  39473. setOpaque (findColour (backgroundColourId).isOpaque());
  39474. }
  39475. void ProgressBar::colourChanged()
  39476. {
  39477. lookAndFeelChanged();
  39478. }
  39479. void ProgressBar::paint (Graphics& g)
  39480. {
  39481. String text;
  39482. if (displayPercentage)
  39483. {
  39484. if (currentValue >= 0 && currentValue <= 1.0)
  39485. text << roundToInt (currentValue * 100.0) << '%';
  39486. }
  39487. else
  39488. {
  39489. text = displayedMessage;
  39490. }
  39491. getLookAndFeel().drawProgressBar (g, *this,
  39492. getWidth(), getHeight(),
  39493. currentValue, text);
  39494. }
  39495. void ProgressBar::visibilityChanged()
  39496. {
  39497. if (isVisible())
  39498. startTimer (30);
  39499. else
  39500. stopTimer();
  39501. }
  39502. void ProgressBar::timerCallback()
  39503. {
  39504. double newProgress = progress;
  39505. const uint32 now = Time::getMillisecondCounter();
  39506. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39507. lastCallbackTime = now;
  39508. if (currentValue != newProgress
  39509. || newProgress < 0 || newProgress >= 1.0
  39510. || currentMessage != displayedMessage)
  39511. {
  39512. if (currentValue < newProgress
  39513. && newProgress >= 0 && newProgress < 1.0
  39514. && currentValue >= 0 && currentValue < 1.0)
  39515. {
  39516. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39517. newProgress);
  39518. }
  39519. currentValue = newProgress;
  39520. currentMessage = displayedMessage;
  39521. repaint();
  39522. }
  39523. }
  39524. END_JUCE_NAMESPACE
  39525. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39526. /*** Start of inlined file: juce_Slider.cpp ***/
  39527. BEGIN_JUCE_NAMESPACE
  39528. class SliderPopupDisplayComponent : public BubbleComponent
  39529. {
  39530. public:
  39531. SliderPopupDisplayComponent (Slider* const owner_)
  39532. : owner (owner_),
  39533. font (15.0f, Font::bold)
  39534. {
  39535. setAlwaysOnTop (true);
  39536. }
  39537. ~SliderPopupDisplayComponent()
  39538. {
  39539. }
  39540. void paintContent (Graphics& g, int w, int h)
  39541. {
  39542. g.setFont (font);
  39543. g.setColour (Colours::black);
  39544. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39545. }
  39546. void getContentSize (int& w, int& h)
  39547. {
  39548. w = font.getStringWidth (text) + 18;
  39549. h = (int) (font.getHeight() * 1.6f);
  39550. }
  39551. void updatePosition (const String& newText)
  39552. {
  39553. if (text != newText)
  39554. {
  39555. text = newText;
  39556. repaint();
  39557. }
  39558. BubbleComponent::setPosition (owner);
  39559. }
  39560. private:
  39561. Slider* owner;
  39562. Font font;
  39563. String text;
  39564. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39565. };
  39566. Slider::Slider (const String& name)
  39567. : Component (name),
  39568. lastCurrentValue (0),
  39569. lastValueMin (0),
  39570. lastValueMax (0),
  39571. minimum (0),
  39572. maximum (10),
  39573. interval (0),
  39574. skewFactor (1.0),
  39575. velocityModeSensitivity (1.0),
  39576. velocityModeOffset (0.0),
  39577. velocityModeThreshold (1),
  39578. rotaryStart (float_Pi * 1.2f),
  39579. rotaryEnd (float_Pi * 2.8f),
  39580. numDecimalPlaces (7),
  39581. sliderRegionStart (0),
  39582. sliderRegionSize (1),
  39583. sliderBeingDragged (-1),
  39584. pixelsForFullDragExtent (250),
  39585. style (LinearHorizontal),
  39586. textBoxPos (TextBoxLeft),
  39587. textBoxWidth (80),
  39588. textBoxHeight (20),
  39589. incDecButtonMode (incDecButtonsNotDraggable),
  39590. editableText (true),
  39591. doubleClickToValue (false),
  39592. isVelocityBased (false),
  39593. userKeyOverridesVelocity (true),
  39594. rotaryStop (true),
  39595. incDecButtonsSideBySide (false),
  39596. sendChangeOnlyOnRelease (false),
  39597. popupDisplayEnabled (false),
  39598. menuEnabled (false),
  39599. menuShown (false),
  39600. scrollWheelEnabled (true),
  39601. snapsToMousePos (true),
  39602. popupDisplay (0),
  39603. parentForPopupDisplay (0)
  39604. {
  39605. setWantsKeyboardFocus (false);
  39606. setRepaintsOnMouseActivity (true);
  39607. lookAndFeelChanged();
  39608. updateText();
  39609. currentValue.addListener (this);
  39610. valueMin.addListener (this);
  39611. valueMax.addListener (this);
  39612. }
  39613. Slider::~Slider()
  39614. {
  39615. currentValue.removeListener (this);
  39616. valueMin.removeListener (this);
  39617. valueMax.removeListener (this);
  39618. popupDisplay = 0;
  39619. }
  39620. void Slider::handleAsyncUpdate()
  39621. {
  39622. cancelPendingUpdate();
  39623. Component::BailOutChecker checker (this);
  39624. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39625. }
  39626. void Slider::sendDragStart()
  39627. {
  39628. startedDragging();
  39629. Component::BailOutChecker checker (this);
  39630. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39631. }
  39632. void Slider::sendDragEnd()
  39633. {
  39634. stoppedDragging();
  39635. sliderBeingDragged = -1;
  39636. Component::BailOutChecker checker (this);
  39637. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39638. }
  39639. void Slider::addListener (SliderListener* const listener)
  39640. {
  39641. listeners.add (listener);
  39642. }
  39643. void Slider::removeListener (SliderListener* const listener)
  39644. {
  39645. listeners.remove (listener);
  39646. }
  39647. void Slider::setSliderStyle (const SliderStyle newStyle)
  39648. {
  39649. if (style != newStyle)
  39650. {
  39651. style = newStyle;
  39652. repaint();
  39653. lookAndFeelChanged();
  39654. }
  39655. }
  39656. void Slider::setRotaryParameters (const float startAngleRadians,
  39657. const float endAngleRadians,
  39658. const bool stopAtEnd)
  39659. {
  39660. // make sure the values are sensible..
  39661. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39662. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39663. jassert (rotaryStart < rotaryEnd);
  39664. rotaryStart = startAngleRadians;
  39665. rotaryEnd = endAngleRadians;
  39666. rotaryStop = stopAtEnd;
  39667. }
  39668. void Slider::setVelocityBasedMode (const bool velBased)
  39669. {
  39670. isVelocityBased = velBased;
  39671. }
  39672. void Slider::setVelocityModeParameters (const double sensitivity,
  39673. const int threshold,
  39674. const double offset,
  39675. const bool userCanPressKeyToSwapMode)
  39676. {
  39677. jassert (threshold >= 0);
  39678. jassert (sensitivity > 0);
  39679. jassert (offset >= 0);
  39680. velocityModeSensitivity = sensitivity;
  39681. velocityModeOffset = offset;
  39682. velocityModeThreshold = threshold;
  39683. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39684. }
  39685. void Slider::setSkewFactor (const double factor)
  39686. {
  39687. skewFactor = factor;
  39688. }
  39689. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39690. {
  39691. if (maximum > minimum)
  39692. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39693. / (maximum - minimum));
  39694. }
  39695. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39696. {
  39697. jassert (distanceForFullScaleDrag > 0);
  39698. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39699. }
  39700. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39701. {
  39702. if (incDecButtonMode != mode)
  39703. {
  39704. incDecButtonMode = mode;
  39705. lookAndFeelChanged();
  39706. }
  39707. }
  39708. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39709. const bool isReadOnly,
  39710. const int textEntryBoxWidth,
  39711. const int textEntryBoxHeight)
  39712. {
  39713. if (textBoxPos != newPosition
  39714. || editableText != (! isReadOnly)
  39715. || textBoxWidth != textEntryBoxWidth
  39716. || textBoxHeight != textEntryBoxHeight)
  39717. {
  39718. textBoxPos = newPosition;
  39719. editableText = ! isReadOnly;
  39720. textBoxWidth = textEntryBoxWidth;
  39721. textBoxHeight = textEntryBoxHeight;
  39722. repaint();
  39723. lookAndFeelChanged();
  39724. }
  39725. }
  39726. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39727. {
  39728. editableText = shouldBeEditable;
  39729. if (valueBox != 0)
  39730. valueBox->setEditable (shouldBeEditable && isEnabled());
  39731. }
  39732. void Slider::showTextBox()
  39733. {
  39734. jassert (editableText); // this should probably be avoided in read-only sliders.
  39735. if (valueBox != 0)
  39736. valueBox->showEditor();
  39737. }
  39738. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39739. {
  39740. if (valueBox != 0)
  39741. {
  39742. valueBox->hideEditor (discardCurrentEditorContents);
  39743. if (discardCurrentEditorContents)
  39744. updateText();
  39745. }
  39746. }
  39747. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39748. {
  39749. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39750. }
  39751. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39752. {
  39753. snapsToMousePos = shouldSnapToMouse;
  39754. }
  39755. void Slider::setPopupDisplayEnabled (const bool enabled,
  39756. Component* const parentComponentToUse)
  39757. {
  39758. popupDisplayEnabled = enabled;
  39759. parentForPopupDisplay = parentComponentToUse;
  39760. }
  39761. void Slider::colourChanged()
  39762. {
  39763. lookAndFeelChanged();
  39764. }
  39765. void Slider::lookAndFeelChanged()
  39766. {
  39767. LookAndFeel& lf = getLookAndFeel();
  39768. if (textBoxPos != NoTextBox)
  39769. {
  39770. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39771. : getTextFromValue (currentValue.getValue()));
  39772. valueBox = 0;
  39773. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39774. valueBox->setWantsKeyboardFocus (false);
  39775. valueBox->setText (previousTextBoxContent, false);
  39776. valueBox->setEditable (editableText && isEnabled());
  39777. valueBox->addListener (this);
  39778. if (style == LinearBar)
  39779. valueBox->addMouseListener (this, false);
  39780. valueBox->setTooltip (getTooltip());
  39781. }
  39782. else
  39783. {
  39784. valueBox = 0;
  39785. }
  39786. if (style == IncDecButtons)
  39787. {
  39788. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39789. incButton->addListener (this);
  39790. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39791. decButton->addListener (this);
  39792. if (incDecButtonMode != incDecButtonsNotDraggable)
  39793. {
  39794. incButton->addMouseListener (this, false);
  39795. decButton->addMouseListener (this, false);
  39796. }
  39797. else
  39798. {
  39799. incButton->setRepeatSpeed (300, 100, 20);
  39800. incButton->addMouseListener (decButton, false);
  39801. decButton->setRepeatSpeed (300, 100, 20);
  39802. decButton->addMouseListener (incButton, false);
  39803. }
  39804. incButton->setTooltip (getTooltip());
  39805. decButton->setTooltip (getTooltip());
  39806. }
  39807. else
  39808. {
  39809. incButton = 0;
  39810. decButton = 0;
  39811. }
  39812. setComponentEffect (lf.getSliderEffect());
  39813. resized();
  39814. repaint();
  39815. }
  39816. void Slider::setRange (const double newMin,
  39817. const double newMax,
  39818. const double newInt)
  39819. {
  39820. if (minimum != newMin
  39821. || maximum != newMax
  39822. || interval != newInt)
  39823. {
  39824. minimum = newMin;
  39825. maximum = newMax;
  39826. interval = newInt;
  39827. // figure out the number of DPs needed to display all values at this
  39828. // interval setting.
  39829. numDecimalPlaces = 7;
  39830. if (newInt != 0)
  39831. {
  39832. int v = abs ((int) (newInt * 10000000));
  39833. while ((v % 10) == 0)
  39834. {
  39835. --numDecimalPlaces;
  39836. v /= 10;
  39837. }
  39838. }
  39839. // keep the current values inside the new range..
  39840. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39841. {
  39842. setValue (getValue(), false, false);
  39843. }
  39844. else
  39845. {
  39846. setMinValue (getMinValue(), false, false);
  39847. setMaxValue (getMaxValue(), false, false);
  39848. }
  39849. updateText();
  39850. }
  39851. }
  39852. void Slider::triggerChangeMessage (const bool synchronous)
  39853. {
  39854. if (synchronous)
  39855. handleAsyncUpdate();
  39856. else
  39857. triggerAsyncUpdate();
  39858. valueChanged();
  39859. }
  39860. void Slider::valueChanged (Value& value)
  39861. {
  39862. if (value.refersToSameSourceAs (currentValue))
  39863. {
  39864. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39865. setValue (currentValue.getValue(), false, false);
  39866. }
  39867. else if (value.refersToSameSourceAs (valueMin))
  39868. setMinValue (valueMin.getValue(), false, false, true);
  39869. else if (value.refersToSameSourceAs (valueMax))
  39870. setMaxValue (valueMax.getValue(), false, false, true);
  39871. }
  39872. double Slider::getValue() const
  39873. {
  39874. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39875. // methods to get the two values.
  39876. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39877. return currentValue.getValue();
  39878. }
  39879. void Slider::setValue (double newValue,
  39880. const bool sendUpdateMessage,
  39881. const bool sendMessageSynchronously)
  39882. {
  39883. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39884. // methods to set the two values.
  39885. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39886. newValue = constrainedValue (newValue);
  39887. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39888. {
  39889. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39890. newValue = jlimit ((double) valueMin.getValue(),
  39891. (double) valueMax.getValue(),
  39892. newValue);
  39893. }
  39894. if (newValue != lastCurrentValue)
  39895. {
  39896. if (valueBox != 0)
  39897. valueBox->hideEditor (true);
  39898. lastCurrentValue = newValue;
  39899. currentValue = newValue;
  39900. updateText();
  39901. repaint();
  39902. if (popupDisplay != 0)
  39903. {
  39904. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39905. ->updatePosition (getTextFromValue (newValue));
  39906. popupDisplay->repaint();
  39907. }
  39908. if (sendUpdateMessage)
  39909. triggerChangeMessage (sendMessageSynchronously);
  39910. }
  39911. }
  39912. double Slider::getMinValue() const
  39913. {
  39914. // The minimum value only applies to sliders that are in two- or three-value mode.
  39915. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39916. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39917. return valueMin.getValue();
  39918. }
  39919. double Slider::getMaxValue() const
  39920. {
  39921. // The maximum value only applies to sliders that are in two- or three-value mode.
  39922. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39923. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39924. return valueMax.getValue();
  39925. }
  39926. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39927. {
  39928. // The minimum value only applies to sliders that are in two- or three-value mode.
  39929. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39930. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39931. newValue = constrainedValue (newValue);
  39932. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39933. {
  39934. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39935. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39936. newValue = jmin ((double) valueMax.getValue(), newValue);
  39937. }
  39938. else
  39939. {
  39940. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39941. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39942. newValue = jmin (lastCurrentValue, newValue);
  39943. }
  39944. if (lastValueMin != newValue)
  39945. {
  39946. lastValueMin = newValue;
  39947. valueMin = newValue;
  39948. repaint();
  39949. if (popupDisplay != 0)
  39950. {
  39951. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39952. ->updatePosition (getTextFromValue (newValue));
  39953. popupDisplay->repaint();
  39954. }
  39955. if (sendUpdateMessage)
  39956. triggerChangeMessage (sendMessageSynchronously);
  39957. }
  39958. }
  39959. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39960. {
  39961. // The maximum value only applies to sliders that are in two- or three-value mode.
  39962. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39963. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39964. newValue = constrainedValue (newValue);
  39965. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39966. {
  39967. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39968. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39969. newValue = jmax ((double) valueMin.getValue(), newValue);
  39970. }
  39971. else
  39972. {
  39973. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39974. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39975. newValue = jmax (lastCurrentValue, newValue);
  39976. }
  39977. if (lastValueMax != newValue)
  39978. {
  39979. lastValueMax = newValue;
  39980. valueMax = newValue;
  39981. repaint();
  39982. if (popupDisplay != 0)
  39983. {
  39984. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39985. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39986. popupDisplay->repaint();
  39987. }
  39988. if (sendUpdateMessage)
  39989. triggerChangeMessage (sendMessageSynchronously);
  39990. }
  39991. }
  39992. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39993. const double valueToSetOnDoubleClick)
  39994. {
  39995. doubleClickToValue = isDoubleClickEnabled;
  39996. doubleClickReturnValue = valueToSetOnDoubleClick;
  39997. }
  39998. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39999. {
  40000. isEnabled_ = doubleClickToValue;
  40001. return doubleClickReturnValue;
  40002. }
  40003. void Slider::updateText()
  40004. {
  40005. if (valueBox != 0)
  40006. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40007. }
  40008. void Slider::setTextValueSuffix (const String& suffix)
  40009. {
  40010. if (textSuffix != suffix)
  40011. {
  40012. textSuffix = suffix;
  40013. updateText();
  40014. }
  40015. }
  40016. const String Slider::getTextValueSuffix() const
  40017. {
  40018. return textSuffix;
  40019. }
  40020. const String Slider::getTextFromValue (double v)
  40021. {
  40022. if (getNumDecimalPlacesToDisplay() > 0)
  40023. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40024. else
  40025. return String (roundToInt (v)) + getTextValueSuffix();
  40026. }
  40027. double Slider::getValueFromText (const String& text)
  40028. {
  40029. String t (text.trimStart());
  40030. if (t.endsWith (textSuffix))
  40031. t = t.substring (0, t.length() - textSuffix.length());
  40032. while (t.startsWithChar ('+'))
  40033. t = t.substring (1).trimStart();
  40034. return t.initialSectionContainingOnly ("0123456789.,-")
  40035. .getDoubleValue();
  40036. }
  40037. double Slider::proportionOfLengthToValue (double proportion)
  40038. {
  40039. if (skewFactor != 1.0 && proportion > 0.0)
  40040. proportion = exp (log (proportion) / skewFactor);
  40041. return minimum + (maximum - minimum) * proportion;
  40042. }
  40043. double Slider::valueToProportionOfLength (double value)
  40044. {
  40045. const double n = (value - minimum) / (maximum - minimum);
  40046. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40047. }
  40048. double Slider::snapValue (double attemptedValue, const bool)
  40049. {
  40050. return attemptedValue;
  40051. }
  40052. void Slider::startedDragging()
  40053. {
  40054. }
  40055. void Slider::stoppedDragging()
  40056. {
  40057. }
  40058. void Slider::valueChanged()
  40059. {
  40060. }
  40061. void Slider::enablementChanged()
  40062. {
  40063. repaint();
  40064. }
  40065. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40066. {
  40067. menuEnabled = menuEnabled_;
  40068. }
  40069. void Slider::setScrollWheelEnabled (const bool enabled)
  40070. {
  40071. scrollWheelEnabled = enabled;
  40072. }
  40073. void Slider::labelTextChanged (Label* label)
  40074. {
  40075. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40076. if (newValue != (double) currentValue.getValue())
  40077. {
  40078. sendDragStart();
  40079. setValue (newValue, true, true);
  40080. sendDragEnd();
  40081. }
  40082. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40083. }
  40084. void Slider::buttonClicked (Button* button)
  40085. {
  40086. if (style == IncDecButtons)
  40087. {
  40088. sendDragStart();
  40089. if (button == incButton)
  40090. setValue (snapValue (getValue() + interval, false), true, true);
  40091. else if (button == decButton)
  40092. setValue (snapValue (getValue() - interval, false), true, true);
  40093. sendDragEnd();
  40094. }
  40095. }
  40096. double Slider::constrainedValue (double value) const
  40097. {
  40098. if (interval > 0)
  40099. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40100. if (value <= minimum || maximum <= minimum)
  40101. value = minimum;
  40102. else if (value >= maximum)
  40103. value = maximum;
  40104. return value;
  40105. }
  40106. float Slider::getLinearSliderPos (const double value)
  40107. {
  40108. double sliderPosProportional;
  40109. if (maximum > minimum)
  40110. {
  40111. if (value < minimum)
  40112. {
  40113. sliderPosProportional = 0.0;
  40114. }
  40115. else if (value > maximum)
  40116. {
  40117. sliderPosProportional = 1.0;
  40118. }
  40119. else
  40120. {
  40121. sliderPosProportional = valueToProportionOfLength (value);
  40122. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40123. }
  40124. }
  40125. else
  40126. {
  40127. sliderPosProportional = 0.5;
  40128. }
  40129. if (isVertical() || style == IncDecButtons)
  40130. sliderPosProportional = 1.0 - sliderPosProportional;
  40131. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40132. }
  40133. bool Slider::isHorizontal() const
  40134. {
  40135. return style == LinearHorizontal
  40136. || style == LinearBar
  40137. || style == TwoValueHorizontal
  40138. || style == ThreeValueHorizontal;
  40139. }
  40140. bool Slider::isVertical() const
  40141. {
  40142. return style == LinearVertical
  40143. || style == TwoValueVertical
  40144. || style == ThreeValueVertical;
  40145. }
  40146. bool Slider::incDecDragDirectionIsHorizontal() const
  40147. {
  40148. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40149. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40150. }
  40151. float Slider::getPositionOfValue (const double value)
  40152. {
  40153. if (isHorizontal() || isVertical())
  40154. {
  40155. return getLinearSliderPos (value);
  40156. }
  40157. else
  40158. {
  40159. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40160. return 0.0f;
  40161. }
  40162. }
  40163. void Slider::paint (Graphics& g)
  40164. {
  40165. if (style != IncDecButtons)
  40166. {
  40167. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40168. {
  40169. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40170. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40171. getLookAndFeel().drawRotarySlider (g,
  40172. sliderRect.getX(),
  40173. sliderRect.getY(),
  40174. sliderRect.getWidth(),
  40175. sliderRect.getHeight(),
  40176. sliderPos,
  40177. rotaryStart, rotaryEnd,
  40178. *this);
  40179. }
  40180. else
  40181. {
  40182. getLookAndFeel().drawLinearSlider (g,
  40183. sliderRect.getX(),
  40184. sliderRect.getY(),
  40185. sliderRect.getWidth(),
  40186. sliderRect.getHeight(),
  40187. getLinearSliderPos (lastCurrentValue),
  40188. getLinearSliderPos (lastValueMin),
  40189. getLinearSliderPos (lastValueMax),
  40190. style,
  40191. *this);
  40192. }
  40193. if (style == LinearBar && valueBox == 0)
  40194. {
  40195. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40196. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40197. }
  40198. }
  40199. }
  40200. void Slider::resized()
  40201. {
  40202. int minXSpace = 0;
  40203. int minYSpace = 0;
  40204. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40205. minXSpace = 30;
  40206. else
  40207. minYSpace = 15;
  40208. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40209. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40210. if (style == LinearBar)
  40211. {
  40212. if (valueBox != 0)
  40213. valueBox->setBounds (getLocalBounds());
  40214. }
  40215. else
  40216. {
  40217. if (textBoxPos == NoTextBox)
  40218. {
  40219. sliderRect = getLocalBounds();
  40220. }
  40221. else if (textBoxPos == TextBoxLeft)
  40222. {
  40223. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40224. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40225. }
  40226. else if (textBoxPos == TextBoxRight)
  40227. {
  40228. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40229. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40230. }
  40231. else if (textBoxPos == TextBoxAbove)
  40232. {
  40233. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40234. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40235. }
  40236. else if (textBoxPos == TextBoxBelow)
  40237. {
  40238. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40239. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40240. }
  40241. }
  40242. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40243. if (style == LinearBar)
  40244. {
  40245. const int barIndent = 1;
  40246. sliderRegionStart = barIndent;
  40247. sliderRegionSize = getWidth() - barIndent * 2;
  40248. sliderRect.setBounds (sliderRegionStart, barIndent,
  40249. sliderRegionSize, getHeight() - barIndent * 2);
  40250. }
  40251. else if (isHorizontal())
  40252. {
  40253. sliderRegionStart = sliderRect.getX() + indent;
  40254. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40255. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40256. sliderRegionSize, sliderRect.getHeight());
  40257. }
  40258. else if (isVertical())
  40259. {
  40260. sliderRegionStart = sliderRect.getY() + indent;
  40261. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40262. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40263. sliderRect.getWidth(), sliderRegionSize);
  40264. }
  40265. else
  40266. {
  40267. sliderRegionStart = 0;
  40268. sliderRegionSize = 100;
  40269. }
  40270. if (style == IncDecButtons)
  40271. {
  40272. Rectangle<int> buttonRect (sliderRect);
  40273. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40274. buttonRect.expand (-2, 0);
  40275. else
  40276. buttonRect.expand (0, -2);
  40277. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40278. if (incDecButtonsSideBySide)
  40279. {
  40280. decButton->setBounds (buttonRect.getX(),
  40281. buttonRect.getY(),
  40282. buttonRect.getWidth() / 2,
  40283. buttonRect.getHeight());
  40284. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40285. incButton->setBounds (buttonRect.getCentreX(),
  40286. buttonRect.getY(),
  40287. buttonRect.getWidth() / 2,
  40288. buttonRect.getHeight());
  40289. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40290. }
  40291. else
  40292. {
  40293. incButton->setBounds (buttonRect.getX(),
  40294. buttonRect.getY(),
  40295. buttonRect.getWidth(),
  40296. buttonRect.getHeight() / 2);
  40297. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40298. decButton->setBounds (buttonRect.getX(),
  40299. buttonRect.getCentreY(),
  40300. buttonRect.getWidth(),
  40301. buttonRect.getHeight() / 2);
  40302. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40303. }
  40304. }
  40305. }
  40306. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40307. {
  40308. repaint();
  40309. }
  40310. void Slider::mouseDown (const MouseEvent& e)
  40311. {
  40312. mouseWasHidden = false;
  40313. incDecDragged = false;
  40314. mouseXWhenLastDragged = e.x;
  40315. mouseYWhenLastDragged = e.y;
  40316. mouseDragStartX = e.getMouseDownX();
  40317. mouseDragStartY = e.getMouseDownY();
  40318. if (isEnabled())
  40319. {
  40320. if (e.mods.isPopupMenu() && menuEnabled)
  40321. {
  40322. menuShown = true;
  40323. PopupMenu m;
  40324. m.setLookAndFeel (&getLookAndFeel());
  40325. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40326. m.addSeparator();
  40327. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40328. {
  40329. PopupMenu rotaryMenu;
  40330. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40331. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40332. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40333. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40334. }
  40335. const int r = m.show();
  40336. if (r == 1)
  40337. {
  40338. setVelocityBasedMode (! isVelocityBased);
  40339. }
  40340. else if (r == 2)
  40341. {
  40342. setSliderStyle (Rotary);
  40343. }
  40344. else if (r == 3)
  40345. {
  40346. setSliderStyle (RotaryHorizontalDrag);
  40347. }
  40348. else if (r == 4)
  40349. {
  40350. setSliderStyle (RotaryVerticalDrag);
  40351. }
  40352. }
  40353. else if (maximum > minimum)
  40354. {
  40355. menuShown = false;
  40356. if (valueBox != 0)
  40357. valueBox->hideEditor (true);
  40358. sliderBeingDragged = 0;
  40359. if (style == TwoValueHorizontal
  40360. || style == TwoValueVertical
  40361. || style == ThreeValueHorizontal
  40362. || style == ThreeValueVertical)
  40363. {
  40364. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40365. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40366. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40367. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40368. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40369. {
  40370. if (maxPosDistance <= minPosDistance)
  40371. sliderBeingDragged = 2;
  40372. else
  40373. sliderBeingDragged = 1;
  40374. }
  40375. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40376. {
  40377. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40378. sliderBeingDragged = 1;
  40379. else if (normalPosDistance >= maxPosDistance)
  40380. sliderBeingDragged = 2;
  40381. }
  40382. }
  40383. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40384. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40385. * valueToProportionOfLength (currentValue.getValue());
  40386. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40387. : ((sliderBeingDragged == 1) ? valueMin
  40388. : currentValue)).getValue();
  40389. valueOnMouseDown = valueWhenLastDragged;
  40390. if (popupDisplayEnabled)
  40391. {
  40392. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40393. popupDisplay = popup;
  40394. if (parentForPopupDisplay != 0)
  40395. {
  40396. parentForPopupDisplay->addChildComponent (popup);
  40397. }
  40398. else
  40399. {
  40400. popup->addToDesktop (0);
  40401. }
  40402. popup->setVisible (true);
  40403. }
  40404. sendDragStart();
  40405. mouseDrag (e);
  40406. }
  40407. }
  40408. }
  40409. void Slider::mouseUp (const MouseEvent&)
  40410. {
  40411. if (isEnabled()
  40412. && (! menuShown)
  40413. && (maximum > minimum)
  40414. && (style != IncDecButtons || incDecDragged))
  40415. {
  40416. restoreMouseIfHidden();
  40417. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40418. triggerChangeMessage (false);
  40419. sendDragEnd();
  40420. popupDisplay = 0;
  40421. if (style == IncDecButtons)
  40422. {
  40423. incButton->setState (Button::buttonNormal);
  40424. decButton->setState (Button::buttonNormal);
  40425. }
  40426. }
  40427. }
  40428. void Slider::restoreMouseIfHidden()
  40429. {
  40430. if (mouseWasHidden)
  40431. {
  40432. mouseWasHidden = false;
  40433. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40434. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40435. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40436. : ((sliderBeingDragged == 1) ? getMinValue()
  40437. : (double) currentValue.getValue());
  40438. Point<int> mousePos;
  40439. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40440. {
  40441. mousePos = Desktop::getLastMouseDownPosition();
  40442. if (style == RotaryHorizontalDrag)
  40443. {
  40444. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40445. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40446. }
  40447. else
  40448. {
  40449. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40450. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40451. }
  40452. }
  40453. else
  40454. {
  40455. const int pixelPos = (int) getLinearSliderPos (pos);
  40456. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40457. isVertical() ? pixelPos : (getHeight() / 2)));
  40458. }
  40459. Desktop::setMousePosition (mousePos);
  40460. }
  40461. }
  40462. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40463. {
  40464. if (isEnabled()
  40465. && style != IncDecButtons
  40466. && style != Rotary
  40467. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40468. {
  40469. restoreMouseIfHidden();
  40470. }
  40471. }
  40472. namespace SliderHelpers
  40473. {
  40474. double smallestAngleBetween (double a1, double a2) throw()
  40475. {
  40476. return jmin (std::abs (a1 - a2),
  40477. std::abs (a1 + double_Pi * 2.0 - a2),
  40478. std::abs (a2 + double_Pi * 2.0 - a1));
  40479. }
  40480. }
  40481. void Slider::mouseDrag (const MouseEvent& e)
  40482. {
  40483. if (isEnabled()
  40484. && (! menuShown)
  40485. && (maximum > minimum))
  40486. {
  40487. if (style == Rotary)
  40488. {
  40489. int dx = e.x - sliderRect.getCentreX();
  40490. int dy = e.y - sliderRect.getCentreY();
  40491. if (dx * dx + dy * dy > 25)
  40492. {
  40493. double angle = std::atan2 ((double) dx, (double) -dy);
  40494. while (angle < 0.0)
  40495. angle += double_Pi * 2.0;
  40496. if (rotaryStop && ! e.mouseWasClicked())
  40497. {
  40498. if (std::abs (angle - lastAngle) > double_Pi)
  40499. {
  40500. if (angle >= lastAngle)
  40501. angle -= double_Pi * 2.0;
  40502. else
  40503. angle += double_Pi * 2.0;
  40504. }
  40505. if (angle >= lastAngle)
  40506. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40507. else
  40508. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40509. }
  40510. else
  40511. {
  40512. while (angle < rotaryStart)
  40513. angle += double_Pi * 2.0;
  40514. if (angle > rotaryEnd)
  40515. {
  40516. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40517. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40518. angle = rotaryStart;
  40519. else
  40520. angle = rotaryEnd;
  40521. }
  40522. }
  40523. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40524. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40525. lastAngle = angle;
  40526. }
  40527. }
  40528. else
  40529. {
  40530. if (style == LinearBar && e.mouseWasClicked()
  40531. && valueBox != 0 && valueBox->isEditable())
  40532. return;
  40533. if (style == IncDecButtons && ! incDecDragged)
  40534. {
  40535. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40536. return;
  40537. incDecDragged = true;
  40538. mouseDragStartX = e.x;
  40539. mouseDragStartY = e.y;
  40540. }
  40541. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40542. : false))
  40543. || ((maximum - minimum) / sliderRegionSize < interval))
  40544. {
  40545. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40546. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40547. if (style == RotaryHorizontalDrag
  40548. || style == RotaryVerticalDrag
  40549. || style == IncDecButtons
  40550. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40551. && ! snapsToMousePos))
  40552. {
  40553. const int mouseDiff = (style == RotaryHorizontalDrag
  40554. || style == LinearHorizontal
  40555. || style == LinearBar
  40556. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40557. ? e.x - mouseDragStartX
  40558. : mouseDragStartY - e.y;
  40559. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40560. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40561. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40562. if (style == IncDecButtons)
  40563. {
  40564. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40565. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40566. }
  40567. }
  40568. else
  40569. {
  40570. if (isVertical())
  40571. scaledMousePos = 1.0 - scaledMousePos;
  40572. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40573. }
  40574. }
  40575. else
  40576. {
  40577. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40578. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40579. ? e.x - mouseXWhenLastDragged
  40580. : e.y - mouseYWhenLastDragged;
  40581. const double maxSpeed = jmax (200, sliderRegionSize);
  40582. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40583. if (speed != 0)
  40584. {
  40585. speed = 0.2 * velocityModeSensitivity
  40586. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40587. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40588. / maxSpeed))));
  40589. if (mouseDiff < 0)
  40590. speed = -speed;
  40591. if (isVertical() || style == RotaryVerticalDrag
  40592. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40593. speed = -speed;
  40594. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40595. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40596. e.source.enableUnboundedMouseMovement (true, false);
  40597. mouseWasHidden = true;
  40598. }
  40599. }
  40600. }
  40601. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40602. if (sliderBeingDragged == 0)
  40603. {
  40604. setValue (snapValue (valueWhenLastDragged, true),
  40605. ! sendChangeOnlyOnRelease, true);
  40606. }
  40607. else if (sliderBeingDragged == 1)
  40608. {
  40609. setMinValue (snapValue (valueWhenLastDragged, true),
  40610. ! sendChangeOnlyOnRelease, false, true);
  40611. if (e.mods.isShiftDown())
  40612. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40613. else
  40614. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40615. }
  40616. else
  40617. {
  40618. jassert (sliderBeingDragged == 2);
  40619. setMaxValue (snapValue (valueWhenLastDragged, true),
  40620. ! sendChangeOnlyOnRelease, false, true);
  40621. if (e.mods.isShiftDown())
  40622. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40623. else
  40624. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40625. }
  40626. mouseXWhenLastDragged = e.x;
  40627. mouseYWhenLastDragged = e.y;
  40628. }
  40629. }
  40630. void Slider::mouseDoubleClick (const MouseEvent&)
  40631. {
  40632. if (doubleClickToValue
  40633. && isEnabled()
  40634. && style != IncDecButtons
  40635. && minimum <= doubleClickReturnValue
  40636. && maximum >= doubleClickReturnValue)
  40637. {
  40638. sendDragStart();
  40639. setValue (doubleClickReturnValue, true, true);
  40640. sendDragEnd();
  40641. }
  40642. }
  40643. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40644. {
  40645. if (scrollWheelEnabled && isEnabled()
  40646. && style != TwoValueHorizontal
  40647. && style != TwoValueVertical)
  40648. {
  40649. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40650. {
  40651. if (valueBox != 0)
  40652. valueBox->hideEditor (false);
  40653. const double value = (double) currentValue.getValue();
  40654. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40655. const double currentPos = valueToProportionOfLength (value);
  40656. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40657. double delta = (newValue != value)
  40658. ? jmax (std::abs (newValue - value), interval) : 0;
  40659. if (value > newValue)
  40660. delta = -delta;
  40661. sendDragStart();
  40662. setValue (snapValue (value + delta, false), true, true);
  40663. sendDragEnd();
  40664. }
  40665. }
  40666. else
  40667. {
  40668. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40669. }
  40670. }
  40671. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40672. {
  40673. }
  40674. void SliderListener::sliderDragEnded (Slider*)
  40675. {
  40676. }
  40677. END_JUCE_NAMESPACE
  40678. /*** End of inlined file: juce_Slider.cpp ***/
  40679. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40680. BEGIN_JUCE_NAMESPACE
  40681. class DragOverlayComp : public Component
  40682. {
  40683. public:
  40684. DragOverlayComp (const Image& image_)
  40685. : image (image_)
  40686. {
  40687. image.duplicateIfShared();
  40688. image.multiplyAllAlphas (0.8f);
  40689. setAlwaysOnTop (true);
  40690. }
  40691. void paint (Graphics& g)
  40692. {
  40693. g.drawImageAt (image, 0, 0);
  40694. }
  40695. private:
  40696. Image image;
  40697. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40698. };
  40699. TableHeaderComponent::TableHeaderComponent()
  40700. : columnsChanged (false),
  40701. columnsResized (false),
  40702. sortChanged (false),
  40703. menuActive (true),
  40704. stretchToFit (false),
  40705. columnIdBeingResized (0),
  40706. columnIdBeingDragged (0),
  40707. columnIdUnderMouse (0),
  40708. lastDeliberateWidth (0)
  40709. {
  40710. }
  40711. TableHeaderComponent::~TableHeaderComponent()
  40712. {
  40713. dragOverlayComp = 0;
  40714. }
  40715. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40716. {
  40717. menuActive = hasMenu;
  40718. }
  40719. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40720. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40721. {
  40722. if (onlyCountVisibleColumns)
  40723. {
  40724. int num = 0;
  40725. for (int i = columns.size(); --i >= 0;)
  40726. if (columns.getUnchecked(i)->isVisible())
  40727. ++num;
  40728. return num;
  40729. }
  40730. else
  40731. {
  40732. return columns.size();
  40733. }
  40734. }
  40735. const String TableHeaderComponent::getColumnName (const int columnId) const
  40736. {
  40737. const ColumnInfo* const ci = getInfoForId (columnId);
  40738. return ci != 0 ? ci->name : String::empty;
  40739. }
  40740. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40741. {
  40742. ColumnInfo* const ci = getInfoForId (columnId);
  40743. if (ci != 0 && ci->name != newName)
  40744. {
  40745. ci->name = newName;
  40746. sendColumnsChanged();
  40747. }
  40748. }
  40749. void TableHeaderComponent::addColumn (const String& columnName,
  40750. const int columnId,
  40751. const int width,
  40752. const int minimumWidth,
  40753. const int maximumWidth,
  40754. const int propertyFlags,
  40755. const int insertIndex)
  40756. {
  40757. // can't have a duplicate or null ID!
  40758. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40759. jassert (width > 0);
  40760. ColumnInfo* const ci = new ColumnInfo();
  40761. ci->name = columnName;
  40762. ci->id = columnId;
  40763. ci->width = width;
  40764. ci->lastDeliberateWidth = width;
  40765. ci->minimumWidth = minimumWidth;
  40766. ci->maximumWidth = maximumWidth;
  40767. if (ci->maximumWidth < 0)
  40768. ci->maximumWidth = std::numeric_limits<int>::max();
  40769. jassert (ci->maximumWidth >= ci->minimumWidth);
  40770. ci->propertyFlags = propertyFlags;
  40771. columns.insert (insertIndex, ci);
  40772. sendColumnsChanged();
  40773. }
  40774. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40775. {
  40776. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40777. if (index >= 0)
  40778. {
  40779. columns.remove (index);
  40780. sortChanged = true;
  40781. sendColumnsChanged();
  40782. }
  40783. }
  40784. void TableHeaderComponent::removeAllColumns()
  40785. {
  40786. if (columns.size() > 0)
  40787. {
  40788. columns.clear();
  40789. sendColumnsChanged();
  40790. }
  40791. }
  40792. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40793. {
  40794. const int currentIndex = getIndexOfColumnId (columnId, false);
  40795. newIndex = visibleIndexToTotalIndex (newIndex);
  40796. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40797. {
  40798. columns.move (currentIndex, newIndex);
  40799. sendColumnsChanged();
  40800. }
  40801. }
  40802. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40803. {
  40804. const ColumnInfo* const ci = getInfoForId (columnId);
  40805. return ci != 0 ? ci->width : 0;
  40806. }
  40807. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40808. {
  40809. ColumnInfo* const ci = getInfoForId (columnId);
  40810. if (ci != 0 && ci->width != newWidth)
  40811. {
  40812. const int numColumns = getNumColumns (true);
  40813. ci->lastDeliberateWidth = ci->width
  40814. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40815. if (stretchToFit)
  40816. {
  40817. const int index = getIndexOfColumnId (columnId, true) + 1;
  40818. if (isPositiveAndBelow (index, numColumns))
  40819. {
  40820. const int x = getColumnPosition (index).getX();
  40821. if (lastDeliberateWidth == 0)
  40822. lastDeliberateWidth = getTotalWidth();
  40823. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40824. }
  40825. }
  40826. repaint();
  40827. columnsResized = true;
  40828. triggerAsyncUpdate();
  40829. }
  40830. }
  40831. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40832. {
  40833. int n = 0;
  40834. for (int i = 0; i < columns.size(); ++i)
  40835. {
  40836. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40837. {
  40838. if (columns.getUnchecked(i)->id == columnId)
  40839. return n;
  40840. ++n;
  40841. }
  40842. }
  40843. return -1;
  40844. }
  40845. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40846. {
  40847. if (onlyCountVisibleColumns)
  40848. index = visibleIndexToTotalIndex (index);
  40849. const ColumnInfo* const ci = columns [index];
  40850. return (ci != 0) ? ci->id : 0;
  40851. }
  40852. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40853. {
  40854. int x = 0, width = 0, n = 0;
  40855. for (int i = 0; i < columns.size(); ++i)
  40856. {
  40857. x += width;
  40858. if (columns.getUnchecked(i)->isVisible())
  40859. {
  40860. width = columns.getUnchecked(i)->width;
  40861. if (n++ == index)
  40862. break;
  40863. }
  40864. else
  40865. {
  40866. width = 0;
  40867. }
  40868. }
  40869. return Rectangle<int> (x, 0, width, getHeight());
  40870. }
  40871. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40872. {
  40873. if (xToFind >= 0)
  40874. {
  40875. int x = 0;
  40876. for (int i = 0; i < columns.size(); ++i)
  40877. {
  40878. const ColumnInfo* const ci = columns.getUnchecked(i);
  40879. if (ci->isVisible())
  40880. {
  40881. x += ci->width;
  40882. if (xToFind < x)
  40883. return ci->id;
  40884. }
  40885. }
  40886. }
  40887. return 0;
  40888. }
  40889. int TableHeaderComponent::getTotalWidth() const
  40890. {
  40891. int w = 0;
  40892. for (int i = columns.size(); --i >= 0;)
  40893. if (columns.getUnchecked(i)->isVisible())
  40894. w += columns.getUnchecked(i)->width;
  40895. return w;
  40896. }
  40897. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40898. {
  40899. stretchToFit = shouldStretchToFit;
  40900. lastDeliberateWidth = getTotalWidth();
  40901. resized();
  40902. }
  40903. bool TableHeaderComponent::isStretchToFitActive() const
  40904. {
  40905. return stretchToFit;
  40906. }
  40907. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40908. {
  40909. if (stretchToFit && getWidth() > 0
  40910. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40911. {
  40912. lastDeliberateWidth = targetTotalWidth;
  40913. resizeColumnsToFit (0, targetTotalWidth);
  40914. }
  40915. }
  40916. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40917. {
  40918. targetTotalWidth = jmax (targetTotalWidth, 0);
  40919. StretchableObjectResizer sor;
  40920. int i;
  40921. for (i = firstColumnIndex; i < columns.size(); ++i)
  40922. {
  40923. ColumnInfo* const ci = columns.getUnchecked(i);
  40924. if (ci->isVisible())
  40925. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40926. }
  40927. sor.resizeToFit (targetTotalWidth);
  40928. int visIndex = 0;
  40929. for (i = firstColumnIndex; i < columns.size(); ++i)
  40930. {
  40931. ColumnInfo* const ci = columns.getUnchecked(i);
  40932. if (ci->isVisible())
  40933. {
  40934. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40935. (int) std::floor (sor.getItemSize (visIndex++)));
  40936. if (newWidth != ci->width)
  40937. {
  40938. ci->width = newWidth;
  40939. repaint();
  40940. columnsResized = true;
  40941. triggerAsyncUpdate();
  40942. }
  40943. }
  40944. }
  40945. }
  40946. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40947. {
  40948. ColumnInfo* const ci = getInfoForId (columnId);
  40949. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40950. {
  40951. if (shouldBeVisible)
  40952. ci->propertyFlags |= visible;
  40953. else
  40954. ci->propertyFlags &= ~visible;
  40955. sendColumnsChanged();
  40956. resized();
  40957. }
  40958. }
  40959. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40960. {
  40961. const ColumnInfo* const ci = getInfoForId (columnId);
  40962. return ci != 0 && ci->isVisible();
  40963. }
  40964. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40965. {
  40966. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40967. {
  40968. for (int i = columns.size(); --i >= 0;)
  40969. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40970. ColumnInfo* const ci = getInfoForId (columnId);
  40971. if (ci != 0)
  40972. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40973. reSortTable();
  40974. }
  40975. }
  40976. int TableHeaderComponent::getSortColumnId() const
  40977. {
  40978. for (int i = columns.size(); --i >= 0;)
  40979. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40980. return columns.getUnchecked(i)->id;
  40981. return 0;
  40982. }
  40983. bool TableHeaderComponent::isSortedForwards() const
  40984. {
  40985. for (int i = columns.size(); --i >= 0;)
  40986. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40987. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40988. return true;
  40989. }
  40990. void TableHeaderComponent::reSortTable()
  40991. {
  40992. sortChanged = true;
  40993. repaint();
  40994. triggerAsyncUpdate();
  40995. }
  40996. const String TableHeaderComponent::toString() const
  40997. {
  40998. String s;
  40999. XmlElement doc ("TABLELAYOUT");
  41000. doc.setAttribute ("sortedCol", getSortColumnId());
  41001. doc.setAttribute ("sortForwards", isSortedForwards());
  41002. for (int i = 0; i < columns.size(); ++i)
  41003. {
  41004. const ColumnInfo* const ci = columns.getUnchecked (i);
  41005. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41006. e->setAttribute ("id", ci->id);
  41007. e->setAttribute ("visible", ci->isVisible());
  41008. e->setAttribute ("width", ci->width);
  41009. }
  41010. return doc.createDocument (String::empty, true, false);
  41011. }
  41012. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41013. {
  41014. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41015. int index = 0;
  41016. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41017. {
  41018. forEachXmlChildElement (*storedXml, col)
  41019. {
  41020. const int tabId = col->getIntAttribute ("id");
  41021. ColumnInfo* const ci = getInfoForId (tabId);
  41022. if (ci != 0)
  41023. {
  41024. columns.move (columns.indexOf (ci), index);
  41025. ci->width = col->getIntAttribute ("width");
  41026. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41027. }
  41028. ++index;
  41029. }
  41030. columnsResized = true;
  41031. sendColumnsChanged();
  41032. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41033. storedXml->getBoolAttribute ("sortForwards", true));
  41034. }
  41035. }
  41036. void TableHeaderComponent::addListener (Listener* const newListener)
  41037. {
  41038. listeners.addIfNotAlreadyThere (newListener);
  41039. }
  41040. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41041. {
  41042. listeners.removeValue (listenerToRemove);
  41043. }
  41044. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41045. {
  41046. const ColumnInfo* const ci = getInfoForId (columnId);
  41047. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41048. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41049. }
  41050. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41051. {
  41052. for (int i = 0; i < columns.size(); ++i)
  41053. {
  41054. const ColumnInfo* const ci = columns.getUnchecked(i);
  41055. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41056. menu.addItem (ci->id, ci->name,
  41057. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41058. isColumnVisible (ci->id));
  41059. }
  41060. }
  41061. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41062. {
  41063. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41064. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41065. }
  41066. void TableHeaderComponent::paint (Graphics& g)
  41067. {
  41068. LookAndFeel& lf = getLookAndFeel();
  41069. lf.drawTableHeaderBackground (g, *this);
  41070. const Rectangle<int> clip (g.getClipBounds());
  41071. int x = 0;
  41072. for (int i = 0; i < columns.size(); ++i)
  41073. {
  41074. const ColumnInfo* const ci = columns.getUnchecked(i);
  41075. if (ci->isVisible())
  41076. {
  41077. if (x + ci->width > clip.getX()
  41078. && (ci->id != columnIdBeingDragged
  41079. || dragOverlayComp == 0
  41080. || ! dragOverlayComp->isVisible()))
  41081. {
  41082. Graphics::ScopedSaveState ss (g);
  41083. g.setOrigin (x, 0);
  41084. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41085. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41086. ci->id == columnIdUnderMouse,
  41087. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41088. ci->propertyFlags);
  41089. }
  41090. x += ci->width;
  41091. if (x >= clip.getRight())
  41092. break;
  41093. }
  41094. }
  41095. }
  41096. void TableHeaderComponent::resized()
  41097. {
  41098. }
  41099. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41100. {
  41101. updateColumnUnderMouse (e.x, e.y);
  41102. }
  41103. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41104. {
  41105. updateColumnUnderMouse (e.x, e.y);
  41106. }
  41107. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41108. {
  41109. updateColumnUnderMouse (e.x, e.y);
  41110. }
  41111. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41112. {
  41113. repaint();
  41114. columnIdBeingResized = 0;
  41115. columnIdBeingDragged = 0;
  41116. if (columnIdUnderMouse != 0)
  41117. {
  41118. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41119. if (e.mods.isPopupMenu())
  41120. columnClicked (columnIdUnderMouse, e.mods);
  41121. }
  41122. if (menuActive && e.mods.isPopupMenu())
  41123. showColumnChooserMenu (columnIdUnderMouse);
  41124. }
  41125. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41126. {
  41127. if (columnIdBeingResized == 0
  41128. && columnIdBeingDragged == 0
  41129. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41130. {
  41131. dragOverlayComp = 0;
  41132. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41133. if (columnIdBeingResized != 0)
  41134. {
  41135. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41136. initialColumnWidth = ci->width;
  41137. }
  41138. else
  41139. {
  41140. beginDrag (e);
  41141. }
  41142. }
  41143. if (columnIdBeingResized != 0)
  41144. {
  41145. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41146. if (ci != 0)
  41147. {
  41148. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41149. initialColumnWidth + e.getDistanceFromDragStartX());
  41150. if (stretchToFit)
  41151. {
  41152. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41153. int minWidthOnRight = 0;
  41154. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41155. if (columns.getUnchecked (i)->isVisible())
  41156. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41157. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41158. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41159. }
  41160. setColumnWidth (columnIdBeingResized, w);
  41161. }
  41162. }
  41163. else if (columnIdBeingDragged != 0)
  41164. {
  41165. if (e.y >= -50 && e.y < getHeight() + 50)
  41166. {
  41167. if (dragOverlayComp != 0)
  41168. {
  41169. dragOverlayComp->setVisible (true);
  41170. dragOverlayComp->setBounds (jlimit (0,
  41171. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41172. e.x - draggingColumnOffset),
  41173. 0,
  41174. dragOverlayComp->getWidth(),
  41175. getHeight());
  41176. for (int i = columns.size(); --i >= 0;)
  41177. {
  41178. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41179. int newIndex = currentIndex;
  41180. if (newIndex > 0)
  41181. {
  41182. // if the previous column isn't draggable, we can't move our column
  41183. // past it, because that'd change the undraggable column's position..
  41184. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41185. if ((previous->propertyFlags & draggable) != 0)
  41186. {
  41187. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41188. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41189. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41190. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41191. {
  41192. --newIndex;
  41193. }
  41194. }
  41195. }
  41196. if (newIndex < columns.size() - 1)
  41197. {
  41198. // if the next column isn't draggable, we can't move our column
  41199. // past it, because that'd change the undraggable column's position..
  41200. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41201. if ((nextCol->propertyFlags & draggable) != 0)
  41202. {
  41203. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41204. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41205. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41206. > abs (dragOverlayComp->getRight() - rightOfNext))
  41207. {
  41208. ++newIndex;
  41209. }
  41210. }
  41211. }
  41212. if (newIndex != currentIndex)
  41213. moveColumn (columnIdBeingDragged, newIndex);
  41214. else
  41215. break;
  41216. }
  41217. }
  41218. }
  41219. else
  41220. {
  41221. endDrag (draggingColumnOriginalIndex);
  41222. }
  41223. }
  41224. }
  41225. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41226. {
  41227. if (columnIdBeingDragged == 0)
  41228. {
  41229. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41230. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41231. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41232. {
  41233. columnIdBeingDragged = 0;
  41234. }
  41235. else
  41236. {
  41237. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41238. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41239. const int temp = columnIdBeingDragged;
  41240. columnIdBeingDragged = 0;
  41241. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41242. columnIdBeingDragged = temp;
  41243. dragOverlayComp->setBounds (columnRect);
  41244. for (int i = listeners.size(); --i >= 0;)
  41245. {
  41246. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41247. i = jmin (i, listeners.size() - 1);
  41248. }
  41249. }
  41250. }
  41251. }
  41252. void TableHeaderComponent::endDrag (const int finalIndex)
  41253. {
  41254. if (columnIdBeingDragged != 0)
  41255. {
  41256. moveColumn (columnIdBeingDragged, finalIndex);
  41257. columnIdBeingDragged = 0;
  41258. repaint();
  41259. for (int i = listeners.size(); --i >= 0;)
  41260. {
  41261. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41262. i = jmin (i, listeners.size() - 1);
  41263. }
  41264. }
  41265. }
  41266. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41267. {
  41268. mouseDrag (e);
  41269. for (int i = columns.size(); --i >= 0;)
  41270. if (columns.getUnchecked (i)->isVisible())
  41271. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41272. columnIdBeingResized = 0;
  41273. repaint();
  41274. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41275. updateColumnUnderMouse (e.x, e.y);
  41276. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41277. columnClicked (columnIdUnderMouse, e.mods);
  41278. dragOverlayComp = 0;
  41279. }
  41280. const MouseCursor TableHeaderComponent::getMouseCursor()
  41281. {
  41282. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41283. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41284. return Component::getMouseCursor();
  41285. }
  41286. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41287. {
  41288. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41289. }
  41290. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41291. {
  41292. for (int i = columns.size(); --i >= 0;)
  41293. if (columns.getUnchecked(i)->id == id)
  41294. return columns.getUnchecked(i);
  41295. return 0;
  41296. }
  41297. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41298. {
  41299. int n = 0;
  41300. for (int i = 0; i < columns.size(); ++i)
  41301. {
  41302. if (columns.getUnchecked(i)->isVisible())
  41303. {
  41304. if (n == visibleIndex)
  41305. return i;
  41306. ++n;
  41307. }
  41308. }
  41309. return -1;
  41310. }
  41311. void TableHeaderComponent::sendColumnsChanged()
  41312. {
  41313. if (stretchToFit && lastDeliberateWidth > 0)
  41314. resizeAllColumnsToFit (lastDeliberateWidth);
  41315. repaint();
  41316. columnsChanged = true;
  41317. triggerAsyncUpdate();
  41318. }
  41319. void TableHeaderComponent::handleAsyncUpdate()
  41320. {
  41321. const bool changed = columnsChanged || sortChanged;
  41322. const bool sized = columnsResized || changed;
  41323. const bool sorted = sortChanged;
  41324. columnsChanged = false;
  41325. columnsResized = false;
  41326. sortChanged = false;
  41327. if (sorted)
  41328. {
  41329. for (int i = listeners.size(); --i >= 0;)
  41330. {
  41331. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41332. i = jmin (i, listeners.size() - 1);
  41333. }
  41334. }
  41335. if (changed)
  41336. {
  41337. for (int i = listeners.size(); --i >= 0;)
  41338. {
  41339. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41340. i = jmin (i, listeners.size() - 1);
  41341. }
  41342. }
  41343. if (sized)
  41344. {
  41345. for (int i = listeners.size(); --i >= 0;)
  41346. {
  41347. listeners.getUnchecked(i)->tableColumnsResized (this);
  41348. i = jmin (i, listeners.size() - 1);
  41349. }
  41350. }
  41351. }
  41352. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41353. {
  41354. if (isPositiveAndBelow (mouseX, getWidth()))
  41355. {
  41356. const int draggableDistance = 3;
  41357. int x = 0;
  41358. for (int i = 0; i < columns.size(); ++i)
  41359. {
  41360. const ColumnInfo* const ci = columns.getUnchecked(i);
  41361. if (ci->isVisible())
  41362. {
  41363. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41364. && (ci->propertyFlags & resizable) != 0)
  41365. return ci->id;
  41366. x += ci->width;
  41367. }
  41368. }
  41369. }
  41370. return 0;
  41371. }
  41372. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41373. {
  41374. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41375. ? getColumnIdAtX (x) : 0;
  41376. if (newCol != columnIdUnderMouse)
  41377. {
  41378. columnIdUnderMouse = newCol;
  41379. repaint();
  41380. }
  41381. }
  41382. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41383. {
  41384. PopupMenu m;
  41385. addMenuItems (m, columnIdClicked);
  41386. if (m.getNumItems() > 0)
  41387. {
  41388. m.setLookAndFeel (&getLookAndFeel());
  41389. const int result = m.show();
  41390. if (result != 0)
  41391. reactToMenuItem (result, columnIdClicked);
  41392. }
  41393. }
  41394. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41395. {
  41396. }
  41397. END_JUCE_NAMESPACE
  41398. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41399. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41400. BEGIN_JUCE_NAMESPACE
  41401. class TableListRowComp : public Component,
  41402. public TooltipClient
  41403. {
  41404. public:
  41405. TableListRowComp (TableListBox& owner_)
  41406. : owner (owner_), row (-1), isSelected (false)
  41407. {
  41408. }
  41409. void paint (Graphics& g)
  41410. {
  41411. TableListBoxModel* const model = owner.getModel();
  41412. if (model != 0)
  41413. {
  41414. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41415. const TableHeaderComponent& header = owner.getHeader();
  41416. const int numColumns = header.getNumColumns (true);
  41417. for (int i = 0; i < numColumns; ++i)
  41418. {
  41419. if (columnComponents[i] == 0)
  41420. {
  41421. const int columnId = header.getColumnIdOfIndex (i, true);
  41422. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41423. Graphics::ScopedSaveState ss (g);
  41424. g.reduceClipRegion (columnRect);
  41425. g.setOrigin (columnRect.getX(), 0);
  41426. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41427. }
  41428. }
  41429. }
  41430. }
  41431. void update (const int newRow, const bool isNowSelected)
  41432. {
  41433. jassert (newRow >= 0);
  41434. if (newRow != row || isNowSelected != isSelected)
  41435. {
  41436. row = newRow;
  41437. isSelected = isNowSelected;
  41438. repaint();
  41439. }
  41440. TableListBoxModel* const model = owner.getModel();
  41441. if (model != 0 && row < owner.getNumRows())
  41442. {
  41443. const Identifier columnProperty ("_tableColumnId");
  41444. const int numColumns = owner.getHeader().getNumColumns (true);
  41445. for (int i = 0; i < numColumns; ++i)
  41446. {
  41447. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41448. Component* comp = columnComponents[i];
  41449. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41450. {
  41451. columnComponents.set (i, 0);
  41452. comp = 0;
  41453. }
  41454. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41455. columnComponents.set (i, comp, false);
  41456. if (comp != 0)
  41457. {
  41458. comp->getProperties().set (columnProperty, columnId);
  41459. addAndMakeVisible (comp);
  41460. resizeCustomComp (i);
  41461. }
  41462. }
  41463. columnComponents.removeRange (numColumns, columnComponents.size());
  41464. }
  41465. else
  41466. {
  41467. columnComponents.clear();
  41468. }
  41469. }
  41470. void resized()
  41471. {
  41472. for (int i = columnComponents.size(); --i >= 0;)
  41473. resizeCustomComp (i);
  41474. }
  41475. void resizeCustomComp (const int index)
  41476. {
  41477. Component* const c = columnComponents.getUnchecked (index);
  41478. if (c != 0)
  41479. c->setBounds (owner.getHeader().getColumnPosition (index)
  41480. .withY (0).withHeight (getHeight()));
  41481. }
  41482. void mouseDown (const MouseEvent& e)
  41483. {
  41484. isDragging = false;
  41485. selectRowOnMouseUp = false;
  41486. if (isEnabled())
  41487. {
  41488. if (! isSelected)
  41489. {
  41490. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41491. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41492. if (columnId != 0 && owner.getModel() != 0)
  41493. owner.getModel()->cellClicked (row, columnId, e);
  41494. }
  41495. else
  41496. {
  41497. selectRowOnMouseUp = true;
  41498. }
  41499. }
  41500. }
  41501. void mouseDrag (const MouseEvent& e)
  41502. {
  41503. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41504. {
  41505. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41506. if (selectedRows.size() > 0)
  41507. {
  41508. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41509. if (dragDescription.isNotEmpty())
  41510. {
  41511. isDragging = true;
  41512. owner.startDragAndDrop (e, dragDescription);
  41513. }
  41514. }
  41515. }
  41516. }
  41517. void mouseUp (const MouseEvent& e)
  41518. {
  41519. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41520. {
  41521. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41522. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41523. if (columnId != 0 && owner.getModel() != 0)
  41524. owner.getModel()->cellClicked (row, columnId, e);
  41525. }
  41526. }
  41527. void mouseDoubleClick (const MouseEvent& e)
  41528. {
  41529. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41530. if (columnId != 0 && owner.getModel() != 0)
  41531. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41532. }
  41533. const String getTooltip()
  41534. {
  41535. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41536. if (columnId != 0 && owner.getModel() != 0)
  41537. return owner.getModel()->getCellTooltip (row, columnId);
  41538. return String::empty;
  41539. }
  41540. Component* findChildComponentForColumn (const int columnId) const
  41541. {
  41542. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41543. }
  41544. private:
  41545. TableListBox& owner;
  41546. OwnedArray<Component> columnComponents;
  41547. int row;
  41548. bool isSelected, isDragging, selectRowOnMouseUp;
  41549. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41550. };
  41551. class TableListBoxHeader : public TableHeaderComponent
  41552. {
  41553. public:
  41554. TableListBoxHeader (TableListBox& owner_)
  41555. : owner (owner_)
  41556. {
  41557. }
  41558. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41559. {
  41560. if (owner.isAutoSizeMenuOptionShown())
  41561. {
  41562. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41563. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41564. menu.addSeparator();
  41565. }
  41566. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41567. }
  41568. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41569. {
  41570. switch (menuReturnId)
  41571. {
  41572. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41573. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41574. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41575. }
  41576. }
  41577. private:
  41578. TableListBox& owner;
  41579. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41580. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41581. };
  41582. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41583. : ListBox (name, 0),
  41584. header (0), model (model_),
  41585. autoSizeOptionsShown (true)
  41586. {
  41587. ListBox::model = this;
  41588. setHeader (new TableListBoxHeader (*this));
  41589. }
  41590. TableListBox::~TableListBox()
  41591. {
  41592. header = 0;
  41593. }
  41594. void TableListBox::setModel (TableListBoxModel* const newModel)
  41595. {
  41596. if (model != newModel)
  41597. {
  41598. model = newModel;
  41599. updateContent();
  41600. }
  41601. }
  41602. void TableListBox::setHeader (TableHeaderComponent* newHeader)
  41603. {
  41604. jassert (newHeader != 0); // you need to supply a real header for a table!
  41605. Rectangle<int> newBounds (0, 0, 100, 28);
  41606. if (header != 0)
  41607. newBounds = header->getBounds();
  41608. header = newHeader;
  41609. header->setBounds (newBounds);
  41610. setHeaderComponent (header);
  41611. header->addListener (this);
  41612. }
  41613. int TableListBox::getHeaderHeight() const
  41614. {
  41615. return header->getHeight();
  41616. }
  41617. void TableListBox::setHeaderHeight (const int newHeight)
  41618. {
  41619. header->setSize (header->getWidth(), newHeight);
  41620. resized();
  41621. }
  41622. void TableListBox::autoSizeColumn (const int columnId)
  41623. {
  41624. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41625. if (width > 0)
  41626. header->setColumnWidth (columnId, width);
  41627. }
  41628. void TableListBox::autoSizeAllColumns()
  41629. {
  41630. for (int i = 0; i < header->getNumColumns (true); ++i)
  41631. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41632. }
  41633. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41634. {
  41635. autoSizeOptionsShown = shouldBeShown;
  41636. }
  41637. bool TableListBox::isAutoSizeMenuOptionShown() const
  41638. {
  41639. return autoSizeOptionsShown;
  41640. }
  41641. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41642. const bool relativeToComponentTopLeft) const
  41643. {
  41644. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41645. if (relativeToComponentTopLeft)
  41646. headerCell.translate (header->getX(), 0);
  41647. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41648. .withX (headerCell.getX())
  41649. .withWidth (headerCell.getWidth());
  41650. }
  41651. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41652. {
  41653. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41654. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41655. }
  41656. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41657. {
  41658. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41659. if (scrollbar != 0)
  41660. {
  41661. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41662. double x = scrollbar->getCurrentRangeStart();
  41663. const double w = scrollbar->getCurrentRangeSize();
  41664. if (pos.getX() < x)
  41665. x = pos.getX();
  41666. else if (pos.getRight() > x + w)
  41667. x += jmax (0.0, pos.getRight() - (x + w));
  41668. scrollbar->setCurrentRangeStart (x);
  41669. }
  41670. }
  41671. int TableListBox::getNumRows()
  41672. {
  41673. return model != 0 ? model->getNumRows() : 0;
  41674. }
  41675. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41676. {
  41677. }
  41678. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41679. {
  41680. if (existingComponentToUpdate == 0)
  41681. existingComponentToUpdate = new TableListRowComp (*this);
  41682. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41683. return existingComponentToUpdate;
  41684. }
  41685. void TableListBox::selectedRowsChanged (int row)
  41686. {
  41687. if (model != 0)
  41688. model->selectedRowsChanged (row);
  41689. }
  41690. void TableListBox::deleteKeyPressed (int row)
  41691. {
  41692. if (model != 0)
  41693. model->deleteKeyPressed (row);
  41694. }
  41695. void TableListBox::returnKeyPressed (int row)
  41696. {
  41697. if (model != 0)
  41698. model->returnKeyPressed (row);
  41699. }
  41700. void TableListBox::backgroundClicked()
  41701. {
  41702. if (model != 0)
  41703. model->backgroundClicked();
  41704. }
  41705. void TableListBox::listWasScrolled()
  41706. {
  41707. if (model != 0)
  41708. model->listWasScrolled();
  41709. }
  41710. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41711. {
  41712. setMinimumContentWidth (header->getTotalWidth());
  41713. repaint();
  41714. updateColumnComponents();
  41715. }
  41716. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41717. {
  41718. setMinimumContentWidth (header->getTotalWidth());
  41719. repaint();
  41720. updateColumnComponents();
  41721. }
  41722. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41723. {
  41724. if (model != 0)
  41725. model->sortOrderChanged (header->getSortColumnId(),
  41726. header->isSortedForwards());
  41727. }
  41728. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41729. {
  41730. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41731. repaint();
  41732. }
  41733. void TableListBox::resized()
  41734. {
  41735. ListBox::resized();
  41736. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41737. setMinimumContentWidth (header->getTotalWidth());
  41738. }
  41739. void TableListBox::updateColumnComponents() const
  41740. {
  41741. const int firstRow = getRowContainingPosition (0, 0);
  41742. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41743. {
  41744. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41745. if (rowComp != 0)
  41746. rowComp->resized();
  41747. }
  41748. }
  41749. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41750. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41751. void TableListBoxModel::backgroundClicked() {}
  41752. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41753. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41754. void TableListBoxModel::selectedRowsChanged (int) {}
  41755. void TableListBoxModel::deleteKeyPressed (int) {}
  41756. void TableListBoxModel::returnKeyPressed (int) {}
  41757. void TableListBoxModel::listWasScrolled() {}
  41758. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41759. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41760. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41761. {
  41762. (void) existingComponentToUpdate;
  41763. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41764. return 0;
  41765. }
  41766. END_JUCE_NAMESPACE
  41767. /*** End of inlined file: juce_TableListBox.cpp ***/
  41768. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41769. BEGIN_JUCE_NAMESPACE
  41770. // a word or space that can't be broken down any further
  41771. struct TextAtom
  41772. {
  41773. String atomText;
  41774. float width;
  41775. int numChars;
  41776. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41777. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41778. const String getText (const juce_wchar passwordCharacter) const
  41779. {
  41780. if (passwordCharacter == 0)
  41781. return atomText;
  41782. else
  41783. return String::repeatedString (String::charToString (passwordCharacter),
  41784. atomText.length());
  41785. }
  41786. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41787. {
  41788. if (passwordCharacter == 0)
  41789. return atomText.substring (0, numChars);
  41790. else if (isNewLine())
  41791. return String::empty;
  41792. else
  41793. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41794. }
  41795. };
  41796. // a run of text with a single font and colour
  41797. class TextEditor::UniformTextSection
  41798. {
  41799. public:
  41800. UniformTextSection (const String& text,
  41801. const Font& font_,
  41802. const Colour& colour_,
  41803. const juce_wchar passwordCharacter)
  41804. : font (font_),
  41805. colour (colour_)
  41806. {
  41807. initialiseAtoms (text, passwordCharacter);
  41808. }
  41809. UniformTextSection (const UniformTextSection& other)
  41810. : font (other.font),
  41811. colour (other.colour)
  41812. {
  41813. atoms.ensureStorageAllocated (other.atoms.size());
  41814. for (int i = 0; i < other.atoms.size(); ++i)
  41815. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41816. }
  41817. ~UniformTextSection()
  41818. {
  41819. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41820. }
  41821. void clear()
  41822. {
  41823. for (int i = atoms.size(); --i >= 0;)
  41824. delete getAtom(i);
  41825. atoms.clear();
  41826. }
  41827. int getNumAtoms() const
  41828. {
  41829. return atoms.size();
  41830. }
  41831. TextAtom* getAtom (const int index) const throw()
  41832. {
  41833. return atoms.getUnchecked (index);
  41834. }
  41835. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41836. {
  41837. if (other.atoms.size() > 0)
  41838. {
  41839. TextAtom* const lastAtom = atoms.getLast();
  41840. int i = 0;
  41841. if (lastAtom != 0)
  41842. {
  41843. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41844. {
  41845. TextAtom* const first = other.getAtom(0);
  41846. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41847. {
  41848. lastAtom->atomText += first->atomText;
  41849. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41850. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41851. delete first;
  41852. ++i;
  41853. }
  41854. }
  41855. }
  41856. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41857. while (i < other.atoms.size())
  41858. {
  41859. atoms.add (other.getAtom(i));
  41860. ++i;
  41861. }
  41862. }
  41863. }
  41864. UniformTextSection* split (const int indexToBreakAt,
  41865. const juce_wchar passwordCharacter)
  41866. {
  41867. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41868. font, colour,
  41869. passwordCharacter);
  41870. int index = 0;
  41871. for (int i = 0; i < atoms.size(); ++i)
  41872. {
  41873. TextAtom* const atom = getAtom(i);
  41874. const int nextIndex = index + atom->numChars;
  41875. if (index == indexToBreakAt)
  41876. {
  41877. int j;
  41878. for (j = i; j < atoms.size(); ++j)
  41879. section2->atoms.add (getAtom (j));
  41880. for (j = atoms.size(); --j >= i;)
  41881. atoms.remove (j);
  41882. break;
  41883. }
  41884. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41885. {
  41886. TextAtom* const secondAtom = new TextAtom();
  41887. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41888. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41889. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41890. section2->atoms.add (secondAtom);
  41891. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41892. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41893. atom->numChars = (uint16) (indexToBreakAt - index);
  41894. int j;
  41895. for (j = i + 1; j < atoms.size(); ++j)
  41896. section2->atoms.add (getAtom (j));
  41897. for (j = atoms.size(); --j > i;)
  41898. atoms.remove (j);
  41899. break;
  41900. }
  41901. index = nextIndex;
  41902. }
  41903. return section2;
  41904. }
  41905. void appendAllText (String::Concatenator& concatenator) const
  41906. {
  41907. for (int i = 0; i < atoms.size(); ++i)
  41908. concatenator.append (getAtom(i)->atomText);
  41909. }
  41910. void appendSubstring (String::Concatenator& concatenator,
  41911. const Range<int>& range) const
  41912. {
  41913. int index = 0;
  41914. for (int i = 0; i < atoms.size(); ++i)
  41915. {
  41916. const TextAtom* const atom = getAtom (i);
  41917. const int nextIndex = index + atom->numChars;
  41918. if (range.getStart() < nextIndex)
  41919. {
  41920. if (range.getEnd() <= index)
  41921. break;
  41922. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41923. if (! r.isEmpty())
  41924. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41925. }
  41926. index = nextIndex;
  41927. }
  41928. }
  41929. int getTotalLength() const
  41930. {
  41931. int total = 0;
  41932. for (int i = atoms.size(); --i >= 0;)
  41933. total += getAtom(i)->numChars;
  41934. return total;
  41935. }
  41936. void setFont (const Font& newFont,
  41937. const juce_wchar passwordCharacter)
  41938. {
  41939. if (font != newFont)
  41940. {
  41941. font = newFont;
  41942. for (int i = atoms.size(); --i >= 0;)
  41943. {
  41944. TextAtom* const atom = atoms.getUnchecked(i);
  41945. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41946. }
  41947. }
  41948. }
  41949. Font font;
  41950. Colour colour;
  41951. private:
  41952. Array <TextAtom*> atoms;
  41953. void initialiseAtoms (const String& textToParse,
  41954. const juce_wchar passwordCharacter)
  41955. {
  41956. String::CharPointerType text (textToParse.getCharPointer());
  41957. while (! text.isEmpty())
  41958. {
  41959. int numChars = 0;
  41960. String::CharPointerType start (text);
  41961. // create a whitespace atom unless it starts with non-ws
  41962. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  41963. {
  41964. do
  41965. {
  41966. ++text;
  41967. ++numChars;
  41968. }
  41969. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  41970. }
  41971. else
  41972. {
  41973. if (*text == '\r')
  41974. {
  41975. ++text;
  41976. ++numChars;
  41977. if (*text == '\n')
  41978. {
  41979. ++start;
  41980. ++text;
  41981. }
  41982. }
  41983. else if (*text == '\n')
  41984. {
  41985. ++text;
  41986. ++numChars;
  41987. }
  41988. else
  41989. {
  41990. while (! text.isEmpty() || text.isWhitespace())
  41991. {
  41992. ++text;
  41993. ++numChars;
  41994. }
  41995. }
  41996. }
  41997. TextAtom* const atom = new TextAtom();
  41998. atom->atomText = String (start, numChars);
  41999. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42000. atom->numChars = (uint16) numChars;
  42001. atoms.add (atom);
  42002. }
  42003. }
  42004. UniformTextSection& operator= (const UniformTextSection& other);
  42005. JUCE_LEAK_DETECTOR (UniformTextSection);
  42006. };
  42007. class TextEditor::Iterator
  42008. {
  42009. public:
  42010. Iterator (const Array <UniformTextSection*>& sections_,
  42011. const float wordWrapWidth_,
  42012. const juce_wchar passwordCharacter_)
  42013. : indexInText (0),
  42014. lineY (0),
  42015. lineHeight (0),
  42016. maxDescent (0),
  42017. atomX (0),
  42018. atomRight (0),
  42019. atom (0),
  42020. currentSection (0),
  42021. sections (sections_),
  42022. sectionIndex (0),
  42023. atomIndex (0),
  42024. wordWrapWidth (wordWrapWidth_),
  42025. passwordCharacter (passwordCharacter_)
  42026. {
  42027. jassert (wordWrapWidth_ > 0);
  42028. if (sections.size() > 0)
  42029. {
  42030. currentSection = sections.getUnchecked (sectionIndex);
  42031. if (currentSection != 0)
  42032. beginNewLine();
  42033. }
  42034. }
  42035. Iterator (const Iterator& other)
  42036. : indexInText (other.indexInText),
  42037. lineY (other.lineY),
  42038. lineHeight (other.lineHeight),
  42039. maxDescent (other.maxDescent),
  42040. atomX (other.atomX),
  42041. atomRight (other.atomRight),
  42042. atom (other.atom),
  42043. currentSection (other.currentSection),
  42044. sections (other.sections),
  42045. sectionIndex (other.sectionIndex),
  42046. atomIndex (other.atomIndex),
  42047. wordWrapWidth (other.wordWrapWidth),
  42048. passwordCharacter (other.passwordCharacter),
  42049. tempAtom (other.tempAtom)
  42050. {
  42051. }
  42052. bool next()
  42053. {
  42054. if (atom == &tempAtom)
  42055. {
  42056. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42057. if (numRemaining > 0)
  42058. {
  42059. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42060. atomX = 0;
  42061. if (tempAtom.numChars > 0)
  42062. lineY += lineHeight;
  42063. indexInText += tempAtom.numChars;
  42064. GlyphArrangement g;
  42065. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42066. int split;
  42067. for (split = 0; split < g.getNumGlyphs(); ++split)
  42068. if (shouldWrap (g.getGlyph (split).getRight()))
  42069. break;
  42070. if (split > 0 && split <= numRemaining)
  42071. {
  42072. tempAtom.numChars = (uint16) split;
  42073. tempAtom.width = g.getGlyph (split - 1).getRight();
  42074. atomRight = atomX + tempAtom.width;
  42075. return true;
  42076. }
  42077. }
  42078. }
  42079. bool forceNewLine = false;
  42080. if (sectionIndex >= sections.size())
  42081. {
  42082. moveToEndOfLastAtom();
  42083. return false;
  42084. }
  42085. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42086. {
  42087. if (atomIndex >= currentSection->getNumAtoms())
  42088. {
  42089. if (++sectionIndex >= sections.size())
  42090. {
  42091. moveToEndOfLastAtom();
  42092. return false;
  42093. }
  42094. atomIndex = 0;
  42095. currentSection = sections.getUnchecked (sectionIndex);
  42096. }
  42097. else
  42098. {
  42099. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42100. if (! lastAtom->isWhitespace())
  42101. {
  42102. // handle the case where the last atom in a section is actually part of the same
  42103. // word as the first atom of the next section...
  42104. float right = atomRight + lastAtom->width;
  42105. float lineHeight2 = lineHeight;
  42106. float maxDescent2 = maxDescent;
  42107. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42108. {
  42109. const UniformTextSection* const s = sections.getUnchecked (section);
  42110. if (s->getNumAtoms() == 0)
  42111. break;
  42112. const TextAtom* const nextAtom = s->getAtom (0);
  42113. if (nextAtom->isWhitespace())
  42114. break;
  42115. right += nextAtom->width;
  42116. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42117. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42118. if (shouldWrap (right))
  42119. {
  42120. lineHeight = lineHeight2;
  42121. maxDescent = maxDescent2;
  42122. forceNewLine = true;
  42123. break;
  42124. }
  42125. if (s->getNumAtoms() > 1)
  42126. break;
  42127. }
  42128. }
  42129. }
  42130. }
  42131. if (atom != 0)
  42132. {
  42133. atomX = atomRight;
  42134. indexInText += atom->numChars;
  42135. if (atom->isNewLine())
  42136. beginNewLine();
  42137. }
  42138. atom = currentSection->getAtom (atomIndex);
  42139. atomRight = atomX + atom->width;
  42140. ++atomIndex;
  42141. if (shouldWrap (atomRight) || forceNewLine)
  42142. {
  42143. if (atom->isWhitespace())
  42144. {
  42145. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42146. atomRight = jmin (atomRight, wordWrapWidth);
  42147. }
  42148. else
  42149. {
  42150. atomRight = atom->width;
  42151. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42152. {
  42153. tempAtom = *atom;
  42154. tempAtom.width = 0;
  42155. tempAtom.numChars = 0;
  42156. atom = &tempAtom;
  42157. if (atomX > 0)
  42158. beginNewLine();
  42159. return next();
  42160. }
  42161. beginNewLine();
  42162. return true;
  42163. }
  42164. }
  42165. return true;
  42166. }
  42167. void beginNewLine()
  42168. {
  42169. atomX = 0;
  42170. lineY += lineHeight;
  42171. int tempSectionIndex = sectionIndex;
  42172. int tempAtomIndex = atomIndex;
  42173. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42174. lineHeight = section->font.getHeight();
  42175. maxDescent = section->font.getDescent();
  42176. float x = (atom != 0) ? atom->width : 0;
  42177. while (! shouldWrap (x))
  42178. {
  42179. if (tempSectionIndex >= sections.size())
  42180. break;
  42181. bool checkSize = false;
  42182. if (tempAtomIndex >= section->getNumAtoms())
  42183. {
  42184. if (++tempSectionIndex >= sections.size())
  42185. break;
  42186. tempAtomIndex = 0;
  42187. section = sections.getUnchecked (tempSectionIndex);
  42188. checkSize = true;
  42189. }
  42190. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42191. if (nextAtom == 0)
  42192. break;
  42193. x += nextAtom->width;
  42194. if (shouldWrap (x) || nextAtom->isNewLine())
  42195. break;
  42196. if (checkSize)
  42197. {
  42198. lineHeight = jmax (lineHeight, section->font.getHeight());
  42199. maxDescent = jmax (maxDescent, section->font.getDescent());
  42200. }
  42201. ++tempAtomIndex;
  42202. }
  42203. }
  42204. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42205. {
  42206. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42207. {
  42208. if (lastSection != currentSection)
  42209. {
  42210. lastSection = currentSection;
  42211. g.setColour (currentSection->colour);
  42212. g.setFont (currentSection->font);
  42213. }
  42214. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42215. GlyphArrangement ga;
  42216. ga.addLineOfText (currentSection->font,
  42217. atom->getTrimmedText (passwordCharacter),
  42218. atomX,
  42219. (float) roundToInt (lineY + lineHeight - maxDescent));
  42220. ga.draw (g);
  42221. }
  42222. }
  42223. void drawSelection (Graphics& g,
  42224. const Range<int>& selection) const
  42225. {
  42226. const int startX = roundToInt (indexToX (selection.getStart()));
  42227. const int endX = roundToInt (indexToX (selection.getEnd()));
  42228. const int y = roundToInt (lineY);
  42229. const int nextY = roundToInt (lineY + lineHeight);
  42230. g.fillRect (startX, y, endX - startX, nextY - y);
  42231. }
  42232. void drawSelectedText (Graphics& g,
  42233. const Range<int>& selection,
  42234. const Colour& selectedTextColour) const
  42235. {
  42236. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42237. {
  42238. GlyphArrangement ga;
  42239. ga.addLineOfText (currentSection->font,
  42240. atom->getTrimmedText (passwordCharacter),
  42241. atomX,
  42242. (float) roundToInt (lineY + lineHeight - maxDescent));
  42243. if (selection.getEnd() < indexInText + atom->numChars)
  42244. {
  42245. GlyphArrangement ga2 (ga);
  42246. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42247. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42248. g.setColour (currentSection->colour);
  42249. ga2.draw (g);
  42250. }
  42251. if (selection.getStart() > indexInText)
  42252. {
  42253. GlyphArrangement ga2 (ga);
  42254. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42255. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42256. g.setColour (currentSection->colour);
  42257. ga2.draw (g);
  42258. }
  42259. g.setColour (selectedTextColour);
  42260. ga.draw (g);
  42261. }
  42262. }
  42263. float indexToX (const int indexToFind) const
  42264. {
  42265. if (indexToFind <= indexInText)
  42266. return atomX;
  42267. if (indexToFind >= indexInText + atom->numChars)
  42268. return atomRight;
  42269. GlyphArrangement g;
  42270. g.addLineOfText (currentSection->font,
  42271. atom->getText (passwordCharacter),
  42272. atomX, 0.0f);
  42273. if (indexToFind - indexInText >= g.getNumGlyphs())
  42274. return atomRight;
  42275. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42276. }
  42277. int xToIndex (const float xToFind) const
  42278. {
  42279. if (xToFind <= atomX || atom->isNewLine())
  42280. return indexInText;
  42281. if (xToFind >= atomRight)
  42282. return indexInText + atom->numChars;
  42283. GlyphArrangement g;
  42284. g.addLineOfText (currentSection->font,
  42285. atom->getText (passwordCharacter),
  42286. atomX, 0.0f);
  42287. int j;
  42288. for (j = 0; j < g.getNumGlyphs(); ++j)
  42289. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42290. break;
  42291. return indexInText + j;
  42292. }
  42293. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42294. {
  42295. while (next())
  42296. {
  42297. if (indexInText + atom->numChars > index)
  42298. {
  42299. cx = indexToX (index);
  42300. cy = lineY;
  42301. lineHeight_ = lineHeight;
  42302. return true;
  42303. }
  42304. }
  42305. cx = atomX;
  42306. cy = lineY;
  42307. lineHeight_ = lineHeight;
  42308. return false;
  42309. }
  42310. int indexInText;
  42311. float lineY, lineHeight, maxDescent;
  42312. float atomX, atomRight;
  42313. const TextAtom* atom;
  42314. const UniformTextSection* currentSection;
  42315. private:
  42316. const Array <UniformTextSection*>& sections;
  42317. int sectionIndex, atomIndex;
  42318. const float wordWrapWidth;
  42319. const juce_wchar passwordCharacter;
  42320. TextAtom tempAtom;
  42321. Iterator& operator= (const Iterator&);
  42322. void moveToEndOfLastAtom()
  42323. {
  42324. if (atom != 0)
  42325. {
  42326. atomX = atomRight;
  42327. if (atom->isNewLine())
  42328. {
  42329. atomX = 0.0f;
  42330. lineY += lineHeight;
  42331. }
  42332. }
  42333. }
  42334. bool shouldWrap (const float x) const
  42335. {
  42336. return (x - 0.0001f) >= wordWrapWidth;
  42337. }
  42338. JUCE_LEAK_DETECTOR (Iterator);
  42339. };
  42340. class TextEditor::InsertAction : public UndoableAction
  42341. {
  42342. public:
  42343. InsertAction (TextEditor& owner_,
  42344. const String& text_,
  42345. const int insertIndex_,
  42346. const Font& font_,
  42347. const Colour& colour_,
  42348. const int oldCaretPos_,
  42349. const int newCaretPos_)
  42350. : owner (owner_),
  42351. text (text_),
  42352. insertIndex (insertIndex_),
  42353. oldCaretPos (oldCaretPos_),
  42354. newCaretPos (newCaretPos_),
  42355. font (font_),
  42356. colour (colour_)
  42357. {
  42358. }
  42359. bool perform()
  42360. {
  42361. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42362. return true;
  42363. }
  42364. bool undo()
  42365. {
  42366. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42367. return true;
  42368. }
  42369. int getSizeInUnits()
  42370. {
  42371. return text.length() + 16;
  42372. }
  42373. private:
  42374. TextEditor& owner;
  42375. const String text;
  42376. const int insertIndex, oldCaretPos, newCaretPos;
  42377. const Font font;
  42378. const Colour colour;
  42379. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42380. };
  42381. class TextEditor::RemoveAction : public UndoableAction
  42382. {
  42383. public:
  42384. RemoveAction (TextEditor& owner_,
  42385. const Range<int> range_,
  42386. const int oldCaretPos_,
  42387. const int newCaretPos_,
  42388. const Array <UniformTextSection*>& removedSections_)
  42389. : owner (owner_),
  42390. range (range_),
  42391. oldCaretPos (oldCaretPos_),
  42392. newCaretPos (newCaretPos_),
  42393. removedSections (removedSections_)
  42394. {
  42395. }
  42396. ~RemoveAction()
  42397. {
  42398. for (int i = removedSections.size(); --i >= 0;)
  42399. {
  42400. UniformTextSection* const section = removedSections.getUnchecked (i);
  42401. section->clear();
  42402. delete section;
  42403. }
  42404. }
  42405. bool perform()
  42406. {
  42407. owner.remove (range, 0, newCaretPos);
  42408. return true;
  42409. }
  42410. bool undo()
  42411. {
  42412. owner.reinsert (range.getStart(), removedSections);
  42413. owner.moveCursorTo (oldCaretPos, false);
  42414. return true;
  42415. }
  42416. int getSizeInUnits()
  42417. {
  42418. int n = 0;
  42419. for (int i = removedSections.size(); --i >= 0;)
  42420. n += removedSections.getUnchecked (i)->getTotalLength();
  42421. return n + 16;
  42422. }
  42423. private:
  42424. TextEditor& owner;
  42425. const Range<int> range;
  42426. const int oldCaretPos, newCaretPos;
  42427. Array <UniformTextSection*> removedSections;
  42428. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42429. };
  42430. class TextEditor::TextHolderComponent : public Component,
  42431. public Timer,
  42432. public ValueListener
  42433. {
  42434. public:
  42435. TextHolderComponent (TextEditor& owner_)
  42436. : owner (owner_)
  42437. {
  42438. setWantsKeyboardFocus (false);
  42439. setInterceptsMouseClicks (false, true);
  42440. owner.getTextValue().addListener (this);
  42441. }
  42442. ~TextHolderComponent()
  42443. {
  42444. owner.getTextValue().removeListener (this);
  42445. }
  42446. void paint (Graphics& g)
  42447. {
  42448. owner.drawContent (g);
  42449. }
  42450. void timerCallback()
  42451. {
  42452. owner.timerCallbackInt();
  42453. }
  42454. const MouseCursor getMouseCursor()
  42455. {
  42456. return owner.getMouseCursor();
  42457. }
  42458. void valueChanged (Value&)
  42459. {
  42460. owner.textWasChangedByValue();
  42461. }
  42462. private:
  42463. TextEditor& owner;
  42464. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42465. };
  42466. class TextEditorViewport : public Viewport
  42467. {
  42468. public:
  42469. TextEditorViewport (TextEditor& owner_)
  42470. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42471. {
  42472. }
  42473. void visibleAreaChanged (const Rectangle<int>&)
  42474. {
  42475. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42476. // appear and disappear, causing the wrap width to change.
  42477. {
  42478. const float wordWrapWidth = owner.getWordWrapWidth();
  42479. if (wordWrapWidth != lastWordWrapWidth)
  42480. {
  42481. lastWordWrapWidth = wordWrapWidth;
  42482. rentrant = true;
  42483. owner.updateTextHolderSize();
  42484. rentrant = false;
  42485. }
  42486. }
  42487. }
  42488. private:
  42489. TextEditor& owner;
  42490. float lastWordWrapWidth;
  42491. bool rentrant;
  42492. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42493. };
  42494. namespace TextEditorDefs
  42495. {
  42496. const int flashSpeedIntervalMs = 380;
  42497. const int textChangeMessageId = 0x10003001;
  42498. const int returnKeyMessageId = 0x10003002;
  42499. const int escapeKeyMessageId = 0x10003003;
  42500. const int focusLossMessageId = 0x10003004;
  42501. const int maxActionsPerTransaction = 100;
  42502. int getCharacterCategory (const juce_wchar character)
  42503. {
  42504. return CharacterFunctions::isLetterOrDigit (character)
  42505. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42506. }
  42507. }
  42508. TextEditor::TextEditor (const String& name,
  42509. const juce_wchar passwordCharacter_)
  42510. : Component (name),
  42511. borderSize (1, 1, 1, 3),
  42512. readOnly (false),
  42513. multiline (false),
  42514. wordWrap (false),
  42515. returnKeyStartsNewLine (false),
  42516. caretVisible (true),
  42517. popupMenuEnabled (true),
  42518. selectAllTextWhenFocused (false),
  42519. scrollbarVisible (true),
  42520. wasFocused (false),
  42521. caretFlashState (true),
  42522. keepCursorOnScreen (true),
  42523. tabKeyUsed (false),
  42524. menuActive (false),
  42525. valueTextNeedsUpdating (false),
  42526. cursorX (0),
  42527. cursorY (0),
  42528. cursorHeight (0),
  42529. maxTextLength (0),
  42530. leftIndent (4),
  42531. topIndent (4),
  42532. lastTransactionTime (0),
  42533. currentFont (14.0f),
  42534. totalNumChars (0),
  42535. caretPosition (0),
  42536. passwordCharacter (passwordCharacter_),
  42537. dragType (notDragging)
  42538. {
  42539. setOpaque (true);
  42540. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42541. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42542. viewport->setWantsKeyboardFocus (false);
  42543. viewport->setScrollBarsShown (false, false);
  42544. setMouseCursor (MouseCursor::IBeamCursor);
  42545. setWantsKeyboardFocus (true);
  42546. }
  42547. TextEditor::~TextEditor()
  42548. {
  42549. textValue.referTo (Value());
  42550. clearInternal (0);
  42551. viewport = 0;
  42552. textHolder = 0;
  42553. }
  42554. void TextEditor::newTransaction()
  42555. {
  42556. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42557. undoManager.beginNewTransaction();
  42558. }
  42559. void TextEditor::doUndoRedo (const bool isRedo)
  42560. {
  42561. if (! isReadOnly())
  42562. {
  42563. if (isRedo ? undoManager.redo()
  42564. : undoManager.undo())
  42565. {
  42566. scrollToMakeSureCursorIsVisible();
  42567. repaint();
  42568. textChanged();
  42569. }
  42570. }
  42571. }
  42572. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42573. const bool shouldWordWrap)
  42574. {
  42575. if (multiline != shouldBeMultiLine
  42576. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42577. {
  42578. multiline = shouldBeMultiLine;
  42579. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42580. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42581. scrollbarVisible && multiline);
  42582. viewport->setViewPosition (0, 0);
  42583. resized();
  42584. scrollToMakeSureCursorIsVisible();
  42585. }
  42586. }
  42587. bool TextEditor::isMultiLine() const
  42588. {
  42589. return multiline;
  42590. }
  42591. void TextEditor::setScrollbarsShown (bool shown)
  42592. {
  42593. if (scrollbarVisible != shown)
  42594. {
  42595. scrollbarVisible = shown;
  42596. shown = shown && isMultiLine();
  42597. viewport->setScrollBarsShown (shown, shown);
  42598. }
  42599. }
  42600. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42601. {
  42602. if (readOnly != shouldBeReadOnly)
  42603. {
  42604. readOnly = shouldBeReadOnly;
  42605. enablementChanged();
  42606. }
  42607. }
  42608. bool TextEditor::isReadOnly() const
  42609. {
  42610. return readOnly || ! isEnabled();
  42611. }
  42612. bool TextEditor::isTextInputActive() const
  42613. {
  42614. return ! isReadOnly();
  42615. }
  42616. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42617. {
  42618. returnKeyStartsNewLine = shouldStartNewLine;
  42619. }
  42620. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42621. {
  42622. tabKeyUsed = shouldTabKeyBeUsed;
  42623. }
  42624. void TextEditor::setPopupMenuEnabled (const bool b)
  42625. {
  42626. popupMenuEnabled = b;
  42627. }
  42628. void TextEditor::setSelectAllWhenFocused (const bool b)
  42629. {
  42630. selectAllTextWhenFocused = b;
  42631. }
  42632. const Font TextEditor::getFont() const
  42633. {
  42634. return currentFont;
  42635. }
  42636. void TextEditor::setFont (const Font& newFont)
  42637. {
  42638. currentFont = newFont;
  42639. scrollToMakeSureCursorIsVisible();
  42640. }
  42641. void TextEditor::applyFontToAllText (const Font& newFont)
  42642. {
  42643. currentFont = newFont;
  42644. const Colour overallColour (findColour (textColourId));
  42645. for (int i = sections.size(); --i >= 0;)
  42646. {
  42647. UniformTextSection* const uts = sections.getUnchecked (i);
  42648. uts->setFont (newFont, passwordCharacter);
  42649. uts->colour = overallColour;
  42650. }
  42651. coalesceSimilarSections();
  42652. updateTextHolderSize();
  42653. scrollToMakeSureCursorIsVisible();
  42654. repaint();
  42655. }
  42656. void TextEditor::colourChanged()
  42657. {
  42658. setOpaque (findColour (backgroundColourId).isOpaque());
  42659. repaint();
  42660. }
  42661. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42662. {
  42663. caretVisible = shouldCaretBeVisible;
  42664. if (shouldCaretBeVisible)
  42665. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42666. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42667. : MouseCursor::NormalCursor);
  42668. }
  42669. void TextEditor::setInputRestrictions (const int maxLen,
  42670. const String& chars)
  42671. {
  42672. maxTextLength = jmax (0, maxLen);
  42673. allowedCharacters = chars;
  42674. }
  42675. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42676. {
  42677. textToShowWhenEmpty = text;
  42678. colourForTextWhenEmpty = colourToUse;
  42679. }
  42680. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42681. {
  42682. if (passwordCharacter != newPasswordCharacter)
  42683. {
  42684. passwordCharacter = newPasswordCharacter;
  42685. resized();
  42686. repaint();
  42687. }
  42688. }
  42689. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42690. {
  42691. viewport->setScrollBarThickness (newThicknessPixels);
  42692. }
  42693. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42694. {
  42695. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42696. }
  42697. void TextEditor::clear()
  42698. {
  42699. clearInternal (0);
  42700. updateTextHolderSize();
  42701. undoManager.clearUndoHistory();
  42702. }
  42703. void TextEditor::setText (const String& newText,
  42704. const bool sendTextChangeMessage)
  42705. {
  42706. const int newLength = newText.length();
  42707. if (newLength != getTotalNumChars() || getText() != newText)
  42708. {
  42709. const int oldCursorPos = caretPosition;
  42710. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42711. clearInternal (0);
  42712. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42713. // if you're adding text with line-feeds to a single-line text editor, it
  42714. // ain't gonna look right!
  42715. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42716. if (cursorWasAtEnd && ! isMultiLine())
  42717. moveCursorTo (getTotalNumChars(), false);
  42718. else
  42719. moveCursorTo (oldCursorPos, false);
  42720. if (sendTextChangeMessage)
  42721. textChanged();
  42722. updateTextHolderSize();
  42723. scrollToMakeSureCursorIsVisible();
  42724. undoManager.clearUndoHistory();
  42725. repaint();
  42726. }
  42727. }
  42728. Value& TextEditor::getTextValue()
  42729. {
  42730. if (valueTextNeedsUpdating)
  42731. {
  42732. valueTextNeedsUpdating = false;
  42733. textValue = getText();
  42734. }
  42735. return textValue;
  42736. }
  42737. void TextEditor::textWasChangedByValue()
  42738. {
  42739. if (textValue.getValueSource().getReferenceCount() > 1)
  42740. setText (textValue.getValue());
  42741. }
  42742. void TextEditor::textChanged()
  42743. {
  42744. updateTextHolderSize();
  42745. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42746. if (textValue.getValueSource().getReferenceCount() > 1)
  42747. {
  42748. valueTextNeedsUpdating = false;
  42749. textValue = getText();
  42750. }
  42751. }
  42752. void TextEditor::returnPressed()
  42753. {
  42754. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42755. }
  42756. void TextEditor::escapePressed()
  42757. {
  42758. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42759. }
  42760. void TextEditor::addListener (TextEditorListener* const newListener)
  42761. {
  42762. listeners.add (newListener);
  42763. }
  42764. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42765. {
  42766. listeners.remove (listenerToRemove);
  42767. }
  42768. void TextEditor::timerCallbackInt()
  42769. {
  42770. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42771. if (caretFlashState != newState)
  42772. {
  42773. caretFlashState = newState;
  42774. if (caretFlashState)
  42775. wasFocused = true;
  42776. if (caretVisible
  42777. && hasKeyboardFocus (false)
  42778. && ! isReadOnly())
  42779. {
  42780. repaintCaret();
  42781. }
  42782. }
  42783. const unsigned int now = Time::getApproximateMillisecondCounter();
  42784. if (now > lastTransactionTime + 200)
  42785. newTransaction();
  42786. }
  42787. void TextEditor::repaintCaret()
  42788. {
  42789. if (! findColour (caretColourId).isTransparent())
  42790. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42791. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42792. 4,
  42793. roundToInt (cursorHeight) + 2);
  42794. }
  42795. void TextEditor::repaintText (const Range<int>& range)
  42796. {
  42797. if (! range.isEmpty())
  42798. {
  42799. float x = 0, y = 0, lh = currentFont.getHeight();
  42800. const float wordWrapWidth = getWordWrapWidth();
  42801. if (wordWrapWidth > 0)
  42802. {
  42803. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42804. i.getCharPosition (range.getStart(), x, y, lh);
  42805. const int y1 = (int) y;
  42806. int y2;
  42807. if (range.getEnd() >= getTotalNumChars())
  42808. {
  42809. y2 = textHolder->getHeight();
  42810. }
  42811. else
  42812. {
  42813. i.getCharPosition (range.getEnd(), x, y, lh);
  42814. y2 = (int) (y + lh * 2.0f);
  42815. }
  42816. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42817. }
  42818. }
  42819. }
  42820. void TextEditor::moveCaret (int newCaretPos)
  42821. {
  42822. if (newCaretPos < 0)
  42823. newCaretPos = 0;
  42824. else if (newCaretPos > getTotalNumChars())
  42825. newCaretPos = getTotalNumChars();
  42826. if (newCaretPos != getCaretPosition())
  42827. {
  42828. repaintCaret();
  42829. caretFlashState = true;
  42830. caretPosition = newCaretPos;
  42831. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42832. scrollToMakeSureCursorIsVisible();
  42833. repaintCaret();
  42834. }
  42835. }
  42836. void TextEditor::setCaretPosition (const int newIndex)
  42837. {
  42838. moveCursorTo (newIndex, false);
  42839. }
  42840. int TextEditor::getCaretPosition() const
  42841. {
  42842. return caretPosition;
  42843. }
  42844. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42845. const int desiredCaretY)
  42846. {
  42847. updateCaretPosition();
  42848. int vx = roundToInt (cursorX) - desiredCaretX;
  42849. int vy = roundToInt (cursorY) - desiredCaretY;
  42850. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42851. {
  42852. vx += desiredCaretX - proportionOfWidth (0.2f);
  42853. }
  42854. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42855. {
  42856. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42857. }
  42858. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42859. if (! isMultiLine())
  42860. {
  42861. vy = viewport->getViewPositionY();
  42862. }
  42863. else
  42864. {
  42865. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42866. const int curH = roundToInt (cursorHeight);
  42867. if (desiredCaretY < 0)
  42868. {
  42869. vy = jmax (0, desiredCaretY + vy);
  42870. }
  42871. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42872. {
  42873. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42874. }
  42875. }
  42876. viewport->setViewPosition (vx, vy);
  42877. }
  42878. const Rectangle<int> TextEditor::getCaretRectangle()
  42879. {
  42880. updateCaretPosition();
  42881. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42882. roundToInt (cursorY) - viewport->getY(),
  42883. 1, roundToInt (cursorHeight));
  42884. }
  42885. float TextEditor::getWordWrapWidth() const
  42886. {
  42887. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42888. : 1.0e10f;
  42889. }
  42890. void TextEditor::updateTextHolderSize()
  42891. {
  42892. const float wordWrapWidth = getWordWrapWidth();
  42893. if (wordWrapWidth > 0)
  42894. {
  42895. float maxWidth = 0.0f;
  42896. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42897. while (i.next())
  42898. maxWidth = jmax (maxWidth, i.atomRight);
  42899. const int w = leftIndent + roundToInt (maxWidth);
  42900. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42901. currentFont.getHeight()));
  42902. textHolder->setSize (w + 1, h + 1);
  42903. }
  42904. }
  42905. int TextEditor::getTextWidth() const
  42906. {
  42907. return textHolder->getWidth();
  42908. }
  42909. int TextEditor::getTextHeight() const
  42910. {
  42911. return textHolder->getHeight();
  42912. }
  42913. void TextEditor::setIndents (const int newLeftIndent,
  42914. const int newTopIndent)
  42915. {
  42916. leftIndent = newLeftIndent;
  42917. topIndent = newTopIndent;
  42918. }
  42919. void TextEditor::setBorder (const BorderSize<int>& border)
  42920. {
  42921. borderSize = border;
  42922. resized();
  42923. }
  42924. const BorderSize<int> TextEditor::getBorder() const
  42925. {
  42926. return borderSize;
  42927. }
  42928. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42929. {
  42930. keepCursorOnScreen = shouldScrollToShowCursor;
  42931. }
  42932. void TextEditor::updateCaretPosition()
  42933. {
  42934. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42935. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42936. }
  42937. void TextEditor::scrollToMakeSureCursorIsVisible()
  42938. {
  42939. updateCaretPosition();
  42940. if (keepCursorOnScreen)
  42941. {
  42942. int x = viewport->getViewPositionX();
  42943. int y = viewport->getViewPositionY();
  42944. const int relativeCursorX = roundToInt (cursorX) - x;
  42945. const int relativeCursorY = roundToInt (cursorY) - y;
  42946. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42947. {
  42948. x += relativeCursorX - proportionOfWidth (0.2f);
  42949. }
  42950. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42951. {
  42952. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42953. }
  42954. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42955. if (! isMultiLine())
  42956. {
  42957. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42958. }
  42959. else
  42960. {
  42961. const int curH = roundToInt (cursorHeight);
  42962. if (relativeCursorY < 0)
  42963. {
  42964. y = jmax (0, relativeCursorY + y);
  42965. }
  42966. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42967. {
  42968. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42969. }
  42970. }
  42971. viewport->setViewPosition (x, y);
  42972. }
  42973. }
  42974. void TextEditor::moveCursorTo (const int newPosition,
  42975. const bool isSelecting)
  42976. {
  42977. if (isSelecting)
  42978. {
  42979. moveCaret (newPosition);
  42980. const Range<int> oldSelection (selection);
  42981. if (dragType == notDragging)
  42982. {
  42983. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42984. dragType = draggingSelectionStart;
  42985. else
  42986. dragType = draggingSelectionEnd;
  42987. }
  42988. if (dragType == draggingSelectionStart)
  42989. {
  42990. if (getCaretPosition() >= selection.getEnd())
  42991. dragType = draggingSelectionEnd;
  42992. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42993. }
  42994. else
  42995. {
  42996. if (getCaretPosition() < selection.getStart())
  42997. dragType = draggingSelectionStart;
  42998. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42999. }
  43000. repaintText (selection.getUnionWith (oldSelection));
  43001. }
  43002. else
  43003. {
  43004. dragType = notDragging;
  43005. repaintText (selection);
  43006. moveCaret (newPosition);
  43007. selection = Range<int>::emptyRange (getCaretPosition());
  43008. }
  43009. }
  43010. int TextEditor::getTextIndexAt (const int x,
  43011. const int y)
  43012. {
  43013. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43014. (float) (y + viewport->getViewPositionY() - topIndent));
  43015. }
  43016. void TextEditor::insertTextAtCaret (const String& newText_)
  43017. {
  43018. String newText (newText_);
  43019. if (allowedCharacters.isNotEmpty())
  43020. newText = newText.retainCharacters (allowedCharacters);
  43021. if (! isMultiLine())
  43022. newText = newText.replaceCharacters ("\r\n", " ");
  43023. else
  43024. newText = newText.replace ("\r\n", "\n");
  43025. const int newCaretPos = selection.getStart() + newText.length();
  43026. const int insertIndex = selection.getStart();
  43027. remove (selection, getUndoManager(),
  43028. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43029. if (maxTextLength > 0)
  43030. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43031. if (newText.isNotEmpty())
  43032. insert (newText,
  43033. insertIndex,
  43034. currentFont,
  43035. findColour (textColourId),
  43036. getUndoManager(),
  43037. newCaretPos);
  43038. textChanged();
  43039. }
  43040. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43041. {
  43042. moveCursorTo (newSelection.getStart(), false);
  43043. moveCursorTo (newSelection.getEnd(), true);
  43044. }
  43045. void TextEditor::copy()
  43046. {
  43047. if (passwordCharacter == 0)
  43048. {
  43049. const String selectedText (getHighlightedText());
  43050. if (selectedText.isNotEmpty())
  43051. SystemClipboard::copyTextToClipboard (selectedText);
  43052. }
  43053. }
  43054. void TextEditor::paste()
  43055. {
  43056. if (! isReadOnly())
  43057. {
  43058. const String clip (SystemClipboard::getTextFromClipboard());
  43059. if (clip.isNotEmpty())
  43060. insertTextAtCaret (clip);
  43061. }
  43062. }
  43063. void TextEditor::cut()
  43064. {
  43065. if (! isReadOnly())
  43066. {
  43067. moveCaret (selection.getEnd());
  43068. insertTextAtCaret (String::empty);
  43069. }
  43070. }
  43071. void TextEditor::drawContent (Graphics& g)
  43072. {
  43073. const float wordWrapWidth = getWordWrapWidth();
  43074. if (wordWrapWidth > 0)
  43075. {
  43076. g.setOrigin (leftIndent, topIndent);
  43077. const Rectangle<int> clip (g.getClipBounds());
  43078. Colour selectedTextColour;
  43079. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43080. while (i.lineY + 200.0 < clip.getY() && i.next())
  43081. {}
  43082. if (! selection.isEmpty())
  43083. {
  43084. g.setColour (findColour (highlightColourId)
  43085. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43086. selectedTextColour = findColour (highlightedTextColourId);
  43087. Iterator i2 (i);
  43088. while (i2.next() && i2.lineY < clip.getBottom())
  43089. {
  43090. if (i2.lineY + i2.lineHeight >= clip.getY()
  43091. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43092. {
  43093. i2.drawSelection (g, selection);
  43094. }
  43095. }
  43096. }
  43097. const UniformTextSection* lastSection = 0;
  43098. while (i.next() && i.lineY < clip.getBottom())
  43099. {
  43100. if (i.lineY + i.lineHeight >= clip.getY())
  43101. {
  43102. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43103. {
  43104. i.drawSelectedText (g, selection, selectedTextColour);
  43105. lastSection = 0;
  43106. }
  43107. else
  43108. {
  43109. i.draw (g, lastSection);
  43110. }
  43111. }
  43112. }
  43113. }
  43114. }
  43115. void TextEditor::paint (Graphics& g)
  43116. {
  43117. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43118. }
  43119. void TextEditor::paintOverChildren (Graphics& g)
  43120. {
  43121. if (caretFlashState
  43122. && hasKeyboardFocus (false)
  43123. && caretVisible
  43124. && ! isReadOnly())
  43125. {
  43126. g.setColour (findColour (caretColourId));
  43127. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43128. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43129. 2.0f, cursorHeight);
  43130. }
  43131. if (textToShowWhenEmpty.isNotEmpty()
  43132. && (! hasKeyboardFocus (false))
  43133. && getTotalNumChars() == 0)
  43134. {
  43135. g.setColour (colourForTextWhenEmpty);
  43136. g.setFont (getFont());
  43137. if (isMultiLine())
  43138. {
  43139. g.drawText (textToShowWhenEmpty,
  43140. 0, 0, getWidth(), getHeight(),
  43141. Justification::centred, true);
  43142. }
  43143. else
  43144. {
  43145. g.drawText (textToShowWhenEmpty,
  43146. leftIndent, topIndent,
  43147. viewport->getWidth() - leftIndent,
  43148. viewport->getHeight() - topIndent,
  43149. Justification::centredLeft, true);
  43150. }
  43151. }
  43152. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43153. }
  43154. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43155. {
  43156. public:
  43157. TextEditorMenuPerformer (TextEditor* const editor_)
  43158. : editor (editor_)
  43159. {
  43160. }
  43161. void modalStateFinished (int returnValue)
  43162. {
  43163. if (editor != 0 && returnValue != 0)
  43164. editor->performPopupMenuAction (returnValue);
  43165. }
  43166. private:
  43167. Component::SafePointer<TextEditor> editor;
  43168. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43169. };
  43170. void TextEditor::mouseDown (const MouseEvent& e)
  43171. {
  43172. beginDragAutoRepeat (100);
  43173. newTransaction();
  43174. if (wasFocused || ! selectAllTextWhenFocused)
  43175. {
  43176. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43177. {
  43178. moveCursorTo (getTextIndexAt (e.x, e.y),
  43179. e.mods.isShiftDown());
  43180. }
  43181. else
  43182. {
  43183. PopupMenu m;
  43184. m.setLookAndFeel (&getLookAndFeel());
  43185. addPopupMenuItems (m, &e);
  43186. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43187. }
  43188. }
  43189. }
  43190. void TextEditor::mouseDrag (const MouseEvent& e)
  43191. {
  43192. if (wasFocused || ! selectAllTextWhenFocused)
  43193. {
  43194. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43195. {
  43196. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43197. }
  43198. }
  43199. }
  43200. void TextEditor::mouseUp (const MouseEvent& e)
  43201. {
  43202. newTransaction();
  43203. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43204. if (wasFocused || ! selectAllTextWhenFocused)
  43205. {
  43206. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43207. {
  43208. moveCaret (getTextIndexAt (e.x, e.y));
  43209. }
  43210. }
  43211. wasFocused = true;
  43212. }
  43213. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43214. {
  43215. int tokenEnd = getTextIndexAt (e.x, e.y);
  43216. int tokenStart = tokenEnd;
  43217. if (e.getNumberOfClicks() > 3)
  43218. {
  43219. tokenStart = 0;
  43220. tokenEnd = getTotalNumChars();
  43221. }
  43222. else
  43223. {
  43224. const String t (getText());
  43225. const int totalLength = getTotalNumChars();
  43226. while (tokenEnd < totalLength)
  43227. {
  43228. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43229. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43230. ++tokenEnd;
  43231. else
  43232. break;
  43233. }
  43234. tokenStart = tokenEnd;
  43235. while (tokenStart > 0)
  43236. {
  43237. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43238. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43239. --tokenStart;
  43240. else
  43241. break;
  43242. }
  43243. if (e.getNumberOfClicks() > 2)
  43244. {
  43245. while (tokenEnd < totalLength)
  43246. {
  43247. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43248. ++tokenEnd;
  43249. else
  43250. break;
  43251. }
  43252. while (tokenStart > 0)
  43253. {
  43254. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43255. --tokenStart;
  43256. else
  43257. break;
  43258. }
  43259. }
  43260. }
  43261. moveCursorTo (tokenEnd, false);
  43262. moveCursorTo (tokenStart, true);
  43263. }
  43264. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43265. {
  43266. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43267. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43268. }
  43269. bool TextEditor::keyPressed (const KeyPress& key)
  43270. {
  43271. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43272. return false;
  43273. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43274. if (key.isKeyCode (KeyPress::leftKey)
  43275. || key.isKeyCode (KeyPress::upKey))
  43276. {
  43277. newTransaction();
  43278. int newPos;
  43279. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43280. newPos = indexAtPosition (cursorX, cursorY - 1);
  43281. else if (moveInWholeWordSteps)
  43282. newPos = findWordBreakBefore (getCaretPosition());
  43283. else
  43284. newPos = getCaretPosition() - 1;
  43285. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43286. }
  43287. else if (key.isKeyCode (KeyPress::rightKey)
  43288. || key.isKeyCode (KeyPress::downKey))
  43289. {
  43290. newTransaction();
  43291. int newPos;
  43292. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43293. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43294. else if (moveInWholeWordSteps)
  43295. newPos = findWordBreakAfter (getCaretPosition());
  43296. else
  43297. newPos = getCaretPosition() + 1;
  43298. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43299. }
  43300. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43301. {
  43302. newTransaction();
  43303. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43304. key.getModifiers().isShiftDown());
  43305. }
  43306. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43307. {
  43308. newTransaction();
  43309. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43310. key.getModifiers().isShiftDown());
  43311. }
  43312. else if (key.isKeyCode (KeyPress::homeKey))
  43313. {
  43314. newTransaction();
  43315. if (isMultiLine() && ! moveInWholeWordSteps)
  43316. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43317. key.getModifiers().isShiftDown());
  43318. else
  43319. moveCursorTo (0, key.getModifiers().isShiftDown());
  43320. }
  43321. else if (key.isKeyCode (KeyPress::endKey))
  43322. {
  43323. newTransaction();
  43324. if (isMultiLine() && ! moveInWholeWordSteps)
  43325. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43326. key.getModifiers().isShiftDown());
  43327. else
  43328. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43329. }
  43330. else if (key.isKeyCode (KeyPress::backspaceKey))
  43331. {
  43332. if (moveInWholeWordSteps)
  43333. {
  43334. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43335. }
  43336. else
  43337. {
  43338. if (selection.isEmpty() && selection.getStart() > 0)
  43339. selection.setStart (selection.getEnd() - 1);
  43340. }
  43341. cut();
  43342. }
  43343. else if (key.isKeyCode (KeyPress::deleteKey))
  43344. {
  43345. if (key.getModifiers().isShiftDown())
  43346. copy();
  43347. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43348. selection.setEnd (selection.getStart() + 1);
  43349. cut();
  43350. }
  43351. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43352. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43353. {
  43354. newTransaction();
  43355. copy();
  43356. }
  43357. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43358. {
  43359. newTransaction();
  43360. copy();
  43361. cut();
  43362. }
  43363. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43364. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43365. {
  43366. newTransaction();
  43367. paste();
  43368. }
  43369. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43370. {
  43371. newTransaction();
  43372. doUndoRedo (false);
  43373. }
  43374. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43375. {
  43376. newTransaction();
  43377. doUndoRedo (true);
  43378. }
  43379. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43380. {
  43381. newTransaction();
  43382. moveCursorTo (getTotalNumChars(), false);
  43383. moveCursorTo (0, true);
  43384. }
  43385. else if (key == KeyPress::returnKey)
  43386. {
  43387. newTransaction();
  43388. if (returnKeyStartsNewLine)
  43389. insertTextAtCaret ("\n");
  43390. else
  43391. returnPressed();
  43392. }
  43393. else if (key.isKeyCode (KeyPress::escapeKey))
  43394. {
  43395. newTransaction();
  43396. moveCursorTo (getCaretPosition(), false);
  43397. escapePressed();
  43398. }
  43399. else if (key.getTextCharacter() >= ' '
  43400. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43401. {
  43402. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43403. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43404. }
  43405. else
  43406. {
  43407. return false;
  43408. }
  43409. return true;
  43410. }
  43411. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43412. {
  43413. if (! isKeyDown)
  43414. return false;
  43415. #if JUCE_WINDOWS
  43416. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43417. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43418. #endif
  43419. // (overridden to avoid forwarding key events to the parent)
  43420. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43421. }
  43422. const int baseMenuItemID = 0x7fff0000;
  43423. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43424. {
  43425. const bool writable = ! isReadOnly();
  43426. if (passwordCharacter == 0)
  43427. {
  43428. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43429. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43430. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43431. }
  43432. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43433. m.addSeparator();
  43434. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43435. m.addSeparator();
  43436. if (getUndoManager() != 0)
  43437. {
  43438. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43439. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43440. }
  43441. }
  43442. void TextEditor::performPopupMenuAction (const int menuItemID)
  43443. {
  43444. switch (menuItemID)
  43445. {
  43446. case baseMenuItemID + 1:
  43447. copy();
  43448. cut();
  43449. break;
  43450. case baseMenuItemID + 2:
  43451. copy();
  43452. break;
  43453. case baseMenuItemID + 3:
  43454. paste();
  43455. break;
  43456. case baseMenuItemID + 4:
  43457. cut();
  43458. break;
  43459. case baseMenuItemID + 5:
  43460. moveCursorTo (getTotalNumChars(), false);
  43461. moveCursorTo (0, true);
  43462. break;
  43463. case baseMenuItemID + 6:
  43464. doUndoRedo (false);
  43465. break;
  43466. case baseMenuItemID + 7:
  43467. doUndoRedo (true);
  43468. break;
  43469. default:
  43470. break;
  43471. }
  43472. }
  43473. void TextEditor::focusGained (FocusChangeType)
  43474. {
  43475. newTransaction();
  43476. caretFlashState = true;
  43477. if (selectAllTextWhenFocused)
  43478. {
  43479. moveCursorTo (0, false);
  43480. moveCursorTo (getTotalNumChars(), true);
  43481. }
  43482. repaint();
  43483. if (caretVisible)
  43484. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43485. ComponentPeer* const peer = getPeer();
  43486. if (peer != 0 && ! isReadOnly())
  43487. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43488. }
  43489. void TextEditor::focusLost (FocusChangeType)
  43490. {
  43491. newTransaction();
  43492. wasFocused = false;
  43493. textHolder->stopTimer();
  43494. caretFlashState = false;
  43495. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43496. repaint();
  43497. }
  43498. void TextEditor::resized()
  43499. {
  43500. viewport->setBoundsInset (borderSize);
  43501. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43502. updateTextHolderSize();
  43503. if (! isMultiLine())
  43504. {
  43505. scrollToMakeSureCursorIsVisible();
  43506. }
  43507. else
  43508. {
  43509. updateCaretPosition();
  43510. }
  43511. }
  43512. void TextEditor::handleCommandMessage (const int commandId)
  43513. {
  43514. Component::BailOutChecker checker (this);
  43515. switch (commandId)
  43516. {
  43517. case TextEditorDefs::textChangeMessageId:
  43518. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43519. break;
  43520. case TextEditorDefs::returnKeyMessageId:
  43521. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43522. break;
  43523. case TextEditorDefs::escapeKeyMessageId:
  43524. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43525. break;
  43526. case TextEditorDefs::focusLossMessageId:
  43527. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43528. break;
  43529. default:
  43530. jassertfalse;
  43531. break;
  43532. }
  43533. }
  43534. void TextEditor::enablementChanged()
  43535. {
  43536. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43537. : MouseCursor::IBeamCursor);
  43538. repaint();
  43539. }
  43540. UndoManager* TextEditor::getUndoManager() throw()
  43541. {
  43542. return isReadOnly() ? 0 : &undoManager;
  43543. }
  43544. void TextEditor::clearInternal (UndoManager* const um)
  43545. {
  43546. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43547. }
  43548. void TextEditor::insert (const String& text,
  43549. const int insertIndex,
  43550. const Font& font,
  43551. const Colour& colour,
  43552. UndoManager* const um,
  43553. const int caretPositionToMoveTo)
  43554. {
  43555. if (text.isNotEmpty())
  43556. {
  43557. if (um != 0)
  43558. {
  43559. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43560. newTransaction();
  43561. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43562. caretPosition, caretPositionToMoveTo));
  43563. }
  43564. else
  43565. {
  43566. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43567. // a line gets moved due to word wrap
  43568. int index = 0;
  43569. int nextIndex = 0;
  43570. for (int i = 0; i < sections.size(); ++i)
  43571. {
  43572. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43573. if (insertIndex == index)
  43574. {
  43575. sections.insert (i, new UniformTextSection (text,
  43576. font, colour,
  43577. passwordCharacter));
  43578. break;
  43579. }
  43580. else if (insertIndex > index && insertIndex < nextIndex)
  43581. {
  43582. splitSection (i, insertIndex - index);
  43583. sections.insert (i + 1, new UniformTextSection (text,
  43584. font, colour,
  43585. passwordCharacter));
  43586. break;
  43587. }
  43588. index = nextIndex;
  43589. }
  43590. if (nextIndex == insertIndex)
  43591. sections.add (new UniformTextSection (text,
  43592. font, colour,
  43593. passwordCharacter));
  43594. coalesceSimilarSections();
  43595. totalNumChars = -1;
  43596. valueTextNeedsUpdating = true;
  43597. moveCursorTo (caretPositionToMoveTo, false);
  43598. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43599. }
  43600. }
  43601. }
  43602. void TextEditor::reinsert (const int insertIndex,
  43603. const Array <UniformTextSection*>& sectionsToInsert)
  43604. {
  43605. int index = 0;
  43606. int nextIndex = 0;
  43607. for (int i = 0; i < sections.size(); ++i)
  43608. {
  43609. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43610. if (insertIndex == index)
  43611. {
  43612. for (int j = sectionsToInsert.size(); --j >= 0;)
  43613. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43614. break;
  43615. }
  43616. else if (insertIndex > index && insertIndex < nextIndex)
  43617. {
  43618. splitSection (i, insertIndex - index);
  43619. for (int j = sectionsToInsert.size(); --j >= 0;)
  43620. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43621. break;
  43622. }
  43623. index = nextIndex;
  43624. }
  43625. if (nextIndex == insertIndex)
  43626. {
  43627. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43628. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43629. }
  43630. coalesceSimilarSections();
  43631. totalNumChars = -1;
  43632. valueTextNeedsUpdating = true;
  43633. }
  43634. void TextEditor::remove (const Range<int>& range,
  43635. UndoManager* const um,
  43636. const int caretPositionToMoveTo)
  43637. {
  43638. if (! range.isEmpty())
  43639. {
  43640. int index = 0;
  43641. for (int i = 0; i < sections.size(); ++i)
  43642. {
  43643. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43644. if (range.getStart() > index && range.getStart() < nextIndex)
  43645. {
  43646. splitSection (i, range.getStart() - index);
  43647. --i;
  43648. }
  43649. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43650. {
  43651. splitSection (i, range.getEnd() - index);
  43652. --i;
  43653. }
  43654. else
  43655. {
  43656. index = nextIndex;
  43657. if (index > range.getEnd())
  43658. break;
  43659. }
  43660. }
  43661. index = 0;
  43662. if (um != 0)
  43663. {
  43664. Array <UniformTextSection*> removedSections;
  43665. for (int i = 0; i < sections.size(); ++i)
  43666. {
  43667. if (range.getEnd() <= range.getStart())
  43668. break;
  43669. UniformTextSection* const section = sections.getUnchecked (i);
  43670. const int nextIndex = index + section->getTotalLength();
  43671. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43672. removedSections.add (new UniformTextSection (*section));
  43673. index = nextIndex;
  43674. }
  43675. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43676. newTransaction();
  43677. um->perform (new RemoveAction (*this, range, caretPosition,
  43678. caretPositionToMoveTo, removedSections));
  43679. }
  43680. else
  43681. {
  43682. Range<int> remainingRange (range);
  43683. for (int i = 0; i < sections.size(); ++i)
  43684. {
  43685. UniformTextSection* const section = sections.getUnchecked (i);
  43686. const int nextIndex = index + section->getTotalLength();
  43687. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43688. {
  43689. sections.remove(i);
  43690. section->clear();
  43691. delete section;
  43692. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43693. if (remainingRange.isEmpty())
  43694. break;
  43695. --i;
  43696. }
  43697. else
  43698. {
  43699. index = nextIndex;
  43700. }
  43701. }
  43702. coalesceSimilarSections();
  43703. totalNumChars = -1;
  43704. valueTextNeedsUpdating = true;
  43705. moveCursorTo (caretPositionToMoveTo, false);
  43706. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43707. }
  43708. }
  43709. }
  43710. const String TextEditor::getText() const
  43711. {
  43712. String t;
  43713. t.preallocateStorage (getTotalNumChars());
  43714. String::Concatenator concatenator (t);
  43715. for (int i = 0; i < sections.size(); ++i)
  43716. sections.getUnchecked (i)->appendAllText (concatenator);
  43717. return t;
  43718. }
  43719. const String TextEditor::getTextInRange (const Range<int>& range) const
  43720. {
  43721. String t;
  43722. if (! range.isEmpty())
  43723. {
  43724. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43725. String::Concatenator concatenator (t);
  43726. int index = 0;
  43727. for (int i = 0; i < sections.size(); ++i)
  43728. {
  43729. const UniformTextSection* const s = sections.getUnchecked (i);
  43730. const int nextIndex = index + s->getTotalLength();
  43731. if (range.getStart() < nextIndex)
  43732. {
  43733. if (range.getEnd() <= index)
  43734. break;
  43735. s->appendSubstring (concatenator, range - index);
  43736. }
  43737. index = nextIndex;
  43738. }
  43739. }
  43740. return t;
  43741. }
  43742. const String TextEditor::getHighlightedText() const
  43743. {
  43744. return getTextInRange (selection);
  43745. }
  43746. int TextEditor::getTotalNumChars() const
  43747. {
  43748. if (totalNumChars < 0)
  43749. {
  43750. totalNumChars = 0;
  43751. for (int i = sections.size(); --i >= 0;)
  43752. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43753. }
  43754. return totalNumChars;
  43755. }
  43756. bool TextEditor::isEmpty() const
  43757. {
  43758. return getTotalNumChars() == 0;
  43759. }
  43760. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43761. {
  43762. const float wordWrapWidth = getWordWrapWidth();
  43763. if (wordWrapWidth > 0 && sections.size() > 0)
  43764. {
  43765. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43766. i.getCharPosition (index, cx, cy, lineHeight);
  43767. }
  43768. else
  43769. {
  43770. cx = cy = 0;
  43771. lineHeight = currentFont.getHeight();
  43772. }
  43773. }
  43774. int TextEditor::indexAtPosition (const float x, const float y)
  43775. {
  43776. const float wordWrapWidth = getWordWrapWidth();
  43777. if (wordWrapWidth > 0)
  43778. {
  43779. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43780. while (i.next())
  43781. {
  43782. if (i.lineY + i.lineHeight > y)
  43783. {
  43784. if (i.lineY > y)
  43785. return jmax (0, i.indexInText - 1);
  43786. if (i.atomX >= x)
  43787. return i.indexInText;
  43788. if (x < i.atomRight)
  43789. return i.xToIndex (x);
  43790. }
  43791. }
  43792. }
  43793. return getTotalNumChars();
  43794. }
  43795. int TextEditor::findWordBreakAfter (const int position) const
  43796. {
  43797. const String t (getTextInRange (Range<int> (position, position + 512)));
  43798. const int totalLength = t.length();
  43799. int i = 0;
  43800. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43801. ++i;
  43802. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43803. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43804. ++i;
  43805. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43806. ++i;
  43807. return position + i;
  43808. }
  43809. int TextEditor::findWordBreakBefore (const int position) const
  43810. {
  43811. if (position <= 0)
  43812. return 0;
  43813. const int startOfBuffer = jmax (0, position - 512);
  43814. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43815. int i = position - startOfBuffer;
  43816. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43817. --i;
  43818. if (i > 0)
  43819. {
  43820. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43821. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43822. --i;
  43823. }
  43824. jassert (startOfBuffer + i >= 0);
  43825. return startOfBuffer + i;
  43826. }
  43827. void TextEditor::splitSection (const int sectionIndex,
  43828. const int charToSplitAt)
  43829. {
  43830. jassert (sections[sectionIndex] != 0);
  43831. sections.insert (sectionIndex + 1,
  43832. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43833. }
  43834. void TextEditor::coalesceSimilarSections()
  43835. {
  43836. for (int i = 0; i < sections.size() - 1; ++i)
  43837. {
  43838. UniformTextSection* const s1 = sections.getUnchecked (i);
  43839. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43840. if (s1->font == s2->font
  43841. && s1->colour == s2->colour)
  43842. {
  43843. s1->append (*s2, passwordCharacter);
  43844. sections.remove (i + 1);
  43845. delete s2;
  43846. --i;
  43847. }
  43848. }
  43849. }
  43850. void TextEditor::Listener::textEditorTextChanged (TextEditor&) {}
  43851. void TextEditor::Listener::textEditorReturnKeyPressed (TextEditor&) {}
  43852. void TextEditor::Listener::textEditorEscapeKeyPressed (TextEditor&) {}
  43853. void TextEditor::Listener::textEditorFocusLost (TextEditor&) {}
  43854. END_JUCE_NAMESPACE
  43855. /*** End of inlined file: juce_TextEditor.cpp ***/
  43856. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43857. BEGIN_JUCE_NAMESPACE
  43858. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43859. class ToolbarSpacerComp : public ToolbarItemComponent
  43860. {
  43861. public:
  43862. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43863. : ToolbarItemComponent (itemId_, String::empty, false),
  43864. fixedSize (fixedSize_),
  43865. drawBar (drawBar_)
  43866. {
  43867. }
  43868. ~ToolbarSpacerComp()
  43869. {
  43870. }
  43871. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43872. int& preferredSize, int& minSize, int& maxSize)
  43873. {
  43874. if (fixedSize <= 0)
  43875. {
  43876. preferredSize = toolbarThickness * 2;
  43877. minSize = 4;
  43878. maxSize = 32768;
  43879. }
  43880. else
  43881. {
  43882. maxSize = roundToInt (toolbarThickness * fixedSize);
  43883. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43884. preferredSize = maxSize;
  43885. if (getEditingMode() == editableOnPalette)
  43886. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43887. }
  43888. return true;
  43889. }
  43890. void paintButtonArea (Graphics&, int, int, bool, bool)
  43891. {
  43892. }
  43893. void contentAreaChanged (const Rectangle<int>&)
  43894. {
  43895. }
  43896. int getResizeOrder() const throw()
  43897. {
  43898. return fixedSize <= 0 ? 0 : 1;
  43899. }
  43900. void paint (Graphics& g)
  43901. {
  43902. const int w = getWidth();
  43903. const int h = getHeight();
  43904. if (drawBar)
  43905. {
  43906. g.setColour (findColour (Toolbar::separatorColourId, true));
  43907. const float thickness = 0.2f;
  43908. if (isToolbarVertical())
  43909. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43910. else
  43911. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43912. }
  43913. if (getEditingMode() != normalMode && ! drawBar)
  43914. {
  43915. g.setColour (findColour (Toolbar::separatorColourId, true));
  43916. const int indentX = jmin (2, (w - 3) / 2);
  43917. const int indentY = jmin (2, (h - 3) / 2);
  43918. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43919. if (fixedSize <= 0)
  43920. {
  43921. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43922. if (isToolbarVertical())
  43923. {
  43924. x1 = w * 0.5f;
  43925. y1 = h * 0.4f;
  43926. x2 = x1;
  43927. y2 = indentX * 2.0f;
  43928. x3 = x1;
  43929. y3 = h * 0.6f;
  43930. x4 = x1;
  43931. y4 = h - y2;
  43932. hw = w * 0.15f;
  43933. hl = w * 0.2f;
  43934. }
  43935. else
  43936. {
  43937. x1 = w * 0.4f;
  43938. y1 = h * 0.5f;
  43939. x2 = indentX * 2.0f;
  43940. y2 = y1;
  43941. x3 = w * 0.6f;
  43942. y3 = y1;
  43943. x4 = w - x2;
  43944. y4 = y1;
  43945. hw = h * 0.15f;
  43946. hl = h * 0.2f;
  43947. }
  43948. Path p;
  43949. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43950. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43951. g.fillPath (p);
  43952. }
  43953. }
  43954. }
  43955. private:
  43956. const float fixedSize;
  43957. const bool drawBar;
  43958. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  43959. };
  43960. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  43961. {
  43962. public:
  43963. MissingItemsComponent (Toolbar& owner_, const int height_)
  43964. : PopupMenu::CustomComponent (true),
  43965. owner (&owner_),
  43966. height (height_)
  43967. {
  43968. for (int i = owner_.items.size(); --i >= 0;)
  43969. {
  43970. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43971. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43972. {
  43973. oldIndexes.insert (0, i);
  43974. addAndMakeVisible (tc, 0);
  43975. }
  43976. }
  43977. layout (400);
  43978. }
  43979. ~MissingItemsComponent()
  43980. {
  43981. if (owner != 0)
  43982. {
  43983. for (int i = 0; i < getNumChildComponents(); ++i)
  43984. {
  43985. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43986. if (tc != 0)
  43987. {
  43988. tc->setVisible (false);
  43989. const int index = oldIndexes.remove (i);
  43990. owner->addChildComponent (tc, index);
  43991. --i;
  43992. }
  43993. }
  43994. owner->resized();
  43995. }
  43996. }
  43997. void layout (const int preferredWidth)
  43998. {
  43999. const int indent = 8;
  44000. int x = indent;
  44001. int y = indent;
  44002. int maxX = 0;
  44003. for (int i = 0; i < getNumChildComponents(); ++i)
  44004. {
  44005. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44006. if (tc != 0)
  44007. {
  44008. int preferredSize = 1, minSize = 1, maxSize = 1;
  44009. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44010. {
  44011. if (x + preferredSize > preferredWidth && x > indent)
  44012. {
  44013. x = indent;
  44014. y += height;
  44015. }
  44016. tc->setBounds (x, y, preferredSize, height);
  44017. x += preferredSize;
  44018. maxX = jmax (maxX, x);
  44019. }
  44020. }
  44021. }
  44022. setSize (maxX + 8, y + height + 8);
  44023. }
  44024. void getIdealSize (int& idealWidth, int& idealHeight)
  44025. {
  44026. idealWidth = getWidth();
  44027. idealHeight = getHeight();
  44028. }
  44029. private:
  44030. Component::SafePointer<Toolbar> owner;
  44031. const int height;
  44032. Array <int> oldIndexes;
  44033. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44034. };
  44035. Toolbar::Toolbar()
  44036. : vertical (false),
  44037. isEditingActive (false),
  44038. toolbarStyle (Toolbar::iconsOnly)
  44039. {
  44040. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44041. missingItemsButton->setAlwaysOnTop (true);
  44042. missingItemsButton->addListener (this);
  44043. }
  44044. Toolbar::~Toolbar()
  44045. {
  44046. items.clear();
  44047. }
  44048. void Toolbar::setVertical (const bool shouldBeVertical)
  44049. {
  44050. if (vertical != shouldBeVertical)
  44051. {
  44052. vertical = shouldBeVertical;
  44053. resized();
  44054. }
  44055. }
  44056. void Toolbar::clear()
  44057. {
  44058. items.clear();
  44059. resized();
  44060. }
  44061. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44062. {
  44063. if (itemId == ToolbarItemFactory::separatorBarId)
  44064. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44065. else if (itemId == ToolbarItemFactory::spacerId)
  44066. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44067. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44068. return new ToolbarSpacerComp (itemId, 0, false);
  44069. return factory.createItem (itemId);
  44070. }
  44071. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44072. const int itemId,
  44073. const int insertIndex)
  44074. {
  44075. // An ID can't be zero - this might indicate a mistake somewhere?
  44076. jassert (itemId != 0);
  44077. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44078. if (tc != 0)
  44079. {
  44080. #if JUCE_DEBUG
  44081. Array <int> allowedIds;
  44082. factory.getAllToolbarItemIds (allowedIds);
  44083. // If your factory can create an item for a given ID, it must also return
  44084. // that ID from its getAllToolbarItemIds() method!
  44085. jassert (allowedIds.contains (itemId));
  44086. #endif
  44087. items.insert (insertIndex, tc);
  44088. addAndMakeVisible (tc, insertIndex);
  44089. }
  44090. }
  44091. void Toolbar::addItem (ToolbarItemFactory& factory,
  44092. const int itemId,
  44093. const int insertIndex)
  44094. {
  44095. addItemInternal (factory, itemId, insertIndex);
  44096. resized();
  44097. }
  44098. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44099. {
  44100. Array <int> ids;
  44101. factoryToUse.getDefaultItemSet (ids);
  44102. clear();
  44103. for (int i = 0; i < ids.size(); ++i)
  44104. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44105. resized();
  44106. }
  44107. void Toolbar::removeToolbarItem (const int itemIndex)
  44108. {
  44109. items.remove (itemIndex);
  44110. resized();
  44111. }
  44112. int Toolbar::getNumItems() const throw()
  44113. {
  44114. return items.size();
  44115. }
  44116. int Toolbar::getItemId (const int itemIndex) const throw()
  44117. {
  44118. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44119. return tc != 0 ? tc->getItemId() : 0;
  44120. }
  44121. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44122. {
  44123. return items [itemIndex];
  44124. }
  44125. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44126. {
  44127. for (;;)
  44128. {
  44129. index += delta;
  44130. ToolbarItemComponent* const tc = getItemComponent (index);
  44131. if (tc == 0)
  44132. break;
  44133. if (tc->isActive)
  44134. return tc;
  44135. }
  44136. return 0;
  44137. }
  44138. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44139. {
  44140. if (toolbarStyle != newStyle)
  44141. {
  44142. toolbarStyle = newStyle;
  44143. updateAllItemPositions (false);
  44144. }
  44145. }
  44146. const String Toolbar::toString() const
  44147. {
  44148. String s ("TB:");
  44149. for (int i = 0; i < getNumItems(); ++i)
  44150. s << getItemId(i) << ' ';
  44151. return s.trimEnd();
  44152. }
  44153. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44154. const String& savedVersion)
  44155. {
  44156. if (! savedVersion.startsWith ("TB:"))
  44157. return false;
  44158. StringArray tokens;
  44159. tokens.addTokens (savedVersion.substring (3), false);
  44160. clear();
  44161. for (int i = 0; i < tokens.size(); ++i)
  44162. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44163. resized();
  44164. return true;
  44165. }
  44166. void Toolbar::paint (Graphics& g)
  44167. {
  44168. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44169. }
  44170. int Toolbar::getThickness() const throw()
  44171. {
  44172. return vertical ? getWidth() : getHeight();
  44173. }
  44174. int Toolbar::getLength() const throw()
  44175. {
  44176. return vertical ? getHeight() : getWidth();
  44177. }
  44178. void Toolbar::setEditingActive (const bool active)
  44179. {
  44180. if (isEditingActive != active)
  44181. {
  44182. isEditingActive = active;
  44183. updateAllItemPositions (false);
  44184. }
  44185. }
  44186. void Toolbar::resized()
  44187. {
  44188. updateAllItemPositions (false);
  44189. }
  44190. void Toolbar::updateAllItemPositions (const bool animate)
  44191. {
  44192. if (getWidth() > 0 && getHeight() > 0)
  44193. {
  44194. StretchableObjectResizer resizer;
  44195. int i;
  44196. for (i = 0; i < items.size(); ++i)
  44197. {
  44198. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44199. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44200. : ToolbarItemComponent::normalMode);
  44201. tc->setStyle (toolbarStyle);
  44202. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44203. int preferredSize = 1, minSize = 1, maxSize = 1;
  44204. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44205. preferredSize, minSize, maxSize))
  44206. {
  44207. tc->isActive = true;
  44208. resizer.addItem (preferredSize, minSize, maxSize,
  44209. spacer != 0 ? spacer->getResizeOrder() : 2);
  44210. }
  44211. else
  44212. {
  44213. tc->isActive = false;
  44214. tc->setVisible (false);
  44215. }
  44216. }
  44217. resizer.resizeToFit (getLength());
  44218. int totalLength = 0;
  44219. for (i = 0; i < resizer.getNumItems(); ++i)
  44220. totalLength += (int) resizer.getItemSize (i);
  44221. const bool itemsOffTheEnd = totalLength > getLength();
  44222. const int extrasButtonSize = getThickness() / 2;
  44223. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44224. missingItemsButton->setVisible (itemsOffTheEnd);
  44225. missingItemsButton->setEnabled (! isEditingActive);
  44226. if (vertical)
  44227. missingItemsButton->setCentrePosition (getWidth() / 2,
  44228. getHeight() - 4 - extrasButtonSize / 2);
  44229. else
  44230. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44231. getHeight() / 2);
  44232. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44233. : missingItemsButton->getX()) - 4
  44234. : getLength();
  44235. int pos = 0, activeIndex = 0;
  44236. for (i = 0; i < items.size(); ++i)
  44237. {
  44238. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44239. if (tc->isActive)
  44240. {
  44241. const int size = (int) resizer.getItemSize (activeIndex++);
  44242. Rectangle<int> newBounds;
  44243. if (vertical)
  44244. newBounds.setBounds (0, pos, getWidth(), size);
  44245. else
  44246. newBounds.setBounds (pos, 0, size, getHeight());
  44247. if (animate)
  44248. {
  44249. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44250. }
  44251. else
  44252. {
  44253. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44254. tc->setBounds (newBounds);
  44255. }
  44256. pos += size;
  44257. tc->setVisible (pos <= maxLength
  44258. && ((! tc->isBeingDragged)
  44259. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44260. }
  44261. }
  44262. }
  44263. }
  44264. void Toolbar::buttonClicked (Button*)
  44265. {
  44266. jassert (missingItemsButton->isShowing());
  44267. if (missingItemsButton->isShowing())
  44268. {
  44269. PopupMenu m;
  44270. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44271. m.showAt (missingItemsButton);
  44272. }
  44273. }
  44274. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44275. Component* /*sourceComponent*/)
  44276. {
  44277. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44278. }
  44279. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44280. {
  44281. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44282. if (tc != 0)
  44283. {
  44284. if (! items.contains (tc))
  44285. {
  44286. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44287. {
  44288. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44289. if (palette != 0)
  44290. palette->replaceComponent (tc);
  44291. }
  44292. else
  44293. {
  44294. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44295. }
  44296. items.add (tc);
  44297. addChildComponent (tc);
  44298. updateAllItemPositions (true);
  44299. }
  44300. for (int i = getNumItems(); --i >= 0;)
  44301. {
  44302. const int currentIndex = items.indexOf (tc);
  44303. int newIndex = currentIndex;
  44304. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44305. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44306. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44307. .getComponentDestination (getChildComponent (newIndex)));
  44308. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44309. if (prev != 0)
  44310. {
  44311. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44312. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44313. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44314. {
  44315. newIndex = getIndexOfChildComponent (prev);
  44316. }
  44317. }
  44318. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44319. if (next != 0)
  44320. {
  44321. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44322. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44323. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44324. {
  44325. newIndex = getIndexOfChildComponent (next) + 1;
  44326. }
  44327. }
  44328. if (newIndex == currentIndex)
  44329. break;
  44330. items.removeObject (tc, false);
  44331. removeChildComponent (tc);
  44332. addChildComponent (tc, newIndex);
  44333. items.insert (newIndex, tc);
  44334. updateAllItemPositions (true);
  44335. }
  44336. }
  44337. }
  44338. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44339. {
  44340. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44341. if (tc != 0 && isParentOf (tc))
  44342. {
  44343. items.removeObject (tc, false);
  44344. removeChildComponent (tc);
  44345. updateAllItemPositions (true);
  44346. }
  44347. }
  44348. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44349. {
  44350. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44351. if (tc != 0)
  44352. tc->setState (Button::buttonNormal);
  44353. }
  44354. void Toolbar::mouseDown (const MouseEvent&)
  44355. {
  44356. }
  44357. class ToolbarCustomisationDialog : public DialogWindow
  44358. {
  44359. public:
  44360. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44361. Toolbar* const toolbar_,
  44362. const int optionFlags)
  44363. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44364. toolbar (toolbar_)
  44365. {
  44366. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44367. setResizable (true, true);
  44368. setResizeLimits (400, 300, 1500, 1000);
  44369. positionNearBar();
  44370. }
  44371. ~ToolbarCustomisationDialog()
  44372. {
  44373. setContentComponent (0, true);
  44374. }
  44375. void closeButtonPressed()
  44376. {
  44377. setVisible (false);
  44378. }
  44379. bool canModalEventBeSentToComponent (const Component* comp)
  44380. {
  44381. return toolbar->isParentOf (comp);
  44382. }
  44383. void positionNearBar()
  44384. {
  44385. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44386. const int tbx = toolbar->getScreenX();
  44387. const int tby = toolbar->getScreenY();
  44388. const int gap = 8;
  44389. int x, y;
  44390. if (toolbar->isVertical())
  44391. {
  44392. y = tby;
  44393. if (tbx > screenSize.getCentreX())
  44394. x = tbx - getWidth() - gap;
  44395. else
  44396. x = tbx + toolbar->getWidth() + gap;
  44397. }
  44398. else
  44399. {
  44400. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44401. if (tby > screenSize.getCentreY())
  44402. y = tby - getHeight() - gap;
  44403. else
  44404. y = tby + toolbar->getHeight() + gap;
  44405. }
  44406. setTopLeftPosition (x, y);
  44407. }
  44408. private:
  44409. Toolbar* const toolbar;
  44410. class CustomiserPanel : public Component,
  44411. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44412. private ButtonListener
  44413. {
  44414. public:
  44415. CustomiserPanel (ToolbarItemFactory& factory_,
  44416. Toolbar* const toolbar_,
  44417. const int optionFlags)
  44418. : factory (factory_),
  44419. toolbar (toolbar_),
  44420. palette (factory_, toolbar_),
  44421. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44422. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44423. defaultButton (TRANS ("Restore to default set of items"))
  44424. {
  44425. addAndMakeVisible (&palette);
  44426. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44427. | Toolbar::allowIconsWithTextChoice
  44428. | Toolbar::allowTextOnlyChoice)) != 0)
  44429. {
  44430. addAndMakeVisible (&styleBox);
  44431. styleBox.setEditableText (false);
  44432. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44433. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44434. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44435. int selectedStyle = 0;
  44436. switch (toolbar_->getStyle())
  44437. {
  44438. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44439. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44440. case Toolbar::textOnly: selectedStyle = 3; break;
  44441. }
  44442. styleBox.setSelectedId (selectedStyle);
  44443. styleBox.addListener (this);
  44444. }
  44445. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44446. {
  44447. addAndMakeVisible (&defaultButton);
  44448. defaultButton.addListener (this);
  44449. }
  44450. addAndMakeVisible (&instructions);
  44451. instructions.setFont (Font (13.0f));
  44452. setSize (500, 300);
  44453. }
  44454. void comboBoxChanged (ComboBox*)
  44455. {
  44456. switch (styleBox.getSelectedId())
  44457. {
  44458. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44459. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44460. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44461. }
  44462. palette.resized(); // to make it update the styles
  44463. }
  44464. void buttonClicked (Button*)
  44465. {
  44466. toolbar->addDefaultItems (factory);
  44467. }
  44468. void paint (Graphics& g)
  44469. {
  44470. Colour background;
  44471. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44472. if (dw != 0)
  44473. background = dw->getBackgroundColour();
  44474. g.setColour (background.contrasting().withAlpha (0.3f));
  44475. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44476. }
  44477. void resized()
  44478. {
  44479. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44480. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44481. defaultButton.changeWidthToFitText (22);
  44482. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44483. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44484. }
  44485. private:
  44486. ToolbarItemFactory& factory;
  44487. Toolbar* const toolbar;
  44488. ToolbarItemPalette palette;
  44489. Label instructions;
  44490. ComboBox styleBox;
  44491. TextButton defaultButton;
  44492. };
  44493. };
  44494. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44495. {
  44496. setEditingActive (true);
  44497. #if JUCE_DEBUG
  44498. WeakReference<Component> checker (this);
  44499. #endif
  44500. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44501. dw.runModalLoop();
  44502. #if JUCE_DEBUG
  44503. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44504. #endif
  44505. setEditingActive (false);
  44506. }
  44507. END_JUCE_NAMESPACE
  44508. /*** End of inlined file: juce_Toolbar.cpp ***/
  44509. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44510. BEGIN_JUCE_NAMESPACE
  44511. ToolbarItemFactory::ToolbarItemFactory()
  44512. {
  44513. }
  44514. ToolbarItemFactory::~ToolbarItemFactory()
  44515. {
  44516. }
  44517. class ItemDragAndDropOverlayComponent : public Component
  44518. {
  44519. public:
  44520. ItemDragAndDropOverlayComponent()
  44521. : isDragging (false)
  44522. {
  44523. setAlwaysOnTop (true);
  44524. setRepaintsOnMouseActivity (true);
  44525. setMouseCursor (MouseCursor::DraggingHandCursor);
  44526. }
  44527. void paint (Graphics& g)
  44528. {
  44529. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44530. if (isMouseOverOrDragging()
  44531. && tc != 0
  44532. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44533. {
  44534. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44535. g.drawRect (0, 0, getWidth(), getHeight(),
  44536. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44537. }
  44538. }
  44539. void mouseDown (const MouseEvent& e)
  44540. {
  44541. isDragging = false;
  44542. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44543. if (tc != 0)
  44544. {
  44545. tc->dragOffsetX = e.x;
  44546. tc->dragOffsetY = e.y;
  44547. }
  44548. }
  44549. void mouseDrag (const MouseEvent& e)
  44550. {
  44551. if (! (isDragging || e.mouseWasClicked()))
  44552. {
  44553. isDragging = true;
  44554. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44555. if (dnd != 0)
  44556. {
  44557. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44558. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44559. if (tc != 0)
  44560. {
  44561. tc->isBeingDragged = true;
  44562. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44563. tc->setVisible (false);
  44564. }
  44565. }
  44566. }
  44567. }
  44568. void mouseUp (const MouseEvent&)
  44569. {
  44570. isDragging = false;
  44571. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44572. if (tc != 0)
  44573. {
  44574. tc->isBeingDragged = false;
  44575. Toolbar* const tb = tc->getToolbar();
  44576. if (tb != 0)
  44577. tb->updateAllItemPositions (true);
  44578. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44579. delete tc;
  44580. }
  44581. }
  44582. void parentSizeChanged()
  44583. {
  44584. setBounds (0, 0, getParentWidth(), getParentHeight());
  44585. }
  44586. private:
  44587. bool isDragging;
  44588. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44589. };
  44590. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44591. const String& labelText,
  44592. const bool isBeingUsedAsAButton_)
  44593. : Button (labelText),
  44594. itemId (itemId_),
  44595. mode (normalMode),
  44596. toolbarStyle (Toolbar::iconsOnly),
  44597. dragOffsetX (0),
  44598. dragOffsetY (0),
  44599. isActive (true),
  44600. isBeingDragged (false),
  44601. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44602. {
  44603. // Your item ID can't be 0!
  44604. jassert (itemId_ != 0);
  44605. }
  44606. ToolbarItemComponent::~ToolbarItemComponent()
  44607. {
  44608. overlayComp = 0;
  44609. }
  44610. Toolbar* ToolbarItemComponent::getToolbar() const
  44611. {
  44612. return dynamic_cast <Toolbar*> (getParentComponent());
  44613. }
  44614. bool ToolbarItemComponent::isToolbarVertical() const
  44615. {
  44616. const Toolbar* const t = getToolbar();
  44617. return t != 0 && t->isVertical();
  44618. }
  44619. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44620. {
  44621. if (toolbarStyle != newStyle)
  44622. {
  44623. toolbarStyle = newStyle;
  44624. repaint();
  44625. resized();
  44626. }
  44627. }
  44628. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44629. {
  44630. if (isBeingUsedAsAButton)
  44631. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44632. over, down, *this);
  44633. if (toolbarStyle != Toolbar::iconsOnly)
  44634. {
  44635. const int indent = contentArea.getX();
  44636. int y = indent;
  44637. int h = getHeight() - indent * 2;
  44638. if (toolbarStyle == Toolbar::iconsWithText)
  44639. {
  44640. y = contentArea.getBottom() + indent / 2;
  44641. h -= contentArea.getHeight();
  44642. }
  44643. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44644. getButtonText(), *this);
  44645. }
  44646. if (! contentArea.isEmpty())
  44647. {
  44648. Graphics::ScopedSaveState ss (g);
  44649. g.reduceClipRegion (contentArea);
  44650. g.setOrigin (contentArea.getX(), contentArea.getY());
  44651. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44652. }
  44653. }
  44654. void ToolbarItemComponent::resized()
  44655. {
  44656. if (toolbarStyle != Toolbar::textOnly)
  44657. {
  44658. const int indent = jmin (proportionOfWidth (0.08f),
  44659. proportionOfHeight (0.08f));
  44660. contentArea = Rectangle<int> (indent, indent,
  44661. getWidth() - indent * 2,
  44662. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44663. : (getHeight() - indent * 2));
  44664. }
  44665. else
  44666. {
  44667. contentArea = Rectangle<int>();
  44668. }
  44669. contentAreaChanged (contentArea);
  44670. }
  44671. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44672. {
  44673. if (mode != newMode)
  44674. {
  44675. mode = newMode;
  44676. repaint();
  44677. if (mode == normalMode)
  44678. {
  44679. overlayComp = 0;
  44680. }
  44681. else if (overlayComp == 0)
  44682. {
  44683. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44684. overlayComp->parentSizeChanged();
  44685. }
  44686. resized();
  44687. }
  44688. }
  44689. END_JUCE_NAMESPACE
  44690. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44691. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44692. BEGIN_JUCE_NAMESPACE
  44693. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44694. Toolbar* const toolbar_)
  44695. : factory (factory_),
  44696. toolbar (toolbar_)
  44697. {
  44698. Component* const itemHolder = new Component();
  44699. viewport.setViewedComponent (itemHolder);
  44700. Array <int> allIds;
  44701. factory.getAllToolbarItemIds (allIds);
  44702. for (int i = 0; i < allIds.size(); ++i)
  44703. addComponent (allIds.getUnchecked (i), -1);
  44704. addAndMakeVisible (&viewport);
  44705. }
  44706. ToolbarItemPalette::~ToolbarItemPalette()
  44707. {
  44708. }
  44709. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44710. {
  44711. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44712. jassert (tc != 0);
  44713. if (tc != 0)
  44714. {
  44715. items.insert (index, tc);
  44716. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44717. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44718. }
  44719. }
  44720. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44721. {
  44722. const int index = items.indexOf (comp);
  44723. jassert (index >= 0);
  44724. items.removeObject (comp, false);
  44725. addComponent (comp->getItemId(), index);
  44726. resized();
  44727. }
  44728. void ToolbarItemPalette::resized()
  44729. {
  44730. viewport.setBoundsInset (BorderSize<int> (1));
  44731. Component* const itemHolder = viewport.getViewedComponent();
  44732. const int indent = 8;
  44733. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44734. const int height = toolbar->getThickness();
  44735. int x = indent;
  44736. int y = indent;
  44737. int maxX = 0;
  44738. for (int i = 0; i < items.size(); ++i)
  44739. {
  44740. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44741. tc->setStyle (toolbar->getStyle());
  44742. int preferredSize = 1, minSize = 1, maxSize = 1;
  44743. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44744. {
  44745. if (x + preferredSize > preferredWidth && x > indent)
  44746. {
  44747. x = indent;
  44748. y += height;
  44749. }
  44750. tc->setBounds (x, y, preferredSize, height);
  44751. x += preferredSize + 8;
  44752. maxX = jmax (maxX, x);
  44753. }
  44754. }
  44755. itemHolder->setSize (maxX, y + height + 8);
  44756. }
  44757. END_JUCE_NAMESPACE
  44758. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44759. /*** Start of inlined file: juce_TreeView.cpp ***/
  44760. BEGIN_JUCE_NAMESPACE
  44761. class TreeViewContentComponent : public Component,
  44762. public TooltipClient
  44763. {
  44764. public:
  44765. TreeViewContentComponent (TreeView& owner_)
  44766. : owner (owner_),
  44767. buttonUnderMouse (0),
  44768. isDragging (false)
  44769. {
  44770. }
  44771. void mouseDown (const MouseEvent& e)
  44772. {
  44773. updateButtonUnderMouse (e);
  44774. isDragging = false;
  44775. needSelectionOnMouseUp = false;
  44776. Rectangle<int> pos;
  44777. TreeViewItem* const item = findItemAt (e.y, pos);
  44778. if (item == 0)
  44779. return;
  44780. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44781. // as selection clicks)
  44782. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44783. {
  44784. if (e.x >= pos.getX() - owner.getIndentSize())
  44785. item->setOpen (! item->isOpen());
  44786. // (clicks to the left of an open/close button are ignored)
  44787. }
  44788. else
  44789. {
  44790. // mouse-down inside the body of the item..
  44791. if (! owner.isMultiSelectEnabled())
  44792. item->setSelected (true, true);
  44793. else if (item->isSelected())
  44794. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44795. else
  44796. selectBasedOnModifiers (item, e.mods);
  44797. if (e.x >= pos.getX())
  44798. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44799. }
  44800. }
  44801. void mouseUp (const MouseEvent& e)
  44802. {
  44803. updateButtonUnderMouse (e);
  44804. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44805. {
  44806. Rectangle<int> pos;
  44807. TreeViewItem* const item = findItemAt (e.y, pos);
  44808. if (item != 0)
  44809. selectBasedOnModifiers (item, e.mods);
  44810. }
  44811. }
  44812. void mouseDoubleClick (const MouseEvent& e)
  44813. {
  44814. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44815. {
  44816. Rectangle<int> pos;
  44817. TreeViewItem* const item = findItemAt (e.y, pos);
  44818. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44819. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44820. }
  44821. }
  44822. void mouseDrag (const MouseEvent& e)
  44823. {
  44824. if (isEnabled()
  44825. && ! (isDragging || e.mouseWasClicked()
  44826. || e.getDistanceFromDragStart() < 5
  44827. || e.mods.isPopupMenu()))
  44828. {
  44829. isDragging = true;
  44830. Rectangle<int> pos;
  44831. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44832. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44833. {
  44834. const String dragDescription (item->getDragSourceDescription());
  44835. if (dragDescription.isNotEmpty())
  44836. {
  44837. DragAndDropContainer* const dragContainer
  44838. = DragAndDropContainer::findParentDragContainerFor (this);
  44839. if (dragContainer != 0)
  44840. {
  44841. pos.setSize (pos.getWidth(), item->itemHeight);
  44842. Image dragImage (Component::createComponentSnapshot (pos, true));
  44843. dragImage.multiplyAllAlphas (0.6f);
  44844. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44845. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44846. }
  44847. else
  44848. {
  44849. // to be able to do a drag-and-drop operation, the treeview needs to
  44850. // be inside a component which is also a DragAndDropContainer.
  44851. jassertfalse;
  44852. }
  44853. }
  44854. }
  44855. }
  44856. }
  44857. void mouseMove (const MouseEvent& e)
  44858. {
  44859. updateButtonUnderMouse (e);
  44860. }
  44861. void mouseExit (const MouseEvent& e)
  44862. {
  44863. updateButtonUnderMouse (e);
  44864. }
  44865. void paint (Graphics& g)
  44866. {
  44867. if (owner.rootItem != 0)
  44868. {
  44869. owner.handleAsyncUpdate();
  44870. if (! owner.rootItemVisible)
  44871. g.setOrigin (0, -owner.rootItem->itemHeight);
  44872. owner.rootItem->paintRecursively (g, getWidth());
  44873. }
  44874. }
  44875. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44876. {
  44877. if (owner.rootItem != 0)
  44878. {
  44879. owner.handleAsyncUpdate();
  44880. if (! owner.rootItemVisible)
  44881. y += owner.rootItem->itemHeight;
  44882. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44883. if (ti != 0)
  44884. itemPosition = ti->getItemPosition (false);
  44885. return ti;
  44886. }
  44887. return 0;
  44888. }
  44889. void updateComponents()
  44890. {
  44891. const int visibleTop = -getY();
  44892. const int visibleBottom = visibleTop + getParentHeight();
  44893. {
  44894. for (int i = items.size(); --i >= 0;)
  44895. items.getUnchecked(i)->shouldKeep = false;
  44896. }
  44897. {
  44898. TreeViewItem* item = owner.rootItem;
  44899. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44900. while (item != 0 && y < visibleBottom)
  44901. {
  44902. y += item->itemHeight;
  44903. if (y >= visibleTop)
  44904. {
  44905. RowItem* const ri = findItem (item->uid);
  44906. if (ri != 0)
  44907. {
  44908. ri->shouldKeep = true;
  44909. }
  44910. else
  44911. {
  44912. Component* const comp = item->createItemComponent();
  44913. if (comp != 0)
  44914. {
  44915. items.add (new RowItem (item, comp, item->uid));
  44916. addAndMakeVisible (comp);
  44917. }
  44918. }
  44919. }
  44920. item = item->getNextVisibleItem (true);
  44921. }
  44922. }
  44923. for (int i = items.size(); --i >= 0;)
  44924. {
  44925. RowItem* const ri = items.getUnchecked(i);
  44926. bool keep = false;
  44927. if (isParentOf (ri->component))
  44928. {
  44929. if (ri->shouldKeep)
  44930. {
  44931. Rectangle<int> pos (ri->item->getItemPosition (false));
  44932. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  44933. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44934. {
  44935. keep = true;
  44936. ri->component->setBounds (pos);
  44937. }
  44938. }
  44939. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  44940. {
  44941. keep = true;
  44942. ri->component->setSize (0, 0);
  44943. }
  44944. }
  44945. if (! keep)
  44946. items.remove (i);
  44947. }
  44948. }
  44949. void updateButtonUnderMouse (const MouseEvent& e)
  44950. {
  44951. TreeViewItem* newItem = 0;
  44952. if (owner.openCloseButtonsVisible)
  44953. {
  44954. Rectangle<int> pos;
  44955. TreeViewItem* item = findItemAt (e.y, pos);
  44956. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44957. {
  44958. newItem = item;
  44959. if (! newItem->mightContainSubItems())
  44960. newItem = 0;
  44961. }
  44962. }
  44963. if (buttonUnderMouse != newItem)
  44964. {
  44965. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44966. {
  44967. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44968. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44969. }
  44970. buttonUnderMouse = newItem;
  44971. if (buttonUnderMouse != 0)
  44972. {
  44973. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44974. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44975. }
  44976. }
  44977. }
  44978. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44979. {
  44980. return item == buttonUnderMouse;
  44981. }
  44982. void resized()
  44983. {
  44984. owner.itemsChanged();
  44985. }
  44986. const String getTooltip()
  44987. {
  44988. Rectangle<int> pos;
  44989. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44990. if (item != 0)
  44991. return item->getTooltip();
  44992. return owner.getTooltip();
  44993. }
  44994. private:
  44995. TreeView& owner;
  44996. struct RowItem
  44997. {
  44998. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  44999. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45000. {
  45001. }
  45002. ~RowItem()
  45003. {
  45004. delete component.get();
  45005. }
  45006. WeakReference<Component> component;
  45007. TreeViewItem* item;
  45008. int uid;
  45009. bool shouldKeep;
  45010. };
  45011. OwnedArray <RowItem> items;
  45012. TreeViewItem* buttonUnderMouse;
  45013. bool isDragging, needSelectionOnMouseUp;
  45014. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45015. {
  45016. TreeViewItem* firstSelected = 0;
  45017. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45018. {
  45019. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45020. jassert (lastSelected != 0);
  45021. int rowStart = firstSelected->getRowNumberInTree();
  45022. int rowEnd = lastSelected->getRowNumberInTree();
  45023. if (rowStart > rowEnd)
  45024. swapVariables (rowStart, rowEnd);
  45025. int ourRow = item->getRowNumberInTree();
  45026. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45027. if (ourRow > otherEnd)
  45028. swapVariables (ourRow, otherEnd);
  45029. for (int i = ourRow; i <= otherEnd; ++i)
  45030. owner.getItemOnRow (i)->setSelected (true, false);
  45031. }
  45032. else
  45033. {
  45034. const bool cmd = modifiers.isCommandDown();
  45035. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45036. }
  45037. }
  45038. bool containsItem (TreeViewItem* const item) const throw()
  45039. {
  45040. for (int i = items.size(); --i >= 0;)
  45041. if (items.getUnchecked(i)->item == item)
  45042. return true;
  45043. return false;
  45044. }
  45045. RowItem* findItem (const int uid) const throw()
  45046. {
  45047. for (int i = items.size(); --i >= 0;)
  45048. {
  45049. RowItem* const ri = items.getUnchecked(i);
  45050. if (ri->uid == uid)
  45051. return ri;
  45052. }
  45053. return 0;
  45054. }
  45055. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45056. {
  45057. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45058. {
  45059. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45060. if (source->isDragging())
  45061. {
  45062. Component* const underMouse = source->getComponentUnderMouse();
  45063. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45064. return true;
  45065. }
  45066. }
  45067. return false;
  45068. }
  45069. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45070. };
  45071. class TreeView::TreeViewport : public Viewport
  45072. {
  45073. public:
  45074. TreeViewport() throw() : lastX (-1) {}
  45075. void updateComponents (const bool triggerResize = false)
  45076. {
  45077. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45078. if (tvc != 0)
  45079. {
  45080. if (triggerResize)
  45081. tvc->resized();
  45082. else
  45083. tvc->updateComponents();
  45084. }
  45085. repaint();
  45086. }
  45087. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45088. {
  45089. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45090. lastX = newVisibleArea.getX();
  45091. updateComponents (hasScrolledSideways);
  45092. }
  45093. private:
  45094. int lastX;
  45095. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45096. };
  45097. TreeView::TreeView (const String& componentName)
  45098. : Component (componentName),
  45099. rootItem (0),
  45100. indentSize (24),
  45101. defaultOpenness (false),
  45102. needsRecalculating (true),
  45103. rootItemVisible (true),
  45104. multiSelectEnabled (false),
  45105. openCloseButtonsVisible (true)
  45106. {
  45107. addAndMakeVisible (viewport = new TreeViewport());
  45108. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45109. viewport->setWantsKeyboardFocus (false);
  45110. setWantsKeyboardFocus (true);
  45111. }
  45112. TreeView::~TreeView()
  45113. {
  45114. if (rootItem != 0)
  45115. rootItem->setOwnerView (0);
  45116. }
  45117. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45118. {
  45119. if (rootItem != newRootItem)
  45120. {
  45121. if (newRootItem != 0)
  45122. {
  45123. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45124. if (newRootItem->ownerView != 0)
  45125. newRootItem->ownerView->setRootItem (0);
  45126. }
  45127. if (rootItem != 0)
  45128. rootItem->setOwnerView (0);
  45129. rootItem = newRootItem;
  45130. if (newRootItem != 0)
  45131. newRootItem->setOwnerView (this);
  45132. needsRecalculating = true;
  45133. handleAsyncUpdate();
  45134. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45135. {
  45136. rootItem->setOpen (false); // force a re-open
  45137. rootItem->setOpen (true);
  45138. }
  45139. }
  45140. }
  45141. void TreeView::deleteRootItem()
  45142. {
  45143. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45144. setRootItem (0);
  45145. }
  45146. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45147. {
  45148. rootItemVisible = shouldBeVisible;
  45149. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45150. {
  45151. rootItem->setOpen (false); // force a re-open
  45152. rootItem->setOpen (true);
  45153. }
  45154. itemsChanged();
  45155. }
  45156. void TreeView::colourChanged()
  45157. {
  45158. setOpaque (findColour (backgroundColourId).isOpaque());
  45159. repaint();
  45160. }
  45161. void TreeView::setIndentSize (const int newIndentSize)
  45162. {
  45163. if (indentSize != newIndentSize)
  45164. {
  45165. indentSize = newIndentSize;
  45166. resized();
  45167. }
  45168. }
  45169. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45170. {
  45171. if (defaultOpenness != isOpenByDefault)
  45172. {
  45173. defaultOpenness = isOpenByDefault;
  45174. itemsChanged();
  45175. }
  45176. }
  45177. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45178. {
  45179. multiSelectEnabled = canMultiSelect;
  45180. }
  45181. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45182. {
  45183. if (openCloseButtonsVisible != shouldBeVisible)
  45184. {
  45185. openCloseButtonsVisible = shouldBeVisible;
  45186. itemsChanged();
  45187. }
  45188. }
  45189. Viewport* TreeView::getViewport() const throw()
  45190. {
  45191. return viewport;
  45192. }
  45193. void TreeView::clearSelectedItems()
  45194. {
  45195. if (rootItem != 0)
  45196. rootItem->deselectAllRecursively();
  45197. }
  45198. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45199. {
  45200. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45201. }
  45202. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45203. {
  45204. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45205. }
  45206. int TreeView::getNumRowsInTree() const
  45207. {
  45208. if (rootItem != 0)
  45209. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45210. return 0;
  45211. }
  45212. TreeViewItem* TreeView::getItemOnRow (int index) const
  45213. {
  45214. if (! rootItemVisible)
  45215. ++index;
  45216. if (rootItem != 0 && index >= 0)
  45217. return rootItem->getItemOnRow (index);
  45218. return 0;
  45219. }
  45220. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45221. {
  45222. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45223. Rectangle<int> pos;
  45224. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45225. }
  45226. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45227. {
  45228. if (rootItem == 0)
  45229. return 0;
  45230. return rootItem->findItemFromIdentifierString (identifierString);
  45231. }
  45232. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45233. {
  45234. XmlElement* e = 0;
  45235. if (rootItem != 0)
  45236. {
  45237. e = rootItem->getOpennessState();
  45238. if (e != 0 && alsoIncludeScrollPosition)
  45239. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45240. }
  45241. return e;
  45242. }
  45243. void TreeView::restoreOpennessState (const XmlElement& newState)
  45244. {
  45245. if (rootItem != 0)
  45246. {
  45247. rootItem->restoreOpennessState (newState);
  45248. if (newState.hasAttribute ("scrollPos"))
  45249. viewport->setViewPosition (viewport->getViewPositionX(),
  45250. newState.getIntAttribute ("scrollPos"));
  45251. }
  45252. }
  45253. void TreeView::paint (Graphics& g)
  45254. {
  45255. g.fillAll (findColour (backgroundColourId));
  45256. }
  45257. void TreeView::resized()
  45258. {
  45259. viewport->setBounds (getLocalBounds());
  45260. itemsChanged();
  45261. handleAsyncUpdate();
  45262. }
  45263. void TreeView::enablementChanged()
  45264. {
  45265. repaint();
  45266. }
  45267. void TreeView::moveSelectedRow (int delta)
  45268. {
  45269. if (delta == 0)
  45270. return;
  45271. int rowSelected = 0;
  45272. TreeViewItem* const firstSelected = getSelectedItem (0);
  45273. if (firstSelected != 0)
  45274. rowSelected = firstSelected->getRowNumberInTree();
  45275. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45276. for (;;)
  45277. {
  45278. TreeViewItem* item = getItemOnRow (rowSelected);
  45279. if (item != 0)
  45280. {
  45281. if (! item->canBeSelected())
  45282. {
  45283. // if the row we want to highlight doesn't allow it, try skipping
  45284. // to the next item..
  45285. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45286. rowSelected + (delta < 0 ? -1 : 1));
  45287. if (rowSelected != nextRowToTry)
  45288. {
  45289. rowSelected = nextRowToTry;
  45290. continue;
  45291. }
  45292. else
  45293. {
  45294. break;
  45295. }
  45296. }
  45297. item->setSelected (true, true);
  45298. scrollToKeepItemVisible (item);
  45299. }
  45300. break;
  45301. }
  45302. }
  45303. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45304. {
  45305. if (item != 0 && item->ownerView == this)
  45306. {
  45307. handleAsyncUpdate();
  45308. item = item->getDeepestOpenParentItem();
  45309. int y = item->y;
  45310. int viewTop = viewport->getViewPositionY();
  45311. if (y < viewTop)
  45312. {
  45313. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45314. }
  45315. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45316. {
  45317. viewport->setViewPosition (viewport->getViewPositionX(),
  45318. (y + item->itemHeight) - viewport->getViewHeight());
  45319. }
  45320. }
  45321. }
  45322. bool TreeView::keyPressed (const KeyPress& key)
  45323. {
  45324. if (key.isKeyCode (KeyPress::upKey))
  45325. {
  45326. moveSelectedRow (-1);
  45327. }
  45328. else if (key.isKeyCode (KeyPress::downKey))
  45329. {
  45330. moveSelectedRow (1);
  45331. }
  45332. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45333. {
  45334. if (rootItem != 0)
  45335. {
  45336. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45337. if (key.isKeyCode (KeyPress::pageUpKey))
  45338. rowsOnScreen = -rowsOnScreen;
  45339. moveSelectedRow (rowsOnScreen);
  45340. }
  45341. }
  45342. else if (key.isKeyCode (KeyPress::homeKey))
  45343. {
  45344. moveSelectedRow (-0x3fffffff);
  45345. }
  45346. else if (key.isKeyCode (KeyPress::endKey))
  45347. {
  45348. moveSelectedRow (0x3fffffff);
  45349. }
  45350. else if (key.isKeyCode (KeyPress::returnKey))
  45351. {
  45352. TreeViewItem* const firstSelected = getSelectedItem (0);
  45353. if (firstSelected != 0)
  45354. firstSelected->setOpen (! firstSelected->isOpen());
  45355. }
  45356. else if (key.isKeyCode (KeyPress::leftKey))
  45357. {
  45358. TreeViewItem* const firstSelected = getSelectedItem (0);
  45359. if (firstSelected != 0)
  45360. {
  45361. if (firstSelected->isOpen())
  45362. {
  45363. firstSelected->setOpen (false);
  45364. }
  45365. else
  45366. {
  45367. TreeViewItem* parent = firstSelected->parentItem;
  45368. if ((! rootItemVisible) && parent == rootItem)
  45369. parent = 0;
  45370. if (parent != 0)
  45371. {
  45372. parent->setSelected (true, true);
  45373. scrollToKeepItemVisible (parent);
  45374. }
  45375. }
  45376. }
  45377. }
  45378. else if (key.isKeyCode (KeyPress::rightKey))
  45379. {
  45380. TreeViewItem* const firstSelected = getSelectedItem (0);
  45381. if (firstSelected != 0)
  45382. {
  45383. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45384. moveSelectedRow (1);
  45385. else
  45386. firstSelected->setOpen (true);
  45387. }
  45388. }
  45389. else
  45390. {
  45391. return false;
  45392. }
  45393. return true;
  45394. }
  45395. void TreeView::itemsChanged() throw()
  45396. {
  45397. needsRecalculating = true;
  45398. repaint();
  45399. triggerAsyncUpdate();
  45400. }
  45401. void TreeView::handleAsyncUpdate()
  45402. {
  45403. if (needsRecalculating)
  45404. {
  45405. needsRecalculating = false;
  45406. const ScopedLock sl (nodeAlterationLock);
  45407. if (rootItem != 0)
  45408. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45409. viewport->updateComponents();
  45410. if (rootItem != 0)
  45411. {
  45412. viewport->getViewedComponent()
  45413. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45414. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45415. }
  45416. else
  45417. {
  45418. viewport->getViewedComponent()->setSize (0, 0);
  45419. }
  45420. }
  45421. }
  45422. class TreeView::InsertPointHighlight : public Component
  45423. {
  45424. public:
  45425. InsertPointHighlight()
  45426. : lastItem (0)
  45427. {
  45428. setSize (100, 12);
  45429. setAlwaysOnTop (true);
  45430. setInterceptsMouseClicks (false, false);
  45431. }
  45432. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45433. {
  45434. lastItem = item;
  45435. lastIndex = insertIndex;
  45436. const int offset = getHeight() / 2;
  45437. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45438. }
  45439. void paint (Graphics& g)
  45440. {
  45441. Path p;
  45442. const float h = (float) getHeight();
  45443. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45444. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45445. p.lineTo ((float) getWidth(), h / 2.0f);
  45446. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45447. g.strokePath (p, PathStrokeType (2.0f));
  45448. }
  45449. TreeViewItem* lastItem;
  45450. int lastIndex;
  45451. private:
  45452. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45453. };
  45454. class TreeView::TargetGroupHighlight : public Component
  45455. {
  45456. public:
  45457. TargetGroupHighlight()
  45458. {
  45459. setAlwaysOnTop (true);
  45460. setInterceptsMouseClicks (false, false);
  45461. }
  45462. void setTargetPosition (TreeViewItem* const item) throw()
  45463. {
  45464. Rectangle<int> r (item->getItemPosition (true));
  45465. r.setHeight (item->getItemHeight());
  45466. setBounds (r);
  45467. }
  45468. void paint (Graphics& g)
  45469. {
  45470. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45471. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45472. }
  45473. private:
  45474. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45475. };
  45476. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45477. {
  45478. beginDragAutoRepeat (100);
  45479. if (dragInsertPointHighlight == 0)
  45480. {
  45481. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45482. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45483. }
  45484. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45485. dragTargetGroupHighlight->setTargetPosition (item);
  45486. }
  45487. void TreeView::hideDragHighlight() throw()
  45488. {
  45489. dragInsertPointHighlight = 0;
  45490. dragTargetGroupHighlight = 0;
  45491. }
  45492. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45493. const StringArray& files, const String& sourceDescription,
  45494. Component* sourceComponent) const throw()
  45495. {
  45496. insertIndex = 0;
  45497. TreeViewItem* item = getItemAt (y);
  45498. if (item == 0)
  45499. return 0;
  45500. Rectangle<int> itemPos (item->getItemPosition (true));
  45501. insertIndex = item->getIndexInParent();
  45502. const int oldY = y;
  45503. y = itemPos.getY();
  45504. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45505. {
  45506. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45507. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45508. {
  45509. // Check if we're trying to drag into an empty group item..
  45510. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45511. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45512. {
  45513. insertIndex = 0;
  45514. x = itemPos.getX() + getIndentSize();
  45515. y = itemPos.getBottom();
  45516. return item;
  45517. }
  45518. }
  45519. }
  45520. if (oldY > itemPos.getCentreY())
  45521. {
  45522. y += item->getItemHeight();
  45523. while (item->isLastOfSiblings() && item->parentItem != 0
  45524. && item->parentItem->parentItem != 0)
  45525. {
  45526. if (x > itemPos.getX())
  45527. break;
  45528. item = item->parentItem;
  45529. itemPos = item->getItemPosition (true);
  45530. insertIndex = item->getIndexInParent();
  45531. }
  45532. ++insertIndex;
  45533. }
  45534. x = itemPos.getX();
  45535. return item->parentItem;
  45536. }
  45537. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45538. {
  45539. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45540. int insertIndex;
  45541. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45542. if (item != 0)
  45543. {
  45544. if (scrolled || dragInsertPointHighlight == 0
  45545. || dragInsertPointHighlight->lastItem != item
  45546. || dragInsertPointHighlight->lastIndex != insertIndex)
  45547. {
  45548. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45549. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45550. showDragHighlight (item, insertIndex, x, y);
  45551. else
  45552. hideDragHighlight();
  45553. }
  45554. }
  45555. else
  45556. {
  45557. hideDragHighlight();
  45558. }
  45559. }
  45560. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45561. {
  45562. hideDragHighlight();
  45563. int insertIndex;
  45564. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45565. if (item != 0)
  45566. {
  45567. if (files.size() > 0)
  45568. {
  45569. if (item->isInterestedInFileDrag (files))
  45570. item->filesDropped (files, insertIndex);
  45571. }
  45572. else
  45573. {
  45574. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45575. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45576. }
  45577. }
  45578. }
  45579. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45580. {
  45581. return true;
  45582. }
  45583. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45584. {
  45585. fileDragMove (files, x, y);
  45586. }
  45587. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45588. {
  45589. handleDrag (files, String::empty, 0, x, y);
  45590. }
  45591. void TreeView::fileDragExit (const StringArray&)
  45592. {
  45593. hideDragHighlight();
  45594. }
  45595. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45596. {
  45597. handleDrop (files, String::empty, 0, x, y);
  45598. }
  45599. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45600. {
  45601. return true;
  45602. }
  45603. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45604. {
  45605. itemDragMove (sourceDescription, sourceComponent, x, y);
  45606. }
  45607. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45608. {
  45609. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45610. }
  45611. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45612. {
  45613. hideDragHighlight();
  45614. }
  45615. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45616. {
  45617. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45618. }
  45619. enum TreeViewOpenness
  45620. {
  45621. opennessDefault = 0,
  45622. opennessClosed = 1,
  45623. opennessOpen = 2
  45624. };
  45625. TreeViewItem::TreeViewItem()
  45626. : ownerView (0),
  45627. parentItem (0),
  45628. y (0),
  45629. itemHeight (0),
  45630. totalHeight (0),
  45631. selected (false),
  45632. redrawNeeded (true),
  45633. drawLinesInside (true),
  45634. drawsInLeftMargin (false),
  45635. openness (opennessDefault)
  45636. {
  45637. static int nextUID = 0;
  45638. uid = nextUID++;
  45639. }
  45640. TreeViewItem::~TreeViewItem()
  45641. {
  45642. }
  45643. const String TreeViewItem::getUniqueName() const
  45644. {
  45645. return String::empty;
  45646. }
  45647. void TreeViewItem::itemOpennessChanged (bool)
  45648. {
  45649. }
  45650. int TreeViewItem::getNumSubItems() const throw()
  45651. {
  45652. return subItems.size();
  45653. }
  45654. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45655. {
  45656. return subItems [index];
  45657. }
  45658. void TreeViewItem::clearSubItems()
  45659. {
  45660. if (subItems.size() > 0)
  45661. {
  45662. if (ownerView != 0)
  45663. {
  45664. const ScopedLock sl (ownerView->nodeAlterationLock);
  45665. subItems.clear();
  45666. treeHasChanged();
  45667. }
  45668. else
  45669. {
  45670. subItems.clear();
  45671. }
  45672. }
  45673. }
  45674. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45675. {
  45676. if (newItem != 0)
  45677. {
  45678. newItem->parentItem = this;
  45679. newItem->setOwnerView (ownerView);
  45680. newItem->y = 0;
  45681. newItem->itemHeight = newItem->getItemHeight();
  45682. newItem->totalHeight = 0;
  45683. newItem->itemWidth = newItem->getItemWidth();
  45684. newItem->totalWidth = 0;
  45685. if (ownerView != 0)
  45686. {
  45687. const ScopedLock sl (ownerView->nodeAlterationLock);
  45688. subItems.insert (insertPosition, newItem);
  45689. treeHasChanged();
  45690. if (newItem->isOpen())
  45691. newItem->itemOpennessChanged (true);
  45692. }
  45693. else
  45694. {
  45695. subItems.insert (insertPosition, newItem);
  45696. if (newItem->isOpen())
  45697. newItem->itemOpennessChanged (true);
  45698. }
  45699. }
  45700. }
  45701. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45702. {
  45703. if (ownerView != 0)
  45704. {
  45705. const ScopedLock sl (ownerView->nodeAlterationLock);
  45706. if (isPositiveAndBelow (index, subItems.size()))
  45707. {
  45708. subItems.remove (index, deleteItem);
  45709. treeHasChanged();
  45710. }
  45711. }
  45712. else
  45713. {
  45714. subItems.remove (index, deleteItem);
  45715. }
  45716. }
  45717. bool TreeViewItem::isOpen() const throw()
  45718. {
  45719. if (openness == opennessDefault)
  45720. return ownerView != 0 && ownerView->defaultOpenness;
  45721. else
  45722. return openness == opennessOpen;
  45723. }
  45724. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45725. {
  45726. if (isOpen() != shouldBeOpen)
  45727. {
  45728. openness = shouldBeOpen ? opennessOpen
  45729. : opennessClosed;
  45730. treeHasChanged();
  45731. itemOpennessChanged (isOpen());
  45732. }
  45733. }
  45734. bool TreeViewItem::isSelected() const throw()
  45735. {
  45736. return selected;
  45737. }
  45738. void TreeViewItem::deselectAllRecursively()
  45739. {
  45740. setSelected (false, false);
  45741. for (int i = 0; i < subItems.size(); ++i)
  45742. subItems.getUnchecked(i)->deselectAllRecursively();
  45743. }
  45744. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45745. const bool deselectOtherItemsFirst)
  45746. {
  45747. if (shouldBeSelected && ! canBeSelected())
  45748. return;
  45749. if (deselectOtherItemsFirst)
  45750. getTopLevelItem()->deselectAllRecursively();
  45751. if (shouldBeSelected != selected)
  45752. {
  45753. selected = shouldBeSelected;
  45754. if (ownerView != 0)
  45755. ownerView->repaint();
  45756. itemSelectionChanged (shouldBeSelected);
  45757. }
  45758. }
  45759. void TreeViewItem::paintItem (Graphics&, int, int)
  45760. {
  45761. }
  45762. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45763. {
  45764. ownerView->getLookAndFeel()
  45765. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45766. }
  45767. void TreeViewItem::itemClicked (const MouseEvent&)
  45768. {
  45769. }
  45770. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45771. {
  45772. if (mightContainSubItems())
  45773. setOpen (! isOpen());
  45774. }
  45775. void TreeViewItem::itemSelectionChanged (bool)
  45776. {
  45777. }
  45778. const String TreeViewItem::getTooltip()
  45779. {
  45780. return String::empty;
  45781. }
  45782. const String TreeViewItem::getDragSourceDescription()
  45783. {
  45784. return String::empty;
  45785. }
  45786. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45787. {
  45788. return false;
  45789. }
  45790. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45791. {
  45792. }
  45793. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45794. {
  45795. return false;
  45796. }
  45797. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45798. {
  45799. }
  45800. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45801. {
  45802. const int indentX = getIndentX();
  45803. int width = itemWidth;
  45804. if (ownerView != 0 && width < 0)
  45805. width = ownerView->viewport->getViewWidth() - indentX;
  45806. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45807. if (relativeToTreeViewTopLeft)
  45808. r -= ownerView->viewport->getViewPosition();
  45809. return r;
  45810. }
  45811. void TreeViewItem::treeHasChanged() const throw()
  45812. {
  45813. if (ownerView != 0)
  45814. ownerView->itemsChanged();
  45815. }
  45816. void TreeViewItem::repaintItem() const
  45817. {
  45818. if (ownerView != 0 && areAllParentsOpen())
  45819. {
  45820. Rectangle<int> r (getItemPosition (true));
  45821. r.setLeft (0);
  45822. ownerView->viewport->repaint (r);
  45823. }
  45824. }
  45825. bool TreeViewItem::areAllParentsOpen() const throw()
  45826. {
  45827. return parentItem == 0
  45828. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45829. }
  45830. void TreeViewItem::updatePositions (int newY)
  45831. {
  45832. y = newY;
  45833. itemHeight = getItemHeight();
  45834. totalHeight = itemHeight;
  45835. itemWidth = getItemWidth();
  45836. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45837. if (isOpen())
  45838. {
  45839. newY += totalHeight;
  45840. for (int i = 0; i < subItems.size(); ++i)
  45841. {
  45842. TreeViewItem* const ti = subItems.getUnchecked(i);
  45843. ti->updatePositions (newY);
  45844. newY += ti->totalHeight;
  45845. totalHeight += ti->totalHeight;
  45846. totalWidth = jmax (totalWidth, ti->totalWidth);
  45847. }
  45848. }
  45849. }
  45850. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45851. {
  45852. TreeViewItem* result = this;
  45853. TreeViewItem* item = this;
  45854. while (item->parentItem != 0)
  45855. {
  45856. item = item->parentItem;
  45857. if (! item->isOpen())
  45858. result = item;
  45859. }
  45860. return result;
  45861. }
  45862. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45863. {
  45864. ownerView = newOwner;
  45865. for (int i = subItems.size(); --i >= 0;)
  45866. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45867. }
  45868. int TreeViewItem::getIndentX() const throw()
  45869. {
  45870. const int indentWidth = ownerView->getIndentSize();
  45871. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45872. if (! ownerView->openCloseButtonsVisible)
  45873. x -= indentWidth;
  45874. TreeViewItem* p = parentItem;
  45875. while (p != 0)
  45876. {
  45877. x += indentWidth;
  45878. p = p->parentItem;
  45879. }
  45880. return x;
  45881. }
  45882. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45883. {
  45884. drawsInLeftMargin = canDrawInLeftMargin;
  45885. }
  45886. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45887. {
  45888. jassert (ownerView != 0);
  45889. if (ownerView == 0)
  45890. return;
  45891. const int indent = getIndentX();
  45892. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45893. {
  45894. Graphics::ScopedSaveState ss (g);
  45895. g.setOrigin (indent, 0);
  45896. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45897. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45898. paintItem (g, itemW, itemHeight);
  45899. }
  45900. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45901. const float halfH = itemHeight * 0.5f;
  45902. int depth = 0;
  45903. TreeViewItem* p = parentItem;
  45904. while (p != 0)
  45905. {
  45906. ++depth;
  45907. p = p->parentItem;
  45908. }
  45909. if (! ownerView->rootItemVisible)
  45910. --depth;
  45911. const int indentWidth = ownerView->getIndentSize();
  45912. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45913. {
  45914. float x = (depth + 0.5f) * indentWidth;
  45915. if (depth >= 0)
  45916. {
  45917. if (parentItem != 0 && parentItem->drawLinesInside)
  45918. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45919. if ((parentItem != 0 && parentItem->drawLinesInside)
  45920. || (parentItem == 0 && drawLinesInside))
  45921. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45922. }
  45923. p = parentItem;
  45924. int d = depth;
  45925. while (p != 0 && --d >= 0)
  45926. {
  45927. x -= (float) indentWidth;
  45928. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45929. && ! p->isLastOfSiblings())
  45930. {
  45931. g.drawLine (x, 0, x, (float) itemHeight);
  45932. }
  45933. p = p->parentItem;
  45934. }
  45935. if (mightContainSubItems())
  45936. {
  45937. Graphics::ScopedSaveState ss (g);
  45938. g.setOrigin (depth * indentWidth, 0);
  45939. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45940. paintOpenCloseButton (g, indentWidth, itemHeight,
  45941. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45942. ->isMouseOverButton (this));
  45943. }
  45944. }
  45945. if (isOpen())
  45946. {
  45947. const Rectangle<int> clip (g.getClipBounds());
  45948. for (int i = 0; i < subItems.size(); ++i)
  45949. {
  45950. TreeViewItem* const ti = subItems.getUnchecked(i);
  45951. const int relY = ti->y - y;
  45952. if (relY >= clip.getBottom())
  45953. break;
  45954. if (relY + ti->totalHeight >= clip.getY())
  45955. {
  45956. Graphics::ScopedSaveState ss (g);
  45957. g.setOrigin (0, relY);
  45958. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45959. ti->paintRecursively (g, width);
  45960. }
  45961. }
  45962. }
  45963. }
  45964. bool TreeViewItem::isLastOfSiblings() const throw()
  45965. {
  45966. return parentItem == 0
  45967. || parentItem->subItems.getLast() == this;
  45968. }
  45969. int TreeViewItem::getIndexInParent() const throw()
  45970. {
  45971. return parentItem == 0 ? 0
  45972. : parentItem->subItems.indexOf (this);
  45973. }
  45974. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45975. {
  45976. return parentItem == 0 ? this
  45977. : parentItem->getTopLevelItem();
  45978. }
  45979. int TreeViewItem::getNumRows() const throw()
  45980. {
  45981. int num = 1;
  45982. if (isOpen())
  45983. {
  45984. for (int i = subItems.size(); --i >= 0;)
  45985. num += subItems.getUnchecked(i)->getNumRows();
  45986. }
  45987. return num;
  45988. }
  45989. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45990. {
  45991. if (index == 0)
  45992. return this;
  45993. if (index > 0 && isOpen())
  45994. {
  45995. --index;
  45996. for (int i = 0; i < subItems.size(); ++i)
  45997. {
  45998. TreeViewItem* const item = subItems.getUnchecked(i);
  45999. if (index == 0)
  46000. return item;
  46001. const int numRows = item->getNumRows();
  46002. if (numRows > index)
  46003. return item->getItemOnRow (index);
  46004. index -= numRows;
  46005. }
  46006. }
  46007. return 0;
  46008. }
  46009. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46010. {
  46011. if (isPositiveAndBelow (targetY, totalHeight))
  46012. {
  46013. const int h = itemHeight;
  46014. if (targetY < h)
  46015. return this;
  46016. if (isOpen())
  46017. {
  46018. targetY -= h;
  46019. for (int i = 0; i < subItems.size(); ++i)
  46020. {
  46021. TreeViewItem* const ti = subItems.getUnchecked(i);
  46022. if (targetY < ti->totalHeight)
  46023. return ti->findItemRecursively (targetY);
  46024. targetY -= ti->totalHeight;
  46025. }
  46026. }
  46027. }
  46028. return 0;
  46029. }
  46030. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46031. {
  46032. int total = isSelected() ? 1 : 0;
  46033. if (depth != 0)
  46034. for (int i = subItems.size(); --i >= 0;)
  46035. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46036. return total;
  46037. }
  46038. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46039. {
  46040. if (isSelected())
  46041. {
  46042. if (index == 0)
  46043. return this;
  46044. --index;
  46045. }
  46046. if (index >= 0)
  46047. {
  46048. for (int i = 0; i < subItems.size(); ++i)
  46049. {
  46050. TreeViewItem* const item = subItems.getUnchecked(i);
  46051. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46052. if (found != 0)
  46053. return found;
  46054. index -= item->countSelectedItemsRecursively (-1);
  46055. }
  46056. }
  46057. return 0;
  46058. }
  46059. int TreeViewItem::getRowNumberInTree() const throw()
  46060. {
  46061. if (parentItem != 0 && ownerView != 0)
  46062. {
  46063. int n = 1 + parentItem->getRowNumberInTree();
  46064. int ourIndex = parentItem->subItems.indexOf (this);
  46065. jassert (ourIndex >= 0);
  46066. while (--ourIndex >= 0)
  46067. n += parentItem->subItems [ourIndex]->getNumRows();
  46068. if (parentItem->parentItem == 0
  46069. && ! ownerView->rootItemVisible)
  46070. --n;
  46071. return n;
  46072. }
  46073. else
  46074. {
  46075. return 0;
  46076. }
  46077. }
  46078. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46079. {
  46080. drawLinesInside = drawLines;
  46081. }
  46082. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46083. {
  46084. if (recurse && isOpen() && subItems.size() > 0)
  46085. return subItems [0];
  46086. if (parentItem != 0)
  46087. {
  46088. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46089. if (nextIndex >= parentItem->subItems.size())
  46090. return parentItem->getNextVisibleItem (false);
  46091. return parentItem->subItems [nextIndex];
  46092. }
  46093. return 0;
  46094. }
  46095. const String TreeViewItem::getItemIdentifierString() const
  46096. {
  46097. String s;
  46098. if (parentItem != 0)
  46099. s = parentItem->getItemIdentifierString();
  46100. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46101. }
  46102. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46103. {
  46104. const String thisId (getUniqueName());
  46105. if (thisId == identifierString)
  46106. return this;
  46107. if (identifierString.startsWith (thisId + "/"))
  46108. {
  46109. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46110. bool wasOpen = isOpen();
  46111. setOpen (true);
  46112. for (int i = subItems.size(); --i >= 0;)
  46113. {
  46114. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46115. if (item != 0)
  46116. return item;
  46117. }
  46118. setOpen (wasOpen);
  46119. }
  46120. return 0;
  46121. }
  46122. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46123. {
  46124. if (e.hasTagName ("CLOSED"))
  46125. {
  46126. setOpen (false);
  46127. }
  46128. else if (e.hasTagName ("OPEN"))
  46129. {
  46130. setOpen (true);
  46131. forEachXmlChildElement (e, n)
  46132. {
  46133. const String id (n->getStringAttribute ("id"));
  46134. for (int i = 0; i < subItems.size(); ++i)
  46135. {
  46136. TreeViewItem* const ti = subItems.getUnchecked(i);
  46137. if (ti->getUniqueName() == id)
  46138. {
  46139. ti->restoreOpennessState (*n);
  46140. break;
  46141. }
  46142. }
  46143. }
  46144. }
  46145. }
  46146. XmlElement* TreeViewItem::getOpennessState() const throw()
  46147. {
  46148. const String name (getUniqueName());
  46149. if (name.isNotEmpty())
  46150. {
  46151. XmlElement* e;
  46152. if (isOpen())
  46153. {
  46154. e = new XmlElement ("OPEN");
  46155. for (int i = 0; i < subItems.size(); ++i)
  46156. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46157. }
  46158. else
  46159. {
  46160. e = new XmlElement ("CLOSED");
  46161. }
  46162. e->setAttribute ("id", name);
  46163. return e;
  46164. }
  46165. else
  46166. {
  46167. // trying to save the openness for an element that has no name - this won't
  46168. // work because it needs the names to identify what to open.
  46169. jassertfalse;
  46170. }
  46171. return 0;
  46172. }
  46173. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& treeViewItem_)
  46174. : treeViewItem (treeViewItem_),
  46175. oldOpenness (treeViewItem_.getOpennessState())
  46176. {
  46177. }
  46178. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  46179. {
  46180. if (oldOpenness != 0)
  46181. treeViewItem.restoreOpennessState (*oldOpenness);
  46182. }
  46183. END_JUCE_NAMESPACE
  46184. /*** End of inlined file: juce_TreeView.cpp ***/
  46185. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46186. BEGIN_JUCE_NAMESPACE
  46187. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46188. : fileList (listToShow)
  46189. {
  46190. }
  46191. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46192. {
  46193. }
  46194. FileBrowserListener::~FileBrowserListener()
  46195. {
  46196. }
  46197. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46198. {
  46199. listeners.add (listener);
  46200. }
  46201. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46202. {
  46203. listeners.remove (listener);
  46204. }
  46205. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46206. {
  46207. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46208. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46209. }
  46210. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46211. {
  46212. if (fileList.getDirectory().exists())
  46213. {
  46214. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46215. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46216. }
  46217. }
  46218. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46219. {
  46220. if (fileList.getDirectory().exists())
  46221. {
  46222. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46223. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46224. }
  46225. }
  46226. END_JUCE_NAMESPACE
  46227. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46228. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46229. BEGIN_JUCE_NAMESPACE
  46230. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46231. TimeSliceThread& thread_)
  46232. : fileFilter (fileFilter_),
  46233. thread (thread_),
  46234. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46235. fileFindHandle (0),
  46236. shouldStop (true)
  46237. {
  46238. }
  46239. DirectoryContentsList::~DirectoryContentsList()
  46240. {
  46241. clear();
  46242. }
  46243. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46244. {
  46245. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46246. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46247. }
  46248. bool DirectoryContentsList::ignoresHiddenFiles() const
  46249. {
  46250. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46251. }
  46252. const File& DirectoryContentsList::getDirectory() const
  46253. {
  46254. return root;
  46255. }
  46256. void DirectoryContentsList::setDirectory (const File& directory,
  46257. const bool includeDirectories,
  46258. const bool includeFiles)
  46259. {
  46260. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46261. if (directory != root)
  46262. {
  46263. clear();
  46264. root = directory;
  46265. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46266. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46267. }
  46268. int newFlags = fileTypeFlags;
  46269. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46270. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46271. setTypeFlags (newFlags);
  46272. }
  46273. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46274. {
  46275. if (fileTypeFlags != newFlags)
  46276. {
  46277. fileTypeFlags = newFlags;
  46278. refresh();
  46279. }
  46280. }
  46281. void DirectoryContentsList::clear()
  46282. {
  46283. shouldStop = true;
  46284. thread.removeTimeSliceClient (this);
  46285. fileFindHandle = 0;
  46286. if (files.size() > 0)
  46287. {
  46288. files.clear();
  46289. changed();
  46290. }
  46291. }
  46292. void DirectoryContentsList::refresh()
  46293. {
  46294. clear();
  46295. if (root.isDirectory())
  46296. {
  46297. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46298. shouldStop = false;
  46299. thread.addTimeSliceClient (this);
  46300. }
  46301. }
  46302. int DirectoryContentsList::getNumFiles() const
  46303. {
  46304. return files.size();
  46305. }
  46306. bool DirectoryContentsList::getFileInfo (const int index,
  46307. FileInfo& result) const
  46308. {
  46309. const ScopedLock sl (fileListLock);
  46310. const FileInfo* const info = files [index];
  46311. if (info != 0)
  46312. {
  46313. result = *info;
  46314. return true;
  46315. }
  46316. return false;
  46317. }
  46318. const File DirectoryContentsList::getFile (const int index) const
  46319. {
  46320. const ScopedLock sl (fileListLock);
  46321. const FileInfo* const info = files [index];
  46322. if (info != 0)
  46323. return root.getChildFile (info->filename);
  46324. return File::nonexistent;
  46325. }
  46326. bool DirectoryContentsList::isStillLoading() const
  46327. {
  46328. return fileFindHandle != 0;
  46329. }
  46330. void DirectoryContentsList::changed()
  46331. {
  46332. sendChangeMessage();
  46333. }
  46334. int DirectoryContentsList::useTimeSlice()
  46335. {
  46336. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46337. bool hasChanged = false;
  46338. for (int i = 100; --i >= 0;)
  46339. {
  46340. if (! checkNextFile (hasChanged))
  46341. {
  46342. if (hasChanged)
  46343. changed();
  46344. return 500;
  46345. }
  46346. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46347. break;
  46348. }
  46349. if (hasChanged)
  46350. changed();
  46351. return 0;
  46352. }
  46353. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46354. {
  46355. if (fileFindHandle != 0)
  46356. {
  46357. bool fileFoundIsDir, isHidden, isReadOnly;
  46358. int64 fileSize;
  46359. Time modTime, creationTime;
  46360. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46361. &modTime, &creationTime, &isReadOnly))
  46362. {
  46363. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46364. fileSize, modTime, creationTime, isReadOnly))
  46365. {
  46366. hasChanged = true;
  46367. }
  46368. return true;
  46369. }
  46370. else
  46371. {
  46372. fileFindHandle = 0;
  46373. }
  46374. }
  46375. return false;
  46376. }
  46377. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46378. const DirectoryContentsList::FileInfo* const second)
  46379. {
  46380. #if JUCE_WINDOWS
  46381. if (first->isDirectory != second->isDirectory)
  46382. return first->isDirectory ? -1 : 1;
  46383. #endif
  46384. return first->filename.compareIgnoreCase (second->filename);
  46385. }
  46386. bool DirectoryContentsList::addFile (const File& file,
  46387. const bool isDir,
  46388. const int64 fileSize,
  46389. const Time& modTime,
  46390. const Time& creationTime,
  46391. const bool isReadOnly)
  46392. {
  46393. if (fileFilter == 0
  46394. || ((! isDir) && fileFilter->isFileSuitable (file))
  46395. || (isDir && fileFilter->isDirectorySuitable (file)))
  46396. {
  46397. ScopedPointer <FileInfo> info (new FileInfo());
  46398. info->filename = file.getFileName();
  46399. info->fileSize = fileSize;
  46400. info->modificationTime = modTime;
  46401. info->creationTime = creationTime;
  46402. info->isDirectory = isDir;
  46403. info->isReadOnly = isReadOnly;
  46404. const ScopedLock sl (fileListLock);
  46405. for (int i = files.size(); --i >= 0;)
  46406. if (files.getUnchecked(i)->filename == info->filename)
  46407. return false;
  46408. files.addSorted (*this, info.release());
  46409. return true;
  46410. }
  46411. return false;
  46412. }
  46413. END_JUCE_NAMESPACE
  46414. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46415. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46416. BEGIN_JUCE_NAMESPACE
  46417. FileBrowserComponent::FileBrowserComponent (int flags_,
  46418. const File& initialFileOrDirectory,
  46419. const FileFilter* fileFilter_,
  46420. FilePreviewComponent* previewComp_)
  46421. : FileFilter (String::empty),
  46422. fileFilter (fileFilter_),
  46423. flags (flags_),
  46424. previewComp (previewComp_),
  46425. currentPathBox ("path"),
  46426. fileLabel ("f", TRANS ("file:")),
  46427. thread ("Juce FileBrowser")
  46428. {
  46429. // You need to specify one or other of the open/save flags..
  46430. jassert ((flags & (saveMode | openMode)) != 0);
  46431. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46432. // You need to specify at least one of these flags..
  46433. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46434. String filename;
  46435. if (initialFileOrDirectory == File::nonexistent)
  46436. {
  46437. currentRoot = File::getCurrentWorkingDirectory();
  46438. }
  46439. else if (initialFileOrDirectory.isDirectory())
  46440. {
  46441. currentRoot = initialFileOrDirectory;
  46442. }
  46443. else
  46444. {
  46445. chosenFiles.add (initialFileOrDirectory);
  46446. currentRoot = initialFileOrDirectory.getParentDirectory();
  46447. filename = initialFileOrDirectory.getFileName();
  46448. }
  46449. fileList = new DirectoryContentsList (this, thread);
  46450. if ((flags & useTreeView) != 0)
  46451. {
  46452. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46453. fileListComponent = tree;
  46454. if ((flags & canSelectMultipleItems) != 0)
  46455. tree->setMultiSelectEnabled (true);
  46456. addAndMakeVisible (tree);
  46457. }
  46458. else
  46459. {
  46460. FileListComponent* const list = new FileListComponent (*fileList);
  46461. fileListComponent = list;
  46462. list->setOutlineThickness (1);
  46463. if ((flags & canSelectMultipleItems) != 0)
  46464. list->setMultipleSelectionEnabled (true);
  46465. addAndMakeVisible (list);
  46466. }
  46467. fileListComponent->addListener (this);
  46468. addAndMakeVisible (&currentPathBox);
  46469. currentPathBox.setEditableText (true);
  46470. StringArray rootNames, rootPaths;
  46471. getRoots (rootNames, rootPaths);
  46472. for (int i = 0; i < rootNames.size(); ++i)
  46473. {
  46474. if (rootNames[i].isEmpty())
  46475. currentPathBox.addSeparator();
  46476. else
  46477. currentPathBox.addItem (rootNames[i], i + 1);
  46478. }
  46479. currentPathBox.addSeparator();
  46480. currentPathBox.addListener (this);
  46481. addAndMakeVisible (&filenameBox);
  46482. filenameBox.setMultiLine (false);
  46483. filenameBox.setSelectAllWhenFocused (true);
  46484. filenameBox.setText (filename, false);
  46485. filenameBox.addListener (this);
  46486. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46487. addAndMakeVisible (&fileLabel);
  46488. fileLabel.attachToComponent (&filenameBox, true);
  46489. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46490. goUpButton->addListener (this);
  46491. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46492. if (previewComp != 0)
  46493. addAndMakeVisible (previewComp);
  46494. setRoot (currentRoot);
  46495. thread.startThread (4);
  46496. }
  46497. FileBrowserComponent::~FileBrowserComponent()
  46498. {
  46499. fileListComponent = 0;
  46500. fileList = 0;
  46501. thread.stopThread (10000);
  46502. }
  46503. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46504. {
  46505. listeners.add (newListener);
  46506. }
  46507. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46508. {
  46509. listeners.remove (listener);
  46510. }
  46511. bool FileBrowserComponent::isSaveMode() const throw()
  46512. {
  46513. return (flags & saveMode) != 0;
  46514. }
  46515. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46516. {
  46517. if (chosenFiles.size() == 0 && currentFileIsValid())
  46518. return 1;
  46519. return chosenFiles.size();
  46520. }
  46521. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46522. {
  46523. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46524. return currentRoot;
  46525. if (! filenameBox.isReadOnly())
  46526. return currentRoot.getChildFile (filenameBox.getText());
  46527. return chosenFiles[index];
  46528. }
  46529. bool FileBrowserComponent::currentFileIsValid() const
  46530. {
  46531. if (isSaveMode())
  46532. return ! getSelectedFile (0).isDirectory();
  46533. else
  46534. return getSelectedFile (0).exists();
  46535. }
  46536. const File FileBrowserComponent::getHighlightedFile() const throw()
  46537. {
  46538. return fileListComponent->getSelectedFile (0);
  46539. }
  46540. void FileBrowserComponent::deselectAllFiles()
  46541. {
  46542. fileListComponent->deselectAllFiles();
  46543. }
  46544. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46545. {
  46546. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46547. }
  46548. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46549. {
  46550. return true;
  46551. }
  46552. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46553. {
  46554. if (f.isDirectory())
  46555. return (flags & canSelectDirectories) != 0
  46556. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46557. return (flags & canSelectFiles) != 0 && f.exists()
  46558. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46559. }
  46560. const File FileBrowserComponent::getRoot() const
  46561. {
  46562. return currentRoot;
  46563. }
  46564. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46565. {
  46566. if (currentRoot != newRootDirectory)
  46567. {
  46568. fileListComponent->scrollToTop();
  46569. String path (newRootDirectory.getFullPathName());
  46570. if (path.isEmpty())
  46571. path = File::separatorString;
  46572. StringArray rootNames, rootPaths;
  46573. getRoots (rootNames, rootPaths);
  46574. if (! rootPaths.contains (path, true))
  46575. {
  46576. bool alreadyListed = false;
  46577. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46578. {
  46579. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46580. {
  46581. alreadyListed = true;
  46582. break;
  46583. }
  46584. }
  46585. if (! alreadyListed)
  46586. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46587. }
  46588. }
  46589. currentRoot = newRootDirectory;
  46590. fileList->setDirectory (currentRoot, true, true);
  46591. String currentRootName (currentRoot.getFullPathName());
  46592. if (currentRootName.isEmpty())
  46593. currentRootName = File::separatorString;
  46594. currentPathBox.setText (currentRootName, true);
  46595. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46596. && currentRoot.getParentDirectory() != currentRoot);
  46597. }
  46598. void FileBrowserComponent::goUp()
  46599. {
  46600. setRoot (getRoot().getParentDirectory());
  46601. }
  46602. void FileBrowserComponent::refresh()
  46603. {
  46604. fileList->refresh();
  46605. }
  46606. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46607. {
  46608. if (fileFilter != newFileFilter)
  46609. {
  46610. fileFilter = newFileFilter;
  46611. refresh();
  46612. }
  46613. }
  46614. const String FileBrowserComponent::getActionVerb() const
  46615. {
  46616. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46617. }
  46618. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46619. {
  46620. return previewComp;
  46621. }
  46622. void FileBrowserComponent::resized()
  46623. {
  46624. getLookAndFeel()
  46625. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46626. &currentPathBox, &filenameBox, goUpButton);
  46627. }
  46628. void FileBrowserComponent::sendListenerChangeMessage()
  46629. {
  46630. Component::BailOutChecker checker (this);
  46631. if (previewComp != 0)
  46632. previewComp->selectedFileChanged (getSelectedFile (0));
  46633. // You shouldn't delete the browser when the file gets changed!
  46634. jassert (! checker.shouldBailOut());
  46635. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46636. }
  46637. void FileBrowserComponent::selectionChanged()
  46638. {
  46639. StringArray newFilenames;
  46640. bool resetChosenFiles = true;
  46641. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46642. {
  46643. const File f (fileListComponent->getSelectedFile (i));
  46644. if (isFileOrDirSuitable (f))
  46645. {
  46646. if (resetChosenFiles)
  46647. {
  46648. chosenFiles.clear();
  46649. resetChosenFiles = false;
  46650. }
  46651. chosenFiles.add (f);
  46652. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46653. }
  46654. }
  46655. if (newFilenames.size() > 0)
  46656. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46657. sendListenerChangeMessage();
  46658. }
  46659. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46660. {
  46661. Component::BailOutChecker checker (this);
  46662. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46663. }
  46664. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46665. {
  46666. if (f.isDirectory())
  46667. {
  46668. setRoot (f);
  46669. if ((flags & canSelectDirectories) != 0)
  46670. filenameBox.setText (String::empty);
  46671. }
  46672. else
  46673. {
  46674. Component::BailOutChecker checker (this);
  46675. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46676. }
  46677. }
  46678. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46679. {
  46680. (void) key;
  46681. #if JUCE_LINUX || JUCE_WINDOWS
  46682. if (key.getModifiers().isCommandDown()
  46683. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46684. {
  46685. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46686. fileList->refresh();
  46687. return true;
  46688. }
  46689. #endif
  46690. return false;
  46691. }
  46692. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46693. {
  46694. sendListenerChangeMessage();
  46695. }
  46696. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46697. {
  46698. if (filenameBox.getText().containsChar (File::separator))
  46699. {
  46700. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46701. if (f.isDirectory())
  46702. {
  46703. setRoot (f);
  46704. chosenFiles.clear();
  46705. filenameBox.setText (String::empty);
  46706. }
  46707. else
  46708. {
  46709. setRoot (f.getParentDirectory());
  46710. chosenFiles.clear();
  46711. chosenFiles.add (f);
  46712. filenameBox.setText (f.getFileName());
  46713. }
  46714. }
  46715. else
  46716. {
  46717. fileDoubleClicked (getSelectedFile (0));
  46718. }
  46719. }
  46720. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46721. {
  46722. }
  46723. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46724. {
  46725. if (! isSaveMode())
  46726. selectionChanged();
  46727. }
  46728. void FileBrowserComponent::buttonClicked (Button*)
  46729. {
  46730. goUp();
  46731. }
  46732. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46733. {
  46734. const String newText (currentPathBox.getText().trim().unquoted());
  46735. if (newText.isNotEmpty())
  46736. {
  46737. const int index = currentPathBox.getSelectedId() - 1;
  46738. StringArray rootNames, rootPaths;
  46739. getRoots (rootNames, rootPaths);
  46740. if (rootPaths [index].isNotEmpty())
  46741. {
  46742. setRoot (File (rootPaths [index]));
  46743. }
  46744. else
  46745. {
  46746. File f (newText);
  46747. for (;;)
  46748. {
  46749. if (f.isDirectory())
  46750. {
  46751. setRoot (f);
  46752. break;
  46753. }
  46754. if (f.getParentDirectory() == f)
  46755. break;
  46756. f = f.getParentDirectory();
  46757. }
  46758. }
  46759. }
  46760. }
  46761. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46762. {
  46763. #if JUCE_WINDOWS
  46764. Array<File> roots;
  46765. File::findFileSystemRoots (roots);
  46766. rootPaths.clear();
  46767. for (int i = 0; i < roots.size(); ++i)
  46768. {
  46769. const File& drive = roots.getReference(i);
  46770. String name (drive.getFullPathName());
  46771. rootPaths.add (name);
  46772. if (drive.isOnHardDisk())
  46773. {
  46774. String volume (drive.getVolumeLabel());
  46775. if (volume.isEmpty())
  46776. volume = TRANS("Hard Drive");
  46777. name << " [" << volume << ']';
  46778. }
  46779. else if (drive.isOnCDRomDrive())
  46780. {
  46781. name << TRANS(" [CD/DVD drive]");
  46782. }
  46783. rootNames.add (name);
  46784. }
  46785. rootPaths.add (String::empty);
  46786. rootNames.add (String::empty);
  46787. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46788. rootNames.add ("Documents");
  46789. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46790. rootNames.add ("Desktop");
  46791. #endif
  46792. #if JUCE_MAC
  46793. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46794. rootNames.add ("Home folder");
  46795. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46796. rootNames.add ("Documents");
  46797. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46798. rootNames.add ("Desktop");
  46799. rootPaths.add (String::empty);
  46800. rootNames.add (String::empty);
  46801. Array <File> volumes;
  46802. File vol ("/Volumes");
  46803. vol.findChildFiles (volumes, File::findDirectories, false);
  46804. for (int i = 0; i < volumes.size(); ++i)
  46805. {
  46806. const File& volume = volumes.getReference(i);
  46807. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46808. {
  46809. rootPaths.add (volume.getFullPathName());
  46810. rootNames.add (volume.getFileName());
  46811. }
  46812. }
  46813. #endif
  46814. #if JUCE_LINUX
  46815. rootPaths.add ("/");
  46816. rootNames.add ("/");
  46817. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46818. rootNames.add ("Home folder");
  46819. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46820. rootNames.add ("Desktop");
  46821. #endif
  46822. }
  46823. END_JUCE_NAMESPACE
  46824. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46825. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46826. BEGIN_JUCE_NAMESPACE
  46827. FileChooser::FileChooser (const String& chooserBoxTitle,
  46828. const File& currentFileOrDirectory,
  46829. const String& fileFilters,
  46830. const bool useNativeDialogBox_)
  46831. : title (chooserBoxTitle),
  46832. filters (fileFilters),
  46833. startingFile (currentFileOrDirectory),
  46834. useNativeDialogBox (useNativeDialogBox_)
  46835. {
  46836. #if JUCE_LINUX
  46837. useNativeDialogBox = false;
  46838. #endif
  46839. if (! fileFilters.containsNonWhitespaceChars())
  46840. filters = "*";
  46841. }
  46842. FileChooser::~FileChooser()
  46843. {
  46844. }
  46845. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46846. {
  46847. return showDialog (false, true, false, false, false, previewComponent);
  46848. }
  46849. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46850. {
  46851. return showDialog (false, true, false, false, true, previewComponent);
  46852. }
  46853. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46854. {
  46855. return showDialog (true, true, false, false, true, previewComponent);
  46856. }
  46857. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46858. {
  46859. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46860. }
  46861. bool FileChooser::browseForDirectory()
  46862. {
  46863. return showDialog (true, false, false, false, false, 0);
  46864. }
  46865. const File FileChooser::getResult() const
  46866. {
  46867. // if you've used a multiple-file select, you should use the getResults() method
  46868. // to retrieve all the files that were chosen.
  46869. jassert (results.size() <= 1);
  46870. return results.getFirst();
  46871. }
  46872. const Array<File>& FileChooser::getResults() const
  46873. {
  46874. return results;
  46875. }
  46876. bool FileChooser::showDialog (const bool selectsDirectories,
  46877. const bool selectsFiles,
  46878. const bool isSave,
  46879. const bool warnAboutOverwritingExistingFiles,
  46880. const bool selectMultipleFiles,
  46881. FilePreviewComponent* const previewComponent)
  46882. {
  46883. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46884. results.clear();
  46885. // the preview component needs to be the right size before you pass it in here..
  46886. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46887. && previewComponent->getHeight() > 10));
  46888. #if JUCE_WINDOWS
  46889. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46890. #elif JUCE_MAC
  46891. if (useNativeDialogBox && (previewComponent == 0))
  46892. #else
  46893. if (false)
  46894. #endif
  46895. {
  46896. showPlatformDialog (results, title, startingFile, filters,
  46897. selectsDirectories, selectsFiles, isSave,
  46898. warnAboutOverwritingExistingFiles,
  46899. selectMultipleFiles,
  46900. previewComponent);
  46901. }
  46902. else
  46903. {
  46904. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46905. selectsDirectories ? "*" : String::empty,
  46906. String::empty);
  46907. int flags = isSave ? FileBrowserComponent::saveMode
  46908. : FileBrowserComponent::openMode;
  46909. if (selectsFiles)
  46910. flags |= FileBrowserComponent::canSelectFiles;
  46911. if (selectsDirectories)
  46912. {
  46913. flags |= FileBrowserComponent::canSelectDirectories;
  46914. if (! isSave)
  46915. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46916. }
  46917. if (selectMultipleFiles)
  46918. flags |= FileBrowserComponent::canSelectMultipleItems;
  46919. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46920. FileChooserDialogBox box (title, String::empty,
  46921. browserComponent,
  46922. warnAboutOverwritingExistingFiles,
  46923. browserComponent.findColour (AlertWindow::backgroundColourId));
  46924. if (box.show())
  46925. {
  46926. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46927. results.add (browserComponent.getSelectedFile (i));
  46928. }
  46929. }
  46930. if (previouslyFocused != 0)
  46931. previouslyFocused->grabKeyboardFocus();
  46932. return results.size() > 0;
  46933. }
  46934. FilePreviewComponent::FilePreviewComponent()
  46935. {
  46936. }
  46937. FilePreviewComponent::~FilePreviewComponent()
  46938. {
  46939. }
  46940. END_JUCE_NAMESPACE
  46941. /*** End of inlined file: juce_FileChooser.cpp ***/
  46942. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46943. BEGIN_JUCE_NAMESPACE
  46944. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46945. const String& instructions,
  46946. FileBrowserComponent& chooserComponent,
  46947. const bool warnAboutOverwritingExistingFiles_,
  46948. const Colour& backgroundColour)
  46949. : ResizableWindow (name, backgroundColour, true),
  46950. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46951. {
  46952. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  46953. setResizable (true, true);
  46954. setResizeLimits (300, 300, 1200, 1000);
  46955. content->okButton.addListener (this);
  46956. content->cancelButton.addListener (this);
  46957. content->newFolderButton.addListener (this);
  46958. content->chooserComponent.addListener (this);
  46959. selectionChanged();
  46960. }
  46961. FileChooserDialogBox::~FileChooserDialogBox()
  46962. {
  46963. content->chooserComponent.removeListener (this);
  46964. }
  46965. bool FileChooserDialogBox::show (int w, int h)
  46966. {
  46967. return showAt (-1, -1, w, h);
  46968. }
  46969. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46970. {
  46971. if (w <= 0)
  46972. {
  46973. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  46974. if (previewComp != 0)
  46975. w = 400 + previewComp->getWidth();
  46976. else
  46977. w = 600;
  46978. }
  46979. if (h <= 0)
  46980. h = 500;
  46981. if (x < 0 || y < 0)
  46982. centreWithSize (w, h);
  46983. else
  46984. setBounds (x, y, w, h);
  46985. const bool ok = (runModalLoop() != 0);
  46986. setVisible (false);
  46987. return ok;
  46988. }
  46989. void FileChooserDialogBox::buttonClicked (Button* button)
  46990. {
  46991. if (button == &(content->okButton))
  46992. {
  46993. okButtonPressed();
  46994. }
  46995. else if (button == &(content->cancelButton))
  46996. {
  46997. closeButtonPressed();
  46998. }
  46999. else if (button == &(content->newFolderButton))
  47000. {
  47001. createNewFolder();
  47002. }
  47003. }
  47004. void FileChooserDialogBox::closeButtonPressed()
  47005. {
  47006. setVisible (false);
  47007. }
  47008. void FileChooserDialogBox::selectionChanged()
  47009. {
  47010. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47011. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47012. && content->chooserComponent.getRoot().isDirectory());
  47013. }
  47014. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47015. {
  47016. }
  47017. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47018. {
  47019. selectionChanged();
  47020. content->okButton.triggerClick();
  47021. }
  47022. void FileChooserDialogBox::okButtonPressed()
  47023. {
  47024. if ((! (warnAboutOverwritingExistingFiles
  47025. && content->chooserComponent.isSaveMode()
  47026. && content->chooserComponent.getSelectedFile(0).exists()))
  47027. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47028. TRANS("File already exists"),
  47029. TRANS("There's already a file called:")
  47030. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47031. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47032. TRANS("overwrite"),
  47033. TRANS("cancel")))
  47034. {
  47035. exitModalState (1);
  47036. }
  47037. }
  47038. void FileChooserDialogBox::createNewFolder()
  47039. {
  47040. File parent (content->chooserComponent.getRoot());
  47041. if (parent.isDirectory())
  47042. {
  47043. AlertWindow aw (TRANS("New Folder"),
  47044. TRANS("Please enter the name for the folder"),
  47045. AlertWindow::NoIcon, this);
  47046. aw.addTextEditor ("name", String::empty, String::empty, false);
  47047. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47048. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47049. if (aw.runModalLoop() != 0)
  47050. {
  47051. aw.setVisible (false);
  47052. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47053. if (! name.isEmpty())
  47054. {
  47055. if (! parent.getChildFile (name).createDirectory())
  47056. {
  47057. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47058. TRANS ("New Folder"),
  47059. TRANS ("Couldn't create the folder!"));
  47060. }
  47061. content->chooserComponent.refresh();
  47062. }
  47063. }
  47064. }
  47065. }
  47066. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47067. : Component (name), instructions (instructions_),
  47068. chooserComponent (chooserComponent_),
  47069. okButton (chooserComponent_.getActionVerb()),
  47070. cancelButton (TRANS ("Cancel")),
  47071. newFolderButton (TRANS ("New Folder"))
  47072. {
  47073. addAndMakeVisible (&chooserComponent);
  47074. addAndMakeVisible (&okButton);
  47075. okButton.addShortcut (KeyPress::returnKey);
  47076. addAndMakeVisible (&cancelButton);
  47077. cancelButton.addShortcut (KeyPress::escapeKey);
  47078. addChildComponent (&newFolderButton);
  47079. setInterceptsMouseClicks (false, true);
  47080. }
  47081. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47082. {
  47083. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47084. text.draw (g);
  47085. }
  47086. void FileChooserDialogBox::ContentComponent::resized()
  47087. {
  47088. const int buttonHeight = 26;
  47089. Rectangle<int> area (getLocalBounds());
  47090. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47091. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47092. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47093. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47094. Rectangle<int> buttonArea (area.reduced (16, 10));
  47095. okButton.changeWidthToFitText (buttonHeight);
  47096. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47097. buttonArea.removeFromRight (16);
  47098. cancelButton.changeWidthToFitText (buttonHeight);
  47099. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47100. newFolderButton.changeWidthToFitText (buttonHeight);
  47101. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47102. }
  47103. END_JUCE_NAMESPACE
  47104. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47105. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47106. BEGIN_JUCE_NAMESPACE
  47107. FileFilter::FileFilter (const String& filterDescription)
  47108. : description (filterDescription)
  47109. {
  47110. }
  47111. FileFilter::~FileFilter()
  47112. {
  47113. }
  47114. const String& FileFilter::getDescription() const throw()
  47115. {
  47116. return description;
  47117. }
  47118. END_JUCE_NAMESPACE
  47119. /*** End of inlined file: juce_FileFilter.cpp ***/
  47120. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47121. BEGIN_JUCE_NAMESPACE
  47122. const Image juce_createIconForFile (const File& file);
  47123. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47124. : ListBox (String::empty, 0),
  47125. DirectoryContentsDisplayComponent (listToShow)
  47126. {
  47127. setModel (this);
  47128. fileList.addChangeListener (this);
  47129. }
  47130. FileListComponent::~FileListComponent()
  47131. {
  47132. fileList.removeChangeListener (this);
  47133. }
  47134. int FileListComponent::getNumSelectedFiles() const
  47135. {
  47136. return getNumSelectedRows();
  47137. }
  47138. const File FileListComponent::getSelectedFile (int index) const
  47139. {
  47140. return fileList.getFile (getSelectedRow (index));
  47141. }
  47142. void FileListComponent::deselectAllFiles()
  47143. {
  47144. deselectAllRows();
  47145. }
  47146. void FileListComponent::scrollToTop()
  47147. {
  47148. getVerticalScrollBar()->setCurrentRangeStart (0);
  47149. }
  47150. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47151. {
  47152. updateContent();
  47153. if (lastDirectory != fileList.getDirectory())
  47154. {
  47155. lastDirectory = fileList.getDirectory();
  47156. deselectAllRows();
  47157. }
  47158. }
  47159. class FileListItemComponent : public Component,
  47160. public TimeSliceClient,
  47161. public AsyncUpdater
  47162. {
  47163. public:
  47164. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47165. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47166. {
  47167. }
  47168. ~FileListItemComponent()
  47169. {
  47170. thread.removeTimeSliceClient (this);
  47171. }
  47172. void paint (Graphics& g)
  47173. {
  47174. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47175. file.getFileName(),
  47176. &icon, fileSize, modTime,
  47177. isDirectory, highlighted,
  47178. index, owner);
  47179. }
  47180. void mouseDown (const MouseEvent& e)
  47181. {
  47182. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47183. owner.sendMouseClickMessage (file, e);
  47184. }
  47185. void mouseDoubleClick (const MouseEvent&)
  47186. {
  47187. owner.sendDoubleClickMessage (file);
  47188. }
  47189. void update (const File& root,
  47190. const DirectoryContentsList::FileInfo* const fileInfo,
  47191. const int index_,
  47192. const bool highlighted_)
  47193. {
  47194. thread.removeTimeSliceClient (this);
  47195. if (highlighted_ != highlighted || index_ != index)
  47196. {
  47197. index = index_;
  47198. highlighted = highlighted_;
  47199. repaint();
  47200. }
  47201. File newFile;
  47202. String newFileSize, newModTime;
  47203. if (fileInfo != 0)
  47204. {
  47205. newFile = root.getChildFile (fileInfo->filename);
  47206. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47207. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47208. }
  47209. if (newFile != file
  47210. || fileSize != newFileSize
  47211. || modTime != newModTime)
  47212. {
  47213. file = newFile;
  47214. fileSize = newFileSize;
  47215. modTime = newModTime;
  47216. icon = Image::null;
  47217. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47218. repaint();
  47219. }
  47220. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47221. {
  47222. updateIcon (true);
  47223. if (! icon.isValid())
  47224. thread.addTimeSliceClient (this);
  47225. }
  47226. }
  47227. int useTimeSlice()
  47228. {
  47229. updateIcon (false);
  47230. return -1;
  47231. }
  47232. void handleAsyncUpdate()
  47233. {
  47234. repaint();
  47235. }
  47236. private:
  47237. FileListComponent& owner;
  47238. TimeSliceThread& thread;
  47239. File file;
  47240. String fileSize, modTime;
  47241. Image icon;
  47242. int index;
  47243. bool highlighted, isDirectory;
  47244. void updateIcon (const bool onlyUpdateIfCached)
  47245. {
  47246. if (icon.isNull())
  47247. {
  47248. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47249. Image im (ImageCache::getFromHashCode (hashCode));
  47250. if (im.isNull() && ! onlyUpdateIfCached)
  47251. {
  47252. im = juce_createIconForFile (file);
  47253. if (im.isValid())
  47254. ImageCache::addImageToCache (im, hashCode);
  47255. }
  47256. if (im.isValid())
  47257. {
  47258. icon = im;
  47259. triggerAsyncUpdate();
  47260. }
  47261. }
  47262. }
  47263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47264. };
  47265. int FileListComponent::getNumRows()
  47266. {
  47267. return fileList.getNumFiles();
  47268. }
  47269. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47270. {
  47271. }
  47272. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47273. {
  47274. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47275. if (comp == 0)
  47276. {
  47277. delete existingComponentToUpdate;
  47278. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47279. }
  47280. DirectoryContentsList::FileInfo fileInfo;
  47281. if (fileList.getFileInfo (row, fileInfo))
  47282. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47283. else
  47284. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47285. return comp;
  47286. }
  47287. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47288. {
  47289. sendSelectionChangeMessage();
  47290. }
  47291. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47292. {
  47293. }
  47294. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47295. {
  47296. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47297. }
  47298. END_JUCE_NAMESPACE
  47299. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47300. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47301. BEGIN_JUCE_NAMESPACE
  47302. FilenameComponent::FilenameComponent (const String& name,
  47303. const File& currentFile,
  47304. const bool canEditFilename,
  47305. const bool isDirectory,
  47306. const bool isForSaving,
  47307. const String& fileBrowserWildcard,
  47308. const String& enforcedSuffix_,
  47309. const String& textWhenNothingSelected)
  47310. : Component (name),
  47311. maxRecentFiles (30),
  47312. isDir (isDirectory),
  47313. isSaving (isForSaving),
  47314. isFileDragOver (false),
  47315. wildcard (fileBrowserWildcard),
  47316. enforcedSuffix (enforcedSuffix_)
  47317. {
  47318. addAndMakeVisible (&filenameBox);
  47319. filenameBox.setEditableText (canEditFilename);
  47320. filenameBox.addListener (this);
  47321. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47322. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47323. setBrowseButtonText ("...");
  47324. setCurrentFile (currentFile, true);
  47325. }
  47326. FilenameComponent::~FilenameComponent()
  47327. {
  47328. }
  47329. void FilenameComponent::paintOverChildren (Graphics& g)
  47330. {
  47331. if (isFileDragOver)
  47332. {
  47333. g.setColour (Colours::red.withAlpha (0.2f));
  47334. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47335. }
  47336. }
  47337. void FilenameComponent::resized()
  47338. {
  47339. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47340. }
  47341. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47342. {
  47343. browseButtonText = newBrowseButtonText;
  47344. lookAndFeelChanged();
  47345. }
  47346. void FilenameComponent::lookAndFeelChanged()
  47347. {
  47348. browseButton = 0;
  47349. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47350. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47351. resized();
  47352. browseButton->addListener (this);
  47353. }
  47354. void FilenameComponent::setTooltip (const String& newTooltip)
  47355. {
  47356. SettableTooltipClient::setTooltip (newTooltip);
  47357. filenameBox.setTooltip (newTooltip);
  47358. }
  47359. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47360. {
  47361. defaultBrowseFile = newDefaultDirectory;
  47362. }
  47363. void FilenameComponent::buttonClicked (Button*)
  47364. {
  47365. FileChooser fc (TRANS("Choose a new file"),
  47366. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47367. : getCurrentFile(),
  47368. wildcard);
  47369. if (isDir ? fc.browseForDirectory()
  47370. : (isSaving ? fc.browseForFileToSave (false)
  47371. : fc.browseForFileToOpen()))
  47372. {
  47373. setCurrentFile (fc.getResult(), true);
  47374. }
  47375. }
  47376. void FilenameComponent::comboBoxChanged (ComboBox*)
  47377. {
  47378. setCurrentFile (getCurrentFile(), true);
  47379. }
  47380. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47381. {
  47382. return true;
  47383. }
  47384. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47385. {
  47386. isFileDragOver = false;
  47387. repaint();
  47388. const File f (filenames[0]);
  47389. if (f.exists() && (f.isDirectory() == isDir))
  47390. setCurrentFile (f, true);
  47391. }
  47392. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47393. {
  47394. isFileDragOver = true;
  47395. repaint();
  47396. }
  47397. void FilenameComponent::fileDragExit (const StringArray&)
  47398. {
  47399. isFileDragOver = false;
  47400. repaint();
  47401. }
  47402. const File FilenameComponent::getCurrentFile() const
  47403. {
  47404. File f (filenameBox.getText());
  47405. if (enforcedSuffix.isNotEmpty())
  47406. f = f.withFileExtension (enforcedSuffix);
  47407. return f;
  47408. }
  47409. void FilenameComponent::setCurrentFile (File newFile,
  47410. const bool addToRecentlyUsedList,
  47411. const bool sendChangeNotification)
  47412. {
  47413. if (enforcedSuffix.isNotEmpty())
  47414. newFile = newFile.withFileExtension (enforcedSuffix);
  47415. if (newFile.getFullPathName() != lastFilename)
  47416. {
  47417. lastFilename = newFile.getFullPathName();
  47418. if (addToRecentlyUsedList)
  47419. addRecentlyUsedFile (newFile);
  47420. filenameBox.setText (lastFilename, true);
  47421. if (sendChangeNotification)
  47422. triggerAsyncUpdate();
  47423. }
  47424. }
  47425. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47426. {
  47427. filenameBox.setEditableText (shouldBeEditable);
  47428. }
  47429. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47430. {
  47431. StringArray names;
  47432. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47433. names.add (filenameBox.getItemText (i));
  47434. return names;
  47435. }
  47436. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47437. {
  47438. if (filenames != getRecentlyUsedFilenames())
  47439. {
  47440. filenameBox.clear();
  47441. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47442. filenameBox.addItem (filenames[i], i + 1);
  47443. }
  47444. }
  47445. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47446. {
  47447. maxRecentFiles = jmax (1, newMaximum);
  47448. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47449. }
  47450. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47451. {
  47452. StringArray files (getRecentlyUsedFilenames());
  47453. if (file.getFullPathName().isNotEmpty())
  47454. {
  47455. files.removeString (file.getFullPathName(), true);
  47456. files.insert (0, file.getFullPathName());
  47457. setRecentlyUsedFilenames (files);
  47458. }
  47459. }
  47460. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47461. {
  47462. listeners.add (listener);
  47463. }
  47464. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47465. {
  47466. listeners.remove (listener);
  47467. }
  47468. void FilenameComponent::handleAsyncUpdate()
  47469. {
  47470. Component::BailOutChecker checker (this);
  47471. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47472. }
  47473. END_JUCE_NAMESPACE
  47474. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47475. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47476. BEGIN_JUCE_NAMESPACE
  47477. FileSearchPathListComponent::FileSearchPathListComponent()
  47478. : addButton ("+"),
  47479. removeButton ("-"),
  47480. changeButton (TRANS ("change...")),
  47481. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47482. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47483. {
  47484. listBox.setModel (this);
  47485. addAndMakeVisible (&listBox);
  47486. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47487. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47488. listBox.setOutlineThickness (1);
  47489. addAndMakeVisible (&addButton);
  47490. addButton.addListener (this);
  47491. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47492. addAndMakeVisible (&removeButton);
  47493. removeButton.addListener (this);
  47494. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47495. addAndMakeVisible (&changeButton);
  47496. changeButton.addListener (this);
  47497. addAndMakeVisible (&upButton);
  47498. upButton.addListener (this);
  47499. {
  47500. Path arrowPath;
  47501. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47502. DrawablePath arrowImage;
  47503. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47504. arrowImage.setPath (arrowPath);
  47505. upButton.setImages (&arrowImage);
  47506. }
  47507. addAndMakeVisible (&downButton);
  47508. downButton.addListener (this);
  47509. {
  47510. Path arrowPath;
  47511. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47512. DrawablePath arrowImage;
  47513. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47514. arrowImage.setPath (arrowPath);
  47515. downButton.setImages (&arrowImage);
  47516. }
  47517. updateButtons();
  47518. }
  47519. FileSearchPathListComponent::~FileSearchPathListComponent()
  47520. {
  47521. }
  47522. void FileSearchPathListComponent::updateButtons()
  47523. {
  47524. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47525. removeButton.setEnabled (anythingSelected);
  47526. changeButton.setEnabled (anythingSelected);
  47527. upButton.setEnabled (anythingSelected);
  47528. downButton.setEnabled (anythingSelected);
  47529. }
  47530. void FileSearchPathListComponent::changed()
  47531. {
  47532. listBox.updateContent();
  47533. listBox.repaint();
  47534. updateButtons();
  47535. }
  47536. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47537. {
  47538. if (newPath.toString() != path.toString())
  47539. {
  47540. path = newPath;
  47541. changed();
  47542. }
  47543. }
  47544. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47545. {
  47546. defaultBrowseTarget = newDefaultDirectory;
  47547. }
  47548. int FileSearchPathListComponent::getNumRows()
  47549. {
  47550. return path.getNumPaths();
  47551. }
  47552. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47553. {
  47554. if (rowIsSelected)
  47555. g.fillAll (findColour (TextEditor::highlightColourId));
  47556. g.setColour (findColour (ListBox::textColourId));
  47557. Font f (height * 0.7f);
  47558. f.setHorizontalScale (0.9f);
  47559. g.setFont (f);
  47560. g.drawText (path [rowNumber].getFullPathName(),
  47561. 4, 0, width - 6, height,
  47562. Justification::centredLeft, true);
  47563. }
  47564. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47565. {
  47566. if (isPositiveAndBelow (row, path.getNumPaths()))
  47567. {
  47568. path.remove (row);
  47569. changed();
  47570. }
  47571. }
  47572. void FileSearchPathListComponent::returnKeyPressed (int row)
  47573. {
  47574. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47575. if (chooser.browseForDirectory())
  47576. {
  47577. path.remove (row);
  47578. path.add (chooser.getResult(), row);
  47579. changed();
  47580. }
  47581. }
  47582. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47583. {
  47584. returnKeyPressed (row);
  47585. }
  47586. void FileSearchPathListComponent::selectedRowsChanged (int)
  47587. {
  47588. updateButtons();
  47589. }
  47590. void FileSearchPathListComponent::paint (Graphics& g)
  47591. {
  47592. g.fillAll (findColour (backgroundColourId));
  47593. }
  47594. void FileSearchPathListComponent::resized()
  47595. {
  47596. const int buttonH = 22;
  47597. const int buttonY = getHeight() - buttonH - 4;
  47598. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47599. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47600. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47601. changeButton.changeWidthToFitText (buttonH);
  47602. downButton.setSize (buttonH * 2, buttonH);
  47603. upButton.setSize (buttonH * 2, buttonH);
  47604. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47605. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47606. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47607. }
  47608. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47609. {
  47610. return true;
  47611. }
  47612. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47613. {
  47614. for (int i = filenames.size(); --i >= 0;)
  47615. {
  47616. const File f (filenames[i]);
  47617. if (f.isDirectory())
  47618. {
  47619. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47620. path.add (f, row);
  47621. changed();
  47622. }
  47623. }
  47624. }
  47625. void FileSearchPathListComponent::buttonClicked (Button* button)
  47626. {
  47627. const int currentRow = listBox.getSelectedRow();
  47628. if (button == &removeButton)
  47629. {
  47630. deleteKeyPressed (currentRow);
  47631. }
  47632. else if (button == &addButton)
  47633. {
  47634. File start (defaultBrowseTarget);
  47635. if (start == File::nonexistent)
  47636. start = path [0];
  47637. if (start == File::nonexistent)
  47638. start = File::getCurrentWorkingDirectory();
  47639. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47640. if (chooser.browseForDirectory())
  47641. {
  47642. path.add (chooser.getResult(), currentRow);
  47643. }
  47644. }
  47645. else if (button == &changeButton)
  47646. {
  47647. returnKeyPressed (currentRow);
  47648. }
  47649. else if (button == &upButton)
  47650. {
  47651. if (currentRow > 0 && currentRow < path.getNumPaths())
  47652. {
  47653. const File f (path[currentRow]);
  47654. path.remove (currentRow);
  47655. path.add (f, currentRow - 1);
  47656. listBox.selectRow (currentRow - 1);
  47657. }
  47658. }
  47659. else if (button == &downButton)
  47660. {
  47661. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47662. {
  47663. const File f (path[currentRow]);
  47664. path.remove (currentRow);
  47665. path.add (f, currentRow + 1);
  47666. listBox.selectRow (currentRow + 1);
  47667. }
  47668. }
  47669. changed();
  47670. }
  47671. END_JUCE_NAMESPACE
  47672. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47673. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47674. BEGIN_JUCE_NAMESPACE
  47675. const Image juce_createIconForFile (const File& file);
  47676. class FileListTreeItem : public TreeViewItem,
  47677. public TimeSliceClient,
  47678. public AsyncUpdater,
  47679. public ChangeListener
  47680. {
  47681. public:
  47682. FileListTreeItem (FileTreeComponent& owner_,
  47683. DirectoryContentsList* const parentContentsList_,
  47684. const int indexInContentsList_,
  47685. const File& file_,
  47686. TimeSliceThread& thread_)
  47687. : file (file_),
  47688. owner (owner_),
  47689. parentContentsList (parentContentsList_),
  47690. indexInContentsList (indexInContentsList_),
  47691. subContentsList (0),
  47692. canDeleteSubContentsList (false),
  47693. thread (thread_),
  47694. icon (0)
  47695. {
  47696. DirectoryContentsList::FileInfo fileInfo;
  47697. if (parentContentsList_ != 0
  47698. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47699. {
  47700. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47701. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47702. isDirectory = fileInfo.isDirectory;
  47703. }
  47704. else
  47705. {
  47706. isDirectory = true;
  47707. }
  47708. }
  47709. ~FileListTreeItem()
  47710. {
  47711. thread.removeTimeSliceClient (this);
  47712. clearSubItems();
  47713. if (canDeleteSubContentsList)
  47714. delete subContentsList;
  47715. }
  47716. bool mightContainSubItems() { return isDirectory; }
  47717. const String getUniqueName() const { return file.getFullPathName(); }
  47718. int getItemHeight() const { return 22; }
  47719. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47720. void itemOpennessChanged (bool isNowOpen)
  47721. {
  47722. if (isNowOpen)
  47723. {
  47724. clearSubItems();
  47725. isDirectory = file.isDirectory();
  47726. if (isDirectory)
  47727. {
  47728. if (subContentsList == 0)
  47729. {
  47730. jassert (parentContentsList != 0);
  47731. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47732. l->setDirectory (file, true, true);
  47733. setSubContentsList (l);
  47734. canDeleteSubContentsList = true;
  47735. }
  47736. changeListenerCallback (0);
  47737. }
  47738. }
  47739. }
  47740. void setSubContentsList (DirectoryContentsList* newList)
  47741. {
  47742. jassert (subContentsList == 0);
  47743. subContentsList = newList;
  47744. newList->addChangeListener (this);
  47745. }
  47746. void changeListenerCallback (ChangeBroadcaster*)
  47747. {
  47748. clearSubItems();
  47749. if (isOpen() && subContentsList != 0)
  47750. {
  47751. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47752. {
  47753. FileListTreeItem* const item
  47754. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47755. addSubItem (item);
  47756. }
  47757. }
  47758. }
  47759. void paintItem (Graphics& g, int width, int height)
  47760. {
  47761. if (file != File::nonexistent)
  47762. {
  47763. updateIcon (true);
  47764. if (icon.isNull())
  47765. thread.addTimeSliceClient (this);
  47766. }
  47767. owner.getLookAndFeel()
  47768. .drawFileBrowserRow (g, width, height,
  47769. file.getFileName(),
  47770. &icon, fileSize, modTime,
  47771. isDirectory, isSelected(),
  47772. indexInContentsList, owner);
  47773. }
  47774. void itemClicked (const MouseEvent& e)
  47775. {
  47776. owner.sendMouseClickMessage (file, e);
  47777. }
  47778. void itemDoubleClicked (const MouseEvent& e)
  47779. {
  47780. TreeViewItem::itemDoubleClicked (e);
  47781. owner.sendDoubleClickMessage (file);
  47782. }
  47783. void itemSelectionChanged (bool)
  47784. {
  47785. owner.sendSelectionChangeMessage();
  47786. }
  47787. int useTimeSlice()
  47788. {
  47789. updateIcon (false);
  47790. return -1;
  47791. }
  47792. void handleAsyncUpdate()
  47793. {
  47794. owner.repaint();
  47795. }
  47796. const File file;
  47797. private:
  47798. FileTreeComponent& owner;
  47799. DirectoryContentsList* parentContentsList;
  47800. int indexInContentsList;
  47801. DirectoryContentsList* subContentsList;
  47802. bool isDirectory, canDeleteSubContentsList;
  47803. TimeSliceThread& thread;
  47804. Image icon;
  47805. String fileSize;
  47806. String modTime;
  47807. void updateIcon (const bool onlyUpdateIfCached)
  47808. {
  47809. if (icon.isNull())
  47810. {
  47811. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47812. Image im (ImageCache::getFromHashCode (hashCode));
  47813. if (im.isNull() && ! onlyUpdateIfCached)
  47814. {
  47815. im = juce_createIconForFile (file);
  47816. if (im.isValid())
  47817. ImageCache::addImageToCache (im, hashCode);
  47818. }
  47819. if (im.isValid())
  47820. {
  47821. icon = im;
  47822. triggerAsyncUpdate();
  47823. }
  47824. }
  47825. }
  47826. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  47827. };
  47828. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47829. : DirectoryContentsDisplayComponent (listToShow)
  47830. {
  47831. FileListTreeItem* const root
  47832. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47833. listToShow.getTimeSliceThread());
  47834. root->setSubContentsList (&listToShow);
  47835. setRootItemVisible (false);
  47836. setRootItem (root);
  47837. }
  47838. FileTreeComponent::~FileTreeComponent()
  47839. {
  47840. deleteRootItem();
  47841. }
  47842. const File FileTreeComponent::getSelectedFile (const int index) const
  47843. {
  47844. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47845. return item != 0 ? item->file
  47846. : File::nonexistent;
  47847. }
  47848. void FileTreeComponent::deselectAllFiles()
  47849. {
  47850. clearSelectedItems();
  47851. }
  47852. void FileTreeComponent::scrollToTop()
  47853. {
  47854. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47855. }
  47856. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47857. {
  47858. dragAndDropDescription = description;
  47859. }
  47860. END_JUCE_NAMESPACE
  47861. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47862. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47863. BEGIN_JUCE_NAMESPACE
  47864. ImagePreviewComponent::ImagePreviewComponent()
  47865. {
  47866. }
  47867. ImagePreviewComponent::~ImagePreviewComponent()
  47868. {
  47869. }
  47870. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47871. {
  47872. const int availableW = proportionOfWidth (0.97f);
  47873. const int availableH = getHeight() - 13 * 4;
  47874. const double scale = jmin (1.0,
  47875. availableW / (double) w,
  47876. availableH / (double) h);
  47877. w = roundToInt (scale * w);
  47878. h = roundToInt (scale * h);
  47879. }
  47880. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47881. {
  47882. if (fileToLoad != file)
  47883. {
  47884. fileToLoad = file;
  47885. startTimer (100);
  47886. }
  47887. }
  47888. void ImagePreviewComponent::timerCallback()
  47889. {
  47890. stopTimer();
  47891. currentThumbnail = Image::null;
  47892. currentDetails = String::empty;
  47893. repaint();
  47894. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47895. if (in != 0)
  47896. {
  47897. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47898. if (format != 0)
  47899. {
  47900. currentThumbnail = format->decodeImage (*in);
  47901. if (currentThumbnail.isValid())
  47902. {
  47903. int w = currentThumbnail.getWidth();
  47904. int h = currentThumbnail.getHeight();
  47905. currentDetails
  47906. << fileToLoad.getFileName() << "\n"
  47907. << format->getFormatName() << "\n"
  47908. << w << " x " << h << " pixels\n"
  47909. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47910. getThumbSize (w, h);
  47911. currentThumbnail = currentThumbnail.rescaled (w, h);
  47912. }
  47913. }
  47914. }
  47915. }
  47916. void ImagePreviewComponent::paint (Graphics& g)
  47917. {
  47918. if (currentThumbnail.isValid())
  47919. {
  47920. g.setFont (13.0f);
  47921. int w = currentThumbnail.getWidth();
  47922. int h = currentThumbnail.getHeight();
  47923. getThumbSize (w, h);
  47924. const int numLines = 4;
  47925. const int totalH = 13 * numLines + h + 4;
  47926. const int y = (getHeight() - totalH) / 2;
  47927. g.drawImageWithin (currentThumbnail,
  47928. (getWidth() - w) / 2, y, w, h,
  47929. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47930. false);
  47931. g.drawFittedText (currentDetails,
  47932. 0, y + h + 4, getWidth(), 100,
  47933. Justification::centredTop, numLines);
  47934. }
  47935. }
  47936. END_JUCE_NAMESPACE
  47937. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47938. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47939. BEGIN_JUCE_NAMESPACE
  47940. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47941. const String& directoryWildcardPatterns,
  47942. const String& description_)
  47943. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47944. : (description_ + " (" + fileWildcardPatterns + ")"))
  47945. {
  47946. parse (fileWildcardPatterns, fileWildcards);
  47947. parse (directoryWildcardPatterns, directoryWildcards);
  47948. }
  47949. WildcardFileFilter::~WildcardFileFilter()
  47950. {
  47951. }
  47952. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47953. {
  47954. return match (file, fileWildcards);
  47955. }
  47956. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47957. {
  47958. return match (file, directoryWildcards);
  47959. }
  47960. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47961. {
  47962. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47963. result.trim();
  47964. result.removeEmptyStrings();
  47965. // special case for *.*, because people use it to mean "any file", but it
  47966. // would actually ignore files with no extension.
  47967. for (int i = result.size(); --i >= 0;)
  47968. if (result[i] == "*.*")
  47969. result.set (i, "*");
  47970. }
  47971. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47972. {
  47973. const String filename (file.getFileName());
  47974. for (int i = wildcards.size(); --i >= 0;)
  47975. if (filename.matchesWildcard (wildcards[i], true))
  47976. return true;
  47977. return false;
  47978. }
  47979. END_JUCE_NAMESPACE
  47980. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47981. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47982. BEGIN_JUCE_NAMESPACE
  47983. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47984. {
  47985. }
  47986. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47987. {
  47988. }
  47989. namespace KeyboardFocusHelpers
  47990. {
  47991. // This will sort a set of components, so that they are ordered in terms of
  47992. // left-to-right and then top-to-bottom.
  47993. class ScreenPositionComparator
  47994. {
  47995. public:
  47996. ScreenPositionComparator() {}
  47997. static int compareElements (const Component* const first, const Component* const second)
  47998. {
  47999. int explicitOrder1 = first->getExplicitFocusOrder();
  48000. if (explicitOrder1 <= 0)
  48001. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48002. int explicitOrder2 = second->getExplicitFocusOrder();
  48003. if (explicitOrder2 <= 0)
  48004. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48005. if (explicitOrder1 != explicitOrder2)
  48006. return explicitOrder1 - explicitOrder2;
  48007. const int diff = first->getY() - second->getY();
  48008. return (diff == 0) ? first->getX() - second->getX()
  48009. : diff;
  48010. }
  48011. };
  48012. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48013. {
  48014. if (parent->getNumChildComponents() > 0)
  48015. {
  48016. Array <Component*> localComps;
  48017. ScreenPositionComparator comparator;
  48018. int i;
  48019. for (i = parent->getNumChildComponents(); --i >= 0;)
  48020. {
  48021. Component* const c = parent->getChildComponent (i);
  48022. if (c->isVisible() && c->isEnabled())
  48023. localComps.addSorted (comparator, c);
  48024. }
  48025. for (i = 0; i < localComps.size(); ++i)
  48026. {
  48027. Component* const c = localComps.getUnchecked (i);
  48028. if (c->getWantsKeyboardFocus())
  48029. comps.add (c);
  48030. if (! c->isFocusContainer())
  48031. findAllFocusableComponents (c, comps);
  48032. }
  48033. }
  48034. }
  48035. }
  48036. namespace KeyboardFocusHelpers
  48037. {
  48038. Component* getIncrementedComponent (Component* const current, const int delta)
  48039. {
  48040. Component* focusContainer = current->getParentComponent();
  48041. if (focusContainer != 0)
  48042. {
  48043. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48044. focusContainer = focusContainer->getParentComponent();
  48045. if (focusContainer != 0)
  48046. {
  48047. Array <Component*> comps;
  48048. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48049. if (comps.size() > 0)
  48050. {
  48051. const int index = comps.indexOf (current);
  48052. return comps [(index + comps.size() + delta) % comps.size()];
  48053. }
  48054. }
  48055. }
  48056. return 0;
  48057. }
  48058. }
  48059. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48060. {
  48061. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48062. }
  48063. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48064. {
  48065. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48066. }
  48067. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48068. {
  48069. Array <Component*> comps;
  48070. if (parentComponent != 0)
  48071. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48072. return comps.getFirst();
  48073. }
  48074. END_JUCE_NAMESPACE
  48075. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48076. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48077. BEGIN_JUCE_NAMESPACE
  48078. bool KeyListener::keyStateChanged (const bool, Component*)
  48079. {
  48080. return false;
  48081. }
  48082. END_JUCE_NAMESPACE
  48083. /*** End of inlined file: juce_KeyListener.cpp ***/
  48084. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48085. BEGIN_JUCE_NAMESPACE
  48086. // N.B. these two includes are put here deliberately to avoid problems with
  48087. // old GCCs failing on long include paths
  48088. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48089. {
  48090. public:
  48091. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48092. const CommandID commandID_,
  48093. const String& keyName,
  48094. const int keyNum_)
  48095. : Button (keyName),
  48096. owner (owner_),
  48097. commandID (commandID_),
  48098. keyNum (keyNum_)
  48099. {
  48100. setWantsKeyboardFocus (false);
  48101. setTriggeredOnMouseDown (keyNum >= 0);
  48102. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48103. : TRANS("click to change this key-mapping"));
  48104. }
  48105. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48106. {
  48107. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48108. keyNum >= 0 ? getName() : String::empty);
  48109. }
  48110. void clicked()
  48111. {
  48112. if (keyNum >= 0)
  48113. {
  48114. // existing key clicked..
  48115. PopupMenu m;
  48116. m.addItem (1, TRANS("change this key-mapping"));
  48117. m.addSeparator();
  48118. m.addItem (2, TRANS("remove this key-mapping"));
  48119. switch (m.show())
  48120. {
  48121. case 1: assignNewKey(); break;
  48122. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48123. default: break;
  48124. }
  48125. }
  48126. else
  48127. {
  48128. assignNewKey(); // + button pressed..
  48129. }
  48130. }
  48131. void fitToContent (const int h) throw()
  48132. {
  48133. if (keyNum < 0)
  48134. {
  48135. setSize (h, h);
  48136. }
  48137. else
  48138. {
  48139. Font f (h * 0.6f);
  48140. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48141. }
  48142. }
  48143. class KeyEntryWindow : public AlertWindow
  48144. {
  48145. public:
  48146. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48147. : AlertWindow (TRANS("New key-mapping"),
  48148. TRANS("Please press a key combination now..."),
  48149. AlertWindow::NoIcon),
  48150. owner (owner_)
  48151. {
  48152. addButton (TRANS("Ok"), 1);
  48153. addButton (TRANS("Cancel"), 0);
  48154. // (avoid return + escape keys getting processed by the buttons..)
  48155. for (int i = getNumChildComponents(); --i >= 0;)
  48156. getChildComponent (i)->setWantsKeyboardFocus (false);
  48157. setWantsKeyboardFocus (true);
  48158. grabKeyboardFocus();
  48159. }
  48160. bool keyPressed (const KeyPress& key)
  48161. {
  48162. lastPress = key;
  48163. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48164. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48165. if (previousCommand != 0)
  48166. message << "\n\n" << TRANS("(Currently assigned to \"")
  48167. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48168. setMessage (message);
  48169. return true;
  48170. }
  48171. bool keyStateChanged (bool)
  48172. {
  48173. return true;
  48174. }
  48175. KeyPress lastPress;
  48176. private:
  48177. KeyMappingEditorComponent& owner;
  48178. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48179. };
  48180. void assignNewKey()
  48181. {
  48182. KeyEntryWindow entryWindow (owner);
  48183. if (entryWindow.runModalLoop() != 0)
  48184. {
  48185. entryWindow.setVisible (false);
  48186. if (entryWindow.lastPress.isValid())
  48187. {
  48188. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48189. if (previousCommand == 0
  48190. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48191. TRANS("Change key-mapping"),
  48192. TRANS("This key is already assigned to the command \"")
  48193. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48194. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48195. TRANS("Re-assign"),
  48196. TRANS("Cancel")))
  48197. {
  48198. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48199. if (keyNum >= 0)
  48200. owner.getMappings().removeKeyPress (commandID, keyNum);
  48201. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48202. }
  48203. }
  48204. }
  48205. }
  48206. private:
  48207. KeyMappingEditorComponent& owner;
  48208. const CommandID commandID;
  48209. const int keyNum;
  48210. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48211. };
  48212. class KeyMappingEditorComponent::ItemComponent : public Component
  48213. {
  48214. public:
  48215. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48216. : owner (owner_), commandID (commandID_)
  48217. {
  48218. setInterceptsMouseClicks (false, true);
  48219. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48220. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48221. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48222. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48223. addKeyPressButton (String::empty, -1, isReadOnly);
  48224. }
  48225. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48226. {
  48227. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48228. keyChangeButtons.add (b);
  48229. b->setEnabled (! isReadOnly);
  48230. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48231. addChildComponent (b);
  48232. }
  48233. void paint (Graphics& g)
  48234. {
  48235. g.setFont (getHeight() * 0.7f);
  48236. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48237. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48238. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48239. Justification::centredLeft, true);
  48240. }
  48241. void resized()
  48242. {
  48243. int x = getWidth() - 4;
  48244. for (int i = keyChangeButtons.size(); --i >= 0;)
  48245. {
  48246. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48247. b->fitToContent (getHeight() - 2);
  48248. b->setTopRightPosition (x, 1);
  48249. x = b->getX() - 5;
  48250. }
  48251. }
  48252. private:
  48253. KeyMappingEditorComponent& owner;
  48254. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48255. const CommandID commandID;
  48256. enum { maxNumAssignments = 3 };
  48257. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48258. };
  48259. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48260. {
  48261. public:
  48262. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48263. : owner (owner_), commandID (commandID_)
  48264. {
  48265. }
  48266. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48267. bool mightContainSubItems() { return false; }
  48268. int getItemHeight() const { return 20; }
  48269. Component* createItemComponent()
  48270. {
  48271. return new ItemComponent (owner, commandID);
  48272. }
  48273. private:
  48274. KeyMappingEditorComponent& owner;
  48275. const CommandID commandID;
  48276. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48277. };
  48278. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48279. {
  48280. public:
  48281. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48282. : owner (owner_), categoryName (name)
  48283. {
  48284. }
  48285. const String getUniqueName() const { return categoryName + "_cat"; }
  48286. bool mightContainSubItems() { return true; }
  48287. int getItemHeight() const { return 28; }
  48288. void paintItem (Graphics& g, int width, int height)
  48289. {
  48290. g.setFont (height * 0.6f, Font::bold);
  48291. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48292. g.drawText (categoryName,
  48293. 2, 0, width - 2, height,
  48294. Justification::centredLeft, true);
  48295. }
  48296. void itemOpennessChanged (bool isNowOpen)
  48297. {
  48298. if (isNowOpen)
  48299. {
  48300. if (getNumSubItems() == 0)
  48301. {
  48302. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48303. for (int i = 0; i < commands.size(); ++i)
  48304. {
  48305. if (owner.shouldCommandBeIncluded (commands[i]))
  48306. addSubItem (new MappingItem (owner, commands[i]));
  48307. }
  48308. }
  48309. }
  48310. else
  48311. {
  48312. clearSubItems();
  48313. }
  48314. }
  48315. private:
  48316. KeyMappingEditorComponent& owner;
  48317. String categoryName;
  48318. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48319. };
  48320. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48321. public ChangeListener,
  48322. public ButtonListener
  48323. {
  48324. public:
  48325. TopLevelItem (KeyMappingEditorComponent& owner_)
  48326. : owner (owner_)
  48327. {
  48328. setLinesDrawnForSubItems (false);
  48329. owner.getMappings().addChangeListener (this);
  48330. }
  48331. ~TopLevelItem()
  48332. {
  48333. owner.getMappings().removeChangeListener (this);
  48334. }
  48335. bool mightContainSubItems() { return true; }
  48336. const String getUniqueName() const { return "keys"; }
  48337. void changeListenerCallback (ChangeBroadcaster*)
  48338. {
  48339. const OpennessRestorer openness (*this);
  48340. clearSubItems();
  48341. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48342. for (int i = 0; i < categories.size(); ++i)
  48343. {
  48344. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48345. int count = 0;
  48346. for (int j = 0; j < commands.size(); ++j)
  48347. if (owner.shouldCommandBeIncluded (commands[j]))
  48348. ++count;
  48349. if (count > 0)
  48350. addSubItem (new CategoryItem (owner, categories[i]));
  48351. }
  48352. }
  48353. void buttonClicked (Button*)
  48354. {
  48355. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48356. TRANS("Reset to defaults"),
  48357. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48358. TRANS("Reset")))
  48359. {
  48360. owner.getMappings().resetToDefaultMappings();
  48361. }
  48362. }
  48363. private:
  48364. KeyMappingEditorComponent& owner;
  48365. };
  48366. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48367. const bool showResetToDefaultButton)
  48368. : mappings (mappingManager),
  48369. resetButton (TRANS ("reset to defaults"))
  48370. {
  48371. treeItem = new TopLevelItem (*this);
  48372. if (showResetToDefaultButton)
  48373. {
  48374. addAndMakeVisible (&resetButton);
  48375. resetButton.addListener (treeItem);
  48376. }
  48377. addAndMakeVisible (&tree);
  48378. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48379. tree.setRootItemVisible (false);
  48380. tree.setDefaultOpenness (true);
  48381. tree.setRootItem (treeItem);
  48382. }
  48383. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48384. {
  48385. tree.setRootItem (0);
  48386. }
  48387. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48388. const Colour& textColour)
  48389. {
  48390. setColour (backgroundColourId, mainBackground);
  48391. setColour (textColourId, textColour);
  48392. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48393. }
  48394. void KeyMappingEditorComponent::parentHierarchyChanged()
  48395. {
  48396. treeItem->changeListenerCallback (0);
  48397. }
  48398. void KeyMappingEditorComponent::resized()
  48399. {
  48400. int h = getHeight();
  48401. if (resetButton.isVisible())
  48402. {
  48403. const int buttonHeight = 20;
  48404. h -= buttonHeight + 8;
  48405. int x = getWidth() - 8;
  48406. resetButton.changeWidthToFitText (buttonHeight);
  48407. resetButton.setTopRightPosition (x, h + 6);
  48408. }
  48409. tree.setBounds (0, 0, getWidth(), h);
  48410. }
  48411. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48412. {
  48413. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48414. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48415. }
  48416. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48417. {
  48418. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48419. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48420. }
  48421. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48422. {
  48423. return key.getTextDescription();
  48424. }
  48425. END_JUCE_NAMESPACE
  48426. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48427. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48428. BEGIN_JUCE_NAMESPACE
  48429. KeyPress::KeyPress() throw()
  48430. : keyCode (0),
  48431. mods (0),
  48432. textCharacter (0)
  48433. {
  48434. }
  48435. KeyPress::KeyPress (const int keyCode_,
  48436. const ModifierKeys& mods_,
  48437. const juce_wchar textCharacter_) throw()
  48438. : keyCode (keyCode_),
  48439. mods (mods_),
  48440. textCharacter (textCharacter_)
  48441. {
  48442. }
  48443. KeyPress::KeyPress (const int keyCode_) throw()
  48444. : keyCode (keyCode_),
  48445. textCharacter (0)
  48446. {
  48447. }
  48448. KeyPress::KeyPress (const KeyPress& other) throw()
  48449. : keyCode (other.keyCode),
  48450. mods (other.mods),
  48451. textCharacter (other.textCharacter)
  48452. {
  48453. }
  48454. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48455. {
  48456. keyCode = other.keyCode;
  48457. mods = other.mods;
  48458. textCharacter = other.textCharacter;
  48459. return *this;
  48460. }
  48461. bool KeyPress::operator== (const KeyPress& other) const throw()
  48462. {
  48463. return mods.getRawFlags() == other.mods.getRawFlags()
  48464. && (textCharacter == other.textCharacter
  48465. || textCharacter == 0
  48466. || other.textCharacter == 0)
  48467. && (keyCode == other.keyCode
  48468. || (keyCode < 256
  48469. && other.keyCode < 256
  48470. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48471. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48472. }
  48473. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48474. {
  48475. return ! operator== (other);
  48476. }
  48477. bool KeyPress::isCurrentlyDown() const
  48478. {
  48479. return isKeyCurrentlyDown (keyCode)
  48480. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48481. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48482. }
  48483. namespace KeyPressHelpers
  48484. {
  48485. struct KeyNameAndCode
  48486. {
  48487. const char* name;
  48488. int code;
  48489. };
  48490. const KeyNameAndCode translations[] =
  48491. {
  48492. { "spacebar", KeyPress::spaceKey },
  48493. { "return", KeyPress::returnKey },
  48494. { "escape", KeyPress::escapeKey },
  48495. { "backspace", KeyPress::backspaceKey },
  48496. { "cursor left", KeyPress::leftKey },
  48497. { "cursor right", KeyPress::rightKey },
  48498. { "cursor up", KeyPress::upKey },
  48499. { "cursor down", KeyPress::downKey },
  48500. { "page up", KeyPress::pageUpKey },
  48501. { "page down", KeyPress::pageDownKey },
  48502. { "home", KeyPress::homeKey },
  48503. { "end", KeyPress::endKey },
  48504. { "delete", KeyPress::deleteKey },
  48505. { "insert", KeyPress::insertKey },
  48506. { "tab", KeyPress::tabKey },
  48507. { "play", KeyPress::playKey },
  48508. { "stop", KeyPress::stopKey },
  48509. { "fast forward", KeyPress::fastForwardKey },
  48510. { "rewind", KeyPress::rewindKey }
  48511. };
  48512. const String numberPadPrefix() { return "numpad "; }
  48513. }
  48514. const KeyPress KeyPress::createFromDescription (const String& desc)
  48515. {
  48516. int modifiers = 0;
  48517. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48518. || desc.containsWholeWordIgnoreCase ("control")
  48519. || desc.containsWholeWordIgnoreCase ("ctl"))
  48520. modifiers |= ModifierKeys::ctrlModifier;
  48521. if (desc.containsWholeWordIgnoreCase ("shift")
  48522. || desc.containsWholeWordIgnoreCase ("shft"))
  48523. modifiers |= ModifierKeys::shiftModifier;
  48524. if (desc.containsWholeWordIgnoreCase ("alt")
  48525. || desc.containsWholeWordIgnoreCase ("option"))
  48526. modifiers |= ModifierKeys::altModifier;
  48527. if (desc.containsWholeWordIgnoreCase ("command")
  48528. || desc.containsWholeWordIgnoreCase ("cmd"))
  48529. modifiers |= ModifierKeys::commandModifier;
  48530. int key = 0;
  48531. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48532. {
  48533. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48534. {
  48535. key = KeyPressHelpers::translations[i].code;
  48536. break;
  48537. }
  48538. }
  48539. if (key == 0)
  48540. {
  48541. // see if it's a numpad key..
  48542. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48543. {
  48544. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48545. if (lastChar >= '0' && lastChar <= '9')
  48546. key = numberPad0 + lastChar - '0';
  48547. else if (lastChar == '+')
  48548. key = numberPadAdd;
  48549. else if (lastChar == '-')
  48550. key = numberPadSubtract;
  48551. else if (lastChar == '*')
  48552. key = numberPadMultiply;
  48553. else if (lastChar == '/')
  48554. key = numberPadDivide;
  48555. else if (lastChar == '.')
  48556. key = numberPadDecimalPoint;
  48557. else if (lastChar == '=')
  48558. key = numberPadEquals;
  48559. else if (desc.endsWith ("separator"))
  48560. key = numberPadSeparator;
  48561. else if (desc.endsWith ("delete"))
  48562. key = numberPadDelete;
  48563. }
  48564. if (key == 0)
  48565. {
  48566. // see if it's a function key..
  48567. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48568. for (int i = 1; i <= 12; ++i)
  48569. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48570. key = F1Key + i - 1;
  48571. if (key == 0)
  48572. {
  48573. // give up and use the hex code..
  48574. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48575. .toLowerCase()
  48576. .retainCharacters ("0123456789abcdef")
  48577. .getHexValue32();
  48578. if (hexCode > 0)
  48579. key = hexCode;
  48580. else
  48581. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48582. }
  48583. }
  48584. }
  48585. return KeyPress (key, ModifierKeys (modifiers), 0);
  48586. }
  48587. const String KeyPress::getTextDescription() const
  48588. {
  48589. String desc;
  48590. if (keyCode > 0)
  48591. {
  48592. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48593. // want to store it as being a slash, not shift+whatever.
  48594. if (textCharacter == '/')
  48595. return "/";
  48596. if (mods.isCtrlDown())
  48597. desc << "ctrl + ";
  48598. if (mods.isShiftDown())
  48599. desc << "shift + ";
  48600. #if JUCE_MAC
  48601. // only do this on the mac, because on Windows ctrl and command are the same,
  48602. // and this would get confusing
  48603. if (mods.isCommandDown())
  48604. desc << "command + ";
  48605. if (mods.isAltDown())
  48606. desc << "option + ";
  48607. #else
  48608. if (mods.isAltDown())
  48609. desc << "alt + ";
  48610. #endif
  48611. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48612. if (keyCode == KeyPressHelpers::translations[i].code)
  48613. return desc + KeyPressHelpers::translations[i].name;
  48614. if (keyCode >= F1Key && keyCode <= F16Key)
  48615. desc << 'F' << (1 + keyCode - F1Key);
  48616. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48617. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48618. else if (keyCode >= 33 && keyCode < 176)
  48619. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48620. else if (keyCode == numberPadAdd)
  48621. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48622. else if (keyCode == numberPadSubtract)
  48623. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48624. else if (keyCode == numberPadMultiply)
  48625. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48626. else if (keyCode == numberPadDivide)
  48627. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48628. else if (keyCode == numberPadSeparator)
  48629. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48630. else if (keyCode == numberPadDecimalPoint)
  48631. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48632. else if (keyCode == numberPadDelete)
  48633. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48634. else
  48635. desc << '#' << String::toHexString (keyCode);
  48636. }
  48637. return desc;
  48638. }
  48639. END_JUCE_NAMESPACE
  48640. /*** End of inlined file: juce_KeyPress.cpp ***/
  48641. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48642. BEGIN_JUCE_NAMESPACE
  48643. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48644. : commandManager (commandManager_)
  48645. {
  48646. // A manager is needed to get the descriptions of commands, and will be called when
  48647. // a command is invoked. So you can't leave this null..
  48648. jassert (commandManager_ != 0);
  48649. Desktop::getInstance().addFocusChangeListener (this);
  48650. }
  48651. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48652. : commandManager (other.commandManager)
  48653. {
  48654. Desktop::getInstance().addFocusChangeListener (this);
  48655. }
  48656. KeyPressMappingSet::~KeyPressMappingSet()
  48657. {
  48658. Desktop::getInstance().removeFocusChangeListener (this);
  48659. }
  48660. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48661. {
  48662. for (int i = 0; i < mappings.size(); ++i)
  48663. if (mappings.getUnchecked(i)->commandID == commandID)
  48664. return mappings.getUnchecked (i)->keypresses;
  48665. return Array <KeyPress> ();
  48666. }
  48667. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48668. const KeyPress& newKeyPress,
  48669. int insertIndex)
  48670. {
  48671. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48672. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48673. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48674. && ! newKeyPress.getModifiers().isShiftDown()));
  48675. if (findCommandForKeyPress (newKeyPress) != commandID)
  48676. {
  48677. removeKeyPress (newKeyPress);
  48678. if (newKeyPress.isValid())
  48679. {
  48680. for (int i = mappings.size(); --i >= 0;)
  48681. {
  48682. if (mappings.getUnchecked(i)->commandID == commandID)
  48683. {
  48684. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48685. sendChangeMessage();
  48686. return;
  48687. }
  48688. }
  48689. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48690. if (ci != 0)
  48691. {
  48692. CommandMapping* const cm = new CommandMapping();
  48693. cm->commandID = commandID;
  48694. cm->keypresses.add (newKeyPress);
  48695. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48696. mappings.add (cm);
  48697. sendChangeMessage();
  48698. }
  48699. }
  48700. }
  48701. }
  48702. void KeyPressMappingSet::resetToDefaultMappings()
  48703. {
  48704. mappings.clear();
  48705. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48706. {
  48707. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48708. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48709. {
  48710. addKeyPress (ci->commandID,
  48711. ci->defaultKeypresses.getReference (j));
  48712. }
  48713. }
  48714. sendChangeMessage();
  48715. }
  48716. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48717. {
  48718. clearAllKeyPresses (commandID);
  48719. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48720. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48721. {
  48722. addKeyPress (ci->commandID,
  48723. ci->defaultKeypresses.getReference (j));
  48724. }
  48725. }
  48726. void KeyPressMappingSet::clearAllKeyPresses()
  48727. {
  48728. if (mappings.size() > 0)
  48729. {
  48730. sendChangeMessage();
  48731. mappings.clear();
  48732. }
  48733. }
  48734. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48735. {
  48736. for (int i = mappings.size(); --i >= 0;)
  48737. {
  48738. if (mappings.getUnchecked(i)->commandID == commandID)
  48739. {
  48740. mappings.remove (i);
  48741. sendChangeMessage();
  48742. }
  48743. }
  48744. }
  48745. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48746. {
  48747. if (keypress.isValid())
  48748. {
  48749. for (int i = mappings.size(); --i >= 0;)
  48750. {
  48751. CommandMapping* const cm = mappings.getUnchecked(i);
  48752. for (int j = cm->keypresses.size(); --j >= 0;)
  48753. {
  48754. if (keypress == cm->keypresses [j])
  48755. {
  48756. cm->keypresses.remove (j);
  48757. sendChangeMessage();
  48758. }
  48759. }
  48760. }
  48761. }
  48762. }
  48763. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48764. {
  48765. for (int i = mappings.size(); --i >= 0;)
  48766. {
  48767. if (mappings.getUnchecked(i)->commandID == commandID)
  48768. {
  48769. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48770. sendChangeMessage();
  48771. break;
  48772. }
  48773. }
  48774. }
  48775. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48776. {
  48777. for (int i = 0; i < mappings.size(); ++i)
  48778. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48779. return mappings.getUnchecked(i)->commandID;
  48780. return 0;
  48781. }
  48782. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48783. {
  48784. for (int i = mappings.size(); --i >= 0;)
  48785. if (mappings.getUnchecked(i)->commandID == commandID)
  48786. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48787. return false;
  48788. }
  48789. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48790. const KeyPress& key,
  48791. const bool isKeyDown,
  48792. const int millisecsSinceKeyPressed,
  48793. Component* const originatingComponent) const
  48794. {
  48795. ApplicationCommandTarget::InvocationInfo info (commandID);
  48796. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48797. info.isKeyDown = isKeyDown;
  48798. info.keyPress = key;
  48799. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48800. info.originatingComponent = originatingComponent;
  48801. commandManager->invoke (info, false);
  48802. }
  48803. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48804. {
  48805. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48806. {
  48807. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48808. {
  48809. // if the XML was created as a set of differences from the default mappings,
  48810. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48811. resetToDefaultMappings();
  48812. }
  48813. else
  48814. {
  48815. // if the XML was created calling createXml (false), then we need to clear all
  48816. // the keys and treat the xml as describing the entire set of mappings.
  48817. clearAllKeyPresses();
  48818. }
  48819. forEachXmlChildElement (xmlVersion, map)
  48820. {
  48821. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48822. if (commandId != 0)
  48823. {
  48824. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48825. if (map->hasTagName ("MAPPING"))
  48826. {
  48827. addKeyPress (commandId, key);
  48828. }
  48829. else if (map->hasTagName ("UNMAPPING"))
  48830. {
  48831. if (containsMapping (commandId, key))
  48832. removeKeyPress (key);
  48833. }
  48834. }
  48835. }
  48836. return true;
  48837. }
  48838. return false;
  48839. }
  48840. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48841. {
  48842. ScopedPointer <KeyPressMappingSet> defaultSet;
  48843. if (saveDifferencesFromDefaultSet)
  48844. {
  48845. defaultSet = new KeyPressMappingSet (commandManager);
  48846. defaultSet->resetToDefaultMappings();
  48847. }
  48848. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48849. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48850. int i;
  48851. for (i = 0; i < mappings.size(); ++i)
  48852. {
  48853. const CommandMapping* const cm = mappings.getUnchecked(i);
  48854. for (int j = 0; j < cm->keypresses.size(); ++j)
  48855. {
  48856. if (defaultSet == 0
  48857. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48858. {
  48859. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48860. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48861. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48862. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48863. }
  48864. }
  48865. }
  48866. if (defaultSet != 0)
  48867. {
  48868. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48869. {
  48870. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48871. for (int j = 0; j < cm->keypresses.size(); ++j)
  48872. {
  48873. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48874. {
  48875. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48876. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48877. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48878. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48879. }
  48880. }
  48881. }
  48882. }
  48883. return doc;
  48884. }
  48885. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48886. Component* originatingComponent)
  48887. {
  48888. bool used = false;
  48889. const CommandID commandID = findCommandForKeyPress (key);
  48890. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48891. if (ci != 0
  48892. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48893. {
  48894. ApplicationCommandInfo info (0);
  48895. if (commandManager->getTargetForCommand (commandID, info) != 0
  48896. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48897. {
  48898. invokeCommand (commandID, key, true, 0, originatingComponent);
  48899. used = true;
  48900. }
  48901. else
  48902. {
  48903. if (originatingComponent != 0)
  48904. originatingComponent->getLookAndFeel().playAlertSound();
  48905. }
  48906. }
  48907. return used;
  48908. }
  48909. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48910. {
  48911. bool used = false;
  48912. const uint32 now = Time::getMillisecondCounter();
  48913. for (int i = mappings.size(); --i >= 0;)
  48914. {
  48915. CommandMapping* const cm = mappings.getUnchecked(i);
  48916. if (cm->wantsKeyUpDownCallbacks)
  48917. {
  48918. for (int j = cm->keypresses.size(); --j >= 0;)
  48919. {
  48920. const KeyPress key (cm->keypresses.getReference (j));
  48921. const bool isDown = key.isCurrentlyDown();
  48922. int keyPressEntryIndex = 0;
  48923. bool wasDown = false;
  48924. for (int k = keysDown.size(); --k >= 0;)
  48925. {
  48926. if (key == keysDown.getUnchecked(k)->key)
  48927. {
  48928. keyPressEntryIndex = k;
  48929. wasDown = true;
  48930. used = true;
  48931. break;
  48932. }
  48933. }
  48934. if (isDown != wasDown)
  48935. {
  48936. int millisecs = 0;
  48937. if (isDown)
  48938. {
  48939. KeyPressTime* const k = new KeyPressTime();
  48940. k->key = key;
  48941. k->timeWhenPressed = now;
  48942. keysDown.add (k);
  48943. }
  48944. else
  48945. {
  48946. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48947. if (now > pressTime)
  48948. millisecs = now - pressTime;
  48949. keysDown.remove (keyPressEntryIndex);
  48950. }
  48951. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48952. used = true;
  48953. }
  48954. }
  48955. }
  48956. }
  48957. return used;
  48958. }
  48959. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48960. {
  48961. if (focusedComponent != 0)
  48962. focusedComponent->keyStateChanged (false);
  48963. }
  48964. END_JUCE_NAMESPACE
  48965. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48966. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48967. BEGIN_JUCE_NAMESPACE
  48968. ModifierKeys::ModifierKeys (const int flags_) throw()
  48969. : flags (flags_)
  48970. {
  48971. }
  48972. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48973. : flags (other.flags)
  48974. {
  48975. }
  48976. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48977. {
  48978. flags = other.flags;
  48979. return *this;
  48980. }
  48981. ModifierKeys ModifierKeys::currentModifiers;
  48982. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48983. {
  48984. return currentModifiers;
  48985. }
  48986. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48987. {
  48988. int num = 0;
  48989. if (isLeftButtonDown()) ++num;
  48990. if (isRightButtonDown()) ++num;
  48991. if (isMiddleButtonDown()) ++num;
  48992. return num;
  48993. }
  48994. END_JUCE_NAMESPACE
  48995. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48996. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48997. BEGIN_JUCE_NAMESPACE
  48998. class ComponentAnimator::AnimationTask
  48999. {
  49000. public:
  49001. AnimationTask (Component* const comp)
  49002. : component (comp)
  49003. {
  49004. }
  49005. void reset (const Rectangle<int>& finalBounds,
  49006. float finalAlpha,
  49007. int millisecondsToSpendMoving,
  49008. bool useProxyComponent,
  49009. double startSpeed_, double endSpeed_)
  49010. {
  49011. msElapsed = 0;
  49012. msTotal = jmax (1, millisecondsToSpendMoving);
  49013. lastProgress = 0;
  49014. destination = finalBounds;
  49015. destAlpha = finalAlpha;
  49016. isMoving = (finalBounds != component->getBounds());
  49017. isChangingAlpha = (finalAlpha != component->getAlpha());
  49018. left = component->getX();
  49019. top = component->getY();
  49020. right = component->getRight();
  49021. bottom = component->getBottom();
  49022. alpha = component->getAlpha();
  49023. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49024. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49025. midSpeed = invTotalDistance;
  49026. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49027. if (useProxyComponent)
  49028. proxy = new ProxyComponent (*component);
  49029. else
  49030. proxy = 0;
  49031. component->setVisible (! useProxyComponent);
  49032. }
  49033. bool useTimeslice (const int elapsed)
  49034. {
  49035. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49036. : static_cast <Component*> (component);
  49037. if (c != 0)
  49038. {
  49039. msElapsed += elapsed;
  49040. double newProgress = msElapsed / (double) msTotal;
  49041. if (newProgress >= 0 && newProgress < 1.0)
  49042. {
  49043. newProgress = timeToDistance (newProgress);
  49044. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49045. jassert (newProgress >= lastProgress);
  49046. lastProgress = newProgress;
  49047. if (delta < 1.0)
  49048. {
  49049. bool stillBusy = false;
  49050. if (isMoving)
  49051. {
  49052. left += (destination.getX() - left) * delta;
  49053. top += (destination.getY() - top) * delta;
  49054. right += (destination.getRight() - right) * delta;
  49055. bottom += (destination.getBottom() - bottom) * delta;
  49056. const Rectangle<int> newBounds (roundToInt (left),
  49057. roundToInt (top),
  49058. roundToInt (right - left),
  49059. roundToInt (bottom - top));
  49060. if (newBounds != destination)
  49061. {
  49062. c->setBounds (newBounds);
  49063. stillBusy = true;
  49064. }
  49065. }
  49066. if (isChangingAlpha)
  49067. {
  49068. alpha += (destAlpha - alpha) * delta;
  49069. c->setAlpha ((float) alpha);
  49070. stillBusy = true;
  49071. }
  49072. if (stillBusy)
  49073. return true;
  49074. }
  49075. }
  49076. }
  49077. moveToFinalDestination();
  49078. return false;
  49079. }
  49080. void moveToFinalDestination()
  49081. {
  49082. if (component != 0)
  49083. {
  49084. component->setAlpha ((float) destAlpha);
  49085. component->setBounds (destination);
  49086. }
  49087. }
  49088. class ProxyComponent : public Component
  49089. {
  49090. public:
  49091. ProxyComponent (Component& component)
  49092. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49093. {
  49094. setBounds (component.getBounds());
  49095. setAlpha (component.getAlpha());
  49096. setInterceptsMouseClicks (false, false);
  49097. Component* const parent = component.getParentComponent();
  49098. if (parent != 0)
  49099. parent->addAndMakeVisible (this);
  49100. else if (component.isOnDesktop() && component.getPeer() != 0)
  49101. addToDesktop (component.getPeer()->getStyleFlags());
  49102. else
  49103. jassertfalse; // seem to be trying to animate a component that's not visible..
  49104. setVisible (true);
  49105. toBehind (&component);
  49106. }
  49107. void paint (Graphics& g)
  49108. {
  49109. g.setOpacity (1.0f);
  49110. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49111. 0, 0, image.getWidth(), image.getHeight());
  49112. }
  49113. private:
  49114. Image image;
  49115. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49116. };
  49117. WeakReference<Component> component;
  49118. ScopedPointer<Component> proxy;
  49119. Rectangle<int> destination;
  49120. double destAlpha;
  49121. int msElapsed, msTotal;
  49122. double startSpeed, midSpeed, endSpeed, lastProgress;
  49123. double left, top, right, bottom, alpha;
  49124. bool isMoving, isChangingAlpha;
  49125. private:
  49126. double timeToDistance (const double time) const throw()
  49127. {
  49128. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49129. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49130. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49131. }
  49132. };
  49133. ComponentAnimator::ComponentAnimator()
  49134. : lastTime (0)
  49135. {
  49136. }
  49137. ComponentAnimator::~ComponentAnimator()
  49138. {
  49139. }
  49140. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49141. {
  49142. for (int i = tasks.size(); --i >= 0;)
  49143. if (component == tasks.getUnchecked(i)->component.get())
  49144. return tasks.getUnchecked(i);
  49145. return 0;
  49146. }
  49147. void ComponentAnimator::animateComponent (Component* const component,
  49148. const Rectangle<int>& finalBounds,
  49149. const float finalAlpha,
  49150. const int millisecondsToSpendMoving,
  49151. const bool useProxyComponent,
  49152. const double startSpeed,
  49153. const double endSpeed)
  49154. {
  49155. // the speeds must be 0 or greater!
  49156. jassert (startSpeed >= 0 && endSpeed >= 0)
  49157. if (component != 0)
  49158. {
  49159. AnimationTask* at = findTaskFor (component);
  49160. if (at == 0)
  49161. {
  49162. at = new AnimationTask (component);
  49163. tasks.add (at);
  49164. sendChangeMessage();
  49165. }
  49166. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49167. useProxyComponent, startSpeed, endSpeed);
  49168. if (! isTimerRunning())
  49169. {
  49170. lastTime = Time::getMillisecondCounter();
  49171. startTimer (1000 / 50);
  49172. }
  49173. }
  49174. }
  49175. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49176. {
  49177. if (component != 0)
  49178. {
  49179. if (component->isShowing() && millisecondsToTake > 0)
  49180. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49181. component->setVisible (false);
  49182. }
  49183. }
  49184. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49185. {
  49186. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49187. {
  49188. component->setAlpha (0.0f);
  49189. component->setVisible (true);
  49190. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49191. }
  49192. }
  49193. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49194. {
  49195. if (tasks.size() > 0)
  49196. {
  49197. if (moveComponentsToTheirFinalPositions)
  49198. for (int i = tasks.size(); --i >= 0;)
  49199. tasks.getUnchecked(i)->moveToFinalDestination();
  49200. tasks.clear();
  49201. sendChangeMessage();
  49202. }
  49203. }
  49204. void ComponentAnimator::cancelAnimation (Component* const component,
  49205. const bool moveComponentToItsFinalPosition)
  49206. {
  49207. AnimationTask* const at = findTaskFor (component);
  49208. if (at != 0)
  49209. {
  49210. if (moveComponentToItsFinalPosition)
  49211. at->moveToFinalDestination();
  49212. tasks.removeObject (at);
  49213. sendChangeMessage();
  49214. }
  49215. }
  49216. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49217. {
  49218. jassert (component != 0);
  49219. AnimationTask* const at = findTaskFor (component);
  49220. if (at != 0)
  49221. return at->destination;
  49222. return component->getBounds();
  49223. }
  49224. bool ComponentAnimator::isAnimating (Component* component) const
  49225. {
  49226. return findTaskFor (component) != 0;
  49227. }
  49228. void ComponentAnimator::timerCallback()
  49229. {
  49230. const uint32 timeNow = Time::getMillisecondCounter();
  49231. if (lastTime == 0 || lastTime == timeNow)
  49232. lastTime = timeNow;
  49233. const int elapsed = timeNow - lastTime;
  49234. for (int i = tasks.size(); --i >= 0;)
  49235. {
  49236. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49237. {
  49238. tasks.remove (i);
  49239. sendChangeMessage();
  49240. }
  49241. }
  49242. lastTime = timeNow;
  49243. if (tasks.size() == 0)
  49244. stopTimer();
  49245. }
  49246. END_JUCE_NAMESPACE
  49247. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49248. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49249. BEGIN_JUCE_NAMESPACE
  49250. namespace ComponentBuilderHelpers
  49251. {
  49252. const String getStateId (const ValueTree& state)
  49253. {
  49254. return state [ComponentBuilder::idProperty].toString();
  49255. }
  49256. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49257. {
  49258. jassert (compId.isNotEmpty());
  49259. for (int i = components.size(); --i >= 0;)
  49260. {
  49261. Component* const c = components.getUnchecked (i);
  49262. if (c->getComponentID() == compId)
  49263. return components.removeAndReturn (i);
  49264. }
  49265. return 0;
  49266. }
  49267. Component* findComponentWithID (Component* const c, const String& compId)
  49268. {
  49269. jassert (compId.isNotEmpty());
  49270. if (c->getComponentID() == compId)
  49271. return c;
  49272. for (int i = c->getNumChildComponents(); --i >= 0;)
  49273. {
  49274. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49275. if (child != 0)
  49276. return child;
  49277. }
  49278. return 0;
  49279. }
  49280. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49281. const ValueTree& state, Component* parent)
  49282. {
  49283. Component* const c = type.addNewComponentFromState (state, parent);
  49284. jassert (c != 0 && c->getParentComponent() == parent);
  49285. c->setComponentID (getStateId (state));
  49286. return c;
  49287. }
  49288. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49289. {
  49290. Component* topLevelComp = builder.getManagedComponent();
  49291. if (topLevelComp != 0)
  49292. {
  49293. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49294. const String uid (getStateId (state));
  49295. if (type == 0 || uid.isEmpty())
  49296. {
  49297. // ..handle the case where a child of the actual state node has changed.
  49298. if (state.getParent().isValid())
  49299. updateComponent (builder, state.getParent());
  49300. }
  49301. else
  49302. {
  49303. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49304. if (changedComp != 0)
  49305. type->updateComponentFromState (changedComp, state);
  49306. }
  49307. }
  49308. }
  49309. }
  49310. const Identifier ComponentBuilder::idProperty ("id");
  49311. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49312. : state (state_), imageProvider (0)
  49313. {
  49314. state.addListener (this);
  49315. }
  49316. ComponentBuilder::~ComponentBuilder()
  49317. {
  49318. state.removeListener (this);
  49319. #if JUCE_DEBUG
  49320. // Don't delete the managed component!! The builder owns that component, and will delete
  49321. // it automatically when it gets deleted.
  49322. jassert (componentRef.get() == static_cast <Component*> (component));
  49323. #endif
  49324. }
  49325. Component* ComponentBuilder::getManagedComponent()
  49326. {
  49327. if (component == 0)
  49328. {
  49329. component = createComponent();
  49330. #if JUCE_DEBUG
  49331. componentRef = component;
  49332. #endif
  49333. }
  49334. return component;
  49335. }
  49336. Component* ComponentBuilder::createComponent()
  49337. {
  49338. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49339. TypeHandler* const type = getHandlerForState (state);
  49340. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49341. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49342. }
  49343. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49344. {
  49345. jassert (type != 0);
  49346. // Don't try to move your types around! Once a type has been added to a builder, the
  49347. // builder owns it, and you should leave it alone!
  49348. jassert (type->builder == 0);
  49349. types.add (type);
  49350. type->builder = this;
  49351. }
  49352. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49353. {
  49354. const Identifier targetType (s.getType());
  49355. for (int i = 0; i < types.size(); ++i)
  49356. {
  49357. TypeHandler* const t = types.getUnchecked(i);
  49358. if (t->getType() == targetType)
  49359. return t;
  49360. }
  49361. return 0;
  49362. }
  49363. int ComponentBuilder::getNumHandlers() const throw()
  49364. {
  49365. return types.size();
  49366. }
  49367. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49368. {
  49369. return types [index];
  49370. }
  49371. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49372. {
  49373. imageProvider = newImageProvider;
  49374. }
  49375. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49376. {
  49377. return imageProvider;
  49378. }
  49379. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49380. {
  49381. ComponentBuilderHelpers::updateComponent (*this, tree);
  49382. }
  49383. void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&)
  49384. {
  49385. ComponentBuilderHelpers::updateComponent (*this, tree);
  49386. }
  49387. void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&)
  49388. {
  49389. ComponentBuilderHelpers::updateComponent (*this, tree);
  49390. }
  49391. void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree)
  49392. {
  49393. ComponentBuilderHelpers::updateComponent (*this, tree);
  49394. }
  49395. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49396. {
  49397. ComponentBuilderHelpers::updateComponent (*this, tree);
  49398. }
  49399. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49400. : builder (0), valueTreeType (valueTreeType_)
  49401. {
  49402. }
  49403. ComponentBuilder::TypeHandler::~TypeHandler()
  49404. {
  49405. }
  49406. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49407. {
  49408. // A type handler needs to be registered with a ComponentBuilder before using it!
  49409. jassert (builder != 0);
  49410. return builder;
  49411. }
  49412. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49413. {
  49414. using namespace ComponentBuilderHelpers;
  49415. const int numExistingChildComps = parent.getNumChildComponents();
  49416. Array <Component*> componentsInOrder;
  49417. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49418. {
  49419. OwnedArray<Component> existingComponents;
  49420. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49421. int i;
  49422. for (i = 0; i < numExistingChildComps; ++i)
  49423. existingComponents.add (parent.getChildComponent (i));
  49424. const int newNumChildren = children.getNumChildren();
  49425. for (i = 0; i < newNumChildren; ++i)
  49426. {
  49427. const ValueTree childState (children.getChild (i));
  49428. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49429. jassert (type != 0);
  49430. if (type != 0)
  49431. {
  49432. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49433. if (c == 0)
  49434. c = createNewComponent (*type, childState, &parent);
  49435. componentsInOrder.add (c);
  49436. }
  49437. }
  49438. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49439. }
  49440. // Make sure the z-order is correct..
  49441. if (componentsInOrder.size() > 0)
  49442. {
  49443. componentsInOrder.getLast()->toFront (false);
  49444. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49445. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49446. }
  49447. }
  49448. END_JUCE_NAMESPACE
  49449. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49450. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49451. BEGIN_JUCE_NAMESPACE
  49452. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49453. : minW (0),
  49454. maxW (0x3fffffff),
  49455. minH (0),
  49456. maxH (0x3fffffff),
  49457. minOffTop (0),
  49458. minOffLeft (0),
  49459. minOffBottom (0),
  49460. minOffRight (0),
  49461. aspectRatio (0.0)
  49462. {
  49463. }
  49464. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49465. {
  49466. }
  49467. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49468. {
  49469. minW = minimumWidth;
  49470. }
  49471. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49472. {
  49473. maxW = maximumWidth;
  49474. }
  49475. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49476. {
  49477. minH = minimumHeight;
  49478. }
  49479. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49480. {
  49481. maxH = maximumHeight;
  49482. }
  49483. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49484. {
  49485. jassert (maxW >= minimumWidth);
  49486. jassert (maxH >= minimumHeight);
  49487. jassert (minimumWidth > 0 && minimumHeight > 0);
  49488. minW = minimumWidth;
  49489. minH = minimumHeight;
  49490. if (minW > maxW)
  49491. maxW = minW;
  49492. if (minH > maxH)
  49493. maxH = minH;
  49494. }
  49495. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49496. {
  49497. jassert (maximumWidth >= minW);
  49498. jassert (maximumHeight >= minH);
  49499. jassert (maximumWidth > 0 && maximumHeight > 0);
  49500. maxW = jmax (minW, maximumWidth);
  49501. maxH = jmax (minH, maximumHeight);
  49502. }
  49503. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49504. const int minimumHeight,
  49505. const int maximumWidth,
  49506. const int maximumHeight) throw()
  49507. {
  49508. jassert (maximumWidth >= minimumWidth);
  49509. jassert (maximumHeight >= minimumHeight);
  49510. jassert (maximumWidth > 0 && maximumHeight > 0);
  49511. jassert (minimumWidth > 0 && minimumHeight > 0);
  49512. minW = jmax (0, minimumWidth);
  49513. minH = jmax (0, minimumHeight);
  49514. maxW = jmax (minW, maximumWidth);
  49515. maxH = jmax (minH, maximumHeight);
  49516. }
  49517. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49518. const int minimumWhenOffTheLeft,
  49519. const int minimumWhenOffTheBottom,
  49520. const int minimumWhenOffTheRight) throw()
  49521. {
  49522. minOffTop = minimumWhenOffTheTop;
  49523. minOffLeft = minimumWhenOffTheLeft;
  49524. minOffBottom = minimumWhenOffTheBottom;
  49525. minOffRight = minimumWhenOffTheRight;
  49526. }
  49527. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49528. {
  49529. aspectRatio = jmax (0.0, widthOverHeight);
  49530. }
  49531. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49532. {
  49533. return aspectRatio;
  49534. }
  49535. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49536. const Rectangle<int>& targetBounds,
  49537. const bool isStretchingTop,
  49538. const bool isStretchingLeft,
  49539. const bool isStretchingBottom,
  49540. const bool isStretchingRight)
  49541. {
  49542. jassert (component != 0);
  49543. Rectangle<int> limits, bounds (targetBounds);
  49544. BorderSize<int> border;
  49545. Component* const parent = component->getParentComponent();
  49546. if (parent == 0)
  49547. {
  49548. ComponentPeer* peer = component->getPeer();
  49549. if (peer != 0)
  49550. border = peer->getFrameSize();
  49551. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49552. }
  49553. else
  49554. {
  49555. limits.setSize (parent->getWidth(), parent->getHeight());
  49556. }
  49557. border.addTo (bounds);
  49558. checkBounds (bounds,
  49559. border.addedTo (component->getBounds()), limits,
  49560. isStretchingTop, isStretchingLeft,
  49561. isStretchingBottom, isStretchingRight);
  49562. border.subtractFrom (bounds);
  49563. applyBoundsToComponent (component, bounds);
  49564. }
  49565. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49566. {
  49567. setBoundsForComponent (component, component->getBounds(),
  49568. false, false, false, false);
  49569. }
  49570. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49571. const Rectangle<int>& bounds)
  49572. {
  49573. component->setBounds (bounds);
  49574. }
  49575. void ComponentBoundsConstrainer::resizeStart()
  49576. {
  49577. }
  49578. void ComponentBoundsConstrainer::resizeEnd()
  49579. {
  49580. }
  49581. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49582. const Rectangle<int>& old,
  49583. const Rectangle<int>& limits,
  49584. const bool isStretchingTop,
  49585. const bool isStretchingLeft,
  49586. const bool isStretchingBottom,
  49587. const bool isStretchingRight)
  49588. {
  49589. // constrain the size if it's being stretched..
  49590. if (isStretchingLeft)
  49591. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49592. if (isStretchingRight)
  49593. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49594. if (isStretchingTop)
  49595. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49596. if (isStretchingBottom)
  49597. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49598. if (bounds.isEmpty())
  49599. return;
  49600. if (minOffTop > 0)
  49601. {
  49602. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49603. if (bounds.getY() < limit)
  49604. {
  49605. if (isStretchingTop)
  49606. bounds.setTop (limits.getY());
  49607. else
  49608. bounds.setY (limit);
  49609. }
  49610. }
  49611. if (minOffLeft > 0)
  49612. {
  49613. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49614. if (bounds.getX() < limit)
  49615. {
  49616. if (isStretchingLeft)
  49617. bounds.setLeft (limits.getX());
  49618. else
  49619. bounds.setX (limit);
  49620. }
  49621. }
  49622. if (minOffBottom > 0)
  49623. {
  49624. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49625. if (bounds.getY() > limit)
  49626. {
  49627. if (isStretchingBottom)
  49628. bounds.setBottom (limits.getBottom());
  49629. else
  49630. bounds.setY (limit);
  49631. }
  49632. }
  49633. if (minOffRight > 0)
  49634. {
  49635. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49636. if (bounds.getX() > limit)
  49637. {
  49638. if (isStretchingRight)
  49639. bounds.setRight (limits.getRight());
  49640. else
  49641. bounds.setX (limit);
  49642. }
  49643. }
  49644. // constrain the aspect ratio if one has been specified..
  49645. if (aspectRatio > 0.0)
  49646. {
  49647. bool adjustWidth;
  49648. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49649. {
  49650. adjustWidth = true;
  49651. }
  49652. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49653. {
  49654. adjustWidth = false;
  49655. }
  49656. else
  49657. {
  49658. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49659. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49660. adjustWidth = (oldRatio > newRatio);
  49661. }
  49662. if (adjustWidth)
  49663. {
  49664. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49665. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49666. {
  49667. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49668. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49669. }
  49670. }
  49671. else
  49672. {
  49673. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49674. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49675. {
  49676. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49677. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49678. }
  49679. }
  49680. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49681. {
  49682. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49683. }
  49684. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49685. {
  49686. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49687. }
  49688. else
  49689. {
  49690. if (isStretchingLeft)
  49691. bounds.setX (old.getRight() - bounds.getWidth());
  49692. if (isStretchingTop)
  49693. bounds.setY (old.getBottom() - bounds.getHeight());
  49694. }
  49695. }
  49696. jassert (! bounds.isEmpty());
  49697. }
  49698. END_JUCE_NAMESPACE
  49699. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49700. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49701. BEGIN_JUCE_NAMESPACE
  49702. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49703. : component (component_),
  49704. lastPeer (0),
  49705. reentrant (false),
  49706. wasShowing (component_->isShowing())
  49707. {
  49708. jassert (component != 0); // can't use this with a null pointer..
  49709. component->addComponentListener (this);
  49710. registerWithParentComps();
  49711. }
  49712. ComponentMovementWatcher::~ComponentMovementWatcher()
  49713. {
  49714. if (component != 0)
  49715. component->removeComponentListener (this);
  49716. unregister();
  49717. }
  49718. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49719. {
  49720. if (component != 0 && ! reentrant)
  49721. {
  49722. const ScopedValueSetter<bool> setter (reentrant, true);
  49723. ComponentPeer* const peer = component->getPeer();
  49724. if (peer != lastPeer)
  49725. {
  49726. componentPeerChanged();
  49727. if (component == 0)
  49728. return;
  49729. lastPeer = peer;
  49730. }
  49731. unregister();
  49732. registerWithParentComps();
  49733. componentMovedOrResized (*component, true, true);
  49734. if (component != 0)
  49735. componentVisibilityChanged (*component);
  49736. }
  49737. }
  49738. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49739. {
  49740. if (component != 0)
  49741. {
  49742. if (wasMoved)
  49743. {
  49744. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49745. wasMoved = lastBounds.getPosition() != pos;
  49746. lastBounds.setPosition (pos);
  49747. }
  49748. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49749. lastBounds.setSize (component->getWidth(), component->getHeight());
  49750. if (wasMoved || wasResized)
  49751. componentMovedOrResized (wasMoved, wasResized);
  49752. }
  49753. }
  49754. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  49755. {
  49756. registeredParentComps.removeValue (&comp);
  49757. if (component == &comp)
  49758. unregister();
  49759. }
  49760. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  49761. {
  49762. if (component != 0)
  49763. {
  49764. const bool isShowingNow = component->isShowing();
  49765. if (wasShowing != isShowingNow)
  49766. {
  49767. wasShowing = isShowingNow;
  49768. componentVisibilityChanged();
  49769. }
  49770. }
  49771. }
  49772. void ComponentMovementWatcher::registerWithParentComps()
  49773. {
  49774. Component* p = component->getParentComponent();
  49775. while (p != 0)
  49776. {
  49777. p->addComponentListener (this);
  49778. registeredParentComps.add (p);
  49779. p = p->getParentComponent();
  49780. }
  49781. }
  49782. void ComponentMovementWatcher::unregister()
  49783. {
  49784. for (int i = registeredParentComps.size(); --i >= 0;)
  49785. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49786. registeredParentComps.clear();
  49787. }
  49788. END_JUCE_NAMESPACE
  49789. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49790. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49791. BEGIN_JUCE_NAMESPACE
  49792. GroupComponent::GroupComponent (const String& componentName,
  49793. const String& labelText)
  49794. : Component (componentName),
  49795. text (labelText),
  49796. justification (Justification::left)
  49797. {
  49798. setInterceptsMouseClicks (false, true);
  49799. }
  49800. GroupComponent::~GroupComponent()
  49801. {
  49802. }
  49803. void GroupComponent::setText (const String& newText)
  49804. {
  49805. if (text != newText)
  49806. {
  49807. text = newText;
  49808. repaint();
  49809. }
  49810. }
  49811. const String GroupComponent::getText() const
  49812. {
  49813. return text;
  49814. }
  49815. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49816. {
  49817. if (justification != newJustification)
  49818. {
  49819. justification = newJustification;
  49820. repaint();
  49821. }
  49822. }
  49823. void GroupComponent::paint (Graphics& g)
  49824. {
  49825. getLookAndFeel()
  49826. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49827. text, justification,
  49828. *this);
  49829. }
  49830. void GroupComponent::enablementChanged()
  49831. {
  49832. repaint();
  49833. }
  49834. void GroupComponent::colourChanged()
  49835. {
  49836. repaint();
  49837. }
  49838. END_JUCE_NAMESPACE
  49839. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49840. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49841. BEGIN_JUCE_NAMESPACE
  49842. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49843. : DocumentWindow (String::empty, backgroundColour,
  49844. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49845. {
  49846. }
  49847. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49848. {
  49849. }
  49850. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49851. {
  49852. MultiDocumentPanel* const owner = getOwner();
  49853. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49854. if (owner != 0)
  49855. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49856. }
  49857. void MultiDocumentPanelWindow::closeButtonPressed()
  49858. {
  49859. MultiDocumentPanel* const owner = getOwner();
  49860. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49861. if (owner != 0)
  49862. owner->closeDocument (getContentComponent(), true);
  49863. }
  49864. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49865. {
  49866. DocumentWindow::activeWindowStatusChanged();
  49867. updateOrder();
  49868. }
  49869. void MultiDocumentPanelWindow::broughtToFront()
  49870. {
  49871. DocumentWindow::broughtToFront();
  49872. updateOrder();
  49873. }
  49874. void MultiDocumentPanelWindow::updateOrder()
  49875. {
  49876. MultiDocumentPanel* const owner = getOwner();
  49877. if (owner != 0)
  49878. owner->updateOrder();
  49879. }
  49880. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49881. {
  49882. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49883. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49884. }
  49885. class MDITabbedComponentInternal : public TabbedComponent
  49886. {
  49887. public:
  49888. MDITabbedComponentInternal()
  49889. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49890. {
  49891. }
  49892. ~MDITabbedComponentInternal()
  49893. {
  49894. }
  49895. void currentTabChanged (int, const String&)
  49896. {
  49897. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49898. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49899. if (owner != 0)
  49900. owner->updateOrder();
  49901. }
  49902. };
  49903. MultiDocumentPanel::MultiDocumentPanel()
  49904. : mode (MaximisedWindowsWithTabs),
  49905. backgroundColour (Colours::lightblue),
  49906. maximumNumDocuments (0),
  49907. numDocsBeforeTabsUsed (0)
  49908. {
  49909. setOpaque (true);
  49910. }
  49911. MultiDocumentPanel::~MultiDocumentPanel()
  49912. {
  49913. closeAllDocuments (false);
  49914. }
  49915. namespace MultiDocHelpers
  49916. {
  49917. bool shouldDeleteComp (Component* const c)
  49918. {
  49919. return c->getProperties() ["mdiDocumentDelete_"];
  49920. }
  49921. }
  49922. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49923. {
  49924. while (components.size() > 0)
  49925. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49926. return false;
  49927. return true;
  49928. }
  49929. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49930. {
  49931. return new MultiDocumentPanelWindow (backgroundColour);
  49932. }
  49933. void MultiDocumentPanel::addWindow (Component* component)
  49934. {
  49935. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49936. dw->setResizable (true, false);
  49937. dw->setContentComponent (component, false, true);
  49938. dw->setName (component->getName());
  49939. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49940. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49941. int x = 4;
  49942. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49943. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49944. x += 16;
  49945. dw->setTopLeftPosition (x, x);
  49946. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49947. if (pos.toString().isNotEmpty())
  49948. dw->restoreWindowStateFromString (pos.toString());
  49949. addAndMakeVisible (dw);
  49950. dw->toFront (true);
  49951. }
  49952. bool MultiDocumentPanel::addDocument (Component* const component,
  49953. const Colour& docColour,
  49954. const bool deleteWhenRemoved)
  49955. {
  49956. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49957. // with a frame-within-a-frame! Just pass in the bare content component.
  49958. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49959. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49960. return false;
  49961. components.add (component);
  49962. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49963. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49964. component->addComponentListener (this);
  49965. if (mode == FloatingWindows)
  49966. {
  49967. if (isFullscreenWhenOneDocument())
  49968. {
  49969. if (components.size() == 1)
  49970. {
  49971. addAndMakeVisible (component);
  49972. }
  49973. else
  49974. {
  49975. if (components.size() == 2)
  49976. addWindow (components.getFirst());
  49977. addWindow (component);
  49978. }
  49979. }
  49980. else
  49981. {
  49982. addWindow (component);
  49983. }
  49984. }
  49985. else
  49986. {
  49987. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49988. {
  49989. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49990. Array <Component*> temp (components);
  49991. for (int i = 0; i < temp.size(); ++i)
  49992. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49993. resized();
  49994. }
  49995. else
  49996. {
  49997. if (tabComponent != 0)
  49998. tabComponent->addTab (component->getName(), docColour, component, false);
  49999. else
  50000. addAndMakeVisible (component);
  50001. }
  50002. setActiveDocument (component);
  50003. }
  50004. resized();
  50005. activeDocumentChanged();
  50006. return true;
  50007. }
  50008. bool MultiDocumentPanel::closeDocument (Component* component,
  50009. const bool checkItsOkToCloseFirst)
  50010. {
  50011. if (components.contains (component))
  50012. {
  50013. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50014. return false;
  50015. component->removeComponentListener (this);
  50016. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50017. component->getProperties().remove ("mdiDocumentDelete_");
  50018. component->getProperties().remove ("mdiDocumentBkg_");
  50019. if (mode == FloatingWindows)
  50020. {
  50021. for (int i = getNumChildComponents(); --i >= 0;)
  50022. {
  50023. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50024. if (dw != 0 && dw->getContentComponent() == component)
  50025. {
  50026. dw->setContentComponent (0, false);
  50027. delete dw;
  50028. break;
  50029. }
  50030. }
  50031. if (shouldDelete)
  50032. delete component;
  50033. components.removeValue (component);
  50034. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50035. {
  50036. for (int i = getNumChildComponents(); --i >= 0;)
  50037. {
  50038. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50039. if (dw != 0)
  50040. {
  50041. dw->setContentComponent (0, false);
  50042. delete dw;
  50043. }
  50044. }
  50045. addAndMakeVisible (components.getFirst());
  50046. }
  50047. }
  50048. else
  50049. {
  50050. jassert (components.indexOf (component) >= 0);
  50051. if (tabComponent != 0)
  50052. {
  50053. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50054. if (tabComponent->getTabContentComponent (i) == component)
  50055. tabComponent->removeTab (i);
  50056. }
  50057. else
  50058. {
  50059. removeChildComponent (component);
  50060. }
  50061. if (shouldDelete)
  50062. delete component;
  50063. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50064. tabComponent = 0;
  50065. components.removeValue (component);
  50066. if (components.size() > 0 && tabComponent == 0)
  50067. addAndMakeVisible (components.getFirst());
  50068. }
  50069. resized();
  50070. activeDocumentChanged();
  50071. }
  50072. else
  50073. {
  50074. jassertfalse;
  50075. }
  50076. return true;
  50077. }
  50078. int MultiDocumentPanel::getNumDocuments() const throw()
  50079. {
  50080. return components.size();
  50081. }
  50082. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50083. {
  50084. return components [index];
  50085. }
  50086. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50087. {
  50088. if (mode == FloatingWindows)
  50089. {
  50090. for (int i = getNumChildComponents(); --i >= 0;)
  50091. {
  50092. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50093. if (dw != 0 && dw->isActiveWindow())
  50094. return dw->getContentComponent();
  50095. }
  50096. }
  50097. return components.getLast();
  50098. }
  50099. void MultiDocumentPanel::setActiveDocument (Component* component)
  50100. {
  50101. if (mode == FloatingWindows)
  50102. {
  50103. component = getContainerComp (component);
  50104. if (component != 0)
  50105. component->toFront (true);
  50106. }
  50107. else if (tabComponent != 0)
  50108. {
  50109. jassert (components.indexOf (component) >= 0);
  50110. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50111. {
  50112. if (tabComponent->getTabContentComponent (i) == component)
  50113. {
  50114. tabComponent->setCurrentTabIndex (i);
  50115. break;
  50116. }
  50117. }
  50118. }
  50119. else
  50120. {
  50121. component->grabKeyboardFocus();
  50122. }
  50123. }
  50124. void MultiDocumentPanel::activeDocumentChanged()
  50125. {
  50126. }
  50127. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50128. {
  50129. maximumNumDocuments = newNumber;
  50130. }
  50131. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50132. {
  50133. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50134. }
  50135. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50136. {
  50137. return numDocsBeforeTabsUsed != 0;
  50138. }
  50139. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50140. {
  50141. if (mode != newLayoutMode)
  50142. {
  50143. mode = newLayoutMode;
  50144. if (mode == FloatingWindows)
  50145. {
  50146. tabComponent = 0;
  50147. }
  50148. else
  50149. {
  50150. for (int i = getNumChildComponents(); --i >= 0;)
  50151. {
  50152. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50153. if (dw != 0)
  50154. {
  50155. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50156. dw->setContentComponent (0, false);
  50157. delete dw;
  50158. }
  50159. }
  50160. }
  50161. resized();
  50162. const Array <Component*> tempComps (components);
  50163. components.clear();
  50164. for (int i = 0; i < tempComps.size(); ++i)
  50165. {
  50166. Component* const c = tempComps.getUnchecked(i);
  50167. addDocument (c,
  50168. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50169. MultiDocHelpers::shouldDeleteComp (c));
  50170. }
  50171. }
  50172. }
  50173. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50174. {
  50175. if (backgroundColour != newBackgroundColour)
  50176. {
  50177. backgroundColour = newBackgroundColour;
  50178. setOpaque (newBackgroundColour.isOpaque());
  50179. repaint();
  50180. }
  50181. }
  50182. void MultiDocumentPanel::paint (Graphics& g)
  50183. {
  50184. g.fillAll (backgroundColour);
  50185. }
  50186. void MultiDocumentPanel::resized()
  50187. {
  50188. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50189. {
  50190. for (int i = getNumChildComponents(); --i >= 0;)
  50191. getChildComponent (i)->setBounds (getLocalBounds());
  50192. }
  50193. setWantsKeyboardFocus (components.size() == 0);
  50194. }
  50195. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50196. {
  50197. if (mode == FloatingWindows)
  50198. {
  50199. for (int i = 0; i < getNumChildComponents(); ++i)
  50200. {
  50201. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50202. if (dw != 0 && dw->getContentComponent() == c)
  50203. {
  50204. c = dw;
  50205. break;
  50206. }
  50207. }
  50208. }
  50209. return c;
  50210. }
  50211. void MultiDocumentPanel::componentNameChanged (Component&)
  50212. {
  50213. if (mode == FloatingWindows)
  50214. {
  50215. for (int i = 0; i < getNumChildComponents(); ++i)
  50216. {
  50217. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50218. if (dw != 0)
  50219. dw->setName (dw->getContentComponent()->getName());
  50220. }
  50221. }
  50222. else if (tabComponent != 0)
  50223. {
  50224. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50225. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50226. }
  50227. }
  50228. void MultiDocumentPanel::updateOrder()
  50229. {
  50230. const Array <Component*> oldList (components);
  50231. if (mode == FloatingWindows)
  50232. {
  50233. components.clear();
  50234. for (int i = 0; i < getNumChildComponents(); ++i)
  50235. {
  50236. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50237. if (dw != 0)
  50238. components.add (dw->getContentComponent());
  50239. }
  50240. }
  50241. else
  50242. {
  50243. if (tabComponent != 0)
  50244. {
  50245. Component* const current = tabComponent->getCurrentContentComponent();
  50246. if (current != 0)
  50247. {
  50248. components.removeValue (current);
  50249. components.add (current);
  50250. }
  50251. }
  50252. }
  50253. if (components != oldList)
  50254. activeDocumentChanged();
  50255. }
  50256. END_JUCE_NAMESPACE
  50257. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50258. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50259. BEGIN_JUCE_NAMESPACE
  50260. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50261. : zone (zoneFlags)
  50262. {}
  50263. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50264. : zone (other.zone)
  50265. {}
  50266. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50267. {
  50268. zone = other.zone;
  50269. return *this;
  50270. }
  50271. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50272. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50273. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50274. const BorderSize<int>& border,
  50275. const Point<int>& position)
  50276. {
  50277. int z = 0;
  50278. if (totalSize.contains (position)
  50279. && ! border.subtractedFrom (totalSize).contains (position))
  50280. {
  50281. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50282. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50283. z |= left;
  50284. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50285. z |= right;
  50286. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50287. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50288. z |= top;
  50289. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50290. z |= bottom;
  50291. }
  50292. return Zone (z);
  50293. }
  50294. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50295. {
  50296. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50297. switch (zone)
  50298. {
  50299. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50300. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50301. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50302. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50303. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50304. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50305. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50306. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50307. default: break;
  50308. }
  50309. return mc;
  50310. }
  50311. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50312. ComponentBoundsConstrainer* const constrainer_)
  50313. : component (componentToResize),
  50314. constrainer (constrainer_),
  50315. borderSize (5),
  50316. mouseZone (0)
  50317. {
  50318. }
  50319. ResizableBorderComponent::~ResizableBorderComponent()
  50320. {
  50321. }
  50322. void ResizableBorderComponent::paint (Graphics& g)
  50323. {
  50324. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50325. }
  50326. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50327. {
  50328. updateMouseZone (e);
  50329. }
  50330. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50331. {
  50332. updateMouseZone (e);
  50333. }
  50334. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50335. {
  50336. if (component == 0)
  50337. {
  50338. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50339. return;
  50340. }
  50341. updateMouseZone (e);
  50342. originalBounds = component->getBounds();
  50343. if (constrainer != 0)
  50344. constrainer->resizeStart();
  50345. }
  50346. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50347. {
  50348. if (component == 0)
  50349. {
  50350. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50351. return;
  50352. }
  50353. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50354. if (constrainer != 0)
  50355. constrainer->setBoundsForComponent (component, bounds,
  50356. mouseZone.isDraggingTopEdge(),
  50357. mouseZone.isDraggingLeftEdge(),
  50358. mouseZone.isDraggingBottomEdge(),
  50359. mouseZone.isDraggingRightEdge());
  50360. else
  50361. component->setBounds (bounds);
  50362. }
  50363. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50364. {
  50365. if (constrainer != 0)
  50366. constrainer->resizeEnd();
  50367. }
  50368. bool ResizableBorderComponent::hitTest (int x, int y)
  50369. {
  50370. return x < borderSize.getLeft()
  50371. || x >= getWidth() - borderSize.getRight()
  50372. || y < borderSize.getTop()
  50373. || y >= getHeight() - borderSize.getBottom();
  50374. }
  50375. void ResizableBorderComponent::setBorderThickness (const BorderSize<int>& newBorderSize)
  50376. {
  50377. if (borderSize != newBorderSize)
  50378. {
  50379. borderSize = newBorderSize;
  50380. repaint();
  50381. }
  50382. }
  50383. const BorderSize<int> ResizableBorderComponent::getBorderThickness() const
  50384. {
  50385. return borderSize;
  50386. }
  50387. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50388. {
  50389. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50390. if (mouseZone != newZone)
  50391. {
  50392. mouseZone = newZone;
  50393. setMouseCursor (newZone.getMouseCursor());
  50394. }
  50395. }
  50396. END_JUCE_NAMESPACE
  50397. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50398. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50399. BEGIN_JUCE_NAMESPACE
  50400. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50401. ComponentBoundsConstrainer* const constrainer_)
  50402. : component (componentToResize),
  50403. constrainer (constrainer_)
  50404. {
  50405. setRepaintsOnMouseActivity (true);
  50406. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50407. }
  50408. ResizableCornerComponent::~ResizableCornerComponent()
  50409. {
  50410. }
  50411. void ResizableCornerComponent::paint (Graphics& g)
  50412. {
  50413. getLookAndFeel()
  50414. .drawCornerResizer (g, getWidth(), getHeight(),
  50415. isMouseOverOrDragging(),
  50416. isMouseButtonDown());
  50417. }
  50418. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50419. {
  50420. if (component == 0)
  50421. {
  50422. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50423. return;
  50424. }
  50425. originalBounds = component->getBounds();
  50426. if (constrainer != 0)
  50427. constrainer->resizeStart();
  50428. }
  50429. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50430. {
  50431. if (component == 0)
  50432. {
  50433. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50434. return;
  50435. }
  50436. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50437. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50438. if (constrainer != 0)
  50439. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50440. else
  50441. component->setBounds (r);
  50442. }
  50443. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50444. {
  50445. if (constrainer != 0)
  50446. constrainer->resizeStart();
  50447. }
  50448. bool ResizableCornerComponent::hitTest (int x, int y)
  50449. {
  50450. if (getWidth() <= 0)
  50451. return false;
  50452. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50453. return y >= yAtX - getHeight() / 4;
  50454. }
  50455. END_JUCE_NAMESPACE
  50456. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50457. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50458. BEGIN_JUCE_NAMESPACE
  50459. class ScrollBar::ScrollbarButton : public Button
  50460. {
  50461. public:
  50462. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50463. : Button (String::empty),
  50464. direction (direction_),
  50465. owner (owner_)
  50466. {
  50467. setWantsKeyboardFocus (false);
  50468. }
  50469. void paintButton (Graphics& g, bool over, bool down)
  50470. {
  50471. getLookAndFeel()
  50472. .drawScrollbarButton (g, owner,
  50473. getWidth(), getHeight(),
  50474. direction,
  50475. owner.isVertical(),
  50476. over, down);
  50477. }
  50478. void clicked()
  50479. {
  50480. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50481. }
  50482. int direction;
  50483. private:
  50484. ScrollBar& owner;
  50485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50486. };
  50487. ScrollBar::ScrollBar (const bool vertical_,
  50488. const bool buttonsAreVisible)
  50489. : totalRange (0.0, 1.0),
  50490. visibleRange (0.0, 0.1),
  50491. singleStepSize (0.1),
  50492. thumbAreaStart (0),
  50493. thumbAreaSize (0),
  50494. thumbStart (0),
  50495. thumbSize (0),
  50496. initialDelayInMillisecs (100),
  50497. repeatDelayInMillisecs (50),
  50498. minimumDelayInMillisecs (10),
  50499. vertical (vertical_),
  50500. isDraggingThumb (false),
  50501. autohides (true)
  50502. {
  50503. setButtonVisibility (buttonsAreVisible);
  50504. setRepaintsOnMouseActivity (true);
  50505. setFocusContainer (true);
  50506. }
  50507. ScrollBar::~ScrollBar()
  50508. {
  50509. upButton = 0;
  50510. downButton = 0;
  50511. }
  50512. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50513. {
  50514. if (totalRange != newRangeLimit)
  50515. {
  50516. totalRange = newRangeLimit;
  50517. setCurrentRange (visibleRange);
  50518. updateThumbPosition();
  50519. }
  50520. }
  50521. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50522. {
  50523. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50524. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50525. }
  50526. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50527. {
  50528. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50529. if (visibleRange != constrainedRange)
  50530. {
  50531. visibleRange = constrainedRange;
  50532. updateThumbPosition();
  50533. triggerAsyncUpdate();
  50534. }
  50535. }
  50536. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50537. {
  50538. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50539. }
  50540. void ScrollBar::setCurrentRangeStart (const double newStart)
  50541. {
  50542. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50543. }
  50544. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50545. {
  50546. singleStepSize = newSingleStepSize;
  50547. }
  50548. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50549. {
  50550. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50551. }
  50552. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50553. {
  50554. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50555. }
  50556. void ScrollBar::scrollToTop()
  50557. {
  50558. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50559. }
  50560. void ScrollBar::scrollToBottom()
  50561. {
  50562. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50563. }
  50564. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50565. const int repeatDelayInMillisecs_,
  50566. const int minimumDelayInMillisecs_)
  50567. {
  50568. initialDelayInMillisecs = initialDelayInMillisecs_;
  50569. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50570. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50571. if (upButton != 0)
  50572. {
  50573. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50574. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50575. }
  50576. }
  50577. void ScrollBar::addListener (Listener* const listener)
  50578. {
  50579. listeners.add (listener);
  50580. }
  50581. void ScrollBar::removeListener (Listener* const listener)
  50582. {
  50583. listeners.remove (listener);
  50584. }
  50585. void ScrollBar::handleAsyncUpdate()
  50586. {
  50587. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50588. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50589. }
  50590. void ScrollBar::updateThumbPosition()
  50591. {
  50592. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50593. : thumbAreaSize);
  50594. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50595. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50596. if (newThumbSize > thumbAreaSize)
  50597. newThumbSize = thumbAreaSize;
  50598. int newThumbStart = thumbAreaStart;
  50599. if (totalRange.getLength() > visibleRange.getLength())
  50600. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50601. / (totalRange.getLength() - visibleRange.getLength()));
  50602. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50603. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50604. {
  50605. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50606. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50607. if (vertical)
  50608. repaint (0, repaintStart, getWidth(), repaintSize);
  50609. else
  50610. repaint (repaintStart, 0, repaintSize, getHeight());
  50611. thumbStart = newThumbStart;
  50612. thumbSize = newThumbSize;
  50613. }
  50614. }
  50615. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50616. {
  50617. if (vertical != shouldBeVertical)
  50618. {
  50619. vertical = shouldBeVertical;
  50620. if (upButton != 0)
  50621. {
  50622. upButton->direction = vertical ? 0 : 3;
  50623. downButton->direction = vertical ? 2 : 1;
  50624. }
  50625. updateThumbPosition();
  50626. }
  50627. }
  50628. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50629. {
  50630. upButton = 0;
  50631. downButton = 0;
  50632. if (buttonsAreVisible)
  50633. {
  50634. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50635. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50636. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50637. }
  50638. updateThumbPosition();
  50639. }
  50640. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50641. {
  50642. autohides = shouldHideWhenFullRange;
  50643. updateThumbPosition();
  50644. }
  50645. bool ScrollBar::autoHides() const throw()
  50646. {
  50647. return autohides;
  50648. }
  50649. void ScrollBar::paint (Graphics& g)
  50650. {
  50651. if (thumbAreaSize > 0)
  50652. {
  50653. LookAndFeel& lf = getLookAndFeel();
  50654. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50655. ? thumbSize : 0;
  50656. if (vertical)
  50657. {
  50658. lf.drawScrollbar (g, *this,
  50659. 0, thumbAreaStart,
  50660. getWidth(), thumbAreaSize,
  50661. vertical,
  50662. thumbStart, thumb,
  50663. isMouseOver(), isMouseButtonDown());
  50664. }
  50665. else
  50666. {
  50667. lf.drawScrollbar (g, *this,
  50668. thumbAreaStart, 0,
  50669. thumbAreaSize, getHeight(),
  50670. vertical,
  50671. thumbStart, thumb,
  50672. isMouseOver(), isMouseButtonDown());
  50673. }
  50674. }
  50675. }
  50676. void ScrollBar::lookAndFeelChanged()
  50677. {
  50678. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50679. }
  50680. void ScrollBar::resized()
  50681. {
  50682. const int length = ((vertical) ? getHeight() : getWidth());
  50683. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50684. : 0;
  50685. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50686. {
  50687. thumbAreaStart = length >> 1;
  50688. thumbAreaSize = 0;
  50689. }
  50690. else
  50691. {
  50692. thumbAreaStart = buttonSize;
  50693. thumbAreaSize = length - (buttonSize << 1);
  50694. }
  50695. if (upButton != 0)
  50696. {
  50697. if (vertical)
  50698. {
  50699. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50700. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50701. }
  50702. else
  50703. {
  50704. upButton->setBounds (0, 0, buttonSize, getHeight());
  50705. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50706. }
  50707. }
  50708. updateThumbPosition();
  50709. }
  50710. void ScrollBar::mouseDown (const MouseEvent& e)
  50711. {
  50712. isDraggingThumb = false;
  50713. lastMousePos = vertical ? e.y : e.x;
  50714. dragStartMousePos = lastMousePos;
  50715. dragStartRange = visibleRange.getStart();
  50716. if (dragStartMousePos < thumbStart)
  50717. {
  50718. moveScrollbarInPages (-1);
  50719. startTimer (400);
  50720. }
  50721. else if (dragStartMousePos >= thumbStart + thumbSize)
  50722. {
  50723. moveScrollbarInPages (1);
  50724. startTimer (400);
  50725. }
  50726. else
  50727. {
  50728. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50729. && (thumbAreaSize > thumbSize);
  50730. }
  50731. }
  50732. void ScrollBar::mouseDrag (const MouseEvent& e)
  50733. {
  50734. const int mousePos = vertical ? e.y : e.x;
  50735. if (isDraggingThumb && lastMousePos != mousePos)
  50736. {
  50737. const int deltaPixels = mousePos - dragStartMousePos;
  50738. setCurrentRangeStart (dragStartRange
  50739. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50740. / (thumbAreaSize - thumbSize));
  50741. }
  50742. lastMousePos = mousePos;
  50743. }
  50744. void ScrollBar::mouseUp (const MouseEvent&)
  50745. {
  50746. isDraggingThumb = false;
  50747. stopTimer();
  50748. repaint();
  50749. }
  50750. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50751. float wheelIncrementX,
  50752. float wheelIncrementY)
  50753. {
  50754. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50755. if (increment < 0)
  50756. increment = jmin (increment * 10.0f, -1.0f);
  50757. else if (increment > 0)
  50758. increment = jmax (increment * 10.0f, 1.0f);
  50759. setCurrentRange (visibleRange - singleStepSize * increment);
  50760. }
  50761. void ScrollBar::timerCallback()
  50762. {
  50763. if (isMouseButtonDown())
  50764. {
  50765. startTimer (40);
  50766. if (lastMousePos < thumbStart)
  50767. setCurrentRange (visibleRange - visibleRange.getLength());
  50768. else if (lastMousePos > thumbStart + thumbSize)
  50769. setCurrentRangeStart (visibleRange.getEnd());
  50770. }
  50771. else
  50772. {
  50773. stopTimer();
  50774. }
  50775. }
  50776. bool ScrollBar::keyPressed (const KeyPress& key)
  50777. {
  50778. if (! isVisible())
  50779. return false;
  50780. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50781. moveScrollbarInSteps (-1);
  50782. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50783. moveScrollbarInSteps (1);
  50784. else if (key.isKeyCode (KeyPress::pageUpKey))
  50785. moveScrollbarInPages (-1);
  50786. else if (key.isKeyCode (KeyPress::pageDownKey))
  50787. moveScrollbarInPages (1);
  50788. else if (key.isKeyCode (KeyPress::homeKey))
  50789. scrollToTop();
  50790. else if (key.isKeyCode (KeyPress::endKey))
  50791. scrollToBottom();
  50792. else
  50793. return false;
  50794. return true;
  50795. }
  50796. END_JUCE_NAMESPACE
  50797. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50798. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50799. BEGIN_JUCE_NAMESPACE
  50800. StretchableLayoutManager::StretchableLayoutManager()
  50801. : totalSize (0)
  50802. {
  50803. }
  50804. StretchableLayoutManager::~StretchableLayoutManager()
  50805. {
  50806. }
  50807. void StretchableLayoutManager::clearAllItems()
  50808. {
  50809. items.clear();
  50810. totalSize = 0;
  50811. }
  50812. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50813. const double minimumSize,
  50814. const double maximumSize,
  50815. const double preferredSize)
  50816. {
  50817. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50818. if (layout == 0)
  50819. {
  50820. layout = new ItemLayoutProperties();
  50821. layout->itemIndex = itemIndex;
  50822. int i;
  50823. for (i = 0; i < items.size(); ++i)
  50824. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50825. break;
  50826. items.insert (i, layout);
  50827. }
  50828. layout->minSize = minimumSize;
  50829. layout->maxSize = maximumSize;
  50830. layout->preferredSize = preferredSize;
  50831. layout->currentSize = 0;
  50832. }
  50833. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50834. double& minimumSize,
  50835. double& maximumSize,
  50836. double& preferredSize) const
  50837. {
  50838. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50839. if (layout != 0)
  50840. {
  50841. minimumSize = layout->minSize;
  50842. maximumSize = layout->maxSize;
  50843. preferredSize = layout->preferredSize;
  50844. return true;
  50845. }
  50846. return false;
  50847. }
  50848. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50849. {
  50850. totalSize = newTotalSize;
  50851. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50852. }
  50853. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50854. {
  50855. int pos = 0;
  50856. for (int i = 0; i < itemIndex; ++i)
  50857. {
  50858. const ItemLayoutProperties* const layout = getInfoFor (i);
  50859. if (layout != 0)
  50860. pos += layout->currentSize;
  50861. }
  50862. return pos;
  50863. }
  50864. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50865. {
  50866. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50867. if (layout != 0)
  50868. return layout->currentSize;
  50869. return 0;
  50870. }
  50871. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50872. {
  50873. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50874. if (layout != 0)
  50875. return -layout->currentSize / (double) totalSize;
  50876. return 0;
  50877. }
  50878. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50879. int newPosition)
  50880. {
  50881. for (int i = items.size(); --i >= 0;)
  50882. {
  50883. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50884. if (layout->itemIndex == itemIndex)
  50885. {
  50886. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50887. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50888. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50889. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50890. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50891. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50892. endPos += layout->currentSize;
  50893. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50894. updatePrefSizesToMatchCurrentPositions();
  50895. break;
  50896. }
  50897. }
  50898. }
  50899. void StretchableLayoutManager::layOutComponents (Component** const components,
  50900. int numComponents,
  50901. int x, int y, int w, int h,
  50902. const bool vertically,
  50903. const bool resizeOtherDimension)
  50904. {
  50905. setTotalSize (vertically ? h : w);
  50906. int pos = vertically ? y : x;
  50907. for (int i = 0; i < numComponents; ++i)
  50908. {
  50909. const ItemLayoutProperties* const layout = getInfoFor (i);
  50910. if (layout != 0)
  50911. {
  50912. Component* const c = components[i];
  50913. if (c != 0)
  50914. {
  50915. if (i == numComponents - 1)
  50916. {
  50917. // if it's the last item, crop it to exactly fit the available space..
  50918. if (resizeOtherDimension)
  50919. {
  50920. if (vertically)
  50921. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50922. else
  50923. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50924. }
  50925. else
  50926. {
  50927. if (vertically)
  50928. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50929. else
  50930. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50931. }
  50932. }
  50933. else
  50934. {
  50935. if (resizeOtherDimension)
  50936. {
  50937. if (vertically)
  50938. c->setBounds (x, pos, w, layout->currentSize);
  50939. else
  50940. c->setBounds (pos, y, layout->currentSize, h);
  50941. }
  50942. else
  50943. {
  50944. if (vertically)
  50945. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50946. else
  50947. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50948. }
  50949. }
  50950. }
  50951. pos += layout->currentSize;
  50952. }
  50953. }
  50954. }
  50955. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50956. {
  50957. for (int i = items.size(); --i >= 0;)
  50958. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50959. return items.getUnchecked(i);
  50960. return 0;
  50961. }
  50962. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50963. const int endIndex,
  50964. const int availableSpace,
  50965. int startPos)
  50966. {
  50967. // calculate the total sizes
  50968. int i;
  50969. double totalIdealSize = 0.0;
  50970. int totalMinimums = 0;
  50971. for (i = startIndex; i < endIndex; ++i)
  50972. {
  50973. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50974. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50975. totalMinimums += layout->currentSize;
  50976. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50977. }
  50978. if (totalIdealSize <= 0)
  50979. totalIdealSize = 1.0;
  50980. // now calc the best sizes..
  50981. int extraSpace = availableSpace - totalMinimums;
  50982. while (extraSpace > 0)
  50983. {
  50984. int numWantingMoreSpace = 0;
  50985. int numHavingTakenExtraSpace = 0;
  50986. // first figure out how many comps want a slice of the extra space..
  50987. for (i = startIndex; i < endIndex; ++i)
  50988. {
  50989. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50990. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50991. const int bestSize = jlimit (layout->currentSize,
  50992. jmax (layout->currentSize,
  50993. sizeToRealSize (layout->maxSize, totalSize)),
  50994. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50995. if (bestSize > layout->currentSize)
  50996. ++numWantingMoreSpace;
  50997. }
  50998. // ..share out the extra space..
  50999. for (i = startIndex; i < endIndex; ++i)
  51000. {
  51001. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51002. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51003. int bestSize = jlimit (layout->currentSize,
  51004. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51005. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51006. const int extraWanted = bestSize - layout->currentSize;
  51007. if (extraWanted > 0)
  51008. {
  51009. const int extraAllowed = jmin (extraWanted,
  51010. extraSpace / jmax (1, numWantingMoreSpace));
  51011. if (extraAllowed > 0)
  51012. {
  51013. ++numHavingTakenExtraSpace;
  51014. --numWantingMoreSpace;
  51015. layout->currentSize += extraAllowed;
  51016. extraSpace -= extraAllowed;
  51017. }
  51018. }
  51019. }
  51020. if (numHavingTakenExtraSpace <= 0)
  51021. break;
  51022. }
  51023. // ..and calculate the end position
  51024. for (i = startIndex; i < endIndex; ++i)
  51025. {
  51026. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51027. startPos += layout->currentSize;
  51028. }
  51029. return startPos;
  51030. }
  51031. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51032. const int endIndex) const
  51033. {
  51034. int totalMinimums = 0;
  51035. for (int i = startIndex; i < endIndex; ++i)
  51036. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51037. return totalMinimums;
  51038. }
  51039. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51040. {
  51041. int totalMaximums = 0;
  51042. for (int i = startIndex; i < endIndex; ++i)
  51043. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51044. return totalMaximums;
  51045. }
  51046. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51047. {
  51048. for (int i = 0; i < items.size(); ++i)
  51049. {
  51050. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51051. layout->preferredSize
  51052. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51053. : getItemCurrentAbsoluteSize (i);
  51054. }
  51055. }
  51056. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51057. {
  51058. if (size < 0)
  51059. size *= -totalSpace;
  51060. return roundToInt (size);
  51061. }
  51062. END_JUCE_NAMESPACE
  51063. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51064. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51065. BEGIN_JUCE_NAMESPACE
  51066. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51067. const int itemIndex_,
  51068. const bool isVertical_)
  51069. : layout (layout_),
  51070. itemIndex (itemIndex_),
  51071. isVertical (isVertical_)
  51072. {
  51073. setRepaintsOnMouseActivity (true);
  51074. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51075. : MouseCursor::UpDownResizeCursor));
  51076. }
  51077. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51078. {
  51079. }
  51080. void StretchableLayoutResizerBar::paint (Graphics& g)
  51081. {
  51082. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51083. getWidth(), getHeight(),
  51084. isVertical,
  51085. isMouseOver(),
  51086. isMouseButtonDown());
  51087. }
  51088. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51089. {
  51090. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51091. }
  51092. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51093. {
  51094. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51095. : e.getDistanceFromDragStartY());
  51096. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51097. {
  51098. layout->setItemPosition (itemIndex, desiredPos);
  51099. hasBeenMoved();
  51100. }
  51101. }
  51102. void StretchableLayoutResizerBar::hasBeenMoved()
  51103. {
  51104. if (getParentComponent() != 0)
  51105. getParentComponent()->resized();
  51106. }
  51107. END_JUCE_NAMESPACE
  51108. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51109. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51110. BEGIN_JUCE_NAMESPACE
  51111. StretchableObjectResizer::StretchableObjectResizer()
  51112. {
  51113. }
  51114. StretchableObjectResizer::~StretchableObjectResizer()
  51115. {
  51116. }
  51117. void StretchableObjectResizer::addItem (const double size,
  51118. const double minSize, const double maxSize,
  51119. const int order)
  51120. {
  51121. // the order must be >= 0 but less than the maximum integer value.
  51122. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51123. Item* const item = new Item();
  51124. item->size = size;
  51125. item->minSize = minSize;
  51126. item->maxSize = maxSize;
  51127. item->order = order;
  51128. items.add (item);
  51129. }
  51130. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51131. {
  51132. const Item* const it = items [index];
  51133. return it != 0 ? it->size : 0;
  51134. }
  51135. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51136. {
  51137. int order = 0;
  51138. for (;;)
  51139. {
  51140. double currentSize = 0;
  51141. double minSize = 0;
  51142. double maxSize = 0;
  51143. int nextHighestOrder = std::numeric_limits<int>::max();
  51144. for (int i = 0; i < items.size(); ++i)
  51145. {
  51146. const Item* const it = items.getUnchecked(i);
  51147. currentSize += it->size;
  51148. if (it->order <= order)
  51149. {
  51150. minSize += it->minSize;
  51151. maxSize += it->maxSize;
  51152. }
  51153. else
  51154. {
  51155. minSize += it->size;
  51156. maxSize += it->size;
  51157. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51158. }
  51159. }
  51160. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51161. if (thisIterationTarget >= currentSize)
  51162. {
  51163. const double availableExtraSpace = maxSize - currentSize;
  51164. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51165. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51166. for (int i = 0; i < items.size(); ++i)
  51167. {
  51168. Item* const it = items.getUnchecked(i);
  51169. if (it->order <= order)
  51170. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51171. }
  51172. }
  51173. else
  51174. {
  51175. const double amountOfSlack = currentSize - minSize;
  51176. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51177. const double scale = targetAmountOfSlack / amountOfSlack;
  51178. for (int i = 0; i < items.size(); ++i)
  51179. {
  51180. Item* const it = items.getUnchecked(i);
  51181. if (it->order <= order)
  51182. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51183. }
  51184. }
  51185. if (nextHighestOrder < std::numeric_limits<int>::max())
  51186. order = nextHighestOrder;
  51187. else
  51188. break;
  51189. }
  51190. }
  51191. END_JUCE_NAMESPACE
  51192. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51193. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51194. BEGIN_JUCE_NAMESPACE
  51195. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51196. : Button (name),
  51197. owner (owner_),
  51198. overlapPixels (0)
  51199. {
  51200. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51201. setComponentEffect (&shadow);
  51202. setWantsKeyboardFocus (false);
  51203. }
  51204. TabBarButton::~TabBarButton()
  51205. {
  51206. }
  51207. int TabBarButton::getIndex() const
  51208. {
  51209. return owner.indexOfTabButton (this);
  51210. }
  51211. void TabBarButton::paintButton (Graphics& g,
  51212. bool isMouseOverButton,
  51213. bool isButtonDown)
  51214. {
  51215. const Rectangle<int> area (getActiveArea());
  51216. g.setOrigin (area.getX(), area.getY());
  51217. getLookAndFeel()
  51218. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51219. owner.getTabBackgroundColour (getIndex()),
  51220. getIndex(), getButtonText(), *this,
  51221. owner.getOrientation(),
  51222. isMouseOverButton, isButtonDown,
  51223. getToggleState());
  51224. }
  51225. void TabBarButton::clicked (const ModifierKeys& mods)
  51226. {
  51227. if (mods.isPopupMenu())
  51228. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51229. else
  51230. owner.setCurrentTabIndex (getIndex());
  51231. }
  51232. bool TabBarButton::hitTest (int mx, int my)
  51233. {
  51234. const Rectangle<int> area (getActiveArea());
  51235. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51236. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51237. {
  51238. if (isPositiveAndBelow (mx, getWidth())
  51239. && my >= area.getY() + overlapPixels
  51240. && my < area.getBottom() - overlapPixels)
  51241. return true;
  51242. }
  51243. else
  51244. {
  51245. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51246. && isPositiveAndBelow (my, getHeight()))
  51247. return true;
  51248. }
  51249. Path p;
  51250. getLookAndFeel()
  51251. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51252. owner.getOrientation(), false, false, getToggleState());
  51253. return p.contains ((float) (mx - area.getX()),
  51254. (float) (my - area.getY()));
  51255. }
  51256. int TabBarButton::getBestTabLength (const int depth)
  51257. {
  51258. return jlimit (depth * 2,
  51259. depth * 7,
  51260. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51261. }
  51262. const Rectangle<int> TabBarButton::getActiveArea()
  51263. {
  51264. Rectangle<int> r (getLocalBounds());
  51265. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51266. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51267. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51268. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51269. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51270. return r;
  51271. }
  51272. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51273. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51274. {
  51275. public:
  51276. BehindFrontTabComp (TabbedButtonBar& owner_)
  51277. : owner (owner_)
  51278. {
  51279. setInterceptsMouseClicks (false, false);
  51280. }
  51281. void paint (Graphics& g)
  51282. {
  51283. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51284. owner, owner.getOrientation());
  51285. }
  51286. void enablementChanged()
  51287. {
  51288. repaint();
  51289. }
  51290. void buttonClicked (Button*)
  51291. {
  51292. owner.showExtraItemsMenu();
  51293. }
  51294. private:
  51295. TabbedButtonBar& owner;
  51296. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51297. };
  51298. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51299. : orientation (orientation_),
  51300. minimumScale (0.7),
  51301. currentTabIndex (-1)
  51302. {
  51303. setInterceptsMouseClicks (false, true);
  51304. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51305. setFocusContainer (true);
  51306. }
  51307. TabbedButtonBar::~TabbedButtonBar()
  51308. {
  51309. tabs.clear();
  51310. extraTabsButton = 0;
  51311. }
  51312. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51313. {
  51314. orientation = newOrientation;
  51315. for (int i = getNumChildComponents(); --i >= 0;)
  51316. getChildComponent (i)->resized();
  51317. resized();
  51318. }
  51319. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51320. {
  51321. return new TabBarButton (name, *this);
  51322. }
  51323. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51324. {
  51325. minimumScale = newMinimumScale;
  51326. resized();
  51327. }
  51328. void TabbedButtonBar::clearTabs()
  51329. {
  51330. tabs.clear();
  51331. extraTabsButton = 0;
  51332. setCurrentTabIndex (-1);
  51333. }
  51334. void TabbedButtonBar::addTab (const String& tabName,
  51335. const Colour& tabBackgroundColour,
  51336. int insertIndex)
  51337. {
  51338. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51339. if (tabName.isNotEmpty())
  51340. {
  51341. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51342. insertIndex = tabs.size();
  51343. TabInfo* newTab = new TabInfo();
  51344. newTab->name = tabName;
  51345. newTab->colour = tabBackgroundColour;
  51346. newTab->component = createTabButton (tabName, insertIndex);
  51347. jassert (newTab->component != 0);
  51348. tabs.insert (insertIndex, newTab);
  51349. addAndMakeVisible (newTab->component, insertIndex);
  51350. resized();
  51351. if (currentTabIndex < 0)
  51352. setCurrentTabIndex (0);
  51353. }
  51354. }
  51355. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51356. {
  51357. TabInfo* const tab = tabs [tabIndex];
  51358. if (tab != 0 && tab->name != newName)
  51359. {
  51360. tab->name = newName;
  51361. tab->component->setButtonText (newName);
  51362. resized();
  51363. }
  51364. }
  51365. void TabbedButtonBar::removeTab (const int tabIndex)
  51366. {
  51367. if (tabs [tabIndex] != 0)
  51368. {
  51369. const int oldTabIndex = currentTabIndex;
  51370. if (currentTabIndex == tabIndex)
  51371. currentTabIndex = -1;
  51372. tabs.remove (tabIndex);
  51373. resized();
  51374. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51375. }
  51376. }
  51377. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51378. {
  51379. tabs.move (currentIndex, newIndex);
  51380. resized();
  51381. }
  51382. int TabbedButtonBar::getNumTabs() const
  51383. {
  51384. return tabs.size();
  51385. }
  51386. const String TabbedButtonBar::getCurrentTabName() const
  51387. {
  51388. TabInfo* tab = tabs [currentTabIndex];
  51389. return tab == 0 ? String::empty : tab->name;
  51390. }
  51391. const StringArray TabbedButtonBar::getTabNames() const
  51392. {
  51393. StringArray names;
  51394. for (int i = 0; i < tabs.size(); ++i)
  51395. names.add (tabs.getUnchecked(i)->name);
  51396. return names;
  51397. }
  51398. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51399. {
  51400. if (currentTabIndex != newIndex)
  51401. {
  51402. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51403. newIndex = -1;
  51404. currentTabIndex = newIndex;
  51405. for (int i = 0; i < tabs.size(); ++i)
  51406. {
  51407. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51408. tb->setToggleState (i == newIndex, false);
  51409. }
  51410. resized();
  51411. if (sendChangeMessage_)
  51412. sendChangeMessage();
  51413. currentTabChanged (newIndex, getCurrentTabName());
  51414. }
  51415. }
  51416. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51417. {
  51418. TabInfo* const tab = tabs[index];
  51419. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51420. }
  51421. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51422. {
  51423. for (int i = tabs.size(); --i >= 0;)
  51424. if (tabs.getUnchecked(i)->component == button)
  51425. return i;
  51426. return -1;
  51427. }
  51428. void TabbedButtonBar::lookAndFeelChanged()
  51429. {
  51430. extraTabsButton = 0;
  51431. resized();
  51432. }
  51433. void TabbedButtonBar::resized()
  51434. {
  51435. int depth = getWidth();
  51436. int length = getHeight();
  51437. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51438. swapVariables (depth, length);
  51439. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51440. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51441. int i, totalLength = overlap;
  51442. int numVisibleButtons = tabs.size();
  51443. for (i = 0; i < tabs.size(); ++i)
  51444. {
  51445. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51446. totalLength += tb->getBestTabLength (depth) - overlap;
  51447. tb->overlapPixels = overlap / 2;
  51448. }
  51449. double scale = 1.0;
  51450. if (totalLength > length)
  51451. scale = jmax (minimumScale, length / (double) totalLength);
  51452. const bool isTooBig = totalLength * scale > length;
  51453. int tabsButtonPos = 0;
  51454. if (isTooBig)
  51455. {
  51456. if (extraTabsButton == 0)
  51457. {
  51458. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51459. extraTabsButton->addListener (behindFrontTab);
  51460. extraTabsButton->setAlwaysOnTop (true);
  51461. extraTabsButton->setTriggeredOnMouseDown (true);
  51462. }
  51463. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51464. extraTabsButton->setSize (buttonSize, buttonSize);
  51465. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51466. {
  51467. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51468. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51469. }
  51470. else
  51471. {
  51472. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51473. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51474. }
  51475. totalLength = 0;
  51476. for (i = 0; i < tabs.size(); ++i)
  51477. {
  51478. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51479. const int newLength = totalLength + tb->getBestTabLength (depth);
  51480. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51481. {
  51482. totalLength += overlap;
  51483. break;
  51484. }
  51485. numVisibleButtons = i + 1;
  51486. totalLength = newLength - overlap;
  51487. }
  51488. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51489. }
  51490. else
  51491. {
  51492. extraTabsButton = 0;
  51493. }
  51494. int pos = 0;
  51495. TabBarButton* frontTab = 0;
  51496. for (i = 0; i < tabs.size(); ++i)
  51497. {
  51498. TabBarButton* const tb = getTabButton (i);
  51499. if (tb != 0)
  51500. {
  51501. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51502. if (i < numVisibleButtons)
  51503. {
  51504. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51505. tb->setBounds (pos, 0, bestLength, getHeight());
  51506. else
  51507. tb->setBounds (0, pos, getWidth(), bestLength);
  51508. tb->toBack();
  51509. if (i == currentTabIndex)
  51510. frontTab = tb;
  51511. tb->setVisible (true);
  51512. }
  51513. else
  51514. {
  51515. tb->setVisible (false);
  51516. }
  51517. pos += bestLength - overlap;
  51518. }
  51519. }
  51520. behindFrontTab->setBounds (getLocalBounds());
  51521. if (frontTab != 0)
  51522. {
  51523. frontTab->toFront (false);
  51524. behindFrontTab->toBehind (frontTab);
  51525. }
  51526. }
  51527. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51528. {
  51529. TabInfo* const tab = tabs [tabIndex];
  51530. return tab == 0 ? Colours::white : tab->colour;
  51531. }
  51532. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51533. {
  51534. TabInfo* const tab = tabs [tabIndex];
  51535. if (tab != 0 && tab->colour != newColour)
  51536. {
  51537. tab->colour = newColour;
  51538. repaint();
  51539. }
  51540. }
  51541. void TabbedButtonBar::showExtraItemsMenu()
  51542. {
  51543. PopupMenu m;
  51544. for (int i = 0; i < tabs.size(); ++i)
  51545. {
  51546. const TabInfo* const tab = tabs.getUnchecked(i);
  51547. if (! tab->component->isVisible())
  51548. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51549. }
  51550. const int res = m.showAt (extraTabsButton);
  51551. if (res != 0)
  51552. setCurrentTabIndex (res - 1);
  51553. }
  51554. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51555. {
  51556. }
  51557. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51558. {
  51559. }
  51560. END_JUCE_NAMESPACE
  51561. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51562. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51563. BEGIN_JUCE_NAMESPACE
  51564. namespace TabbedComponentHelpers
  51565. {
  51566. const Identifier deleteComponentId ("deleteByTabComp_");
  51567. void deleteIfNecessary (Component* const comp)
  51568. {
  51569. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51570. delete comp;
  51571. }
  51572. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
  51573. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51574. {
  51575. switch (orientation)
  51576. {
  51577. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51578. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51579. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51580. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51581. default: jassertfalse; break;
  51582. }
  51583. return Rectangle<int>();
  51584. }
  51585. }
  51586. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51587. {
  51588. public:
  51589. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51590. : TabbedButtonBar (orientation_),
  51591. owner (owner_)
  51592. {
  51593. }
  51594. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51595. {
  51596. owner.changeCallback (newCurrentTabIndex, newTabName);
  51597. }
  51598. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51599. {
  51600. owner.popupMenuClickOnTab (tabIndex, tabName);
  51601. }
  51602. const Colour getTabBackgroundColour (const int tabIndex)
  51603. {
  51604. return owner.tabs->getTabBackgroundColour (tabIndex);
  51605. }
  51606. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51607. {
  51608. return owner.createTabButton (tabName, tabIndex);
  51609. }
  51610. private:
  51611. TabbedComponent& owner;
  51612. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51613. };
  51614. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51615. : tabDepth (30),
  51616. outlineThickness (1),
  51617. edgeIndent (0)
  51618. {
  51619. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51620. }
  51621. TabbedComponent::~TabbedComponent()
  51622. {
  51623. clearTabs();
  51624. tabs = 0;
  51625. }
  51626. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51627. {
  51628. tabs->setOrientation (orientation);
  51629. resized();
  51630. }
  51631. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51632. {
  51633. return tabs->getOrientation();
  51634. }
  51635. void TabbedComponent::setTabBarDepth (const int newDepth)
  51636. {
  51637. if (tabDepth != newDepth)
  51638. {
  51639. tabDepth = newDepth;
  51640. resized();
  51641. }
  51642. }
  51643. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51644. {
  51645. return new TabBarButton (tabName, *tabs);
  51646. }
  51647. void TabbedComponent::clearTabs()
  51648. {
  51649. if (panelComponent != 0)
  51650. {
  51651. panelComponent->setVisible (false);
  51652. removeChildComponent (panelComponent);
  51653. panelComponent = 0;
  51654. }
  51655. tabs->clearTabs();
  51656. for (int i = contentComponents.size(); --i >= 0;)
  51657. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51658. contentComponents.clear();
  51659. }
  51660. void TabbedComponent::addTab (const String& tabName,
  51661. const Colour& tabBackgroundColour,
  51662. Component* const contentComponent,
  51663. const bool deleteComponentWhenNotNeeded,
  51664. const int insertIndex)
  51665. {
  51666. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51667. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51668. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51669. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51670. }
  51671. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51672. {
  51673. tabs->setTabName (tabIndex, newName);
  51674. }
  51675. void TabbedComponent::removeTab (const int tabIndex)
  51676. {
  51677. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51678. {
  51679. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51680. contentComponents.remove (tabIndex);
  51681. tabs->removeTab (tabIndex);
  51682. }
  51683. }
  51684. int TabbedComponent::getNumTabs() const
  51685. {
  51686. return tabs->getNumTabs();
  51687. }
  51688. const StringArray TabbedComponent::getTabNames() const
  51689. {
  51690. return tabs->getTabNames();
  51691. }
  51692. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51693. {
  51694. return contentComponents [tabIndex];
  51695. }
  51696. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51697. {
  51698. return tabs->getTabBackgroundColour (tabIndex);
  51699. }
  51700. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51701. {
  51702. tabs->setTabBackgroundColour (tabIndex, newColour);
  51703. if (getCurrentTabIndex() == tabIndex)
  51704. repaint();
  51705. }
  51706. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51707. {
  51708. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51709. }
  51710. int TabbedComponent::getCurrentTabIndex() const
  51711. {
  51712. return tabs->getCurrentTabIndex();
  51713. }
  51714. const String TabbedComponent::getCurrentTabName() const
  51715. {
  51716. return tabs->getCurrentTabName();
  51717. }
  51718. void TabbedComponent::setOutline (const int thickness)
  51719. {
  51720. outlineThickness = thickness;
  51721. resized();
  51722. repaint();
  51723. }
  51724. void TabbedComponent::setIndent (const int indentThickness)
  51725. {
  51726. edgeIndent = indentThickness;
  51727. resized();
  51728. repaint();
  51729. }
  51730. void TabbedComponent::paint (Graphics& g)
  51731. {
  51732. g.fillAll (findColour (backgroundColourId));
  51733. Rectangle<int> content (getLocalBounds());
  51734. BorderSize<int> outline (outlineThickness);
  51735. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  51736. g.reduceClipRegion (content);
  51737. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51738. if (outlineThickness > 0)
  51739. {
  51740. RectangleList rl (content);
  51741. rl.subtract (outline.subtractedFrom (content));
  51742. g.reduceClipRegion (rl);
  51743. g.fillAll (findColour (outlineColourId));
  51744. }
  51745. }
  51746. void TabbedComponent::resized()
  51747. {
  51748. Rectangle<int> content (getLocalBounds());
  51749. BorderSize<int> outline (outlineThickness);
  51750. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  51751. content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  51752. for (int i = contentComponents.size(); --i >= 0;)
  51753. if (contentComponents.getReference (i) != 0)
  51754. contentComponents.getReference (i)->setBounds (content);
  51755. }
  51756. void TabbedComponent::lookAndFeelChanged()
  51757. {
  51758. for (int i = contentComponents.size(); --i >= 0;)
  51759. if (contentComponents.getReference (i) != 0)
  51760. contentComponents.getReference (i)->lookAndFeelChanged();
  51761. }
  51762. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  51763. {
  51764. if (panelComponent != 0)
  51765. {
  51766. panelComponent->setVisible (false);
  51767. removeChildComponent (panelComponent);
  51768. panelComponent = 0;
  51769. }
  51770. if (getCurrentTabIndex() >= 0)
  51771. {
  51772. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51773. if (panelComponent != 0)
  51774. {
  51775. // do these ops as two stages instead of addAndMakeVisible() so that the
  51776. // component has always got a parent when it gets the visibilityChanged() callback
  51777. addChildComponent (panelComponent);
  51778. panelComponent->setVisible (true);
  51779. panelComponent->toFront (true);
  51780. }
  51781. repaint();
  51782. }
  51783. resized();
  51784. currentTabChanged (newCurrentTabIndex, newTabName);
  51785. }
  51786. void TabbedComponent::currentTabChanged (const int, const String&) {}
  51787. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  51788. END_JUCE_NAMESPACE
  51789. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51790. /*** Start of inlined file: juce_Viewport.cpp ***/
  51791. BEGIN_JUCE_NAMESPACE
  51792. Viewport::Viewport (const String& componentName)
  51793. : Component (componentName),
  51794. scrollBarThickness (0),
  51795. singleStepX (16),
  51796. singleStepY (16),
  51797. showHScrollbar (true),
  51798. showVScrollbar (true),
  51799. verticalScrollBar (true),
  51800. horizontalScrollBar (false)
  51801. {
  51802. // content holder is used to clip the contents so they don't overlap the scrollbars
  51803. addAndMakeVisible (&contentHolder);
  51804. contentHolder.setInterceptsMouseClicks (false, true);
  51805. addChildComponent (&verticalScrollBar);
  51806. addChildComponent (&horizontalScrollBar);
  51807. verticalScrollBar.addListener (this);
  51808. horizontalScrollBar.addListener (this);
  51809. setInterceptsMouseClicks (false, true);
  51810. setWantsKeyboardFocus (true);
  51811. }
  51812. Viewport::~Viewport()
  51813. {
  51814. deleteContentComp();
  51815. }
  51816. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  51817. {
  51818. }
  51819. void Viewport::deleteContentComp()
  51820. {
  51821. // This sets the content comp to a null pointer before deleting the old one, in case
  51822. // anything tries to use the old one while it's in mid-deletion..
  51823. ScopedPointer<Component> oldCompDeleter (contentComp);
  51824. contentComp = 0;
  51825. }
  51826. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51827. {
  51828. if (contentComp.get() != newViewedComponent)
  51829. {
  51830. deleteContentComp();
  51831. contentComp = newViewedComponent;
  51832. if (contentComp != 0)
  51833. {
  51834. contentHolder.addAndMakeVisible (contentComp);
  51835. setViewPosition (0, 0);
  51836. contentComp->addComponentListener (this);
  51837. }
  51838. updateVisibleArea();
  51839. }
  51840. }
  51841. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51842. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51843. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51844. {
  51845. if (contentComp != 0)
  51846. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51847. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51848. }
  51849. void Viewport::setViewPosition (const Point<int>& newPosition)
  51850. {
  51851. setViewPosition (newPosition.getX(), newPosition.getY());
  51852. }
  51853. void Viewport::setViewPositionProportionately (const double x, const double y)
  51854. {
  51855. if (contentComp != 0)
  51856. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51857. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51858. }
  51859. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51860. {
  51861. if (contentComp != 0)
  51862. {
  51863. int dx = 0, dy = 0;
  51864. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51865. {
  51866. if (mouseX < activeBorderThickness)
  51867. dx = activeBorderThickness - mouseX;
  51868. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51869. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51870. if (dx < 0)
  51871. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51872. else
  51873. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51874. }
  51875. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51876. {
  51877. if (mouseY < activeBorderThickness)
  51878. dy = activeBorderThickness - mouseY;
  51879. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51880. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51881. if (dy < 0)
  51882. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51883. else
  51884. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51885. }
  51886. if (dx != 0 || dy != 0)
  51887. {
  51888. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51889. contentComp->getY() + dy);
  51890. return true;
  51891. }
  51892. }
  51893. return false;
  51894. }
  51895. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51896. {
  51897. updateVisibleArea();
  51898. }
  51899. void Viewport::resized()
  51900. {
  51901. updateVisibleArea();
  51902. }
  51903. void Viewport::updateVisibleArea()
  51904. {
  51905. const int scrollbarWidth = getScrollBarThickness();
  51906. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51907. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51908. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51909. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51910. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51911. Rectangle<int> contentArea (getLocalBounds());
  51912. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51913. {
  51914. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51915. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51916. if (vBarVisible)
  51917. contentArea.setWidth (getWidth() - scrollbarWidth);
  51918. if (hBarVisible)
  51919. contentArea.setHeight (getHeight() - scrollbarWidth);
  51920. if (! contentArea.contains (contentComp->getBounds()))
  51921. {
  51922. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51923. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51924. }
  51925. }
  51926. if (vBarVisible)
  51927. contentArea.setWidth (getWidth() - scrollbarWidth);
  51928. if (hBarVisible)
  51929. contentArea.setHeight (getHeight() - scrollbarWidth);
  51930. contentHolder.setBounds (contentArea);
  51931. Rectangle<int> contentBounds;
  51932. if (contentComp != 0)
  51933. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  51934. Point<int> visibleOrigin (-contentBounds.getPosition());
  51935. if (hBarVisible)
  51936. {
  51937. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51938. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51939. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51940. horizontalScrollBar.setSingleStepSize (singleStepX);
  51941. horizontalScrollBar.cancelPendingUpdate();
  51942. }
  51943. else if (canShowHBar)
  51944. {
  51945. visibleOrigin.setX (0);
  51946. }
  51947. if (vBarVisible)
  51948. {
  51949. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51950. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51951. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51952. verticalScrollBar.setSingleStepSize (singleStepY);
  51953. verticalScrollBar.cancelPendingUpdate();
  51954. }
  51955. else if (canShowVBar)
  51956. {
  51957. visibleOrigin.setY (0);
  51958. }
  51959. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51960. horizontalScrollBar.setVisible (hBarVisible);
  51961. verticalScrollBar.setVisible (vBarVisible);
  51962. setViewPosition (visibleOrigin);
  51963. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51964. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51965. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51966. if (lastVisibleArea != visibleArea)
  51967. {
  51968. lastVisibleArea = visibleArea;
  51969. visibleAreaChanged (visibleArea);
  51970. }
  51971. horizontalScrollBar.handleUpdateNowIfNeeded();
  51972. verticalScrollBar.handleUpdateNowIfNeeded();
  51973. }
  51974. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51975. {
  51976. if (singleStepX != stepX || singleStepY != stepY)
  51977. {
  51978. singleStepX = stepX;
  51979. singleStepY = stepY;
  51980. updateVisibleArea();
  51981. }
  51982. }
  51983. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51984. const bool showHorizontalScrollbarIfNeeded)
  51985. {
  51986. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51987. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51988. {
  51989. showVScrollbar = showVerticalScrollbarIfNeeded;
  51990. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51991. updateVisibleArea();
  51992. }
  51993. }
  51994. void Viewport::setScrollBarThickness (const int thickness)
  51995. {
  51996. if (scrollBarThickness != thickness)
  51997. {
  51998. scrollBarThickness = thickness;
  51999. updateVisibleArea();
  52000. }
  52001. }
  52002. int Viewport::getScrollBarThickness() const
  52003. {
  52004. return scrollBarThickness > 0 ? scrollBarThickness
  52005. : getLookAndFeel().getDefaultScrollbarWidth();
  52006. }
  52007. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52008. {
  52009. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52010. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52011. }
  52012. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52013. {
  52014. const int newRangeStartInt = roundToInt (newRangeStart);
  52015. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52016. {
  52017. setViewPosition (newRangeStartInt, getViewPositionY());
  52018. }
  52019. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52020. {
  52021. setViewPosition (getViewPositionX(), newRangeStartInt);
  52022. }
  52023. }
  52024. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52025. {
  52026. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52027. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52028. }
  52029. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52030. {
  52031. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52032. {
  52033. const bool hasVertBar = verticalScrollBar.isVisible();
  52034. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52035. if (hasHorzBar || hasVertBar)
  52036. {
  52037. if (wheelIncrementX != 0)
  52038. {
  52039. wheelIncrementX *= 14.0f * singleStepX;
  52040. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52041. : jmax (wheelIncrementX, 1.0f);
  52042. }
  52043. if (wheelIncrementY != 0)
  52044. {
  52045. wheelIncrementY *= 14.0f * singleStepY;
  52046. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52047. : jmax (wheelIncrementY, 1.0f);
  52048. }
  52049. Point<int> pos (getViewPosition());
  52050. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52051. {
  52052. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52053. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52054. }
  52055. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52056. {
  52057. if (wheelIncrementX == 0 && ! hasVertBar)
  52058. wheelIncrementX = wheelIncrementY;
  52059. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52060. }
  52061. else if (hasVertBar && wheelIncrementY != 0)
  52062. {
  52063. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52064. }
  52065. if (pos != getViewPosition())
  52066. {
  52067. setViewPosition (pos);
  52068. return true;
  52069. }
  52070. }
  52071. }
  52072. return false;
  52073. }
  52074. bool Viewport::keyPressed (const KeyPress& key)
  52075. {
  52076. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52077. || key.isKeyCode (KeyPress::downKey)
  52078. || key.isKeyCode (KeyPress::pageUpKey)
  52079. || key.isKeyCode (KeyPress::pageDownKey)
  52080. || key.isKeyCode (KeyPress::homeKey)
  52081. || key.isKeyCode (KeyPress::endKey);
  52082. if (verticalScrollBar.isVisible() && isUpDownKey)
  52083. return verticalScrollBar.keyPressed (key);
  52084. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52085. || key.isKeyCode (KeyPress::rightKey);
  52086. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52087. return horizontalScrollBar.keyPressed (key);
  52088. return false;
  52089. }
  52090. END_JUCE_NAMESPACE
  52091. /*** End of inlined file: juce_Viewport.cpp ***/
  52092. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52093. BEGIN_JUCE_NAMESPACE
  52094. namespace LookAndFeelHelpers
  52095. {
  52096. void createRoundedPath (Path& p,
  52097. const float x, const float y,
  52098. const float w, const float h,
  52099. const float cs,
  52100. const bool curveTopLeft, const bool curveTopRight,
  52101. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52102. {
  52103. const float cs2 = 2.0f * cs;
  52104. if (curveTopLeft)
  52105. {
  52106. p.startNewSubPath (x, y + cs);
  52107. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52108. }
  52109. else
  52110. {
  52111. p.startNewSubPath (x, y);
  52112. }
  52113. if (curveTopRight)
  52114. {
  52115. p.lineTo (x + w - cs, y);
  52116. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52117. }
  52118. else
  52119. {
  52120. p.lineTo (x + w, y);
  52121. }
  52122. if (curveBottomRight)
  52123. {
  52124. p.lineTo (x + w, y + h - cs);
  52125. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52126. }
  52127. else
  52128. {
  52129. p.lineTo (x + w, y + h);
  52130. }
  52131. if (curveBottomLeft)
  52132. {
  52133. p.lineTo (x + cs, y + h);
  52134. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52135. }
  52136. else
  52137. {
  52138. p.lineTo (x, y + h);
  52139. }
  52140. p.closeSubPath();
  52141. }
  52142. const Colour createBaseColour (const Colour& buttonColour,
  52143. const bool hasKeyboardFocus,
  52144. const bool isMouseOverButton,
  52145. const bool isButtonDown) throw()
  52146. {
  52147. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52148. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52149. if (isButtonDown)
  52150. return baseColour.contrasting (0.2f);
  52151. else if (isMouseOverButton)
  52152. return baseColour.contrasting (0.1f);
  52153. return baseColour;
  52154. }
  52155. const TextLayout layoutTooltipText (const String& text) throw()
  52156. {
  52157. const float tooltipFontSize = 12.0f;
  52158. const int maxToolTipWidth = 400;
  52159. const Font f (tooltipFontSize, Font::bold);
  52160. TextLayout tl (text, f);
  52161. tl.layout (maxToolTipWidth, Justification::left, true);
  52162. return tl;
  52163. }
  52164. LookAndFeel* defaultLF = 0;
  52165. LookAndFeel* currentDefaultLF = 0;
  52166. }
  52167. LookAndFeel::LookAndFeel()
  52168. {
  52169. /* if this fails it means you're trying to create a LookAndFeel object before
  52170. the static Colours have been initialised. That ain't gonna work. It probably
  52171. means that you're using a static LookAndFeel object and that your compiler has
  52172. decided to intialise it before the Colours class.
  52173. */
  52174. jassert (Colours::white == Colour (0xffffffff));
  52175. // set up the standard set of colours..
  52176. const int textButtonColour = 0xffbbbbff;
  52177. const int textHighlightColour = 0x401111ee;
  52178. const int standardOutlineColour = 0xb2808080;
  52179. static const int standardColours[] =
  52180. {
  52181. TextButton::buttonColourId, textButtonColour,
  52182. TextButton::buttonOnColourId, 0xff4444ff,
  52183. TextButton::textColourOnId, 0xff000000,
  52184. TextButton::textColourOffId, 0xff000000,
  52185. ComboBox::buttonColourId, 0xffbbbbff,
  52186. ComboBox::outlineColourId, standardOutlineColour,
  52187. ToggleButton::textColourId, 0xff000000,
  52188. TextEditor::backgroundColourId, 0xffffffff,
  52189. TextEditor::textColourId, 0xff000000,
  52190. TextEditor::highlightColourId, textHighlightColour,
  52191. TextEditor::highlightedTextColourId, 0xff000000,
  52192. TextEditor::caretColourId, 0xff000000,
  52193. TextEditor::outlineColourId, 0x00000000,
  52194. TextEditor::focusedOutlineColourId, textButtonColour,
  52195. TextEditor::shadowColourId, 0x38000000,
  52196. Label::backgroundColourId, 0x00000000,
  52197. Label::textColourId, 0xff000000,
  52198. Label::outlineColourId, 0x00000000,
  52199. ScrollBar::backgroundColourId, 0x00000000,
  52200. ScrollBar::thumbColourId, 0xffffffff,
  52201. TreeView::linesColourId, 0x4c000000,
  52202. TreeView::backgroundColourId, 0x00000000,
  52203. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52204. PopupMenu::backgroundColourId, 0xffffffff,
  52205. PopupMenu::textColourId, 0xff000000,
  52206. PopupMenu::headerTextColourId, 0xff000000,
  52207. PopupMenu::highlightedTextColourId, 0xffffffff,
  52208. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52209. ComboBox::textColourId, 0xff000000,
  52210. ComboBox::backgroundColourId, 0xffffffff,
  52211. ComboBox::arrowColourId, 0x99000000,
  52212. ListBox::backgroundColourId, 0xffffffff,
  52213. ListBox::outlineColourId, standardOutlineColour,
  52214. ListBox::textColourId, 0xff000000,
  52215. Slider::backgroundColourId, 0x00000000,
  52216. Slider::thumbColourId, textButtonColour,
  52217. Slider::trackColourId, 0x7fffffff,
  52218. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52219. Slider::rotarySliderOutlineColourId, 0x66000000,
  52220. Slider::textBoxTextColourId, 0xff000000,
  52221. Slider::textBoxBackgroundColourId, 0xffffffff,
  52222. Slider::textBoxHighlightColourId, textHighlightColour,
  52223. Slider::textBoxOutlineColourId, standardOutlineColour,
  52224. ResizableWindow::backgroundColourId, 0xff777777,
  52225. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52226. AlertWindow::backgroundColourId, 0xffededed,
  52227. AlertWindow::textColourId, 0xff000000,
  52228. AlertWindow::outlineColourId, 0xff666666,
  52229. ProgressBar::backgroundColourId, 0xffeeeeee,
  52230. ProgressBar::foregroundColourId, 0xffaaaaee,
  52231. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52232. TooltipWindow::textColourId, 0xff000000,
  52233. TooltipWindow::outlineColourId, 0x4c000000,
  52234. TabbedComponent::backgroundColourId, 0x00000000,
  52235. TabbedComponent::outlineColourId, 0xff777777,
  52236. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52237. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52238. Toolbar::backgroundColourId, 0xfff6f8f9,
  52239. Toolbar::separatorColourId, 0x4c000000,
  52240. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52241. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52242. Toolbar::labelTextColourId, 0xff000000,
  52243. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52244. HyperlinkButton::textColourId, 0xcc1111ee,
  52245. GroupComponent::outlineColourId, 0x66000000,
  52246. GroupComponent::textColourId, 0xff000000,
  52247. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52248. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52249. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52250. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52251. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52252. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52253. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52254. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52255. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52256. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52257. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52258. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52259. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52260. CodeEditorComponent::caretColourId, 0xff000000,
  52261. CodeEditorComponent::highlightColourId, textHighlightColour,
  52262. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52263. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52264. ColourSelector::labelTextColourId, 0xff000000,
  52265. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52266. KeyMappingEditorComponent::textColourId, 0xff000000,
  52267. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52268. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52269. DrawableButton::textColourId, 0xff000000,
  52270. };
  52271. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52272. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52273. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52274. if (defaultSansName.isEmpty())
  52275. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52276. defaultSans = defaultSansName;
  52277. defaultSerif = defaultSerifName;
  52278. defaultFixed = defaultFixedName;
  52279. Font::setFallbackFontName (defaultFallback);
  52280. }
  52281. LookAndFeel::~LookAndFeel()
  52282. {
  52283. if (this == LookAndFeelHelpers::currentDefaultLF)
  52284. setDefaultLookAndFeel (0);
  52285. }
  52286. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52287. {
  52288. const int index = colourIds.indexOf (colourId);
  52289. if (index >= 0)
  52290. return colours [index];
  52291. jassertfalse;
  52292. return Colours::black;
  52293. }
  52294. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52295. {
  52296. const int index = colourIds.indexOf (colourId);
  52297. if (index >= 0)
  52298. {
  52299. colours.set (index, colour);
  52300. }
  52301. else
  52302. {
  52303. colourIds.add (colourId);
  52304. colours.add (colour);
  52305. }
  52306. }
  52307. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52308. {
  52309. return colourIds.contains (colourId);
  52310. }
  52311. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52312. {
  52313. // if this happens, your app hasn't initialised itself properly.. if you're
  52314. // trying to hack your own main() function, have a look at
  52315. // JUCEApplication::initialiseForGUI()
  52316. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52317. return *LookAndFeelHelpers::currentDefaultLF;
  52318. }
  52319. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52320. {
  52321. using namespace LookAndFeelHelpers;
  52322. if (newDefaultLookAndFeel == 0)
  52323. {
  52324. if (defaultLF == 0)
  52325. defaultLF = new LookAndFeel();
  52326. newDefaultLookAndFeel = defaultLF;
  52327. }
  52328. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52329. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52330. {
  52331. Component* const c = Desktop::getInstance().getComponent (i);
  52332. if (c != 0)
  52333. c->sendLookAndFeelChange();
  52334. }
  52335. }
  52336. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52337. {
  52338. using namespace LookAndFeelHelpers;
  52339. if (currentDefaultLF == defaultLF)
  52340. currentDefaultLF = 0;
  52341. deleteAndZero (defaultLF);
  52342. }
  52343. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52344. {
  52345. String faceName (font.getTypefaceName());
  52346. if (faceName == Font::getDefaultSansSerifFontName())
  52347. faceName = defaultSans;
  52348. else if (faceName == Font::getDefaultSerifFontName())
  52349. faceName = defaultSerif;
  52350. else if (faceName == Font::getDefaultMonospacedFontName())
  52351. faceName = defaultFixed;
  52352. Font f (font);
  52353. f.setTypefaceName (faceName);
  52354. return Typeface::createSystemTypefaceFor (f);
  52355. }
  52356. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52357. {
  52358. defaultSans = newName;
  52359. }
  52360. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52361. {
  52362. return component.getMouseCursor();
  52363. }
  52364. void LookAndFeel::drawButtonBackground (Graphics& g,
  52365. Button& button,
  52366. const Colour& backgroundColour,
  52367. bool isMouseOverButton,
  52368. bool isButtonDown)
  52369. {
  52370. const int width = button.getWidth();
  52371. const int height = button.getHeight();
  52372. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52373. const float halfThickness = outlineThickness * 0.5f;
  52374. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52375. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52376. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52377. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52378. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52379. button.hasKeyboardFocus (true),
  52380. isMouseOverButton, isButtonDown)
  52381. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52382. drawGlassLozenge (g,
  52383. indentL,
  52384. indentT,
  52385. width - indentL - indentR,
  52386. height - indentT - indentB,
  52387. baseColour, outlineThickness, -1.0f,
  52388. button.isConnectedOnLeft(),
  52389. button.isConnectedOnRight(),
  52390. button.isConnectedOnTop(),
  52391. button.isConnectedOnBottom());
  52392. }
  52393. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52394. {
  52395. return button.getFont();
  52396. }
  52397. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52398. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52399. {
  52400. Font font (getFontForTextButton (button));
  52401. g.setFont (font);
  52402. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52403. : TextButton::textColourOffId)
  52404. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52405. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52406. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52407. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52408. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52409. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52410. g.drawFittedText (button.getButtonText(),
  52411. leftIndent,
  52412. yIndent,
  52413. button.getWidth() - leftIndent - rightIndent,
  52414. button.getHeight() - yIndent * 2,
  52415. Justification::centred, 2);
  52416. }
  52417. void LookAndFeel::drawTickBox (Graphics& g,
  52418. Component& component,
  52419. float x, float y, float w, float h,
  52420. const bool ticked,
  52421. const bool isEnabled,
  52422. const bool isMouseOverButton,
  52423. const bool isButtonDown)
  52424. {
  52425. const float boxSize = w * 0.7f;
  52426. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52427. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52428. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52429. true, isMouseOverButton, isButtonDown),
  52430. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52431. if (ticked)
  52432. {
  52433. Path tick;
  52434. tick.startNewSubPath (1.5f, 3.0f);
  52435. tick.lineTo (3.0f, 6.0f);
  52436. tick.lineTo (6.0f, 0.0f);
  52437. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52438. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52439. .translated (x, y));
  52440. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52441. }
  52442. }
  52443. void LookAndFeel::drawToggleButton (Graphics& g,
  52444. ToggleButton& button,
  52445. bool isMouseOverButton,
  52446. bool isButtonDown)
  52447. {
  52448. if (button.hasKeyboardFocus (true))
  52449. {
  52450. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52451. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52452. }
  52453. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52454. const float tickWidth = fontSize * 1.1f;
  52455. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52456. tickWidth, tickWidth,
  52457. button.getToggleState(),
  52458. button.isEnabled(),
  52459. isMouseOverButton,
  52460. isButtonDown);
  52461. g.setColour (button.findColour (ToggleButton::textColourId));
  52462. g.setFont (fontSize);
  52463. if (! button.isEnabled())
  52464. g.setOpacity (0.5f);
  52465. const int textX = (int) tickWidth + 5;
  52466. g.drawFittedText (button.getButtonText(),
  52467. textX, 0,
  52468. button.getWidth() - textX - 2, button.getHeight(),
  52469. Justification::centredLeft, 10);
  52470. }
  52471. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52472. {
  52473. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52474. const int tickWidth = jmin (24, button.getHeight());
  52475. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52476. button.getHeight());
  52477. }
  52478. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52479. const String& message,
  52480. const String& button1,
  52481. const String& button2,
  52482. const String& button3,
  52483. AlertWindow::AlertIconType iconType,
  52484. int numButtons,
  52485. Component* associatedComponent)
  52486. {
  52487. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52488. if (numButtons == 1)
  52489. {
  52490. aw->addButton (button1, 0,
  52491. KeyPress (KeyPress::escapeKey, 0, 0),
  52492. KeyPress (KeyPress::returnKey, 0, 0));
  52493. }
  52494. else
  52495. {
  52496. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52497. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52498. if (button1ShortCut == button2ShortCut)
  52499. button2ShortCut = KeyPress();
  52500. if (numButtons == 2)
  52501. {
  52502. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52503. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52504. }
  52505. else if (numButtons == 3)
  52506. {
  52507. aw->addButton (button1, 1, button1ShortCut);
  52508. aw->addButton (button2, 2, button2ShortCut);
  52509. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52510. }
  52511. }
  52512. return aw;
  52513. }
  52514. void LookAndFeel::drawAlertBox (Graphics& g,
  52515. AlertWindow& alert,
  52516. const Rectangle<int>& textArea,
  52517. TextLayout& textLayout)
  52518. {
  52519. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52520. int iconSpaceUsed = 0;
  52521. Justification alignment (Justification::horizontallyCentred);
  52522. const int iconWidth = 80;
  52523. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52524. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52525. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52526. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52527. iconSize, iconSize);
  52528. if (alert.getAlertType() != AlertWindow::NoIcon)
  52529. {
  52530. Path icon;
  52531. uint32 colour;
  52532. char character;
  52533. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52534. {
  52535. colour = 0x55ff5555;
  52536. character = '!';
  52537. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52538. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52539. (float) iconRect.getX(), (float) iconRect.getBottom());
  52540. icon = icon.createPathWithRoundedCorners (5.0f);
  52541. }
  52542. else
  52543. {
  52544. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52545. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52546. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52547. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52548. }
  52549. GlyphArrangement ga;
  52550. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52551. String::charToString (character),
  52552. (float) iconRect.getX(), (float) iconRect.getY(),
  52553. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52554. Justification::centred, false);
  52555. ga.createPath (icon);
  52556. icon.setUsingNonZeroWinding (false);
  52557. g.setColour (Colour (colour));
  52558. g.fillPath (icon);
  52559. iconSpaceUsed = iconWidth;
  52560. alignment = Justification::left;
  52561. }
  52562. g.setColour (alert.findColour (AlertWindow::textColourId));
  52563. textLayout.drawWithin (g,
  52564. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52565. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52566. alignment.getFlags() | Justification::top);
  52567. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52568. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52569. }
  52570. int LookAndFeel::getAlertBoxWindowFlags()
  52571. {
  52572. return ComponentPeer::windowAppearsOnTaskbar
  52573. | ComponentPeer::windowHasDropShadow;
  52574. }
  52575. int LookAndFeel::getAlertWindowButtonHeight()
  52576. {
  52577. return 28;
  52578. }
  52579. const Font LookAndFeel::getAlertWindowMessageFont()
  52580. {
  52581. return Font (15.0f);
  52582. }
  52583. const Font LookAndFeel::getAlertWindowFont()
  52584. {
  52585. return Font (12.0f);
  52586. }
  52587. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52588. int width, int height,
  52589. double progress, const String& textToShow)
  52590. {
  52591. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52592. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52593. g.fillAll (background);
  52594. if (progress >= 0.0f && progress < 1.0f)
  52595. {
  52596. drawGlassLozenge (g, 1.0f, 1.0f,
  52597. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52598. (float) (height - 2),
  52599. foreground,
  52600. 0.5f, 0.0f,
  52601. true, true, true, true);
  52602. }
  52603. else
  52604. {
  52605. // spinning bar..
  52606. g.setColour (foreground);
  52607. const int stripeWidth = height * 2;
  52608. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52609. Path p;
  52610. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52611. p.addQuadrilateral (x, 0.0f,
  52612. x + stripeWidth * 0.5f, 0.0f,
  52613. x, (float) height,
  52614. x - stripeWidth * 0.5f, (float) height);
  52615. Image im (Image::ARGB, width, height, true);
  52616. {
  52617. Graphics g2 (im);
  52618. drawGlassLozenge (g2, 1.0f, 1.0f,
  52619. (float) (width - 2),
  52620. (float) (height - 2),
  52621. foreground,
  52622. 0.5f, 0.0f,
  52623. true, true, true, true);
  52624. }
  52625. g.setTiledImageFill (im, 0, 0, 0.85f);
  52626. g.fillPath (p);
  52627. }
  52628. if (textToShow.isNotEmpty())
  52629. {
  52630. g.setColour (Colour::contrasting (background, foreground));
  52631. g.setFont (height * 0.6f);
  52632. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52633. }
  52634. }
  52635. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52636. {
  52637. const float radius = jmin (w, h) * 0.4f;
  52638. const float thickness = radius * 0.15f;
  52639. Path p;
  52640. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52641. radius * 0.6f, thickness,
  52642. thickness * 0.5f);
  52643. const float cx = x + w * 0.5f;
  52644. const float cy = y + h * 0.5f;
  52645. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52646. for (int i = 0; i < 12; ++i)
  52647. {
  52648. const int n = (i + 12 - animationIndex) % 12;
  52649. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52650. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52651. .translated (cx, cy));
  52652. }
  52653. }
  52654. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52655. ScrollBar& scrollbar,
  52656. int width, int height,
  52657. int buttonDirection,
  52658. bool /*isScrollbarVertical*/,
  52659. bool /*isMouseOverButton*/,
  52660. bool isButtonDown)
  52661. {
  52662. Path p;
  52663. if (buttonDirection == 0)
  52664. p.addTriangle (width * 0.5f, height * 0.2f,
  52665. width * 0.1f, height * 0.7f,
  52666. width * 0.9f, height * 0.7f);
  52667. else if (buttonDirection == 1)
  52668. p.addTriangle (width * 0.8f, height * 0.5f,
  52669. width * 0.3f, height * 0.1f,
  52670. width * 0.3f, height * 0.9f);
  52671. else if (buttonDirection == 2)
  52672. p.addTriangle (width * 0.5f, height * 0.8f,
  52673. width * 0.1f, height * 0.3f,
  52674. width * 0.9f, height * 0.3f);
  52675. else if (buttonDirection == 3)
  52676. p.addTriangle (width * 0.2f, height * 0.5f,
  52677. width * 0.7f, height * 0.1f,
  52678. width * 0.7f, height * 0.9f);
  52679. if (isButtonDown)
  52680. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52681. else
  52682. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52683. g.fillPath (p);
  52684. g.setColour (Colour (0x80000000));
  52685. g.strokePath (p, PathStrokeType (0.5f));
  52686. }
  52687. void LookAndFeel::drawScrollbar (Graphics& g,
  52688. ScrollBar& scrollbar,
  52689. int x, int y,
  52690. int width, int height,
  52691. bool isScrollbarVertical,
  52692. int thumbStartPosition,
  52693. int thumbSize,
  52694. bool /*isMouseOver*/,
  52695. bool /*isMouseDown*/)
  52696. {
  52697. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52698. Path slotPath, thumbPath;
  52699. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52700. const float slotIndentx2 = slotIndent * 2.0f;
  52701. const float thumbIndent = slotIndent + 1.0f;
  52702. const float thumbIndentx2 = thumbIndent * 2.0f;
  52703. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52704. if (isScrollbarVertical)
  52705. {
  52706. slotPath.addRoundedRectangle (x + slotIndent,
  52707. y + slotIndent,
  52708. width - slotIndentx2,
  52709. height - slotIndentx2,
  52710. (width - slotIndentx2) * 0.5f);
  52711. if (thumbSize > 0)
  52712. thumbPath.addRoundedRectangle (x + thumbIndent,
  52713. thumbStartPosition + thumbIndent,
  52714. width - thumbIndentx2,
  52715. thumbSize - thumbIndentx2,
  52716. (width - thumbIndentx2) * 0.5f);
  52717. gx1 = (float) x;
  52718. gx2 = x + width * 0.7f;
  52719. }
  52720. else
  52721. {
  52722. slotPath.addRoundedRectangle (x + slotIndent,
  52723. y + slotIndent,
  52724. width - slotIndentx2,
  52725. height - slotIndentx2,
  52726. (height - slotIndentx2) * 0.5f);
  52727. if (thumbSize > 0)
  52728. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52729. y + thumbIndent,
  52730. thumbSize - thumbIndentx2,
  52731. height - thumbIndentx2,
  52732. (height - thumbIndentx2) * 0.5f);
  52733. gy1 = (float) y;
  52734. gy2 = y + height * 0.7f;
  52735. }
  52736. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52737. Colour trackColour1, trackColour2;
  52738. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52739. {
  52740. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52741. }
  52742. else
  52743. {
  52744. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52745. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52746. }
  52747. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52748. trackColour2, gx2, gy2, false));
  52749. g.fillPath (slotPath);
  52750. if (isScrollbarVertical)
  52751. {
  52752. gx1 = x + width * 0.6f;
  52753. gx2 = (float) x + width;
  52754. }
  52755. else
  52756. {
  52757. gy1 = y + height * 0.6f;
  52758. gy2 = (float) y + height;
  52759. }
  52760. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52761. Colour (0x19000000), gx2, gy2, false));
  52762. g.fillPath (slotPath);
  52763. g.setColour (thumbColour);
  52764. g.fillPath (thumbPath);
  52765. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52766. Colours::transparentBlack, gx2, gy2, false));
  52767. g.saveState();
  52768. if (isScrollbarVertical)
  52769. g.reduceClipRegion (x + width / 2, y, width, height);
  52770. else
  52771. g.reduceClipRegion (x, y + height / 2, width, height);
  52772. g.fillPath (thumbPath);
  52773. g.restoreState();
  52774. g.setColour (Colour (0x4c000000));
  52775. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52776. }
  52777. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52778. {
  52779. return 0;
  52780. }
  52781. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52782. {
  52783. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52784. }
  52785. int LookAndFeel::getDefaultScrollbarWidth()
  52786. {
  52787. return 18;
  52788. }
  52789. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52790. {
  52791. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52792. : scrollbar.getHeight());
  52793. }
  52794. const Path LookAndFeel::getTickShape (const float height)
  52795. {
  52796. static const unsigned char tickShapeData[] =
  52797. {
  52798. 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,
  52799. 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,
  52800. 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,
  52801. 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,
  52802. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52803. };
  52804. Path p;
  52805. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52806. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52807. return p;
  52808. }
  52809. const Path LookAndFeel::getCrossShape (const float height)
  52810. {
  52811. static const unsigned char crossShapeData[] =
  52812. {
  52813. 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,
  52814. 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,
  52815. 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,
  52816. 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,
  52817. 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,
  52818. 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,
  52819. 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
  52820. };
  52821. Path p;
  52822. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52823. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52824. return p;
  52825. }
  52826. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52827. {
  52828. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52829. x += (w - boxSize) >> 1;
  52830. y += (h - boxSize) >> 1;
  52831. w = boxSize;
  52832. h = boxSize;
  52833. g.setColour (Colour (0xe5ffffff));
  52834. g.fillRect (x, y, w, h);
  52835. g.setColour (Colour (0x80000000));
  52836. g.drawRect (x, y, w, h);
  52837. const float size = boxSize / 2 + 1.0f;
  52838. const float centre = (float) (boxSize / 2);
  52839. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52840. if (isPlus)
  52841. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52842. }
  52843. void LookAndFeel::drawBubble (Graphics& g,
  52844. float tipX, float tipY,
  52845. float boxX, float boxY,
  52846. float boxW, float boxH)
  52847. {
  52848. int side = 0;
  52849. if (tipX < boxX)
  52850. side = 1;
  52851. else if (tipX > boxX + boxW)
  52852. side = 3;
  52853. else if (tipY > boxY + boxH)
  52854. side = 2;
  52855. const float indent = 2.0f;
  52856. Path p;
  52857. p.addBubble (boxX + indent,
  52858. boxY + indent,
  52859. boxW - indent * 2.0f,
  52860. boxH - indent * 2.0f,
  52861. 5.0f,
  52862. tipX, tipY,
  52863. side,
  52864. 0.5f,
  52865. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52866. //xxx need to take comp as param for colour
  52867. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52868. g.fillPath (p);
  52869. //xxx as above
  52870. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52871. g.strokePath (p, PathStrokeType (1.33f));
  52872. }
  52873. const Font LookAndFeel::getPopupMenuFont()
  52874. {
  52875. return Font (17.0f);
  52876. }
  52877. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52878. const bool isSeparator,
  52879. int standardMenuItemHeight,
  52880. int& idealWidth,
  52881. int& idealHeight)
  52882. {
  52883. if (isSeparator)
  52884. {
  52885. idealWidth = 50;
  52886. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52887. }
  52888. else
  52889. {
  52890. Font font (getPopupMenuFont());
  52891. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52892. font.setHeight (standardMenuItemHeight / 1.3f);
  52893. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52894. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52895. }
  52896. }
  52897. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52898. {
  52899. const Colour background (findColour (PopupMenu::backgroundColourId));
  52900. g.fillAll (background);
  52901. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52902. for (int i = 0; i < height; i += 3)
  52903. g.fillRect (0, i, width, 1);
  52904. #if ! JUCE_MAC
  52905. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52906. g.drawRect (0, 0, width, height);
  52907. #endif
  52908. }
  52909. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52910. int width, int height,
  52911. bool isScrollUpArrow)
  52912. {
  52913. const Colour background (findColour (PopupMenu::backgroundColourId));
  52914. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52915. background.withAlpha (0.0f),
  52916. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52917. false));
  52918. g.fillRect (1, 1, width - 2, height - 2);
  52919. const float hw = width * 0.5f;
  52920. const float arrowW = height * 0.3f;
  52921. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52922. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52923. Path p;
  52924. p.addTriangle (hw - arrowW, y1,
  52925. hw + arrowW, y1,
  52926. hw, y2);
  52927. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52928. g.fillPath (p);
  52929. }
  52930. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52931. int width, int height,
  52932. const bool isSeparator,
  52933. const bool isActive,
  52934. const bool isHighlighted,
  52935. const bool isTicked,
  52936. const bool hasSubMenu,
  52937. const String& text,
  52938. const String& shortcutKeyText,
  52939. Image* image,
  52940. const Colour* const textColourToUse)
  52941. {
  52942. const float halfH = height * 0.5f;
  52943. if (isSeparator)
  52944. {
  52945. const float separatorIndent = 5.5f;
  52946. g.setColour (Colour (0x33000000));
  52947. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52948. g.setColour (Colour (0x66ffffff));
  52949. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52950. }
  52951. else
  52952. {
  52953. Colour textColour (findColour (PopupMenu::textColourId));
  52954. if (textColourToUse != 0)
  52955. textColour = *textColourToUse;
  52956. if (isHighlighted)
  52957. {
  52958. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52959. g.fillRect (1, 1, width - 2, height - 2);
  52960. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52961. }
  52962. else
  52963. {
  52964. g.setColour (textColour);
  52965. }
  52966. if (! isActive)
  52967. g.setOpacity (0.3f);
  52968. Font font (getPopupMenuFont());
  52969. if (font.getHeight() > height / 1.3f)
  52970. font.setHeight (height / 1.3f);
  52971. g.setFont (font);
  52972. const int leftBorder = (height * 5) / 4;
  52973. const int rightBorder = 4;
  52974. if (image != 0)
  52975. {
  52976. g.drawImageWithin (*image,
  52977. 2, 1, leftBorder - 4, height - 2,
  52978. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52979. }
  52980. else if (isTicked)
  52981. {
  52982. const Path tick (getTickShape (1.0f));
  52983. const float th = font.getAscent();
  52984. const float ty = halfH - th * 0.5f;
  52985. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52986. th, true));
  52987. }
  52988. g.drawFittedText (text,
  52989. leftBorder, 0,
  52990. width - (leftBorder + rightBorder), height,
  52991. Justification::centredLeft, 1);
  52992. if (shortcutKeyText.isNotEmpty())
  52993. {
  52994. Font f2 (font);
  52995. f2.setHeight (f2.getHeight() * 0.75f);
  52996. f2.setHorizontalScale (0.95f);
  52997. g.setFont (f2);
  52998. g.drawText (shortcutKeyText,
  52999. leftBorder,
  53000. 0,
  53001. width - (leftBorder + rightBorder + 4),
  53002. height,
  53003. Justification::centredRight,
  53004. true);
  53005. }
  53006. if (hasSubMenu)
  53007. {
  53008. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53009. const float x = width - height * 0.6f;
  53010. Path p;
  53011. p.addTriangle (x, halfH - arrowH * 0.5f,
  53012. x, halfH + arrowH * 0.5f,
  53013. x + arrowH * 0.6f, halfH);
  53014. g.fillPath (p);
  53015. }
  53016. }
  53017. }
  53018. int LookAndFeel::getMenuWindowFlags()
  53019. {
  53020. return ComponentPeer::windowHasDropShadow;
  53021. }
  53022. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53023. bool, MenuBarComponent& menuBar)
  53024. {
  53025. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53026. if (menuBar.isEnabled())
  53027. {
  53028. drawShinyButtonShape (g,
  53029. -4.0f, 0.0f,
  53030. width + 8.0f, (float) height,
  53031. 0.0f,
  53032. baseColour,
  53033. 0.4f,
  53034. true, true, true, true);
  53035. }
  53036. else
  53037. {
  53038. g.fillAll (baseColour);
  53039. }
  53040. }
  53041. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53042. {
  53043. return Font (menuBar.getHeight() * 0.7f);
  53044. }
  53045. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53046. {
  53047. return getMenuBarFont (menuBar, itemIndex, itemText)
  53048. .getStringWidth (itemText) + menuBar.getHeight();
  53049. }
  53050. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53051. int width, int height,
  53052. int itemIndex,
  53053. const String& itemText,
  53054. bool isMouseOverItem,
  53055. bool isMenuOpen,
  53056. bool /*isMouseOverBar*/,
  53057. MenuBarComponent& menuBar)
  53058. {
  53059. if (! menuBar.isEnabled())
  53060. {
  53061. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53062. .withMultipliedAlpha (0.5f));
  53063. }
  53064. else if (isMenuOpen || isMouseOverItem)
  53065. {
  53066. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53067. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53068. }
  53069. else
  53070. {
  53071. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53072. }
  53073. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53074. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53075. }
  53076. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53077. TextEditor& textEditor)
  53078. {
  53079. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53080. }
  53081. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53082. {
  53083. if (textEditor.isEnabled())
  53084. {
  53085. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53086. {
  53087. const int border = 2;
  53088. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53089. g.drawRect (0, 0, width, height, border);
  53090. g.setOpacity (1.0f);
  53091. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53092. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53093. }
  53094. else
  53095. {
  53096. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53097. g.drawRect (0, 0, width, height);
  53098. g.setOpacity (1.0f);
  53099. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53100. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53101. }
  53102. }
  53103. }
  53104. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53105. const bool isButtonDown,
  53106. int buttonX, int buttonY,
  53107. int buttonW, int buttonH,
  53108. ComboBox& box)
  53109. {
  53110. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53111. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53112. {
  53113. g.setColour (box.findColour (TextButton::buttonColourId));
  53114. g.drawRect (0, 0, width, height, 2);
  53115. }
  53116. else
  53117. {
  53118. g.setColour (box.findColour (ComboBox::outlineColourId));
  53119. g.drawRect (0, 0, width, height);
  53120. }
  53121. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53122. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53123. box.hasKeyboardFocus (true),
  53124. false, isButtonDown)
  53125. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53126. drawGlassLozenge (g,
  53127. buttonX + outlineThickness, buttonY + outlineThickness,
  53128. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53129. baseColour, outlineThickness, -1.0f,
  53130. true, true, true, true);
  53131. if (box.isEnabled())
  53132. {
  53133. const float arrowX = 0.3f;
  53134. const float arrowH = 0.2f;
  53135. Path p;
  53136. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53137. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53138. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53139. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53140. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53141. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53142. g.setColour (box.findColour (ComboBox::arrowColourId));
  53143. g.fillPath (p);
  53144. }
  53145. }
  53146. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53147. {
  53148. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53149. }
  53150. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53151. {
  53152. return new Label (String::empty, String::empty);
  53153. }
  53154. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53155. {
  53156. label.setBounds (1, 1,
  53157. box.getWidth() + 3 - box.getHeight(),
  53158. box.getHeight() - 2);
  53159. label.setFont (getComboBoxFont (box));
  53160. }
  53161. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53162. {
  53163. g.fillAll (label.findColour (Label::backgroundColourId));
  53164. if (! label.isBeingEdited())
  53165. {
  53166. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53167. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53168. g.setFont (label.getFont());
  53169. g.drawFittedText (label.getText(),
  53170. label.getHorizontalBorderSize(),
  53171. label.getVerticalBorderSize(),
  53172. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53173. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53174. label.getJustificationType(),
  53175. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53176. label.getMinimumHorizontalScale());
  53177. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53178. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53179. }
  53180. else if (label.isEnabled())
  53181. {
  53182. g.setColour (label.findColour (Label::outlineColourId));
  53183. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53184. }
  53185. }
  53186. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53187. int x, int y,
  53188. int width, int height,
  53189. float /*sliderPos*/,
  53190. float /*minSliderPos*/,
  53191. float /*maxSliderPos*/,
  53192. const Slider::SliderStyle /*style*/,
  53193. Slider& slider)
  53194. {
  53195. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53196. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53197. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53198. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53199. Path indent;
  53200. if (slider.isHorizontal())
  53201. {
  53202. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53203. const float ih = sliderRadius;
  53204. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53205. gradCol2, 0.0f, iy + ih, false));
  53206. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53207. width + sliderRadius, ih,
  53208. 5.0f);
  53209. g.fillPath (indent);
  53210. }
  53211. else
  53212. {
  53213. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53214. const float iw = sliderRadius;
  53215. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53216. gradCol2, ix + iw, 0.0f, false));
  53217. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53218. iw, height + sliderRadius,
  53219. 5.0f);
  53220. g.fillPath (indent);
  53221. }
  53222. g.setColour (Colour (0x4c000000));
  53223. g.strokePath (indent, PathStrokeType (0.5f));
  53224. }
  53225. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53226. int x, int y,
  53227. int width, int height,
  53228. float sliderPos,
  53229. float minSliderPos,
  53230. float maxSliderPos,
  53231. const Slider::SliderStyle style,
  53232. Slider& slider)
  53233. {
  53234. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53235. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53236. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53237. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53238. slider.isMouseButtonDown() && slider.isEnabled()));
  53239. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53240. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53241. {
  53242. float kx, ky;
  53243. if (style == Slider::LinearVertical)
  53244. {
  53245. kx = x + width * 0.5f;
  53246. ky = sliderPos;
  53247. }
  53248. else
  53249. {
  53250. kx = sliderPos;
  53251. ky = y + height * 0.5f;
  53252. }
  53253. drawGlassSphere (g,
  53254. kx - sliderRadius,
  53255. ky - sliderRadius,
  53256. sliderRadius * 2.0f,
  53257. knobColour, outlineThickness);
  53258. }
  53259. else
  53260. {
  53261. if (style == Slider::ThreeValueVertical)
  53262. {
  53263. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53264. sliderPos - sliderRadius,
  53265. sliderRadius * 2.0f,
  53266. knobColour, outlineThickness);
  53267. }
  53268. else if (style == Slider::ThreeValueHorizontal)
  53269. {
  53270. drawGlassSphere (g,sliderPos - sliderRadius,
  53271. y + height * 0.5f - sliderRadius,
  53272. sliderRadius * 2.0f,
  53273. knobColour, outlineThickness);
  53274. }
  53275. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53276. {
  53277. const float sr = jmin (sliderRadius, width * 0.4f);
  53278. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53279. minSliderPos - sliderRadius,
  53280. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53281. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53282. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53283. }
  53284. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53285. {
  53286. const float sr = jmin (sliderRadius, height * 0.4f);
  53287. drawGlassPointer (g, minSliderPos - sr,
  53288. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53289. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53290. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53291. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53292. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53293. }
  53294. }
  53295. }
  53296. void LookAndFeel::drawLinearSlider (Graphics& g,
  53297. int x, int y,
  53298. int width, int height,
  53299. float sliderPos,
  53300. float minSliderPos,
  53301. float maxSliderPos,
  53302. const Slider::SliderStyle style,
  53303. Slider& slider)
  53304. {
  53305. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53306. if (style == Slider::LinearBar)
  53307. {
  53308. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53309. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53310. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53311. false, isMouseOver,
  53312. isMouseOver || slider.isMouseButtonDown()));
  53313. drawShinyButtonShape (g,
  53314. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53315. baseColour,
  53316. slider.isEnabled() ? 0.9f : 0.3f,
  53317. true, true, true, true);
  53318. }
  53319. else
  53320. {
  53321. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53322. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53323. }
  53324. }
  53325. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53326. {
  53327. return jmin (7,
  53328. slider.getHeight() / 2,
  53329. slider.getWidth() / 2) + 2;
  53330. }
  53331. void LookAndFeel::drawRotarySlider (Graphics& g,
  53332. int x, int y,
  53333. int width, int height,
  53334. float sliderPos,
  53335. const float rotaryStartAngle,
  53336. const float rotaryEndAngle,
  53337. Slider& slider)
  53338. {
  53339. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53340. const float centreX = x + width * 0.5f;
  53341. const float centreY = y + height * 0.5f;
  53342. const float rx = centreX - radius;
  53343. const float ry = centreY - radius;
  53344. const float rw = radius * 2.0f;
  53345. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53346. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53347. if (radius > 12.0f)
  53348. {
  53349. if (slider.isEnabled())
  53350. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53351. else
  53352. g.setColour (Colour (0x80808080));
  53353. const float thickness = 0.7f;
  53354. {
  53355. Path filledArc;
  53356. filledArc.addPieSegment (rx, ry, rw, rw,
  53357. rotaryStartAngle,
  53358. angle,
  53359. thickness);
  53360. g.fillPath (filledArc);
  53361. }
  53362. if (thickness > 0)
  53363. {
  53364. const float innerRadius = radius * 0.2f;
  53365. Path p;
  53366. p.addTriangle (-innerRadius, 0.0f,
  53367. 0.0f, -radius * thickness * 1.1f,
  53368. innerRadius, 0.0f);
  53369. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53370. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53371. }
  53372. if (slider.isEnabled())
  53373. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53374. else
  53375. g.setColour (Colour (0x80808080));
  53376. Path outlineArc;
  53377. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53378. outlineArc.closeSubPath();
  53379. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53380. }
  53381. else
  53382. {
  53383. if (slider.isEnabled())
  53384. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53385. else
  53386. g.setColour (Colour (0x80808080));
  53387. Path p;
  53388. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53389. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53390. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53391. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53392. }
  53393. }
  53394. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53395. {
  53396. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53397. }
  53398. class SliderLabelComp : public Label
  53399. {
  53400. public:
  53401. SliderLabelComp() : Label (String::empty, String::empty) {}
  53402. ~SliderLabelComp() {}
  53403. void mouseWheelMove (const MouseEvent&, float, float) {}
  53404. };
  53405. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53406. {
  53407. Label* const l = new SliderLabelComp();
  53408. l->setJustificationType (Justification::centred);
  53409. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53410. l->setColour (Label::backgroundColourId,
  53411. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53412. : slider.findColour (Slider::textBoxBackgroundColourId));
  53413. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53414. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53415. l->setColour (TextEditor::backgroundColourId,
  53416. slider.findColour (Slider::textBoxBackgroundColourId)
  53417. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53418. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53419. return l;
  53420. }
  53421. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53422. {
  53423. return 0;
  53424. }
  53425. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53426. {
  53427. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53428. width = tl.getWidth() + 14;
  53429. height = tl.getHeight() + 6;
  53430. }
  53431. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53432. {
  53433. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53434. const Colour textCol (findColour (TooltipWindow::textColourId));
  53435. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53436. g.setColour (findColour (TooltipWindow::outlineColourId));
  53437. g.drawRect (0, 0, width, height, 1);
  53438. #endif
  53439. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53440. g.setColour (findColour (TooltipWindow::textColourId));
  53441. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53442. }
  53443. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53444. {
  53445. return new TextButton (text, TRANS("click to browse for a different file"));
  53446. }
  53447. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53448. ComboBox* filenameBox,
  53449. Button* browseButton)
  53450. {
  53451. browseButton->setSize (80, filenameComp.getHeight());
  53452. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53453. if (tb != 0)
  53454. tb->changeWidthToFitText();
  53455. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53456. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53457. }
  53458. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53459. int imageX, int imageY, int imageW, int imageH,
  53460. const Colour& overlayColour,
  53461. float imageOpacity,
  53462. ImageButton& button)
  53463. {
  53464. if (! button.isEnabled())
  53465. imageOpacity *= 0.3f;
  53466. if (! overlayColour.isOpaque())
  53467. {
  53468. g.setOpacity (imageOpacity);
  53469. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53470. 0, 0, image->getWidth(), image->getHeight(), false);
  53471. }
  53472. if (! overlayColour.isTransparent())
  53473. {
  53474. g.setColour (overlayColour);
  53475. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53476. 0, 0, image->getWidth(), image->getHeight(), true);
  53477. }
  53478. }
  53479. void LookAndFeel::drawCornerResizer (Graphics& g,
  53480. int w, int h,
  53481. bool /*isMouseOver*/,
  53482. bool /*isMouseDragging*/)
  53483. {
  53484. const float lineThickness = jmin (w, h) * 0.075f;
  53485. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53486. {
  53487. g.setColour (Colours::lightgrey);
  53488. g.drawLine (w * i,
  53489. h + 1.0f,
  53490. w + 1.0f,
  53491. h * i,
  53492. lineThickness);
  53493. g.setColour (Colours::darkgrey);
  53494. g.drawLine (w * i + lineThickness,
  53495. h + 1.0f,
  53496. w + 1.0f,
  53497. h * i + lineThickness,
  53498. lineThickness);
  53499. }
  53500. }
  53501. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize<int>& border)
  53502. {
  53503. if (! border.isEmpty())
  53504. {
  53505. const Rectangle<int> fullSize (0, 0, w, h);
  53506. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53507. g.saveState();
  53508. g.excludeClipRegion (centreArea);
  53509. g.setColour (Colour (0x50000000));
  53510. g.drawRect (fullSize);
  53511. g.setColour (Colour (0x19000000));
  53512. g.drawRect (centreArea.expanded (1, 1));
  53513. g.restoreState();
  53514. }
  53515. }
  53516. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53517. const BorderSize<int>& /*border*/, ResizableWindow& window)
  53518. {
  53519. g.fillAll (window.getBackgroundColour());
  53520. }
  53521. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53522. const BorderSize<int>& /*border*/, ResizableWindow&)
  53523. {
  53524. }
  53525. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53526. Graphics& g, int w, int h,
  53527. int titleSpaceX, int titleSpaceW,
  53528. const Image* icon,
  53529. bool drawTitleTextOnLeft)
  53530. {
  53531. const bool isActive = window.isActiveWindow();
  53532. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53533. 0.0f, 0.0f,
  53534. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53535. 0.0f, (float) h, false));
  53536. g.fillAll();
  53537. Font font (h * 0.65f, Font::bold);
  53538. g.setFont (font);
  53539. int textW = font.getStringWidth (window.getName());
  53540. int iconW = 0;
  53541. int iconH = 0;
  53542. if (icon != 0)
  53543. {
  53544. iconH = (int) font.getHeight();
  53545. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53546. }
  53547. textW = jmin (titleSpaceW, textW + iconW);
  53548. int textX = drawTitleTextOnLeft ? titleSpaceX
  53549. : jmax (titleSpaceX, (w - textW) / 2);
  53550. if (textX + textW > titleSpaceX + titleSpaceW)
  53551. textX = titleSpaceX + titleSpaceW - textW;
  53552. if (icon != 0)
  53553. {
  53554. g.setOpacity (isActive ? 1.0f : 0.6f);
  53555. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53556. RectanglePlacement::centred, false);
  53557. textX += iconW;
  53558. textW -= iconW;
  53559. }
  53560. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53561. g.setColour (findColour (DocumentWindow::textColourId));
  53562. else
  53563. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53564. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53565. }
  53566. class GlassWindowButton : public Button
  53567. {
  53568. public:
  53569. GlassWindowButton (const String& name, const Colour& col,
  53570. const Path& normalShape_,
  53571. const Path& toggledShape_) throw()
  53572. : Button (name),
  53573. colour (col),
  53574. normalShape (normalShape_),
  53575. toggledShape (toggledShape_)
  53576. {
  53577. }
  53578. ~GlassWindowButton()
  53579. {
  53580. }
  53581. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53582. {
  53583. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53584. if (! isEnabled())
  53585. alpha *= 0.5f;
  53586. float x = 0, y = 0, diam;
  53587. if (getWidth() < getHeight())
  53588. {
  53589. diam = (float) getWidth();
  53590. y = (getHeight() - getWidth()) * 0.5f;
  53591. }
  53592. else
  53593. {
  53594. diam = (float) getHeight();
  53595. y = (getWidth() - getHeight()) * 0.5f;
  53596. }
  53597. x += diam * 0.05f;
  53598. y += diam * 0.05f;
  53599. diam *= 0.9f;
  53600. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53601. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53602. g.fillEllipse (x, y, diam, diam);
  53603. x += 2.0f;
  53604. y += 2.0f;
  53605. diam -= 4.0f;
  53606. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53607. Path& p = getToggleState() ? toggledShape : normalShape;
  53608. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53609. diam * 0.4f, diam * 0.4f, true));
  53610. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53611. g.fillPath (p, t);
  53612. }
  53613. private:
  53614. Colour colour;
  53615. Path normalShape, toggledShape;
  53616. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53617. };
  53618. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53619. {
  53620. Path shape;
  53621. const float crossThickness = 0.25f;
  53622. if (buttonType == DocumentWindow::closeButton)
  53623. {
  53624. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53625. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53626. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53627. }
  53628. else if (buttonType == DocumentWindow::minimiseButton)
  53629. {
  53630. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53631. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53632. }
  53633. else if (buttonType == DocumentWindow::maximiseButton)
  53634. {
  53635. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53636. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53637. Path fullscreenShape;
  53638. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53639. fullscreenShape.lineTo (0.0f, 100.0f);
  53640. fullscreenShape.lineTo (0.0f, 0.0f);
  53641. fullscreenShape.lineTo (100.0f, 0.0f);
  53642. fullscreenShape.lineTo (100.0f, 45.0f);
  53643. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53644. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53645. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53646. }
  53647. jassertfalse;
  53648. return 0;
  53649. }
  53650. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53651. int titleBarX,
  53652. int titleBarY,
  53653. int titleBarW,
  53654. int titleBarH,
  53655. Button* minimiseButton,
  53656. Button* maximiseButton,
  53657. Button* closeButton,
  53658. bool positionTitleBarButtonsOnLeft)
  53659. {
  53660. const int buttonW = titleBarH - titleBarH / 8;
  53661. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53662. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53663. if (closeButton != 0)
  53664. {
  53665. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53666. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53667. }
  53668. if (positionTitleBarButtonsOnLeft)
  53669. swapVariables (minimiseButton, maximiseButton);
  53670. if (maximiseButton != 0)
  53671. {
  53672. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53673. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53674. }
  53675. if (minimiseButton != 0)
  53676. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53677. }
  53678. int LookAndFeel::getDefaultMenuBarHeight()
  53679. {
  53680. return 24;
  53681. }
  53682. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53683. {
  53684. return new DropShadower (0.4f, 1, 5, 10);
  53685. }
  53686. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53687. int w, int h,
  53688. bool /*isVerticalBar*/,
  53689. bool isMouseOver,
  53690. bool isMouseDragging)
  53691. {
  53692. float alpha = 0.5f;
  53693. if (isMouseOver || isMouseDragging)
  53694. {
  53695. g.fillAll (Colour (0x190000ff));
  53696. alpha = 1.0f;
  53697. }
  53698. const float cx = w * 0.5f;
  53699. const float cy = h * 0.5f;
  53700. const float cr = jmin (w, h) * 0.4f;
  53701. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53702. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53703. true));
  53704. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53705. }
  53706. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53707. const String& text,
  53708. const Justification& position,
  53709. GroupComponent& group)
  53710. {
  53711. const float textH = 15.0f;
  53712. const float indent = 3.0f;
  53713. const float textEdgeGap = 4.0f;
  53714. float cs = 5.0f;
  53715. Font f (textH);
  53716. Path p;
  53717. float x = indent;
  53718. float y = f.getAscent() - 3.0f;
  53719. float w = jmax (0.0f, width - x * 2.0f);
  53720. float h = jmax (0.0f, height - y - indent);
  53721. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53722. const float cs2 = 2.0f * cs;
  53723. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53724. float textX = cs + textEdgeGap;
  53725. if (position.testFlags (Justification::horizontallyCentred))
  53726. textX = cs + (w - cs2 - textW) * 0.5f;
  53727. else if (position.testFlags (Justification::right))
  53728. textX = w - cs - textW - textEdgeGap;
  53729. p.startNewSubPath (x + textX + textW, y);
  53730. p.lineTo (x + w - cs, y);
  53731. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53732. p.lineTo (x + w, y + h - cs);
  53733. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53734. p.lineTo (x + cs, y + h);
  53735. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53736. p.lineTo (x, y + cs);
  53737. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53738. p.lineTo (x + textX, y);
  53739. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53740. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53741. .withMultipliedAlpha (alpha));
  53742. g.strokePath (p, PathStrokeType (2.0f));
  53743. g.setColour (group.findColour (GroupComponent::textColourId)
  53744. .withMultipliedAlpha (alpha));
  53745. g.setFont (f);
  53746. g.drawText (text,
  53747. roundToInt (x + textX), 0,
  53748. roundToInt (textW),
  53749. roundToInt (textH),
  53750. Justification::centred, true);
  53751. }
  53752. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53753. {
  53754. return 1 + tabDepth / 3;
  53755. }
  53756. int LookAndFeel::getTabButtonSpaceAroundImage()
  53757. {
  53758. return 4;
  53759. }
  53760. void LookAndFeel::createTabButtonShape (Path& p,
  53761. int width, int height,
  53762. int /*tabIndex*/,
  53763. const String& /*text*/,
  53764. Button& /*button*/,
  53765. TabbedButtonBar::Orientation orientation,
  53766. const bool /*isMouseOver*/,
  53767. const bool /*isMouseDown*/,
  53768. const bool /*isFrontTab*/)
  53769. {
  53770. const float w = (float) width;
  53771. const float h = (float) height;
  53772. float length = w;
  53773. float depth = h;
  53774. if (orientation == TabbedButtonBar::TabsAtLeft
  53775. || orientation == TabbedButtonBar::TabsAtRight)
  53776. {
  53777. swapVariables (length, depth);
  53778. }
  53779. const float indent = (float) getTabButtonOverlap ((int) depth);
  53780. const float overhang = 4.0f;
  53781. if (orientation == TabbedButtonBar::TabsAtLeft)
  53782. {
  53783. p.startNewSubPath (w, 0.0f);
  53784. p.lineTo (0.0f, indent);
  53785. p.lineTo (0.0f, h - indent);
  53786. p.lineTo (w, h);
  53787. p.lineTo (w + overhang, h + overhang);
  53788. p.lineTo (w + overhang, -overhang);
  53789. }
  53790. else if (orientation == TabbedButtonBar::TabsAtRight)
  53791. {
  53792. p.startNewSubPath (0.0f, 0.0f);
  53793. p.lineTo (w, indent);
  53794. p.lineTo (w, h - indent);
  53795. p.lineTo (0.0f, h);
  53796. p.lineTo (-overhang, h + overhang);
  53797. p.lineTo (-overhang, -overhang);
  53798. }
  53799. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53800. {
  53801. p.startNewSubPath (0.0f, 0.0f);
  53802. p.lineTo (indent, h);
  53803. p.lineTo (w - indent, h);
  53804. p.lineTo (w, 0.0f);
  53805. p.lineTo (w + overhang, -overhang);
  53806. p.lineTo (-overhang, -overhang);
  53807. }
  53808. else
  53809. {
  53810. p.startNewSubPath (0.0f, h);
  53811. p.lineTo (indent, 0.0f);
  53812. p.lineTo (w - indent, 0.0f);
  53813. p.lineTo (w, h);
  53814. p.lineTo (w + overhang, h + overhang);
  53815. p.lineTo (-overhang, h + overhang);
  53816. }
  53817. p.closeSubPath();
  53818. p = p.createPathWithRoundedCorners (3.0f);
  53819. }
  53820. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53821. const Path& path,
  53822. const Colour& preferredColour,
  53823. int /*tabIndex*/,
  53824. const String& /*text*/,
  53825. Button& button,
  53826. TabbedButtonBar::Orientation /*orientation*/,
  53827. const bool /*isMouseOver*/,
  53828. const bool /*isMouseDown*/,
  53829. const bool isFrontTab)
  53830. {
  53831. g.setColour (isFrontTab ? preferredColour
  53832. : preferredColour.withMultipliedAlpha (0.9f));
  53833. g.fillPath (path);
  53834. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53835. : TabbedButtonBar::tabOutlineColourId, false)
  53836. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53837. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53838. }
  53839. void LookAndFeel::drawTabButtonText (Graphics& g,
  53840. int x, int y, int w, int h,
  53841. const Colour& preferredBackgroundColour,
  53842. int /*tabIndex*/,
  53843. const String& text,
  53844. Button& button,
  53845. TabbedButtonBar::Orientation orientation,
  53846. const bool isMouseOver,
  53847. const bool isMouseDown,
  53848. const bool isFrontTab)
  53849. {
  53850. int length = w;
  53851. int depth = h;
  53852. if (orientation == TabbedButtonBar::TabsAtLeft
  53853. || orientation == TabbedButtonBar::TabsAtRight)
  53854. {
  53855. swapVariables (length, depth);
  53856. }
  53857. Font font (depth * 0.6f);
  53858. font.setUnderline (button.hasKeyboardFocus (false));
  53859. GlyphArrangement textLayout;
  53860. textLayout.addFittedText (font, text.trim(),
  53861. 0.0f, 0.0f, (float) length, (float) depth,
  53862. Justification::centred,
  53863. jmax (1, depth / 12));
  53864. AffineTransform transform;
  53865. if (orientation == TabbedButtonBar::TabsAtLeft)
  53866. {
  53867. transform = transform.rotated (float_Pi * -0.5f)
  53868. .translated ((float) x, (float) (y + h));
  53869. }
  53870. else if (orientation == TabbedButtonBar::TabsAtRight)
  53871. {
  53872. transform = transform.rotated (float_Pi * 0.5f)
  53873. .translated ((float) (x + w), (float) y);
  53874. }
  53875. else
  53876. {
  53877. transform = transform.translated ((float) x, (float) y);
  53878. }
  53879. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53880. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53881. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53882. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53883. else
  53884. g.setColour (preferredBackgroundColour.contrasting());
  53885. if (! (isMouseOver || isMouseDown))
  53886. g.setOpacity (0.8f);
  53887. if (! button.isEnabled())
  53888. g.setOpacity (0.3f);
  53889. textLayout.draw (g, transform);
  53890. }
  53891. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53892. const String& text,
  53893. int tabDepth,
  53894. Button&)
  53895. {
  53896. Font f (tabDepth * 0.6f);
  53897. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53898. }
  53899. void LookAndFeel::drawTabButton (Graphics& g,
  53900. int w, int h,
  53901. const Colour& preferredColour,
  53902. int tabIndex,
  53903. const String& text,
  53904. Button& button,
  53905. TabbedButtonBar::Orientation orientation,
  53906. const bool isMouseOver,
  53907. const bool isMouseDown,
  53908. const bool isFrontTab)
  53909. {
  53910. int length = w;
  53911. int depth = h;
  53912. if (orientation == TabbedButtonBar::TabsAtLeft
  53913. || orientation == TabbedButtonBar::TabsAtRight)
  53914. {
  53915. swapVariables (length, depth);
  53916. }
  53917. Path tabShape;
  53918. createTabButtonShape (tabShape, w, h,
  53919. tabIndex, text, button, orientation,
  53920. isMouseOver, isMouseDown, isFrontTab);
  53921. fillTabButtonShape (g, tabShape, preferredColour,
  53922. tabIndex, text, button, orientation,
  53923. isMouseOver, isMouseDown, isFrontTab);
  53924. const int indent = getTabButtonOverlap (depth);
  53925. int x = 0, y = 0;
  53926. if (orientation == TabbedButtonBar::TabsAtLeft
  53927. || orientation == TabbedButtonBar::TabsAtRight)
  53928. {
  53929. y += indent;
  53930. h -= indent * 2;
  53931. }
  53932. else
  53933. {
  53934. x += indent;
  53935. w -= indent * 2;
  53936. }
  53937. drawTabButtonText (g, x, y, w, h, preferredColour,
  53938. tabIndex, text, button, orientation,
  53939. isMouseOver, isMouseDown, isFrontTab);
  53940. }
  53941. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53942. int w, int h,
  53943. TabbedButtonBar& tabBar,
  53944. TabbedButtonBar::Orientation orientation)
  53945. {
  53946. const float shadowSize = 0.2f;
  53947. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53948. Rectangle<int> shadowRect;
  53949. if (orientation == TabbedButtonBar::TabsAtLeft)
  53950. {
  53951. x1 = (float) w;
  53952. x2 = w * (1.0f - shadowSize);
  53953. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53954. }
  53955. else if (orientation == TabbedButtonBar::TabsAtRight)
  53956. {
  53957. x2 = w * shadowSize;
  53958. shadowRect.setBounds (0, 0, (int) x2, h);
  53959. }
  53960. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53961. {
  53962. y2 = h * shadowSize;
  53963. shadowRect.setBounds (0, 0, w, (int) y2);
  53964. }
  53965. else
  53966. {
  53967. y1 = (float) h;
  53968. y2 = h * (1.0f - shadowSize);
  53969. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53970. }
  53971. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53972. Colours::transparentBlack, x2, y2, false));
  53973. shadowRect.expand (2, 2);
  53974. g.fillRect (shadowRect);
  53975. g.setColour (Colour (0x80000000));
  53976. if (orientation == TabbedButtonBar::TabsAtLeft)
  53977. {
  53978. g.fillRect (w - 1, 0, 1, h);
  53979. }
  53980. else if (orientation == TabbedButtonBar::TabsAtRight)
  53981. {
  53982. g.fillRect (0, 0, 1, h);
  53983. }
  53984. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53985. {
  53986. g.fillRect (0, 0, w, 1);
  53987. }
  53988. else
  53989. {
  53990. g.fillRect (0, h - 1, w, 1);
  53991. }
  53992. }
  53993. Button* LookAndFeel::createTabBarExtrasButton()
  53994. {
  53995. const float thickness = 7.0f;
  53996. const float indent = 22.0f;
  53997. Path p;
  53998. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53999. DrawablePath ellipse;
  54000. ellipse.setPath (p);
  54001. ellipse.setFill (Colour (0x99ffffff));
  54002. p.clear();
  54003. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54004. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54005. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54006. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54007. p.setUsingNonZeroWinding (false);
  54008. DrawablePath dp;
  54009. dp.setPath (p);
  54010. dp.setFill (Colour (0x59000000));
  54011. DrawableComposite normalImage;
  54012. normalImage.addAndMakeVisible (ellipse.createCopy());
  54013. normalImage.addAndMakeVisible (dp.createCopy());
  54014. dp.setFill (Colour (0xcc000000));
  54015. DrawableComposite overImage;
  54016. overImage.addAndMakeVisible (ellipse.createCopy());
  54017. overImage.addAndMakeVisible (dp.createCopy());
  54018. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54019. db->setImages (&normalImage, &overImage, 0);
  54020. return db;
  54021. }
  54022. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54023. {
  54024. g.fillAll (Colours::white);
  54025. const int w = header.getWidth();
  54026. const int h = header.getHeight();
  54027. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54028. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54029. false));
  54030. g.fillRect (0, h / 2, w, h);
  54031. g.setColour (Colour (0x33000000));
  54032. g.fillRect (0, h - 1, w, 1);
  54033. for (int i = header.getNumColumns (true); --i >= 0;)
  54034. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54035. }
  54036. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54037. int width, int height,
  54038. bool isMouseOver, bool isMouseDown,
  54039. int columnFlags)
  54040. {
  54041. if (isMouseDown)
  54042. g.fillAll (Colour (0x8899aadd));
  54043. else if (isMouseOver)
  54044. g.fillAll (Colour (0x5599aadd));
  54045. int rightOfText = width - 4;
  54046. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54047. {
  54048. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54049. const float bottom = height - top;
  54050. const float w = height * 0.5f;
  54051. const float x = rightOfText - (w * 1.25f);
  54052. rightOfText = (int) x;
  54053. Path sortArrow;
  54054. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54055. g.setColour (Colour (0x99000000));
  54056. g.fillPath (sortArrow);
  54057. }
  54058. g.setColour (Colours::black);
  54059. g.setFont (height * 0.5f, Font::bold);
  54060. const int textX = 4;
  54061. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54062. }
  54063. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54064. {
  54065. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54066. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54067. background.darker (0.1f),
  54068. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54069. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54070. false));
  54071. g.fillAll();
  54072. }
  54073. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54074. {
  54075. return createTabBarExtrasButton();
  54076. }
  54077. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54078. bool isMouseOver, bool isMouseDown,
  54079. ToolbarItemComponent& component)
  54080. {
  54081. if (isMouseDown)
  54082. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54083. else if (isMouseOver)
  54084. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54085. }
  54086. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54087. const String& text, ToolbarItemComponent& component)
  54088. {
  54089. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54090. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54091. const float fontHeight = jmin (14.0f, height * 0.85f);
  54092. g.setFont (fontHeight);
  54093. g.drawFittedText (text,
  54094. x, y, width, height,
  54095. Justification::centred,
  54096. jmax (1, height / (int) fontHeight));
  54097. }
  54098. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54099. bool isOpen, int width, int height)
  54100. {
  54101. const int buttonSize = (height * 3) / 4;
  54102. const int buttonIndent = (height - buttonSize) / 2;
  54103. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54104. const int textX = buttonIndent * 2 + buttonSize + 2;
  54105. g.setColour (Colours::black);
  54106. g.setFont (height * 0.7f, Font::bold);
  54107. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54108. }
  54109. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54110. PropertyComponent&)
  54111. {
  54112. g.setColour (Colour (0x66ffffff));
  54113. g.fillRect (0, 0, width, height - 1);
  54114. }
  54115. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54116. PropertyComponent& component)
  54117. {
  54118. g.setColour (Colours::black);
  54119. if (! component.isEnabled())
  54120. g.setOpacity (0.6f);
  54121. g.setFont (jmin (height, 24) * 0.65f);
  54122. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54123. g.drawFittedText (component.getName(),
  54124. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54125. Justification::centredLeft, 2);
  54126. }
  54127. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54128. {
  54129. return Rectangle<int> (component.getWidth() / 3, 1,
  54130. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54131. }
  54132. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54133. {
  54134. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54135. {
  54136. Graphics g2 (content);
  54137. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54138. g2.fillPath (path);
  54139. g2.setColour (Colours::white.withAlpha (0.8f));
  54140. g2.strokePath (path, PathStrokeType (2.0f));
  54141. }
  54142. DropShadowEffect shadow;
  54143. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54144. shadow.applyEffect (content, g, 1.0f);
  54145. }
  54146. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54147. const String& instructions,
  54148. GlyphArrangement& text,
  54149. int width)
  54150. {
  54151. text.clear();
  54152. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54153. 8.0f, 22.0f, width - 16.0f,
  54154. Justification::centred);
  54155. text.addJustifiedText (Font (14.0f), instructions,
  54156. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54157. Justification::centred);
  54158. }
  54159. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54160. const String& filename, Image* icon,
  54161. const String& fileSizeDescription,
  54162. const String& fileTimeDescription,
  54163. const bool isDirectory,
  54164. const bool isItemSelected,
  54165. const int /*itemIndex*/,
  54166. DirectoryContentsDisplayComponent&)
  54167. {
  54168. if (isItemSelected)
  54169. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54170. const int x = 32;
  54171. g.setColour (Colours::black);
  54172. if (icon != 0 && icon->isValid())
  54173. {
  54174. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54175. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54176. false);
  54177. }
  54178. else
  54179. {
  54180. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54181. : getDefaultDocumentFileImage();
  54182. if (d != 0)
  54183. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54184. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54185. }
  54186. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54187. g.setFont (height * 0.7f);
  54188. if (width > 450 && ! isDirectory)
  54189. {
  54190. const int sizeX = roundToInt (width * 0.7f);
  54191. const int dateX = roundToInt (width * 0.8f);
  54192. g.drawFittedText (filename,
  54193. x, 0, sizeX - x, height,
  54194. Justification::centredLeft, 1);
  54195. g.setFont (height * 0.5f);
  54196. g.setColour (Colours::darkgrey);
  54197. if (! isDirectory)
  54198. {
  54199. g.drawFittedText (fileSizeDescription,
  54200. sizeX, 0, dateX - sizeX - 8, height,
  54201. Justification::centredRight, 1);
  54202. g.drawFittedText (fileTimeDescription,
  54203. dateX, 0, width - 8 - dateX, height,
  54204. Justification::centredRight, 1);
  54205. }
  54206. }
  54207. else
  54208. {
  54209. g.drawFittedText (filename,
  54210. x, 0, width - x, height,
  54211. Justification::centredLeft, 1);
  54212. }
  54213. }
  54214. Button* LookAndFeel::createFileBrowserGoUpButton()
  54215. {
  54216. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54217. Path arrowPath;
  54218. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54219. DrawablePath arrowImage;
  54220. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54221. arrowImage.setPath (arrowPath);
  54222. goUpButton->setImages (&arrowImage);
  54223. return goUpButton;
  54224. }
  54225. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54226. DirectoryContentsDisplayComponent* fileListComponent,
  54227. FilePreviewComponent* previewComp,
  54228. ComboBox* currentPathBox,
  54229. TextEditor* filenameBox,
  54230. Button* goUpButton)
  54231. {
  54232. const int x = 8;
  54233. int w = browserComp.getWidth() - x - x;
  54234. if (previewComp != 0)
  54235. {
  54236. const int previewWidth = w / 3;
  54237. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54238. w -= previewWidth + 4;
  54239. }
  54240. int y = 4;
  54241. const int controlsHeight = 22;
  54242. const int bottomSectionHeight = controlsHeight + 8;
  54243. const int upButtonWidth = 50;
  54244. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54245. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54246. y += controlsHeight + 4;
  54247. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54248. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54249. y = listAsComp->getBottom() + 4;
  54250. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54251. }
  54252. // Pulls a drawable out of compressed valuetree data..
  54253. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54254. {
  54255. MemoryInputStream m (data, numBytes, false);
  54256. GZIPDecompressorInputStream gz (m);
  54257. ValueTree drawable (ValueTree::readFromStream (gz));
  54258. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54259. }
  54260. const Drawable* LookAndFeel::getDefaultFolderImage()
  54261. {
  54262. if (folderImage == 0)
  54263. {
  54264. static const unsigned char drawableData[] =
  54265. { 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,
  54266. 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,
  54267. 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,
  54268. 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,
  54269. 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,
  54270. 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,
  54271. 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,
  54272. 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,
  54273. 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,
  54274. 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,
  54275. 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,
  54276. 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,
  54277. 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,
  54278. 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,
  54279. 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 };
  54280. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54281. }
  54282. return folderImage;
  54283. }
  54284. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54285. {
  54286. if (documentImage == 0)
  54287. {
  54288. static const unsigned char drawableData[] =
  54289. { 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,
  54290. 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,
  54291. 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,
  54292. 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,
  54293. 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,
  54294. 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,
  54295. 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,
  54296. 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,
  54297. 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,
  54298. 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,
  54299. 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,
  54300. 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,
  54301. 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,
  54302. 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,
  54303. 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,
  54304. 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,
  54305. 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,
  54306. 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,
  54307. 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,
  54308. 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,
  54309. 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,
  54310. 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,
  54311. 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 };
  54312. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54313. }
  54314. return documentImage;
  54315. }
  54316. void LookAndFeel::playAlertSound()
  54317. {
  54318. PlatformUtilities::beep();
  54319. }
  54320. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54321. {
  54322. g.setColour (Colours::white.withAlpha (0.7f));
  54323. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54324. g.setColour (Colours::black.withAlpha (0.2f));
  54325. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54326. const int totalBlocks = 7;
  54327. const int numBlocks = roundToInt (totalBlocks * level);
  54328. const float w = (width - 6.0f) / (float) totalBlocks;
  54329. for (int i = 0; i < totalBlocks; ++i)
  54330. {
  54331. if (i >= numBlocks)
  54332. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54333. else
  54334. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54335. : Colours::red);
  54336. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54337. }
  54338. }
  54339. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54340. {
  54341. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54342. if (keyDescription.isNotEmpty())
  54343. {
  54344. if (button.isEnabled())
  54345. {
  54346. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54347. g.fillAll (textColour.withAlpha (alpha));
  54348. g.setOpacity (0.3f);
  54349. g.drawBevel (0, 0, width, height, 2);
  54350. }
  54351. g.setColour (textColour);
  54352. g.setFont (height * 0.6f);
  54353. g.drawFittedText (keyDescription,
  54354. 3, 0, width - 6, height,
  54355. Justification::centred, 1);
  54356. }
  54357. else
  54358. {
  54359. const float thickness = 7.0f;
  54360. const float indent = 22.0f;
  54361. Path p;
  54362. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54363. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54364. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54365. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54366. p.setUsingNonZeroWinding (false);
  54367. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54368. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54369. }
  54370. if (button.hasKeyboardFocus (false))
  54371. {
  54372. g.setColour (textColour.withAlpha (0.4f));
  54373. g.drawRect (0, 0, width, height);
  54374. }
  54375. }
  54376. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54377. float x, float y, float w, float h,
  54378. float maxCornerSize,
  54379. const Colour& baseColour,
  54380. const float strokeWidth,
  54381. const bool flatOnLeft,
  54382. const bool flatOnRight,
  54383. const bool flatOnTop,
  54384. const bool flatOnBottom) throw()
  54385. {
  54386. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54387. return;
  54388. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54389. Path outline;
  54390. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54391. ! (flatOnLeft || flatOnTop),
  54392. ! (flatOnRight || flatOnTop),
  54393. ! (flatOnLeft || flatOnBottom),
  54394. ! (flatOnRight || flatOnBottom));
  54395. ColourGradient cg (baseColour, 0.0f, y,
  54396. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54397. false);
  54398. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54399. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54400. g.setGradientFill (cg);
  54401. g.fillPath (outline);
  54402. g.setColour (Colour (0x80000000));
  54403. g.strokePath (outline, PathStrokeType (strokeWidth));
  54404. }
  54405. void LookAndFeel::drawGlassSphere (Graphics& g,
  54406. const float x, const float y,
  54407. const float diameter,
  54408. const Colour& colour,
  54409. const float outlineThickness) throw()
  54410. {
  54411. if (diameter <= outlineThickness)
  54412. return;
  54413. Path p;
  54414. p.addEllipse (x, y, diameter, diameter);
  54415. {
  54416. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54417. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54418. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54419. g.setGradientFill (cg);
  54420. g.fillPath (p);
  54421. }
  54422. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54423. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54424. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54425. ColourGradient cg (Colours::transparentBlack,
  54426. x + diameter * 0.5f, y + diameter * 0.5f,
  54427. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54428. x, y + diameter * 0.5f, true);
  54429. cg.addColour (0.7, Colours::transparentBlack);
  54430. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54431. g.setGradientFill (cg);
  54432. g.fillPath (p);
  54433. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54434. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54435. }
  54436. void LookAndFeel::drawGlassPointer (Graphics& g,
  54437. const float x, const float y,
  54438. const float diameter,
  54439. const Colour& colour, const float outlineThickness,
  54440. const int direction) throw()
  54441. {
  54442. if (diameter <= outlineThickness)
  54443. return;
  54444. Path p;
  54445. p.startNewSubPath (x + diameter * 0.5f, y);
  54446. p.lineTo (x + diameter, y + diameter * 0.6f);
  54447. p.lineTo (x + diameter, y + diameter);
  54448. p.lineTo (x, y + diameter);
  54449. p.lineTo (x, y + diameter * 0.6f);
  54450. p.closeSubPath();
  54451. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54452. {
  54453. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54454. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54455. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54456. g.setGradientFill (cg);
  54457. g.fillPath (p);
  54458. }
  54459. ColourGradient cg (Colours::transparentBlack,
  54460. x + diameter * 0.5f, y + diameter * 0.5f,
  54461. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54462. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54463. cg.addColour (0.5, Colours::transparentBlack);
  54464. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54465. g.setGradientFill (cg);
  54466. g.fillPath (p);
  54467. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54468. g.strokePath (p, PathStrokeType (outlineThickness));
  54469. }
  54470. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54471. const float x, const float y,
  54472. const float width, const float height,
  54473. const Colour& colour,
  54474. const float outlineThickness,
  54475. const float cornerSize,
  54476. const bool flatOnLeft,
  54477. const bool flatOnRight,
  54478. const bool flatOnTop,
  54479. const bool flatOnBottom) throw()
  54480. {
  54481. if (width <= outlineThickness || height <= outlineThickness)
  54482. return;
  54483. const int intX = (int) x;
  54484. const int intY = (int) y;
  54485. const int intW = (int) width;
  54486. const int intH = (int) height;
  54487. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54488. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54489. const int intEdge = (int) edgeBlurRadius;
  54490. Path outline;
  54491. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54492. ! (flatOnLeft || flatOnTop),
  54493. ! (flatOnRight || flatOnTop),
  54494. ! (flatOnLeft || flatOnBottom),
  54495. ! (flatOnRight || flatOnBottom));
  54496. {
  54497. ColourGradient cg (colour.darker (0.2f), 0, y,
  54498. colour.darker (0.2f), 0, y + height, false);
  54499. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54500. cg.addColour (0.4, colour);
  54501. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54502. g.setGradientFill (cg);
  54503. g.fillPath (outline);
  54504. }
  54505. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54506. colour.darker (0.2f), x, y + height * 0.5f, true);
  54507. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54508. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54509. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54510. {
  54511. g.saveState();
  54512. g.setGradientFill (cg);
  54513. g.reduceClipRegion (intX, intY, intEdge, intH);
  54514. g.fillPath (outline);
  54515. g.restoreState();
  54516. }
  54517. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54518. {
  54519. cg.point1.setX (x + width - edgeBlurRadius);
  54520. cg.point2.setX (x + width);
  54521. g.saveState();
  54522. g.setGradientFill (cg);
  54523. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54524. g.fillPath (outline);
  54525. g.restoreState();
  54526. }
  54527. {
  54528. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54529. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54530. Path highlight;
  54531. LookAndFeelHelpers::createRoundedPath (highlight,
  54532. x + leftIndent,
  54533. y + cs * 0.1f,
  54534. width - (leftIndent + rightIndent),
  54535. height * 0.4f, cs * 0.4f,
  54536. ! (flatOnLeft || flatOnTop),
  54537. ! (flatOnRight || flatOnTop),
  54538. ! (flatOnLeft || flatOnBottom),
  54539. ! (flatOnRight || flatOnBottom));
  54540. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54541. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54542. g.fillPath (highlight);
  54543. }
  54544. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54545. g.strokePath (outline, PathStrokeType (outlineThickness));
  54546. }
  54547. END_JUCE_NAMESPACE
  54548. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54549. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54550. BEGIN_JUCE_NAMESPACE
  54551. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54552. {
  54553. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54554. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54555. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54556. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54557. setColour (Slider::thumbColourId, Colours::white);
  54558. setColour (Slider::trackColourId, Colour (0x7f000000));
  54559. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54560. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54561. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54562. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54563. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54564. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54565. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54566. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54567. }
  54568. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54569. {
  54570. }
  54571. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54572. Button& button,
  54573. const Colour& backgroundColour,
  54574. bool isMouseOverButton,
  54575. bool isButtonDown)
  54576. {
  54577. const int width = button.getWidth();
  54578. const int height = button.getHeight();
  54579. const float indent = 2.0f;
  54580. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54581. roundToInt (height * 0.4f));
  54582. Path p;
  54583. p.addRoundedRectangle (indent, indent,
  54584. width - indent * 2.0f,
  54585. height - indent * 2.0f,
  54586. (float) cornerSize);
  54587. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54588. if (isMouseOverButton)
  54589. {
  54590. if (isButtonDown)
  54591. bc = bc.brighter();
  54592. else if (bc.getBrightness() > 0.5f)
  54593. bc = bc.darker (0.1f);
  54594. else
  54595. bc = bc.brighter (0.1f);
  54596. }
  54597. g.setColour (bc);
  54598. g.fillPath (p);
  54599. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54600. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54601. }
  54602. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54603. Component& /*component*/,
  54604. float x, float y, float w, float h,
  54605. const bool ticked,
  54606. const bool isEnabled,
  54607. const bool /*isMouseOverButton*/,
  54608. const bool isButtonDown)
  54609. {
  54610. Path box;
  54611. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54612. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54613. : Colours::lightgrey.withAlpha (0.1f));
  54614. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54615. g.fillPath (box, trans);
  54616. g.setColour (Colours::black.withAlpha (0.6f));
  54617. g.strokePath (box, PathStrokeType (0.9f), trans);
  54618. if (ticked)
  54619. {
  54620. Path tick;
  54621. tick.startNewSubPath (1.5f, 3.0f);
  54622. tick.lineTo (3.0f, 6.0f);
  54623. tick.lineTo (6.0f, 0.0f);
  54624. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54625. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54626. }
  54627. }
  54628. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54629. ToggleButton& button,
  54630. bool isMouseOverButton,
  54631. bool isButtonDown)
  54632. {
  54633. if (button.hasKeyboardFocus (true))
  54634. {
  54635. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54636. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54637. }
  54638. const int tickWidth = jmin (20, button.getHeight() - 4);
  54639. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54640. (float) tickWidth, (float) tickWidth,
  54641. button.getToggleState(),
  54642. button.isEnabled(),
  54643. isMouseOverButton,
  54644. isButtonDown);
  54645. g.setColour (button.findColour (ToggleButton::textColourId));
  54646. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54647. if (! button.isEnabled())
  54648. g.setOpacity (0.5f);
  54649. const int textX = tickWidth + 5;
  54650. g.drawFittedText (button.getButtonText(),
  54651. textX, 4,
  54652. button.getWidth() - textX - 2, button.getHeight() - 8,
  54653. Justification::centredLeft, 10);
  54654. }
  54655. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54656. int width, int height,
  54657. double progress, const String& textToShow)
  54658. {
  54659. if (progress < 0 || progress >= 1.0)
  54660. {
  54661. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54662. }
  54663. else
  54664. {
  54665. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54666. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54667. g.fillAll (background);
  54668. g.setColour (foreground);
  54669. g.fillRect (1, 1,
  54670. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54671. height - 2);
  54672. if (textToShow.isNotEmpty())
  54673. {
  54674. g.setColour (Colour::contrasting (background, foreground));
  54675. g.setFont (height * 0.6f);
  54676. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54677. }
  54678. }
  54679. }
  54680. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54681. ScrollBar& bar,
  54682. int width, int height,
  54683. int buttonDirection,
  54684. bool isScrollbarVertical,
  54685. bool isMouseOverButton,
  54686. bool isButtonDown)
  54687. {
  54688. if (isScrollbarVertical)
  54689. width -= 2;
  54690. else
  54691. height -= 2;
  54692. Path p;
  54693. if (buttonDirection == 0)
  54694. p.addTriangle (width * 0.5f, height * 0.2f,
  54695. width * 0.1f, height * 0.7f,
  54696. width * 0.9f, height * 0.7f);
  54697. else if (buttonDirection == 1)
  54698. p.addTriangle (width * 0.8f, height * 0.5f,
  54699. width * 0.3f, height * 0.1f,
  54700. width * 0.3f, height * 0.9f);
  54701. else if (buttonDirection == 2)
  54702. p.addTriangle (width * 0.5f, height * 0.8f,
  54703. width * 0.1f, height * 0.3f,
  54704. width * 0.9f, height * 0.3f);
  54705. else if (buttonDirection == 3)
  54706. p.addTriangle (width * 0.2f, height * 0.5f,
  54707. width * 0.7f, height * 0.1f,
  54708. width * 0.7f, height * 0.9f);
  54709. if (isButtonDown)
  54710. g.setColour (Colours::white);
  54711. else if (isMouseOverButton)
  54712. g.setColour (Colours::white.withAlpha (0.7f));
  54713. else
  54714. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54715. g.fillPath (p);
  54716. g.setColour (Colours::black.withAlpha (0.5f));
  54717. g.strokePath (p, PathStrokeType (0.5f));
  54718. }
  54719. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54720. ScrollBar& bar,
  54721. int x, int y,
  54722. int width, int height,
  54723. bool isScrollbarVertical,
  54724. int thumbStartPosition,
  54725. int thumbSize,
  54726. bool isMouseOver,
  54727. bool isMouseDown)
  54728. {
  54729. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54730. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54731. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54732. if (thumbSize > 0.0f)
  54733. {
  54734. Rectangle<int> thumb;
  54735. if (isScrollbarVertical)
  54736. {
  54737. width -= 2;
  54738. g.fillRect (x + roundToInt (width * 0.35f), y,
  54739. roundToInt (width * 0.3f), height);
  54740. thumb.setBounds (x + 1, thumbStartPosition,
  54741. width - 2, thumbSize);
  54742. }
  54743. else
  54744. {
  54745. height -= 2;
  54746. g.fillRect (x, y + roundToInt (height * 0.35f),
  54747. width, roundToInt (height * 0.3f));
  54748. thumb.setBounds (thumbStartPosition, y + 1,
  54749. thumbSize, height - 2);
  54750. }
  54751. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54752. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54753. g.fillRect (thumb);
  54754. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54755. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54756. if (thumbSize > 16)
  54757. {
  54758. for (int i = 3; --i >= 0;)
  54759. {
  54760. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54761. g.setColour (Colours::black.withAlpha (0.15f));
  54762. if (isScrollbarVertical)
  54763. {
  54764. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54765. g.setColour (Colours::white.withAlpha (0.15f));
  54766. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54767. }
  54768. else
  54769. {
  54770. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54771. g.setColour (Colours::white.withAlpha (0.15f));
  54772. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54773. }
  54774. }
  54775. }
  54776. }
  54777. }
  54778. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54779. {
  54780. return &scrollbarShadow;
  54781. }
  54782. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54783. {
  54784. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54785. g.setColour (Colours::black.withAlpha (0.6f));
  54786. g.drawRect (0, 0, width, height);
  54787. }
  54788. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54789. bool, MenuBarComponent& menuBar)
  54790. {
  54791. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54792. }
  54793. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54794. {
  54795. if (textEditor.isEnabled())
  54796. {
  54797. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54798. g.drawRect (0, 0, width, height);
  54799. }
  54800. }
  54801. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54802. const bool isButtonDown,
  54803. int buttonX, int buttonY,
  54804. int buttonW, int buttonH,
  54805. ComboBox& box)
  54806. {
  54807. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54808. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54809. : ComboBox::backgroundColourId));
  54810. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54811. g.setColour (box.findColour (ComboBox::outlineColourId));
  54812. g.drawRect (0, 0, width, height);
  54813. const float arrowX = 0.2f;
  54814. const float arrowH = 0.3f;
  54815. if (box.isEnabled())
  54816. {
  54817. Path p;
  54818. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54819. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54820. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54821. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54822. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54823. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54824. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54825. : ComboBox::buttonColourId));
  54826. g.fillPath (p);
  54827. }
  54828. }
  54829. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54830. {
  54831. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54832. f.setHorizontalScale (0.9f);
  54833. return f;
  54834. }
  54835. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54836. {
  54837. Path p;
  54838. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54839. g.setColour (fill);
  54840. g.fillPath (p);
  54841. g.setColour (outline);
  54842. g.strokePath (p, PathStrokeType (0.3f));
  54843. }
  54844. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54845. int x, int y,
  54846. int w, int h,
  54847. float sliderPos,
  54848. float minSliderPos,
  54849. float maxSliderPos,
  54850. const Slider::SliderStyle style,
  54851. Slider& slider)
  54852. {
  54853. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54854. if (style == Slider::LinearBar)
  54855. {
  54856. g.setColour (slider.findColour (Slider::thumbColourId));
  54857. g.fillRect (x, y, (int) sliderPos - x, h);
  54858. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54859. g.drawRect (x, y, (int) sliderPos - x, h);
  54860. }
  54861. else
  54862. {
  54863. g.setColour (slider.findColour (Slider::trackColourId)
  54864. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54865. if (slider.isHorizontal())
  54866. {
  54867. g.fillRect (x, y + roundToInt (h * 0.6f),
  54868. w, roundToInt (h * 0.2f));
  54869. }
  54870. else
  54871. {
  54872. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54873. jmin (4, roundToInt (w * 0.2f)), h);
  54874. }
  54875. float alpha = 0.35f;
  54876. if (slider.isEnabled())
  54877. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54878. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54879. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54880. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54881. {
  54882. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54883. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54884. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54885. fill, outline);
  54886. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54887. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54888. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54889. fill, outline);
  54890. }
  54891. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54892. {
  54893. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54894. minSliderPos - 7.0f, y + h * 0.9f ,
  54895. minSliderPos, y + h * 0.9f,
  54896. fill, outline);
  54897. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54898. maxSliderPos, y + h * 0.9f,
  54899. maxSliderPos + 7.0f, y + h * 0.9f,
  54900. fill, outline);
  54901. }
  54902. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54903. {
  54904. drawTriangle (g, sliderPos, y + h * 0.9f,
  54905. sliderPos - 7.0f, y + h * 0.2f,
  54906. sliderPos + 7.0f, y + h * 0.2f,
  54907. fill, outline);
  54908. }
  54909. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54910. {
  54911. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54912. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54913. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54914. fill, outline);
  54915. }
  54916. }
  54917. }
  54918. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54919. {
  54920. if (isIncrement)
  54921. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54922. else
  54923. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54924. }
  54925. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54926. {
  54927. return &scrollbarShadow;
  54928. }
  54929. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54930. {
  54931. return 8;
  54932. }
  54933. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54934. int w, int h,
  54935. bool isMouseOver,
  54936. bool isMouseDragging)
  54937. {
  54938. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54939. : Colours::darkgrey);
  54940. const float lineThickness = jmin (w, h) * 0.1f;
  54941. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54942. {
  54943. g.drawLine (w * i,
  54944. h + 1.0f,
  54945. w + 1.0f,
  54946. h * i,
  54947. lineThickness);
  54948. }
  54949. }
  54950. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54951. {
  54952. Path shape;
  54953. if (buttonType == DocumentWindow::closeButton)
  54954. {
  54955. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54956. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54957. ShapeButton* const b = new ShapeButton ("close",
  54958. Colour (0x7fff3333),
  54959. Colour (0xd7ff3333),
  54960. Colour (0xf7ff3333));
  54961. b->setShape (shape, true, true, true);
  54962. return b;
  54963. }
  54964. else if (buttonType == DocumentWindow::minimiseButton)
  54965. {
  54966. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54967. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54968. DrawablePath dp;
  54969. dp.setPath (shape);
  54970. dp.setFill (Colours::black.withAlpha (0.3f));
  54971. b->setImages (&dp);
  54972. return b;
  54973. }
  54974. else if (buttonType == DocumentWindow::maximiseButton)
  54975. {
  54976. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54977. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54978. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54979. DrawablePath dp;
  54980. dp.setPath (shape);
  54981. dp.setFill (Colours::black.withAlpha (0.3f));
  54982. b->setImages (&dp);
  54983. return b;
  54984. }
  54985. jassertfalse;
  54986. return 0;
  54987. }
  54988. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54989. int titleBarX,
  54990. int titleBarY,
  54991. int titleBarW,
  54992. int titleBarH,
  54993. Button* minimiseButton,
  54994. Button* maximiseButton,
  54995. Button* closeButton,
  54996. bool positionTitleBarButtonsOnLeft)
  54997. {
  54998. titleBarY += titleBarH / 8;
  54999. titleBarH -= titleBarH / 4;
  55000. const int buttonW = titleBarH;
  55001. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55002. : titleBarX + titleBarW - buttonW - 4;
  55003. if (closeButton != 0)
  55004. {
  55005. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55006. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55007. : -(buttonW + buttonW / 5);
  55008. }
  55009. if (positionTitleBarButtonsOnLeft)
  55010. swapVariables (minimiseButton, maximiseButton);
  55011. if (maximiseButton != 0)
  55012. {
  55013. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55014. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55015. }
  55016. if (minimiseButton != 0)
  55017. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55018. }
  55019. END_JUCE_NAMESPACE
  55020. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55021. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55022. BEGIN_JUCE_NAMESPACE
  55023. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55024. : model (0),
  55025. itemUnderMouse (-1),
  55026. currentPopupIndex (-1),
  55027. topLevelIndexClicked (0),
  55028. lastMouseX (0),
  55029. lastMouseY (0)
  55030. {
  55031. setRepaintsOnMouseActivity (true);
  55032. setWantsKeyboardFocus (false);
  55033. setMouseClickGrabsKeyboardFocus (false);
  55034. setModel (model_);
  55035. }
  55036. MenuBarComponent::~MenuBarComponent()
  55037. {
  55038. setModel (0);
  55039. Desktop::getInstance().removeGlobalMouseListener (this);
  55040. }
  55041. MenuBarModel* MenuBarComponent::getModel() const throw()
  55042. {
  55043. return model;
  55044. }
  55045. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55046. {
  55047. if (model != newModel)
  55048. {
  55049. if (model != 0)
  55050. model->removeListener (this);
  55051. model = newModel;
  55052. if (model != 0)
  55053. model->addListener (this);
  55054. repaint();
  55055. menuBarItemsChanged (0);
  55056. }
  55057. }
  55058. void MenuBarComponent::paint (Graphics& g)
  55059. {
  55060. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55061. getLookAndFeel().drawMenuBarBackground (g,
  55062. getWidth(),
  55063. getHeight(),
  55064. isMouseOverBar,
  55065. *this);
  55066. if (model != 0)
  55067. {
  55068. for (int i = 0; i < menuNames.size(); ++i)
  55069. {
  55070. Graphics::ScopedSaveState ss (g);
  55071. g.setOrigin (xPositions [i], 0);
  55072. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55073. getLookAndFeel().drawMenuBarItem (g,
  55074. xPositions[i + 1] - xPositions[i],
  55075. getHeight(),
  55076. i,
  55077. menuNames[i],
  55078. i == itemUnderMouse,
  55079. i == currentPopupIndex,
  55080. isMouseOverBar,
  55081. *this);
  55082. }
  55083. }
  55084. }
  55085. void MenuBarComponent::resized()
  55086. {
  55087. xPositions.clear();
  55088. int x = 0;
  55089. xPositions.add (x);
  55090. for (int i = 0; i < menuNames.size(); ++i)
  55091. {
  55092. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55093. xPositions.add (x);
  55094. }
  55095. }
  55096. int MenuBarComponent::getItemAt (const int x, const int y)
  55097. {
  55098. for (int i = 0; i < xPositions.size(); ++i)
  55099. if (x >= xPositions[i] && x < xPositions[i + 1])
  55100. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55101. return -1;
  55102. }
  55103. void MenuBarComponent::repaintMenuItem (int index)
  55104. {
  55105. if (isPositiveAndBelow (index, xPositions.size()))
  55106. {
  55107. const int x1 = xPositions [index];
  55108. const int x2 = xPositions [index + 1];
  55109. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55110. }
  55111. }
  55112. void MenuBarComponent::setItemUnderMouse (const int index)
  55113. {
  55114. if (itemUnderMouse != index)
  55115. {
  55116. repaintMenuItem (itemUnderMouse);
  55117. itemUnderMouse = index;
  55118. repaintMenuItem (itemUnderMouse);
  55119. }
  55120. }
  55121. void MenuBarComponent::setOpenItem (int index)
  55122. {
  55123. if (currentPopupIndex != index)
  55124. {
  55125. repaintMenuItem (currentPopupIndex);
  55126. currentPopupIndex = index;
  55127. repaintMenuItem (currentPopupIndex);
  55128. if (index >= 0)
  55129. Desktop::getInstance().addGlobalMouseListener (this);
  55130. else
  55131. Desktop::getInstance().removeGlobalMouseListener (this);
  55132. }
  55133. }
  55134. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55135. {
  55136. setItemUnderMouse (getItemAt (x, y));
  55137. }
  55138. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55139. {
  55140. public:
  55141. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55142. : bar (bar_), topLevelIndex (topLevelIndex_)
  55143. {
  55144. }
  55145. void modalStateFinished (int returnValue)
  55146. {
  55147. if (bar != 0)
  55148. bar->menuDismissed (topLevelIndex, returnValue);
  55149. }
  55150. private:
  55151. Component::SafePointer<MenuBarComponent> bar;
  55152. const int topLevelIndex;
  55153. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55154. };
  55155. void MenuBarComponent::showMenu (int index)
  55156. {
  55157. if (index != currentPopupIndex)
  55158. {
  55159. PopupMenu::dismissAllActiveMenus();
  55160. menuBarItemsChanged (0);
  55161. setOpenItem (index);
  55162. setItemUnderMouse (index);
  55163. if (index >= 0)
  55164. {
  55165. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55166. menuNames [itemUnderMouse]));
  55167. if (m.lookAndFeel == 0)
  55168. m.setLookAndFeel (&getLookAndFeel());
  55169. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55170. m.showMenu (localAreaToGlobal (itemPos),
  55171. 0, itemPos.getWidth(), 0, 0, this,
  55172. new AsyncCallback (this, index));
  55173. }
  55174. }
  55175. }
  55176. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55177. {
  55178. topLevelIndexClicked = topLevelIndex;
  55179. postCommandMessage (itemId);
  55180. }
  55181. void MenuBarComponent::handleCommandMessage (int commandId)
  55182. {
  55183. const Point<int> mousePos (getMouseXYRelative());
  55184. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55185. if (currentPopupIndex == topLevelIndexClicked)
  55186. setOpenItem (-1);
  55187. if (commandId != 0 && model != 0)
  55188. model->menuItemSelected (commandId, topLevelIndexClicked);
  55189. }
  55190. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55191. {
  55192. if (e.eventComponent == this)
  55193. updateItemUnderMouse (e.x, e.y);
  55194. }
  55195. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55196. {
  55197. if (e.eventComponent == this)
  55198. updateItemUnderMouse (e.x, e.y);
  55199. }
  55200. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55201. {
  55202. if (currentPopupIndex < 0)
  55203. {
  55204. const MouseEvent e2 (e.getEventRelativeTo (this));
  55205. updateItemUnderMouse (e2.x, e2.y);
  55206. currentPopupIndex = -2;
  55207. showMenu (itemUnderMouse);
  55208. }
  55209. }
  55210. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55211. {
  55212. const MouseEvent e2 (e.getEventRelativeTo (this));
  55213. const int item = getItemAt (e2.x, e2.y);
  55214. if (item >= 0)
  55215. showMenu (item);
  55216. }
  55217. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55218. {
  55219. const MouseEvent e2 (e.getEventRelativeTo (this));
  55220. updateItemUnderMouse (e2.x, e2.y);
  55221. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55222. {
  55223. setOpenItem (-1);
  55224. PopupMenu::dismissAllActiveMenus();
  55225. }
  55226. }
  55227. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55228. {
  55229. const MouseEvent e2 (e.getEventRelativeTo (this));
  55230. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55231. {
  55232. if (currentPopupIndex >= 0)
  55233. {
  55234. const int item = getItemAt (e2.x, e2.y);
  55235. if (item >= 0)
  55236. showMenu (item);
  55237. }
  55238. else
  55239. {
  55240. updateItemUnderMouse (e2.x, e2.y);
  55241. }
  55242. lastMouseX = e2.x;
  55243. lastMouseY = e2.y;
  55244. }
  55245. }
  55246. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55247. {
  55248. bool used = false;
  55249. const int numMenus = menuNames.size();
  55250. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55251. if (key.isKeyCode (KeyPress::leftKey))
  55252. {
  55253. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55254. used = true;
  55255. }
  55256. else if (key.isKeyCode (KeyPress::rightKey))
  55257. {
  55258. showMenu ((currentIndex + 1) % numMenus);
  55259. used = true;
  55260. }
  55261. return used;
  55262. }
  55263. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55264. {
  55265. StringArray newNames;
  55266. if (model != 0)
  55267. newNames = model->getMenuBarNames();
  55268. if (newNames != menuNames)
  55269. {
  55270. menuNames = newNames;
  55271. repaint();
  55272. resized();
  55273. }
  55274. }
  55275. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55276. const ApplicationCommandTarget::InvocationInfo& info)
  55277. {
  55278. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55279. return;
  55280. for (int i = 0; i < menuNames.size(); ++i)
  55281. {
  55282. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55283. if (menu.containsCommandItem (info.commandID))
  55284. {
  55285. setItemUnderMouse (i);
  55286. startTimer (200);
  55287. break;
  55288. }
  55289. }
  55290. }
  55291. void MenuBarComponent::timerCallback()
  55292. {
  55293. stopTimer();
  55294. const Point<int> mousePos (getMouseXYRelative());
  55295. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55296. }
  55297. END_JUCE_NAMESPACE
  55298. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55299. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55300. BEGIN_JUCE_NAMESPACE
  55301. MenuBarModel::MenuBarModel() throw()
  55302. : manager (0)
  55303. {
  55304. }
  55305. MenuBarModel::~MenuBarModel()
  55306. {
  55307. setApplicationCommandManagerToWatch (0);
  55308. }
  55309. void MenuBarModel::menuItemsChanged()
  55310. {
  55311. triggerAsyncUpdate();
  55312. }
  55313. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55314. {
  55315. if (manager != newManager)
  55316. {
  55317. if (manager != 0)
  55318. manager->removeListener (this);
  55319. manager = newManager;
  55320. if (manager != 0)
  55321. manager->addListener (this);
  55322. }
  55323. }
  55324. void MenuBarModel::addListener (Listener* const newListener) throw()
  55325. {
  55326. listeners.add (newListener);
  55327. }
  55328. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55329. {
  55330. // Trying to remove a listener that isn't on the list!
  55331. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55332. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55333. jassert (listeners.contains (listenerToRemove));
  55334. listeners.remove (listenerToRemove);
  55335. }
  55336. void MenuBarModel::handleAsyncUpdate()
  55337. {
  55338. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55339. }
  55340. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55341. {
  55342. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55343. }
  55344. void MenuBarModel::applicationCommandListChanged()
  55345. {
  55346. menuItemsChanged();
  55347. }
  55348. END_JUCE_NAMESPACE
  55349. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55350. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55351. BEGIN_JUCE_NAMESPACE
  55352. class PopupMenu::Item
  55353. {
  55354. public:
  55355. Item()
  55356. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55357. usesColour (false), customComp (0), commandManager (0)
  55358. {
  55359. }
  55360. Item (const int itemId_,
  55361. const String& text_,
  55362. const bool active_,
  55363. const bool isTicked_,
  55364. const Image& im,
  55365. const Colour& textColour_,
  55366. const bool usesColour_,
  55367. CustomComponent* const customComp_,
  55368. const PopupMenu* const subMenu_,
  55369. ApplicationCommandManager* const commandManager_)
  55370. : itemId (itemId_), text (text_), textColour (textColour_),
  55371. active (active_), isSeparator (false), isTicked (isTicked_),
  55372. usesColour (usesColour_), image (im), customComp (customComp_),
  55373. commandManager (commandManager_)
  55374. {
  55375. if (subMenu_ != 0)
  55376. subMenu = new PopupMenu (*subMenu_);
  55377. if (commandManager_ != 0 && itemId_ != 0)
  55378. {
  55379. String shortcutKey;
  55380. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55381. ->getKeyPressesAssignedToCommand (itemId_));
  55382. for (int i = 0; i < keyPresses.size(); ++i)
  55383. {
  55384. const String key (keyPresses.getReference(i).getTextDescription());
  55385. if (shortcutKey.isNotEmpty())
  55386. shortcutKey << ", ";
  55387. if (key.length() == 1)
  55388. shortcutKey << "shortcut: '" << key << '\'';
  55389. else
  55390. shortcutKey << key;
  55391. }
  55392. shortcutKey = shortcutKey.trim();
  55393. if (shortcutKey.isNotEmpty())
  55394. text << "<end>" << shortcutKey;
  55395. }
  55396. }
  55397. Item (const Item& other)
  55398. : itemId (other.itemId),
  55399. text (other.text),
  55400. textColour (other.textColour),
  55401. active (other.active),
  55402. isSeparator (other.isSeparator),
  55403. isTicked (other.isTicked),
  55404. usesColour (other.usesColour),
  55405. image (other.image),
  55406. customComp (other.customComp),
  55407. commandManager (other.commandManager)
  55408. {
  55409. if (other.subMenu != 0)
  55410. subMenu = new PopupMenu (*(other.subMenu));
  55411. }
  55412. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55413. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55414. const int itemId;
  55415. String text;
  55416. const Colour textColour;
  55417. const bool active, isSeparator, isTicked, usesColour;
  55418. Image image;
  55419. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55420. ScopedPointer <PopupMenu> subMenu;
  55421. ApplicationCommandManager* const commandManager;
  55422. private:
  55423. Item& operator= (const Item&);
  55424. JUCE_LEAK_DETECTOR (Item);
  55425. };
  55426. class PopupMenu::ItemComponent : public Component
  55427. {
  55428. public:
  55429. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight, Component* const parent)
  55430. : itemInfo (itemInfo_),
  55431. isHighlighted (false)
  55432. {
  55433. if (itemInfo.customComp != 0)
  55434. addAndMakeVisible (itemInfo.customComp);
  55435. parent->addAndMakeVisible (this);
  55436. int itemW = 80;
  55437. int itemH = 16;
  55438. getIdealSize (itemW, itemH, standardItemHeight);
  55439. setSize (itemW, jlimit (2, 600, itemH));
  55440. addMouseListener (parent, false);
  55441. }
  55442. ~ItemComponent()
  55443. {
  55444. if (itemInfo.customComp != 0)
  55445. removeChildComponent (itemInfo.customComp);
  55446. }
  55447. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55448. {
  55449. if (itemInfo.customComp != 0)
  55450. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55451. else
  55452. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55453. itemInfo.isSeparator,
  55454. standardItemHeight,
  55455. idealWidth, idealHeight);
  55456. }
  55457. void paint (Graphics& g)
  55458. {
  55459. if (itemInfo.customComp == 0)
  55460. {
  55461. String mainText (itemInfo.text);
  55462. String endText;
  55463. const int endIndex = mainText.indexOf ("<end>");
  55464. if (endIndex >= 0)
  55465. {
  55466. endText = mainText.substring (endIndex + 5).trim();
  55467. mainText = mainText.substring (0, endIndex);
  55468. }
  55469. getLookAndFeel()
  55470. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55471. itemInfo.isSeparator,
  55472. itemInfo.active,
  55473. isHighlighted,
  55474. itemInfo.isTicked,
  55475. itemInfo.subMenu != 0,
  55476. mainText, endText,
  55477. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55478. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55479. }
  55480. }
  55481. void resized()
  55482. {
  55483. if (getNumChildComponents() > 0)
  55484. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55485. }
  55486. void setHighlighted (bool shouldBeHighlighted)
  55487. {
  55488. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55489. if (isHighlighted != shouldBeHighlighted)
  55490. {
  55491. isHighlighted = shouldBeHighlighted;
  55492. if (itemInfo.customComp != 0)
  55493. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55494. repaint();
  55495. }
  55496. }
  55497. PopupMenu::Item itemInfo;
  55498. private:
  55499. bool isHighlighted;
  55500. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55501. };
  55502. namespace PopupMenuSettings
  55503. {
  55504. const int scrollZone = 24;
  55505. const int borderSize = 2;
  55506. const int timerInterval = 50;
  55507. const int dismissCommandId = 0x6287345f;
  55508. }
  55509. class PopupMenu::Window : public Component,
  55510. private Timer
  55511. {
  55512. public:
  55513. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55514. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55515. const int minimumWidth_, const int maximumNumColumns_,
  55516. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55517. ApplicationCommandManager** const managerOfChosenCommand_,
  55518. Component* const componentAttachedTo_)
  55519. : Component ("menu"),
  55520. owner (owner_),
  55521. activeSubMenu (0),
  55522. managerOfChosenCommand (managerOfChosenCommand_),
  55523. componentAttachedTo (componentAttachedTo_),
  55524. componentAttachedToOriginal (componentAttachedTo_),
  55525. minimumWidth (minimumWidth_),
  55526. maximumNumColumns (maximumNumColumns_),
  55527. standardItemHeight (standardItemHeight_),
  55528. isOver (false),
  55529. hasBeenOver (false),
  55530. isDown (false),
  55531. needsToScroll (false),
  55532. dismissOnMouseUp (dismissOnMouseUp_),
  55533. hideOnExit (false),
  55534. disableMouseMoves (false),
  55535. hasAnyJuceCompHadFocus (false),
  55536. numColumns (0),
  55537. contentHeight (0),
  55538. childYOffset (0),
  55539. menuCreationTime (Time::getMillisecondCounter()),
  55540. lastMouseMoveTime (0),
  55541. timeEnteredCurrentChildComp (0),
  55542. scrollAcceleration (1.0)
  55543. {
  55544. lastFocused = lastScroll = menuCreationTime;
  55545. setWantsKeyboardFocus (false);
  55546. setMouseClickGrabsKeyboardFocus (false);
  55547. setAlwaysOnTop (true);
  55548. setLookAndFeel (menu.lookAndFeel);
  55549. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55550. for (int i = 0; i < menu.items.size(); ++i)
  55551. items.add (new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight, this));
  55552. calculateWindowPos (target, alignToRectangle);
  55553. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55554. updateYPositions();
  55555. if (itemIdThatMustBeVisible != 0)
  55556. {
  55557. const int y = target.getY() - windowPos.getY();
  55558. ensureItemIsVisible (itemIdThatMustBeVisible,
  55559. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55560. }
  55561. resizeToBestWindowPos();
  55562. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55563. getActiveWindows().add (this);
  55564. Desktop::getInstance().addGlobalMouseListener (this);
  55565. }
  55566. ~Window()
  55567. {
  55568. getActiveWindows().removeValue (this);
  55569. Desktop::getInstance().removeGlobalMouseListener (this);
  55570. activeSubMenu = 0;
  55571. items.clear();
  55572. }
  55573. static Window* create (const PopupMenu& menu,
  55574. bool dismissOnMouseUp,
  55575. Window* const owner_,
  55576. const Rectangle<int>& target,
  55577. int minimumWidth,
  55578. int maximumNumColumns,
  55579. int standardItemHeight,
  55580. bool alignToRectangle,
  55581. int itemIdThatMustBeVisible,
  55582. ApplicationCommandManager** managerOfChosenCommand,
  55583. Component* componentAttachedTo)
  55584. {
  55585. if (menu.items.size() > 0)
  55586. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55587. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55588. managerOfChosenCommand, componentAttachedTo);
  55589. return 0;
  55590. }
  55591. void paint (Graphics& g)
  55592. {
  55593. if (isOpaque())
  55594. g.fillAll (Colours::white);
  55595. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55596. }
  55597. void paintOverChildren (Graphics& g)
  55598. {
  55599. if (isScrolling())
  55600. {
  55601. LookAndFeel& lf = getLookAndFeel();
  55602. if (isScrollZoneActive (false))
  55603. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55604. if (isScrollZoneActive (true))
  55605. {
  55606. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55607. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55608. }
  55609. }
  55610. }
  55611. bool isScrollZoneActive (bool bottomOne) const
  55612. {
  55613. return isScrolling()
  55614. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55615. : childYOffset > 0);
  55616. }
  55617. // hide this and all sub-comps
  55618. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55619. {
  55620. if (isVisible())
  55621. {
  55622. activeSubMenu = 0;
  55623. currentChild = 0;
  55624. exitModalState (item != 0 ? item->itemId : 0);
  55625. if (makeInvisible)
  55626. setVisible (false);
  55627. if (item != 0
  55628. && item->commandManager != 0
  55629. && item->itemId != 0)
  55630. {
  55631. *managerOfChosenCommand = item->commandManager;
  55632. }
  55633. }
  55634. }
  55635. void dismissMenu (const PopupMenu::Item* const item)
  55636. {
  55637. if (owner != 0)
  55638. {
  55639. owner->dismissMenu (item);
  55640. }
  55641. else
  55642. {
  55643. if (item != 0)
  55644. {
  55645. // need a copy of this on the stack as the one passed in will get deleted during this call
  55646. const PopupMenu::Item mi (*item);
  55647. hide (&mi, false);
  55648. }
  55649. else
  55650. {
  55651. hide (0, false);
  55652. }
  55653. }
  55654. }
  55655. void mouseMove (const MouseEvent&) { timerCallback(); }
  55656. void mouseDown (const MouseEvent&) { timerCallback(); }
  55657. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55658. void mouseUp (const MouseEvent&) { timerCallback(); }
  55659. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55660. {
  55661. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55662. lastMouse = Point<int> (-1, -1);
  55663. }
  55664. bool keyPressed (const KeyPress& key)
  55665. {
  55666. if (key.isKeyCode (KeyPress::downKey))
  55667. {
  55668. selectNextItem (1);
  55669. }
  55670. else if (key.isKeyCode (KeyPress::upKey))
  55671. {
  55672. selectNextItem (-1);
  55673. }
  55674. else if (key.isKeyCode (KeyPress::leftKey))
  55675. {
  55676. if (owner != 0)
  55677. {
  55678. Component::SafePointer<Window> parentWindow (owner);
  55679. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55680. hide (0, true);
  55681. if (parentWindow != 0)
  55682. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55683. disableTimerUntilMouseMoves();
  55684. }
  55685. else if (componentAttachedTo != 0)
  55686. {
  55687. componentAttachedTo->keyPressed (key);
  55688. }
  55689. }
  55690. else if (key.isKeyCode (KeyPress::rightKey))
  55691. {
  55692. disableTimerUntilMouseMoves();
  55693. if (showSubMenuFor (currentChild))
  55694. {
  55695. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55696. activeSubMenu->selectNextItem (1);
  55697. }
  55698. else if (componentAttachedTo != 0)
  55699. {
  55700. componentAttachedTo->keyPressed (key);
  55701. }
  55702. }
  55703. else if (key.isKeyCode (KeyPress::returnKey))
  55704. {
  55705. triggerCurrentlyHighlightedItem();
  55706. }
  55707. else if (key.isKeyCode (KeyPress::escapeKey))
  55708. {
  55709. dismissMenu (0);
  55710. }
  55711. else
  55712. {
  55713. return false;
  55714. }
  55715. return true;
  55716. }
  55717. void inputAttemptWhenModal()
  55718. {
  55719. WeakReference<Component> deletionChecker (this);
  55720. timerCallback();
  55721. if (deletionChecker != 0 && ! isOverAnyMenu())
  55722. {
  55723. if (componentAttachedTo != 0)
  55724. {
  55725. // we want to dismiss the menu, but if we do it synchronously, then
  55726. // the mouse-click will be allowed to pass through. That's good, except
  55727. // when the user clicks on the button that orginally popped the menu up,
  55728. // as they'll expect the menu to go away, and in fact it'll just
  55729. // come back. So only dismiss synchronously if they're not on the original
  55730. // comp that we're attached to.
  55731. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55732. if (componentAttachedTo->reallyContains (mousePos, true))
  55733. {
  55734. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55735. return;
  55736. }
  55737. }
  55738. dismissMenu (0);
  55739. }
  55740. }
  55741. void handleCommandMessage (int commandId)
  55742. {
  55743. Component::handleCommandMessage (commandId);
  55744. if (commandId == PopupMenuSettings::dismissCommandId)
  55745. dismissMenu (0);
  55746. }
  55747. void timerCallback()
  55748. {
  55749. if (! isVisible())
  55750. return;
  55751. if (componentAttachedTo != componentAttachedToOriginal)
  55752. {
  55753. dismissMenu (0);
  55754. return;
  55755. }
  55756. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55757. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55758. return;
  55759. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55760. // move rather than a real timer callback
  55761. const Point<int> globalMousePos (Desktop::getMousePosition());
  55762. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55763. const uint32 now = Time::getMillisecondCounter();
  55764. if (now > timeEnteredCurrentChildComp + 100
  55765. && reallyContains (localMousePos, true)
  55766. && currentChild != 0
  55767. && (! disableMouseMoves)
  55768. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55769. {
  55770. showSubMenuFor (currentChild);
  55771. }
  55772. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55773. {
  55774. highlightItemUnderMouse (globalMousePos, localMousePos);
  55775. }
  55776. bool overScrollArea = false;
  55777. if (isScrolling()
  55778. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55779. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55780. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55781. {
  55782. if (now > lastScroll + 20)
  55783. {
  55784. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55785. int amount = 0;
  55786. for (int i = 0; i < items.size() && amount == 0; ++i)
  55787. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55788. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55789. lastScroll = now;
  55790. }
  55791. overScrollArea = true;
  55792. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55793. }
  55794. else
  55795. {
  55796. scrollAcceleration = 1.0;
  55797. }
  55798. const bool wasDown = isDown;
  55799. bool isOverAny = isOverAnyMenu();
  55800. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55801. {
  55802. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55803. isOverAny = isOverAnyMenu();
  55804. }
  55805. if (hideOnExit && hasBeenOver && ! isOverAny)
  55806. {
  55807. hide (0, true);
  55808. }
  55809. else
  55810. {
  55811. isDown = hasBeenOver
  55812. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55813. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55814. bool anyFocused = Process::isForegroundProcess();
  55815. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55816. {
  55817. // because no component at all may have focus, our test here will
  55818. // only be triggered when something has focus and then loses it.
  55819. anyFocused = ! hasAnyJuceCompHadFocus;
  55820. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55821. {
  55822. if (ComponentPeer::getPeer (i)->isFocused())
  55823. {
  55824. anyFocused = true;
  55825. hasAnyJuceCompHadFocus = true;
  55826. break;
  55827. }
  55828. }
  55829. }
  55830. if (! anyFocused)
  55831. {
  55832. if (now > lastFocused + 10)
  55833. {
  55834. wasHiddenBecauseOfAppChange() = true;
  55835. dismissMenu (0);
  55836. return; // may have been deleted by the previous call..
  55837. }
  55838. }
  55839. else if (wasDown && now > menuCreationTime + 250
  55840. && ! (isDown || overScrollArea))
  55841. {
  55842. isOver = reallyContains (localMousePos, true);
  55843. if (isOver)
  55844. {
  55845. triggerCurrentlyHighlightedItem();
  55846. }
  55847. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55848. {
  55849. dismissMenu (0);
  55850. }
  55851. return; // may have been deleted by the previous calls..
  55852. }
  55853. else
  55854. {
  55855. lastFocused = now;
  55856. }
  55857. }
  55858. }
  55859. static Array<Window*>& getActiveWindows()
  55860. {
  55861. static Array<Window*> activeMenuWindows;
  55862. return activeMenuWindows;
  55863. }
  55864. static bool& wasHiddenBecauseOfAppChange() throw()
  55865. {
  55866. static bool b = false;
  55867. return b;
  55868. }
  55869. private:
  55870. Window* owner;
  55871. OwnedArray <PopupMenu::ItemComponent> items;
  55872. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55873. ScopedPointer <Window> activeSubMenu;
  55874. ApplicationCommandManager** managerOfChosenCommand;
  55875. WeakReference<Component> componentAttachedTo;
  55876. Component* componentAttachedToOriginal;
  55877. Rectangle<int> windowPos;
  55878. Point<int> lastMouse;
  55879. int minimumWidth, maximumNumColumns, standardItemHeight;
  55880. bool isOver, hasBeenOver, isDown, needsToScroll;
  55881. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55882. int numColumns, contentHeight, childYOffset;
  55883. Array <int> columnWidths;
  55884. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55885. double scrollAcceleration;
  55886. bool overlaps (const Rectangle<int>& r) const
  55887. {
  55888. return r.intersects (getBounds())
  55889. || (owner != 0 && owner->overlaps (r));
  55890. }
  55891. bool isOverAnyMenu() const
  55892. {
  55893. return (owner != 0) ? owner->isOverAnyMenu()
  55894. : isOverChildren();
  55895. }
  55896. bool isOverChildren() const
  55897. {
  55898. return isVisible()
  55899. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55900. }
  55901. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55902. {
  55903. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  55904. isOver = reallyContains (relPos, true);
  55905. if (activeSubMenu != 0)
  55906. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55907. }
  55908. bool treeContains (const Window* const window) const throw()
  55909. {
  55910. const Window* mw = this;
  55911. while (mw->owner != 0)
  55912. mw = mw->owner;
  55913. while (mw != 0)
  55914. {
  55915. if (mw == window)
  55916. return true;
  55917. mw = mw->activeSubMenu;
  55918. }
  55919. return false;
  55920. }
  55921. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55922. {
  55923. const Rectangle<int> mon (Desktop::getInstance()
  55924. .getMonitorAreaContaining (target.getCentre(),
  55925. #if JUCE_MAC
  55926. true));
  55927. #else
  55928. false)); // on windows, don't stop the menu overlapping the taskbar
  55929. #endif
  55930. int x, y, widthToUse, heightToUse;
  55931. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55932. if (alignToRectangle)
  55933. {
  55934. x = target.getX();
  55935. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55936. const int spaceOver = target.getY() - mon.getY();
  55937. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55938. y = target.getBottom();
  55939. else
  55940. y = target.getY() - heightToUse;
  55941. }
  55942. else
  55943. {
  55944. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55945. if (owner != 0)
  55946. {
  55947. if (owner->owner != 0)
  55948. {
  55949. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55950. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55951. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55952. tendTowardsRight = true;
  55953. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55954. tendTowardsRight = false;
  55955. }
  55956. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55957. {
  55958. tendTowardsRight = true;
  55959. }
  55960. }
  55961. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55962. target.getX() - mon.getX()) - 32;
  55963. if (biggestSpace < widthToUse)
  55964. {
  55965. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55966. if (numColumns > 1)
  55967. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55968. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55969. }
  55970. if (tendTowardsRight)
  55971. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55972. else
  55973. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55974. y = target.getY();
  55975. if (target.getCentreY() > mon.getCentreY())
  55976. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55977. }
  55978. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55979. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55980. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55981. // sets this flag if it's big enough to obscure any of its parent menus
  55982. hideOnExit = (owner != 0)
  55983. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55984. }
  55985. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55986. {
  55987. numColumns = 0;
  55988. contentHeight = 0;
  55989. const int maxMenuH = getParentHeight() - 24;
  55990. int totalW;
  55991. do
  55992. {
  55993. ++numColumns;
  55994. totalW = workOutBestSize (maxMenuW);
  55995. if (totalW > maxMenuW)
  55996. {
  55997. numColumns = jmax (1, numColumns - 1);
  55998. totalW = workOutBestSize (maxMenuW); // to update col widths
  55999. break;
  56000. }
  56001. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56002. {
  56003. break;
  56004. }
  56005. } while (numColumns < maximumNumColumns);
  56006. const int actualH = jmin (contentHeight, maxMenuH);
  56007. needsToScroll = contentHeight > actualH;
  56008. width = updateYPositions();
  56009. height = actualH + PopupMenuSettings::borderSize * 2;
  56010. }
  56011. int workOutBestSize (const int maxMenuW)
  56012. {
  56013. int totalW = 0;
  56014. contentHeight = 0;
  56015. int childNum = 0;
  56016. for (int col = 0; col < numColumns; ++col)
  56017. {
  56018. int i, colW = 50, colH = 0;
  56019. const int numChildren = jmin (items.size() - childNum,
  56020. (items.size() + numColumns - 1) / numColumns);
  56021. for (i = numChildren; --i >= 0;)
  56022. {
  56023. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56024. colH += items.getUnchecked (childNum + i)->getHeight();
  56025. }
  56026. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56027. columnWidths.set (col, colW);
  56028. totalW += colW;
  56029. contentHeight = jmax (contentHeight, colH);
  56030. childNum += numChildren;
  56031. }
  56032. if (totalW < minimumWidth)
  56033. {
  56034. totalW = minimumWidth;
  56035. for (int col = 0; col < numColumns; ++col)
  56036. columnWidths.set (0, totalW / numColumns);
  56037. }
  56038. return totalW;
  56039. }
  56040. void ensureItemIsVisible (const int itemId, int wantedY)
  56041. {
  56042. jassert (itemId != 0)
  56043. for (int i = items.size(); --i >= 0;)
  56044. {
  56045. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56046. if (m != 0
  56047. && m->itemInfo.itemId == itemId
  56048. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56049. {
  56050. const int currentY = m->getY();
  56051. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56052. {
  56053. if (wantedY < 0)
  56054. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56055. jmax (PopupMenuSettings::scrollZone,
  56056. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56057. currentY);
  56058. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56059. int deltaY = wantedY - currentY;
  56060. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56061. jmin (windowPos.getHeight(), mon.getHeight()));
  56062. const int newY = jlimit (mon.getY(),
  56063. mon.getBottom() - windowPos.getHeight(),
  56064. windowPos.getY() + deltaY);
  56065. deltaY -= newY - windowPos.getY();
  56066. childYOffset -= deltaY;
  56067. windowPos.setPosition (windowPos.getX(), newY);
  56068. updateYPositions();
  56069. }
  56070. break;
  56071. }
  56072. }
  56073. }
  56074. void resizeToBestWindowPos()
  56075. {
  56076. Rectangle<int> r (windowPos);
  56077. if (childYOffset < 0)
  56078. {
  56079. r.setBounds (r.getX(), r.getY() - childYOffset,
  56080. r.getWidth(), r.getHeight() + childYOffset);
  56081. }
  56082. else if (childYOffset > 0)
  56083. {
  56084. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56085. if (spaceAtBottom > 0)
  56086. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56087. }
  56088. setBounds (r);
  56089. updateYPositions();
  56090. }
  56091. void alterChildYPos (const int delta)
  56092. {
  56093. if (isScrolling())
  56094. {
  56095. childYOffset += delta;
  56096. if (delta < 0)
  56097. {
  56098. childYOffset = jmax (childYOffset, 0);
  56099. }
  56100. else if (delta > 0)
  56101. {
  56102. childYOffset = jmin (childYOffset,
  56103. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56104. }
  56105. updateYPositions();
  56106. }
  56107. else
  56108. {
  56109. childYOffset = 0;
  56110. }
  56111. resizeToBestWindowPos();
  56112. repaint();
  56113. }
  56114. int updateYPositions()
  56115. {
  56116. int x = 0;
  56117. int childNum = 0;
  56118. for (int col = 0; col < numColumns; ++col)
  56119. {
  56120. const int numChildren = jmin (items.size() - childNum,
  56121. (items.size() + numColumns - 1) / numColumns);
  56122. const int colW = columnWidths [col];
  56123. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56124. for (int i = 0; i < numChildren; ++i)
  56125. {
  56126. Component* const c = items.getUnchecked (childNum + i);
  56127. c->setBounds (x, y, colW, c->getHeight());
  56128. y += c->getHeight();
  56129. }
  56130. x += colW;
  56131. childNum += numChildren;
  56132. }
  56133. return x;
  56134. }
  56135. bool isScrolling() const throw()
  56136. {
  56137. return childYOffset != 0 || needsToScroll;
  56138. }
  56139. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56140. {
  56141. if (currentChild != 0)
  56142. currentChild->setHighlighted (false);
  56143. currentChild = child;
  56144. if (currentChild != 0)
  56145. {
  56146. currentChild->setHighlighted (true);
  56147. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56148. }
  56149. }
  56150. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56151. {
  56152. activeSubMenu = 0;
  56153. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56154. {
  56155. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56156. dismissOnMouseUp,
  56157. this,
  56158. childComp->getScreenBounds(),
  56159. 0, maximumNumColumns,
  56160. standardItemHeight,
  56161. false, 0, managerOfChosenCommand,
  56162. componentAttachedTo);
  56163. if (activeSubMenu != 0)
  56164. {
  56165. activeSubMenu->setVisible (true);
  56166. activeSubMenu->enterModalState (false);
  56167. activeSubMenu->toFront (false);
  56168. return true;
  56169. }
  56170. }
  56171. return false;
  56172. }
  56173. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56174. {
  56175. isOver = reallyContains (localMousePos, true);
  56176. if (isOver)
  56177. hasBeenOver = true;
  56178. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56179. {
  56180. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56181. if (disableMouseMoves && isOver)
  56182. disableMouseMoves = false;
  56183. }
  56184. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56185. return;
  56186. bool isMovingTowardsMenu = false;
  56187. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56188. {
  56189. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56190. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56191. // extends from the last mouse pos to the submenu's rectangle..
  56192. float subX = (float) activeSubMenu->getScreenX();
  56193. if (activeSubMenu->getX() > getX())
  56194. {
  56195. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56196. }
  56197. else
  56198. {
  56199. lastMouse += Point<int> (2, 0);
  56200. subX += activeSubMenu->getWidth();
  56201. }
  56202. Path areaTowardsSubMenu;
  56203. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56204. subX, (float) activeSubMenu->getScreenY(),
  56205. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56206. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56207. }
  56208. lastMouse = globalMousePos;
  56209. if (! isMovingTowardsMenu)
  56210. {
  56211. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56212. if (c == this)
  56213. c = 0;
  56214. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56215. if (mic == 0 && c != 0)
  56216. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56217. if (mic != currentChild
  56218. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56219. {
  56220. if (isOver && (c != 0) && (activeSubMenu != 0))
  56221. activeSubMenu->hide (0, true);
  56222. if (! isOver)
  56223. mic = 0;
  56224. setCurrentlyHighlightedChild (mic);
  56225. }
  56226. }
  56227. }
  56228. void triggerCurrentlyHighlightedItem()
  56229. {
  56230. if (currentChild != 0
  56231. && currentChild->itemInfo.canBeTriggered()
  56232. && (currentChild->itemInfo.customComp == 0
  56233. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56234. {
  56235. dismissMenu (&currentChild->itemInfo);
  56236. }
  56237. }
  56238. void selectNextItem (const int delta)
  56239. {
  56240. disableTimerUntilMouseMoves();
  56241. PopupMenu::ItemComponent* mic = 0;
  56242. bool wasLastOne = (currentChild == 0);
  56243. const int numItems = items.size();
  56244. for (int i = 0; i < numItems + 1; ++i)
  56245. {
  56246. int index = (delta > 0) ? i : (numItems - 1 - i);
  56247. index = (index + numItems) % numItems;
  56248. mic = items.getUnchecked (index);
  56249. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56250. && wasLastOne)
  56251. break;
  56252. if (mic == currentChild)
  56253. wasLastOne = true;
  56254. }
  56255. setCurrentlyHighlightedChild (mic);
  56256. }
  56257. void disableTimerUntilMouseMoves()
  56258. {
  56259. disableMouseMoves = true;
  56260. if (owner != 0)
  56261. owner->disableTimerUntilMouseMoves();
  56262. }
  56263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56264. };
  56265. PopupMenu::PopupMenu()
  56266. : lookAndFeel (0),
  56267. separatorPending (false)
  56268. {
  56269. }
  56270. PopupMenu::PopupMenu (const PopupMenu& other)
  56271. : lookAndFeel (other.lookAndFeel),
  56272. separatorPending (false)
  56273. {
  56274. items.addCopiesOf (other.items);
  56275. }
  56276. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56277. {
  56278. if (this != &other)
  56279. {
  56280. lookAndFeel = other.lookAndFeel;
  56281. clear();
  56282. items.addCopiesOf (other.items);
  56283. }
  56284. return *this;
  56285. }
  56286. PopupMenu::~PopupMenu()
  56287. {
  56288. clear();
  56289. }
  56290. void PopupMenu::clear()
  56291. {
  56292. items.clear();
  56293. separatorPending = false;
  56294. }
  56295. void PopupMenu::addSeparatorIfPending()
  56296. {
  56297. if (separatorPending)
  56298. {
  56299. separatorPending = false;
  56300. if (items.size() > 0)
  56301. items.add (new Item());
  56302. }
  56303. }
  56304. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56305. const bool isActive, const bool isTicked, const Image& iconToUse)
  56306. {
  56307. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56308. // didn't pick anything, so you shouldn't use it as the id
  56309. // for an item..
  56310. addSeparatorIfPending();
  56311. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56312. Colours::black, false, 0, 0, 0));
  56313. }
  56314. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56315. const int commandID,
  56316. const String& displayName)
  56317. {
  56318. jassert (commandManager != 0 && commandID != 0);
  56319. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56320. if (registeredInfo != 0)
  56321. {
  56322. ApplicationCommandInfo info (*registeredInfo);
  56323. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56324. addSeparatorIfPending();
  56325. items.add (new Item (commandID,
  56326. displayName.isNotEmpty() ? displayName
  56327. : info.shortName,
  56328. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56329. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56330. Image::null,
  56331. Colours::black,
  56332. false,
  56333. 0, 0,
  56334. commandManager));
  56335. }
  56336. }
  56337. void PopupMenu::addColouredItem (const int itemResultId,
  56338. const String& itemText,
  56339. const Colour& itemTextColour,
  56340. const bool isActive,
  56341. const bool isTicked,
  56342. const Image& iconToUse)
  56343. {
  56344. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56345. // didn't pick anything, so you shouldn't use it as the id
  56346. // for an item..
  56347. addSeparatorIfPending();
  56348. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56349. itemTextColour, true, 0, 0, 0));
  56350. }
  56351. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56352. {
  56353. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56354. // didn't pick anything, so you shouldn't use it as the id
  56355. // for an item..
  56356. addSeparatorIfPending();
  56357. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56358. Colours::black, false, customComponent, 0, 0));
  56359. }
  56360. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56361. {
  56362. public:
  56363. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56364. const bool triggerMenuItemAutomaticallyWhenClicked)
  56365. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56366. width (w), height (h)
  56367. {
  56368. addAndMakeVisible (comp);
  56369. }
  56370. void getIdealSize (int& idealWidth, int& idealHeight)
  56371. {
  56372. idealWidth = width;
  56373. idealHeight = height;
  56374. }
  56375. void resized()
  56376. {
  56377. if (getChildComponent(0) != 0)
  56378. getChildComponent(0)->setBounds (getLocalBounds());
  56379. }
  56380. private:
  56381. const int width, height;
  56382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56383. };
  56384. void PopupMenu::addCustomItem (const int itemResultId,
  56385. Component* customComponent,
  56386. int idealWidth, int idealHeight,
  56387. const bool triggerMenuItemAutomaticallyWhenClicked)
  56388. {
  56389. addCustomItem (itemResultId,
  56390. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56391. triggerMenuItemAutomaticallyWhenClicked));
  56392. }
  56393. void PopupMenu::addSubMenu (const String& subMenuName,
  56394. const PopupMenu& subMenu,
  56395. const bool isActive,
  56396. const Image& iconToUse,
  56397. const bool isTicked)
  56398. {
  56399. addSeparatorIfPending();
  56400. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56401. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56402. }
  56403. void PopupMenu::addSeparator()
  56404. {
  56405. separatorPending = true;
  56406. }
  56407. class HeaderItemComponent : public PopupMenu::CustomComponent
  56408. {
  56409. public:
  56410. HeaderItemComponent (const String& name)
  56411. : PopupMenu::CustomComponent (false)
  56412. {
  56413. setName (name);
  56414. }
  56415. void paint (Graphics& g)
  56416. {
  56417. Font f (getLookAndFeel().getPopupMenuFont());
  56418. f.setBold (true);
  56419. g.setFont (f);
  56420. g.setColour (findColour (PopupMenu::headerTextColourId));
  56421. g.drawFittedText (getName(),
  56422. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56423. Justification::bottomLeft, 1);
  56424. }
  56425. void getIdealSize (int& idealWidth, int& idealHeight)
  56426. {
  56427. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56428. idealHeight += idealHeight / 2;
  56429. idealWidth += idealWidth / 4;
  56430. }
  56431. private:
  56432. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56433. };
  56434. void PopupMenu::addSectionHeader (const String& title)
  56435. {
  56436. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56437. }
  56438. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56439. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56440. {
  56441. public:
  56442. PopupMenuCompletionCallback()
  56443. : managerOfChosenCommand (0)
  56444. {
  56445. }
  56446. void modalStateFinished (int result)
  56447. {
  56448. if (managerOfChosenCommand != 0 && result != 0)
  56449. {
  56450. ApplicationCommandTarget::InvocationInfo info (result);
  56451. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56452. managerOfChosenCommand->invoke (info, true);
  56453. }
  56454. // (this would be the place to fade out the component, if that's what's required)
  56455. component = 0;
  56456. }
  56457. ApplicationCommandManager* managerOfChosenCommand;
  56458. ScopedPointer<Component> component;
  56459. private:
  56460. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56461. };
  56462. int PopupMenu::showMenu (const Rectangle<int>& target,
  56463. const int itemIdThatMustBeVisible,
  56464. const int minimumWidth,
  56465. const int maximumNumColumns,
  56466. const int standardItemHeight,
  56467. Component* const componentAttachedTo,
  56468. ModalComponentManager::Callback* userCallback)
  56469. {
  56470. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56471. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56472. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56473. Window::wasHiddenBecauseOfAppChange() = false;
  56474. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56475. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56476. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56477. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56478. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56479. &callback->managerOfChosenCommand, componentAttachedTo);
  56480. if (callback->component == 0)
  56481. return 0;
  56482. callback->component->enterModalState (false, userCallbackDeleter.release());
  56483. callback->component->toFront (false); // need to do this after making it modal, or it could
  56484. // be stuck behind other comps that are already modal..
  56485. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56486. callbackDeleter.release();
  56487. if (userCallback != 0)
  56488. return 0;
  56489. const int result = callback->component->runModalLoop();
  56490. if (! Window::wasHiddenBecauseOfAppChange())
  56491. {
  56492. if (prevTopLevel != 0)
  56493. prevTopLevel->toFront (true);
  56494. if (prevFocused != 0)
  56495. prevFocused->grabKeyboardFocus();
  56496. }
  56497. return result;
  56498. }
  56499. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56500. const int minimumWidth, const int maximumNumColumns,
  56501. const int standardItemHeight,
  56502. ModalComponentManager::Callback* callback)
  56503. {
  56504. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56505. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56506. standardItemHeight, 0, callback);
  56507. }
  56508. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56509. const int itemIdThatMustBeVisible,
  56510. const int minimumWidth, const int maximumNumColumns,
  56511. const int standardItemHeight,
  56512. ModalComponentManager::Callback* callback)
  56513. {
  56514. return showMenu (screenAreaToAttachTo,
  56515. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56516. standardItemHeight, 0, callback);
  56517. }
  56518. int PopupMenu::showAt (Component* componentToAttachTo,
  56519. const int itemIdThatMustBeVisible,
  56520. const int minimumWidth, const int maximumNumColumns,
  56521. const int standardItemHeight,
  56522. ModalComponentManager::Callback* callback)
  56523. {
  56524. if (componentToAttachTo != 0)
  56525. {
  56526. return showMenu (componentToAttachTo->getScreenBounds(),
  56527. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56528. standardItemHeight, componentToAttachTo, callback);
  56529. }
  56530. else
  56531. {
  56532. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56533. standardItemHeight, callback);
  56534. }
  56535. }
  56536. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56537. {
  56538. const int numWindows = Window::getActiveWindows().size();
  56539. for (int i = numWindows; --i >= 0;)
  56540. {
  56541. Window* const pmw = Window::getActiveWindows()[i];
  56542. if (pmw != 0)
  56543. pmw->dismissMenu (0);
  56544. }
  56545. return numWindows > 0;
  56546. }
  56547. int PopupMenu::getNumItems() const throw()
  56548. {
  56549. int num = 0;
  56550. for (int i = items.size(); --i >= 0;)
  56551. if (! (items.getUnchecked(i))->isSeparator)
  56552. ++num;
  56553. return num;
  56554. }
  56555. bool PopupMenu::containsCommandItem (const int commandID) const
  56556. {
  56557. for (int i = items.size(); --i >= 0;)
  56558. {
  56559. const Item* mi = items.getUnchecked (i);
  56560. if ((mi->itemId == commandID && mi->commandManager != 0)
  56561. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56562. {
  56563. return true;
  56564. }
  56565. }
  56566. return false;
  56567. }
  56568. bool PopupMenu::containsAnyActiveItems() const throw()
  56569. {
  56570. for (int i = items.size(); --i >= 0;)
  56571. {
  56572. const Item* const mi = items.getUnchecked (i);
  56573. if (mi->subMenu != 0)
  56574. {
  56575. if (mi->subMenu->containsAnyActiveItems())
  56576. return true;
  56577. }
  56578. else if (mi->active)
  56579. {
  56580. return true;
  56581. }
  56582. }
  56583. return false;
  56584. }
  56585. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56586. {
  56587. lookAndFeel = newLookAndFeel;
  56588. }
  56589. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56590. : isHighlighted (false),
  56591. triggeredAutomatically (isTriggeredAutomatically_)
  56592. {
  56593. }
  56594. PopupMenu::CustomComponent::~CustomComponent()
  56595. {
  56596. }
  56597. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56598. {
  56599. isHighlighted = shouldBeHighlighted;
  56600. repaint();
  56601. }
  56602. void PopupMenu::CustomComponent::triggerMenuItem()
  56603. {
  56604. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56605. if (mic != 0)
  56606. {
  56607. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56608. if (pmw != 0)
  56609. {
  56610. pmw->dismissMenu (&mic->itemInfo);
  56611. }
  56612. else
  56613. {
  56614. // something must have gone wrong with the component hierarchy if this happens..
  56615. jassertfalse;
  56616. }
  56617. }
  56618. else
  56619. {
  56620. // why isn't this component inside a menu? Not much point triggering the item if
  56621. // there's no menu.
  56622. jassertfalse;
  56623. }
  56624. }
  56625. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56626. : subMenu (0),
  56627. itemId (0),
  56628. isSeparator (false),
  56629. isTicked (false),
  56630. isEnabled (false),
  56631. isCustomComponent (false),
  56632. isSectionHeader (false),
  56633. customColour (0),
  56634. customImage (0),
  56635. menu (menu_),
  56636. index (0)
  56637. {
  56638. }
  56639. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56640. {
  56641. }
  56642. bool PopupMenu::MenuItemIterator::next()
  56643. {
  56644. if (index >= menu.items.size())
  56645. return false;
  56646. const Item* const item = menu.items.getUnchecked (index);
  56647. ++index;
  56648. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56649. subMenu = item->subMenu;
  56650. itemId = item->itemId;
  56651. isSeparator = item->isSeparator;
  56652. isTicked = item->isTicked;
  56653. isEnabled = item->active;
  56654. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  56655. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56656. customColour = item->usesColour ? &(item->textColour) : 0;
  56657. customImage = item->image;
  56658. commandManager = item->commandManager;
  56659. return true;
  56660. }
  56661. END_JUCE_NAMESPACE
  56662. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56663. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56664. BEGIN_JUCE_NAMESPACE
  56665. ComponentDragger::ComponentDragger()
  56666. {
  56667. }
  56668. ComponentDragger::~ComponentDragger()
  56669. {
  56670. }
  56671. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56672. {
  56673. jassert (componentToDrag != 0);
  56674. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56675. if (componentToDrag != 0)
  56676. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56677. }
  56678. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56679. ComponentBoundsConstrainer* const constrainer)
  56680. {
  56681. jassert (componentToDrag != 0);
  56682. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56683. if (componentToDrag != 0)
  56684. {
  56685. Rectangle<int> bounds (componentToDrag->getBounds());
  56686. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56687. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56688. // the current mouse position instead of the one that the event contains...
  56689. if (componentToDrag->isOnDesktop())
  56690. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56691. else
  56692. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56693. if (constrainer != 0)
  56694. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56695. else
  56696. componentToDrag->setBounds (bounds);
  56697. }
  56698. }
  56699. END_JUCE_NAMESPACE
  56700. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56701. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56702. BEGIN_JUCE_NAMESPACE
  56703. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56704. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56705. class DragImageComponent : public Component,
  56706. public Timer
  56707. {
  56708. public:
  56709. DragImageComponent (const Image& im,
  56710. const String& desc,
  56711. Component* const sourceComponent,
  56712. Component* const mouseDragSource_,
  56713. DragAndDropContainer* const o,
  56714. const Point<int>& imageOffset_)
  56715. : image (im),
  56716. source (sourceComponent),
  56717. mouseDragSource (mouseDragSource_),
  56718. owner (o),
  56719. dragDesc (desc),
  56720. imageOffset (imageOffset_),
  56721. hasCheckedForExternalDrag (false),
  56722. drawImage (true)
  56723. {
  56724. setSize (im.getWidth(), im.getHeight());
  56725. if (mouseDragSource == 0)
  56726. mouseDragSource = source;
  56727. mouseDragSource->addMouseListener (this, false);
  56728. startTimer (200);
  56729. setInterceptsMouseClicks (false, false);
  56730. setAlwaysOnTop (true);
  56731. }
  56732. ~DragImageComponent()
  56733. {
  56734. if (owner->dragImageComponent == this)
  56735. owner->dragImageComponent.release();
  56736. if (mouseDragSource != 0)
  56737. {
  56738. mouseDragSource->removeMouseListener (this);
  56739. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56740. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56741. }
  56742. }
  56743. void paint (Graphics& g)
  56744. {
  56745. if (isOpaque())
  56746. g.fillAll (Colours::white);
  56747. if (drawImage)
  56748. {
  56749. g.setOpacity (1.0f);
  56750. g.drawImageAt (image, 0, 0);
  56751. }
  56752. }
  56753. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56754. {
  56755. Component* hit = getParentComponent();
  56756. if (hit == 0)
  56757. {
  56758. hit = Desktop::getInstance().findComponentAt (screenPos);
  56759. }
  56760. else
  56761. {
  56762. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56763. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56764. }
  56765. // (note: use a local copy of the dragDesc member in case the callback runs
  56766. // a modal loop and deletes this object before the method completes)
  56767. const String dragDescLocal (dragDesc);
  56768. while (hit != 0)
  56769. {
  56770. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56771. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56772. {
  56773. relativePos = hit->getLocalPoint (0, screenPos);
  56774. return ddt;
  56775. }
  56776. hit = hit->getParentComponent();
  56777. }
  56778. return 0;
  56779. }
  56780. void mouseUp (const MouseEvent& e)
  56781. {
  56782. if (e.originalComponent != this)
  56783. {
  56784. if (mouseDragSource != 0)
  56785. mouseDragSource->removeMouseListener (this);
  56786. bool dropAccepted = false;
  56787. DragAndDropTarget* ddt = 0;
  56788. Point<int> relPos;
  56789. if (isVisible())
  56790. {
  56791. setVisible (false);
  56792. ddt = findTarget (e.getScreenPosition(), relPos);
  56793. // fade this component and remove it - it'll be deleted later by the timer callback
  56794. dropAccepted = ddt != 0;
  56795. setVisible (true);
  56796. if (dropAccepted || source == 0)
  56797. {
  56798. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56799. }
  56800. else
  56801. {
  56802. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56803. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56804. Desktop::getInstance().getAnimator().animateComponent (this,
  56805. getBounds() + (target - ourCentre),
  56806. 0.0f, 120,
  56807. true, 1.0, 1.0);
  56808. }
  56809. }
  56810. if (getParentComponent() != 0)
  56811. getParentComponent()->removeChildComponent (this);
  56812. if (dropAccepted && ddt != 0)
  56813. {
  56814. // (note: use a local copy of the dragDesc member in case the callback runs
  56815. // a modal loop and deletes this object before the method completes)
  56816. const String dragDescLocal (dragDesc);
  56817. currentlyOverComp = 0;
  56818. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56819. }
  56820. // careful - this object could now be deleted..
  56821. }
  56822. }
  56823. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56824. {
  56825. // (note: use a local copy of the dragDesc member in case the callback runs
  56826. // a modal loop and deletes this object before it returns)
  56827. const String dragDescLocal (dragDesc);
  56828. Point<int> newPos (screenPos + imageOffset);
  56829. if (getParentComponent() != 0)
  56830. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56831. //if (newX != getX() || newY != getY())
  56832. {
  56833. setTopLeftPosition (newPos.getX(), newPos.getY());
  56834. Point<int> relPos;
  56835. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56836. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56837. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56838. if (ddtComp != currentlyOverComp)
  56839. {
  56840. if (currentlyOverComp != 0 && source != 0
  56841. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56842. {
  56843. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56844. }
  56845. currentlyOverComp = ddtComp;
  56846. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56847. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56848. }
  56849. DragAndDropTarget* target = getCurrentlyOver();
  56850. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56851. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56852. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56853. {
  56854. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56855. {
  56856. hasCheckedForExternalDrag = true;
  56857. StringArray files;
  56858. bool canMoveFiles = false;
  56859. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56860. && files.size() > 0)
  56861. {
  56862. WeakReference<Component> cdw (this);
  56863. setVisible (false);
  56864. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56865. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56866. if (cdw != 0)
  56867. delete this;
  56868. return;
  56869. }
  56870. }
  56871. }
  56872. }
  56873. }
  56874. void mouseDrag (const MouseEvent& e)
  56875. {
  56876. if (e.originalComponent != this)
  56877. updateLocation (true, e.getScreenPosition());
  56878. }
  56879. void timerCallback()
  56880. {
  56881. if (source == 0)
  56882. {
  56883. delete this;
  56884. }
  56885. else if (! isMouseButtonDownAnywhere())
  56886. {
  56887. if (mouseDragSource != 0)
  56888. mouseDragSource->removeMouseListener (this);
  56889. delete this;
  56890. }
  56891. }
  56892. private:
  56893. Image image;
  56894. WeakReference<Component> source;
  56895. WeakReference<Component> mouseDragSource;
  56896. DragAndDropContainer* const owner;
  56897. WeakReference<Component> currentlyOverComp;
  56898. DragAndDropTarget* getCurrentlyOver()
  56899. {
  56900. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  56901. }
  56902. String dragDesc;
  56903. const Point<int> imageOffset;
  56904. bool hasCheckedForExternalDrag, drawImage;
  56905. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  56906. };
  56907. DragAndDropContainer::DragAndDropContainer()
  56908. {
  56909. }
  56910. DragAndDropContainer::~DragAndDropContainer()
  56911. {
  56912. dragImageComponent = 0;
  56913. }
  56914. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56915. Component* sourceComponent,
  56916. const Image& dragImage_,
  56917. const bool allowDraggingToExternalWindows,
  56918. const Point<int>* imageOffsetFromMouse)
  56919. {
  56920. Image dragImage (dragImage_);
  56921. if (dragImageComponent == 0)
  56922. {
  56923. Component* const thisComp = dynamic_cast <Component*> (this);
  56924. if (thisComp == 0)
  56925. {
  56926. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56927. return;
  56928. }
  56929. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56930. if (draggingSource == 0 || ! draggingSource->isDragging())
  56931. {
  56932. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56933. return;
  56934. }
  56935. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56936. Point<int> imageOffset;
  56937. if (dragImage.isNull())
  56938. {
  56939. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56940. .convertedToFormat (Image::ARGB);
  56941. dragImage.multiplyAllAlphas (0.6f);
  56942. const int lo = 150;
  56943. const int hi = 400;
  56944. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  56945. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56946. for (int y = dragImage.getHeight(); --y >= 0;)
  56947. {
  56948. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56949. for (int x = dragImage.getWidth(); --x >= 0;)
  56950. {
  56951. const int dx = x - clipped.getX();
  56952. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56953. if (distance > lo)
  56954. {
  56955. const float alpha = (distance > hi) ? 0
  56956. : (hi - distance) / (float) (hi - lo)
  56957. + Random::getSystemRandom().nextFloat() * 0.008f;
  56958. dragImage.multiplyAlphaAt (x, y, alpha);
  56959. }
  56960. }
  56961. }
  56962. imageOffset = -clipped;
  56963. }
  56964. else
  56965. {
  56966. if (imageOffsetFromMouse == 0)
  56967. imageOffset = -dragImage.getBounds().getCentre();
  56968. else
  56969. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56970. }
  56971. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56972. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56973. currentDragDesc = sourceDescription;
  56974. if (allowDraggingToExternalWindows)
  56975. {
  56976. if (! Desktop::canUseSemiTransparentWindows())
  56977. dragImageComponent->setOpaque (true);
  56978. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56979. | ComponentPeer::windowIsTemporary
  56980. | ComponentPeer::windowIgnoresKeyPresses);
  56981. }
  56982. else
  56983. thisComp->addChildComponent (dragImageComponent);
  56984. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56985. dragImageComponent->setVisible (true);
  56986. }
  56987. }
  56988. bool DragAndDropContainer::isDragAndDropActive() const
  56989. {
  56990. return dragImageComponent != 0;
  56991. }
  56992. const String DragAndDropContainer::getCurrentDragDescription() const
  56993. {
  56994. return (dragImageComponent != 0) ? currentDragDesc
  56995. : String::empty;
  56996. }
  56997. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56998. {
  56999. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57000. }
  57001. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57002. {
  57003. return false;
  57004. }
  57005. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57006. {
  57007. }
  57008. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57009. {
  57010. }
  57011. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57012. {
  57013. }
  57014. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57015. {
  57016. return true;
  57017. }
  57018. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57019. {
  57020. }
  57021. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57022. {
  57023. }
  57024. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57025. {
  57026. }
  57027. END_JUCE_NAMESPACE
  57028. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57029. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57030. BEGIN_JUCE_NAMESPACE
  57031. class MouseCursor::SharedCursorHandle
  57032. {
  57033. public:
  57034. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57035. : handle (createStandardMouseCursor (type)),
  57036. refCount (1),
  57037. standardType (type),
  57038. isStandard (true)
  57039. {
  57040. }
  57041. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57042. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57043. refCount (1),
  57044. standardType (MouseCursor::NormalCursor),
  57045. isStandard (false)
  57046. {
  57047. }
  57048. ~SharedCursorHandle()
  57049. {
  57050. deleteMouseCursor (handle, isStandard);
  57051. }
  57052. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57053. {
  57054. const ScopedLock sl (getLock());
  57055. for (int i = 0; i < getCursors().size(); ++i)
  57056. {
  57057. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57058. if (sc->standardType == type)
  57059. return sc->retain();
  57060. }
  57061. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57062. getCursors().add (sc);
  57063. return sc;
  57064. }
  57065. SharedCursorHandle* retain() throw()
  57066. {
  57067. ++refCount;
  57068. return this;
  57069. }
  57070. void release()
  57071. {
  57072. if (--refCount == 0)
  57073. {
  57074. if (isStandard)
  57075. {
  57076. const ScopedLock sl (getLock());
  57077. getCursors().removeValue (this);
  57078. }
  57079. delete this;
  57080. }
  57081. }
  57082. void* getHandle() const throw() { return handle; }
  57083. private:
  57084. void* const handle;
  57085. Atomic <int> refCount;
  57086. const MouseCursor::StandardCursorType standardType;
  57087. const bool isStandard;
  57088. static CriticalSection& getLock()
  57089. {
  57090. static CriticalSection lock;
  57091. return lock;
  57092. }
  57093. static Array <SharedCursorHandle*>& getCursors()
  57094. {
  57095. static Array <SharedCursorHandle*> cursors;
  57096. return cursors;
  57097. }
  57098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57099. };
  57100. MouseCursor::MouseCursor()
  57101. : cursorHandle (0)
  57102. {
  57103. }
  57104. MouseCursor::MouseCursor (const StandardCursorType type)
  57105. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57106. {
  57107. }
  57108. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57109. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57110. {
  57111. }
  57112. MouseCursor::MouseCursor (const MouseCursor& other)
  57113. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57114. {
  57115. }
  57116. MouseCursor::~MouseCursor()
  57117. {
  57118. if (cursorHandle != 0)
  57119. cursorHandle->release();
  57120. }
  57121. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57122. {
  57123. if (other.cursorHandle != 0)
  57124. other.cursorHandle->retain();
  57125. if (cursorHandle != 0)
  57126. cursorHandle->release();
  57127. cursorHandle = other.cursorHandle;
  57128. return *this;
  57129. }
  57130. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57131. {
  57132. return getHandle() == other.getHandle();
  57133. }
  57134. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57135. {
  57136. return getHandle() != other.getHandle();
  57137. }
  57138. void* MouseCursor::getHandle() const throw()
  57139. {
  57140. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57141. }
  57142. void MouseCursor::showWaitCursor()
  57143. {
  57144. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57145. }
  57146. void MouseCursor::hideWaitCursor()
  57147. {
  57148. Desktop::getInstance().getMainMouseSource().revealCursor();
  57149. }
  57150. END_JUCE_NAMESPACE
  57151. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57152. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57153. BEGIN_JUCE_NAMESPACE
  57154. MouseEvent::MouseEvent (MouseInputSource& source_,
  57155. const Point<int>& position,
  57156. const ModifierKeys& mods_,
  57157. Component* const eventComponent_,
  57158. Component* const originator,
  57159. const Time& eventTime_,
  57160. const Point<int> mouseDownPos_,
  57161. const Time& mouseDownTime_,
  57162. const int numberOfClicks_,
  57163. const bool mouseWasDragged) throw()
  57164. : x (position.getX()),
  57165. y (position.getY()),
  57166. mods (mods_),
  57167. eventComponent (eventComponent_),
  57168. originalComponent (originator),
  57169. eventTime (eventTime_),
  57170. source (source_),
  57171. mouseDownPos (mouseDownPos_),
  57172. mouseDownTime (mouseDownTime_),
  57173. numberOfClicks (numberOfClicks_),
  57174. wasMovedSinceMouseDown (mouseWasDragged)
  57175. {
  57176. }
  57177. MouseEvent::~MouseEvent() throw()
  57178. {
  57179. }
  57180. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57181. {
  57182. if (otherComponent == 0)
  57183. {
  57184. jassertfalse;
  57185. return *this;
  57186. }
  57187. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57188. mods, otherComponent, originalComponent, eventTime,
  57189. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57190. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57191. }
  57192. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57193. {
  57194. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57195. eventTime, mouseDownPos, mouseDownTime,
  57196. numberOfClicks, wasMovedSinceMouseDown);
  57197. }
  57198. bool MouseEvent::mouseWasClicked() const throw()
  57199. {
  57200. return ! wasMovedSinceMouseDown;
  57201. }
  57202. int MouseEvent::getMouseDownX() const throw()
  57203. {
  57204. return mouseDownPos.getX();
  57205. }
  57206. int MouseEvent::getMouseDownY() const throw()
  57207. {
  57208. return mouseDownPos.getY();
  57209. }
  57210. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57211. {
  57212. return mouseDownPos;
  57213. }
  57214. int MouseEvent::getDistanceFromDragStartX() const throw()
  57215. {
  57216. return x - mouseDownPos.getX();
  57217. }
  57218. int MouseEvent::getDistanceFromDragStartY() const throw()
  57219. {
  57220. return y - mouseDownPos.getY();
  57221. }
  57222. int MouseEvent::getDistanceFromDragStart() const throw()
  57223. {
  57224. return mouseDownPos.getDistanceFrom (getPosition());
  57225. }
  57226. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57227. {
  57228. return getPosition() - mouseDownPos;
  57229. }
  57230. int MouseEvent::getLengthOfMousePress() const throw()
  57231. {
  57232. if (mouseDownTime.toMilliseconds() > 0)
  57233. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57234. return 0;
  57235. }
  57236. const Point<int> MouseEvent::getPosition() const throw()
  57237. {
  57238. return Point<int> (x, y);
  57239. }
  57240. int MouseEvent::getScreenX() const
  57241. {
  57242. return getScreenPosition().getX();
  57243. }
  57244. int MouseEvent::getScreenY() const
  57245. {
  57246. return getScreenPosition().getY();
  57247. }
  57248. const Point<int> MouseEvent::getScreenPosition() const
  57249. {
  57250. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57251. }
  57252. int MouseEvent::getMouseDownScreenX() const
  57253. {
  57254. return getMouseDownScreenPosition().getX();
  57255. }
  57256. int MouseEvent::getMouseDownScreenY() const
  57257. {
  57258. return getMouseDownScreenPosition().getY();
  57259. }
  57260. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57261. {
  57262. return eventComponent->localPointToGlobal (mouseDownPos);
  57263. }
  57264. int MouseEvent::doubleClickTimeOutMs = 400;
  57265. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57266. {
  57267. doubleClickTimeOutMs = newTime;
  57268. }
  57269. int MouseEvent::getDoubleClickTimeout() throw()
  57270. {
  57271. return doubleClickTimeOutMs;
  57272. }
  57273. END_JUCE_NAMESPACE
  57274. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57275. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57276. BEGIN_JUCE_NAMESPACE
  57277. class MouseInputSourceInternal : public AsyncUpdater
  57278. {
  57279. public:
  57280. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57281. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57282. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57283. mouseEventCounter (0)
  57284. {
  57285. }
  57286. bool isDragging() const throw()
  57287. {
  57288. return buttonState.isAnyMouseButtonDown();
  57289. }
  57290. Component* getComponentUnderMouse() const
  57291. {
  57292. return static_cast <Component*> (componentUnderMouse);
  57293. }
  57294. const ModifierKeys getCurrentModifiers() const
  57295. {
  57296. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57297. }
  57298. ComponentPeer* getPeer()
  57299. {
  57300. if (! ComponentPeer::isValidPeer (lastPeer))
  57301. lastPeer = 0;
  57302. return lastPeer;
  57303. }
  57304. Component* findComponentAt (const Point<int>& screenPos)
  57305. {
  57306. ComponentPeer* const peer = getPeer();
  57307. if (peer != 0)
  57308. {
  57309. Component* const comp = peer->getComponent();
  57310. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57311. // (the contains() call is needed to test for overlapping desktop windows)
  57312. if (comp->contains (relativePos))
  57313. return comp->getComponentAt (relativePos);
  57314. }
  57315. return 0;
  57316. }
  57317. const Point<int> getScreenPosition() const
  57318. {
  57319. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57320. // value, because that can cause continuity problems.
  57321. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57322. : lastScreenPos);
  57323. }
  57324. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57325. {
  57326. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57327. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57328. }
  57329. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57330. {
  57331. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57332. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57333. }
  57334. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57335. {
  57336. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57337. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57338. }
  57339. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57340. {
  57341. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57342. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57343. }
  57344. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57345. {
  57346. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57347. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57348. }
  57349. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57350. {
  57351. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57352. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57353. }
  57354. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57355. {
  57356. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57357. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57358. }
  57359. // (returns true if the button change caused a modal event loop)
  57360. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57361. {
  57362. if (buttonState == newButtonState)
  57363. return false;
  57364. setScreenPos (screenPos, time, false);
  57365. // (ignore secondary clicks when there's already a button down)
  57366. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57367. {
  57368. buttonState = newButtonState;
  57369. return false;
  57370. }
  57371. const int lastCounter = mouseEventCounter;
  57372. if (buttonState.isAnyMouseButtonDown())
  57373. {
  57374. Component* const current = getComponentUnderMouse();
  57375. if (current != 0)
  57376. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57377. enableUnboundedMouseMovement (false, false);
  57378. }
  57379. buttonState = newButtonState;
  57380. if (buttonState.isAnyMouseButtonDown())
  57381. {
  57382. Desktop::getInstance().incrementMouseClickCounter();
  57383. Component* const current = getComponentUnderMouse();
  57384. if (current != 0)
  57385. {
  57386. registerMouseDown (screenPos, time, current, buttonState);
  57387. sendMouseDown (current, screenPos, time);
  57388. }
  57389. }
  57390. return lastCounter != mouseEventCounter;
  57391. }
  57392. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57393. {
  57394. Component* current = getComponentUnderMouse();
  57395. if (newComponent != current)
  57396. {
  57397. WeakReference<Component> safeNewComp (newComponent);
  57398. const ModifierKeys originalButtonState (buttonState);
  57399. if (current != 0)
  57400. {
  57401. setButtons (screenPos, time, ModifierKeys());
  57402. sendMouseExit (current, screenPos, time);
  57403. buttonState = originalButtonState;
  57404. }
  57405. componentUnderMouse = safeNewComp;
  57406. current = getComponentUnderMouse();
  57407. if (current != 0)
  57408. sendMouseEnter (current, screenPos, time);
  57409. revealCursor (false);
  57410. setButtons (screenPos, time, originalButtonState);
  57411. }
  57412. }
  57413. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57414. {
  57415. ModifierKeys::updateCurrentModifiers();
  57416. if (newPeer != lastPeer)
  57417. {
  57418. setComponentUnderMouse (0, screenPos, time);
  57419. lastPeer = newPeer;
  57420. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57421. }
  57422. }
  57423. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57424. {
  57425. if (! isDragging())
  57426. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57427. if (newScreenPos != lastScreenPos || forceUpdate)
  57428. {
  57429. cancelPendingUpdate();
  57430. lastScreenPos = newScreenPos;
  57431. Component* const current = getComponentUnderMouse();
  57432. if (current != 0)
  57433. {
  57434. if (isDragging())
  57435. {
  57436. registerMouseDrag (newScreenPos);
  57437. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57438. if (isUnboundedMouseModeOn)
  57439. handleUnboundedDrag (current);
  57440. }
  57441. else
  57442. {
  57443. sendMouseMove (current, newScreenPos, time);
  57444. }
  57445. }
  57446. revealCursor (false);
  57447. }
  57448. }
  57449. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57450. {
  57451. jassert (newPeer != 0);
  57452. lastTime = time;
  57453. ++mouseEventCounter;
  57454. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57455. if (isDragging() && newMods.isAnyMouseButtonDown())
  57456. {
  57457. setScreenPos (screenPos, time, false);
  57458. }
  57459. else
  57460. {
  57461. setPeer (newPeer, screenPos, time);
  57462. ComponentPeer* peer = getPeer();
  57463. if (peer != 0)
  57464. {
  57465. if (setButtons (screenPos, time, newMods))
  57466. return; // some modal events have been dispatched, so the current event is now out-of-date
  57467. peer = getPeer();
  57468. if (peer != 0)
  57469. setScreenPos (screenPos, time, false);
  57470. }
  57471. }
  57472. }
  57473. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57474. {
  57475. jassert (peer != 0);
  57476. lastTime = time;
  57477. ++mouseEventCounter;
  57478. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57479. setPeer (peer, screenPos, time);
  57480. setScreenPos (screenPos, time, false);
  57481. triggerFakeMove();
  57482. if (! isDragging())
  57483. {
  57484. Component* current = getComponentUnderMouse();
  57485. if (current != 0)
  57486. sendMouseWheel (current, screenPos, time, x, y);
  57487. }
  57488. }
  57489. const Time getLastMouseDownTime() const throw()
  57490. {
  57491. return Time (mouseDowns[0].time);
  57492. }
  57493. const Point<int> getLastMouseDownPosition() const throw()
  57494. {
  57495. return mouseDowns[0].position;
  57496. }
  57497. int getNumberOfMultipleClicks() const throw()
  57498. {
  57499. int numClicks = 0;
  57500. if (mouseDowns[0].time != Time())
  57501. {
  57502. if (! mouseMovedSignificantlySincePressed)
  57503. ++numClicks;
  57504. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57505. {
  57506. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57507. ++numClicks;
  57508. else
  57509. break;
  57510. }
  57511. }
  57512. return numClicks;
  57513. }
  57514. bool hasMouseMovedSignificantlySincePressed() const throw()
  57515. {
  57516. return mouseMovedSignificantlySincePressed
  57517. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57518. }
  57519. void triggerFakeMove()
  57520. {
  57521. triggerAsyncUpdate();
  57522. }
  57523. void handleAsyncUpdate()
  57524. {
  57525. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57526. }
  57527. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57528. {
  57529. enable = enable && isDragging();
  57530. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57531. if (enable != isUnboundedMouseModeOn)
  57532. {
  57533. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57534. {
  57535. // when released, return the mouse to within the component's bounds
  57536. Component* current = getComponentUnderMouse();
  57537. if (current != 0)
  57538. Desktop::setMousePosition (current->getScreenBounds()
  57539. .getConstrainedPoint (lastScreenPos));
  57540. }
  57541. isUnboundedMouseModeOn = enable;
  57542. unboundedMouseOffset = Point<int>();
  57543. revealCursor (true);
  57544. }
  57545. }
  57546. void handleUnboundedDrag (Component* current)
  57547. {
  57548. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57549. if (! screenArea.contains (lastScreenPos))
  57550. {
  57551. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57552. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57553. Desktop::setMousePosition (componentCentre);
  57554. }
  57555. else if (isCursorVisibleUntilOffscreen
  57556. && (! unboundedMouseOffset.isOrigin())
  57557. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57558. {
  57559. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57560. unboundedMouseOffset = Point<int>();
  57561. }
  57562. }
  57563. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57564. {
  57565. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57566. {
  57567. cursor = MouseCursor::NoCursor;
  57568. forcedUpdate = true;
  57569. }
  57570. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57571. {
  57572. currentCursorHandle = cursor.getHandle();
  57573. cursor.showInWindow (getPeer());
  57574. }
  57575. }
  57576. void hideCursor()
  57577. {
  57578. showMouseCursor (MouseCursor::NoCursor, true);
  57579. }
  57580. void revealCursor (bool forcedUpdate)
  57581. {
  57582. MouseCursor mc (MouseCursor::NormalCursor);
  57583. Component* current = getComponentUnderMouse();
  57584. if (current != 0)
  57585. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57586. showMouseCursor (mc, forcedUpdate);
  57587. }
  57588. const int index;
  57589. const bool isMouseDevice;
  57590. Point<int> lastScreenPos;
  57591. ModifierKeys buttonState;
  57592. private:
  57593. MouseInputSource& source;
  57594. WeakReference<Component> componentUnderMouse;
  57595. ComponentPeer* lastPeer;
  57596. Point<int> unboundedMouseOffset;
  57597. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57598. void* currentCursorHandle;
  57599. int mouseEventCounter;
  57600. struct RecentMouseDown
  57601. {
  57602. RecentMouseDown() : component (0)
  57603. {
  57604. }
  57605. Point<int> position;
  57606. Time time;
  57607. Component* component;
  57608. ModifierKeys buttons;
  57609. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57610. {
  57611. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57612. && abs (position.getX() - other.position.getX()) < 8
  57613. && abs (position.getY() - other.position.getY()) < 8
  57614. && buttons == other.buttons;;
  57615. }
  57616. };
  57617. RecentMouseDown mouseDowns[4];
  57618. bool mouseMovedSignificantlySincePressed;
  57619. Time lastTime;
  57620. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57621. Component* const component, const ModifierKeys& modifiers) throw()
  57622. {
  57623. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57624. mouseDowns[i] = mouseDowns[i - 1];
  57625. mouseDowns[0].position = screenPos;
  57626. mouseDowns[0].time = time;
  57627. mouseDowns[0].component = component;
  57628. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57629. mouseMovedSignificantlySincePressed = false;
  57630. }
  57631. void registerMouseDrag (const Point<int>& screenPos) throw()
  57632. {
  57633. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57634. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57635. }
  57636. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57637. };
  57638. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57639. {
  57640. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57641. }
  57642. MouseInputSource::~MouseInputSource()
  57643. {
  57644. }
  57645. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57646. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57647. bool MouseInputSource::canHover() const { return isMouse(); }
  57648. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57649. int MouseInputSource::getIndex() const { return pimpl->index; }
  57650. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57651. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57652. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57653. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57654. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57655. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57656. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57657. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57658. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57659. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57660. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57661. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57662. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57663. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57664. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57665. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57666. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57667. {
  57668. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57669. }
  57670. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57671. {
  57672. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57673. }
  57674. END_JUCE_NAMESPACE
  57675. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57676. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57677. BEGIN_JUCE_NAMESPACE
  57678. void MouseListener::mouseEnter (const MouseEvent&)
  57679. {
  57680. }
  57681. void MouseListener::mouseExit (const MouseEvent&)
  57682. {
  57683. }
  57684. void MouseListener::mouseDown (const MouseEvent&)
  57685. {
  57686. }
  57687. void MouseListener::mouseUp (const MouseEvent&)
  57688. {
  57689. }
  57690. void MouseListener::mouseDrag (const MouseEvent&)
  57691. {
  57692. }
  57693. void MouseListener::mouseMove (const MouseEvent&)
  57694. {
  57695. }
  57696. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57697. {
  57698. }
  57699. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57700. {
  57701. }
  57702. END_JUCE_NAMESPACE
  57703. /*** End of inlined file: juce_MouseListener.cpp ***/
  57704. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57705. BEGIN_JUCE_NAMESPACE
  57706. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57707. const String& buttonTextWhenTrue,
  57708. const String& buttonTextWhenFalse)
  57709. : PropertyComponent (name),
  57710. onText (buttonTextWhenTrue),
  57711. offText (buttonTextWhenFalse)
  57712. {
  57713. addAndMakeVisible (&button);
  57714. button.setClickingTogglesState (false);
  57715. button.addListener (this);
  57716. }
  57717. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57718. const String& name,
  57719. const String& buttonText)
  57720. : PropertyComponent (name),
  57721. onText (buttonText),
  57722. offText (buttonText)
  57723. {
  57724. addAndMakeVisible (&button);
  57725. button.setClickingTogglesState (false);
  57726. button.setButtonText (buttonText);
  57727. button.getToggleStateValue().referTo (valueToControl);
  57728. button.setClickingTogglesState (true);
  57729. }
  57730. BooleanPropertyComponent::~BooleanPropertyComponent()
  57731. {
  57732. }
  57733. void BooleanPropertyComponent::setState (const bool newState)
  57734. {
  57735. button.setToggleState (newState, true);
  57736. }
  57737. bool BooleanPropertyComponent::getState() const
  57738. {
  57739. return button.getToggleState();
  57740. }
  57741. void BooleanPropertyComponent::paint (Graphics& g)
  57742. {
  57743. PropertyComponent::paint (g);
  57744. g.setColour (Colours::white);
  57745. g.fillRect (button.getBounds());
  57746. g.setColour (findColour (ComboBox::outlineColourId));
  57747. g.drawRect (button.getBounds());
  57748. }
  57749. void BooleanPropertyComponent::refresh()
  57750. {
  57751. button.setToggleState (getState(), false);
  57752. button.setButtonText (button.getToggleState() ? onText : offText);
  57753. }
  57754. void BooleanPropertyComponent::buttonClicked (Button*)
  57755. {
  57756. setState (! getState());
  57757. }
  57758. END_JUCE_NAMESPACE
  57759. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57760. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57761. BEGIN_JUCE_NAMESPACE
  57762. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57763. const bool triggerOnMouseDown)
  57764. : PropertyComponent (name)
  57765. {
  57766. addAndMakeVisible (&button);
  57767. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57768. button.addListener (this);
  57769. }
  57770. ButtonPropertyComponent::~ButtonPropertyComponent()
  57771. {
  57772. }
  57773. void ButtonPropertyComponent::refresh()
  57774. {
  57775. button.setButtonText (getButtonText());
  57776. }
  57777. void ButtonPropertyComponent::buttonClicked (Button*)
  57778. {
  57779. buttonClicked();
  57780. }
  57781. END_JUCE_NAMESPACE
  57782. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57783. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57784. BEGIN_JUCE_NAMESPACE
  57785. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57786. public ValueListener
  57787. {
  57788. public:
  57789. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57790. : sourceValue (sourceValue_),
  57791. mappings (mappings_)
  57792. {
  57793. sourceValue.addListener (this);
  57794. }
  57795. ~RemapperValueSource() {}
  57796. const var getValue() const
  57797. {
  57798. return mappings.indexOf (sourceValue.getValue()) + 1;
  57799. }
  57800. void setValue (const var& newValue)
  57801. {
  57802. const var remappedVal (mappings [(int) newValue - 1]);
  57803. if (remappedVal != sourceValue)
  57804. sourceValue = remappedVal;
  57805. }
  57806. void valueChanged (Value&)
  57807. {
  57808. sendChangeMessage (true);
  57809. }
  57810. protected:
  57811. Value sourceValue;
  57812. Array<var> mappings;
  57813. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57814. };
  57815. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57816. : PropertyComponent (name),
  57817. isCustomClass (true)
  57818. {
  57819. }
  57820. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57821. const String& name,
  57822. const StringArray& choices_,
  57823. const Array <var>& correspondingValues)
  57824. : PropertyComponent (name),
  57825. choices (choices_),
  57826. isCustomClass (false)
  57827. {
  57828. // The array of corresponding values must contain one value for each of the items in
  57829. // the choices array!
  57830. jassert (correspondingValues.size() == choices.size());
  57831. createComboBox();
  57832. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57833. }
  57834. ChoicePropertyComponent::~ChoicePropertyComponent()
  57835. {
  57836. }
  57837. void ChoicePropertyComponent::createComboBox()
  57838. {
  57839. addAndMakeVisible (&comboBox);
  57840. for (int i = 0; i < choices.size(); ++i)
  57841. {
  57842. if (choices[i].isNotEmpty())
  57843. comboBox.addItem (choices[i], i + 1);
  57844. else
  57845. comboBox.addSeparator();
  57846. }
  57847. comboBox.setEditableText (false);
  57848. }
  57849. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57850. {
  57851. jassertfalse; // you need to override this method in your subclass!
  57852. }
  57853. int ChoicePropertyComponent::getIndex() const
  57854. {
  57855. jassertfalse; // you need to override this method in your subclass!
  57856. return -1;
  57857. }
  57858. const StringArray& ChoicePropertyComponent::getChoices() const
  57859. {
  57860. return choices;
  57861. }
  57862. void ChoicePropertyComponent::refresh()
  57863. {
  57864. if (isCustomClass)
  57865. {
  57866. if (! comboBox.isVisible())
  57867. {
  57868. createComboBox();
  57869. comboBox.addListener (this);
  57870. }
  57871. comboBox.setSelectedId (getIndex() + 1, true);
  57872. }
  57873. }
  57874. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57875. {
  57876. if (isCustomClass)
  57877. {
  57878. const int newIndex = comboBox.getSelectedId() - 1;
  57879. if (newIndex != getIndex())
  57880. setIndex (newIndex);
  57881. }
  57882. }
  57883. END_JUCE_NAMESPACE
  57884. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57885. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57886. BEGIN_JUCE_NAMESPACE
  57887. PropertyComponent::PropertyComponent (const String& name,
  57888. const int preferredHeight_)
  57889. : Component (name),
  57890. preferredHeight (preferredHeight_)
  57891. {
  57892. jassert (name.isNotEmpty());
  57893. }
  57894. PropertyComponent::~PropertyComponent()
  57895. {
  57896. }
  57897. void PropertyComponent::paint (Graphics& g)
  57898. {
  57899. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57900. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57901. }
  57902. void PropertyComponent::resized()
  57903. {
  57904. if (getNumChildComponents() > 0)
  57905. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57906. }
  57907. void PropertyComponent::enablementChanged()
  57908. {
  57909. repaint();
  57910. }
  57911. END_JUCE_NAMESPACE
  57912. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57913. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57914. BEGIN_JUCE_NAMESPACE
  57915. class PropertySectionComponent : public Component
  57916. {
  57917. public:
  57918. PropertySectionComponent (const String& sectionTitle,
  57919. const Array <PropertyComponent*>& newProperties,
  57920. const bool sectionIsOpen_)
  57921. : Component (sectionTitle),
  57922. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57923. sectionIsOpen (sectionIsOpen_)
  57924. {
  57925. propertyComps.addArray (newProperties);
  57926. for (int i = propertyComps.size(); --i >= 0;)
  57927. {
  57928. addAndMakeVisible (propertyComps.getUnchecked(i));
  57929. propertyComps.getUnchecked(i)->refresh();
  57930. }
  57931. }
  57932. ~PropertySectionComponent()
  57933. {
  57934. propertyComps.clear();
  57935. }
  57936. void paint (Graphics& g)
  57937. {
  57938. if (titleHeight > 0)
  57939. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57940. }
  57941. void resized()
  57942. {
  57943. int y = titleHeight;
  57944. for (int i = 0; i < propertyComps.size(); ++i)
  57945. {
  57946. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  57947. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  57948. y = pec->getBottom();
  57949. }
  57950. }
  57951. int getPreferredHeight() const
  57952. {
  57953. int y = titleHeight;
  57954. if (isOpen())
  57955. {
  57956. for (int i = propertyComps.size(); --i >= 0;)
  57957. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  57958. }
  57959. return y;
  57960. }
  57961. void setOpen (const bool open)
  57962. {
  57963. if (sectionIsOpen != open)
  57964. {
  57965. sectionIsOpen = open;
  57966. for (int i = propertyComps.size(); --i >= 0;)
  57967. propertyComps.getUnchecked(i)->setVisible (open);
  57968. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57969. if (pp != 0)
  57970. pp->resized();
  57971. }
  57972. }
  57973. bool isOpen() const
  57974. {
  57975. return sectionIsOpen;
  57976. }
  57977. void refreshAll() const
  57978. {
  57979. for (int i = propertyComps.size(); --i >= 0;)
  57980. propertyComps.getUnchecked (i)->refresh();
  57981. }
  57982. void mouseUp (const MouseEvent& e)
  57983. {
  57984. if (e.getMouseDownX() < titleHeight
  57985. && e.x < titleHeight
  57986. && e.y < titleHeight
  57987. && e.getNumberOfClicks() != 2)
  57988. {
  57989. setOpen (! isOpen());
  57990. }
  57991. }
  57992. void mouseDoubleClick (const MouseEvent& e)
  57993. {
  57994. if (e.y < titleHeight)
  57995. setOpen (! isOpen());
  57996. }
  57997. private:
  57998. OwnedArray <PropertyComponent> propertyComps;
  57999. int titleHeight;
  58000. bool sectionIsOpen;
  58001. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58002. };
  58003. class PropertyPanel::PropertyHolderComponent : public Component
  58004. {
  58005. public:
  58006. PropertyHolderComponent() {}
  58007. void paint (Graphics&) {}
  58008. void updateLayout (int width)
  58009. {
  58010. int y = 0;
  58011. for (int i = 0; i < sections.size(); ++i)
  58012. {
  58013. PropertySectionComponent* const section = sections.getUnchecked(i);
  58014. section->setBounds (0, y, width, section->getPreferredHeight());
  58015. y = section->getBottom();
  58016. }
  58017. setSize (width, y);
  58018. repaint();
  58019. }
  58020. void refreshAll() const
  58021. {
  58022. for (int i = 0; i < sections.size(); ++i)
  58023. sections.getUnchecked(i)->refreshAll();
  58024. }
  58025. void clear()
  58026. {
  58027. sections.clear();
  58028. }
  58029. void addSection (PropertySectionComponent* newSection)
  58030. {
  58031. sections.add (newSection);
  58032. addAndMakeVisible (newSection, 0);
  58033. }
  58034. int getNumSections() const throw() { return sections.size(); }
  58035. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58036. private:
  58037. OwnedArray<PropertySectionComponent> sections;
  58038. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58039. };
  58040. PropertyPanel::PropertyPanel()
  58041. {
  58042. messageWhenEmpty = TRANS("(nothing selected)");
  58043. addAndMakeVisible (&viewport);
  58044. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58045. viewport.setFocusContainer (true);
  58046. }
  58047. PropertyPanel::~PropertyPanel()
  58048. {
  58049. clear();
  58050. }
  58051. void PropertyPanel::paint (Graphics& g)
  58052. {
  58053. if (propertyHolderComponent->getNumSections() == 0)
  58054. {
  58055. g.setColour (Colours::black.withAlpha (0.5f));
  58056. g.setFont (14.0f);
  58057. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58058. Justification::centred, true);
  58059. }
  58060. }
  58061. void PropertyPanel::resized()
  58062. {
  58063. viewport.setBounds (getLocalBounds());
  58064. updatePropHolderLayout();
  58065. }
  58066. void PropertyPanel::clear()
  58067. {
  58068. if (propertyHolderComponent->getNumSections() > 0)
  58069. {
  58070. propertyHolderComponent->clear();
  58071. repaint();
  58072. }
  58073. }
  58074. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58075. {
  58076. if (propertyHolderComponent->getNumSections() == 0)
  58077. repaint();
  58078. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58079. updatePropHolderLayout();
  58080. }
  58081. void PropertyPanel::addSection (const String& sectionTitle,
  58082. const Array <PropertyComponent*>& newProperties,
  58083. const bool shouldBeOpen)
  58084. {
  58085. jassert (sectionTitle.isNotEmpty());
  58086. if (propertyHolderComponent->getNumSections() == 0)
  58087. repaint();
  58088. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58089. updatePropHolderLayout();
  58090. }
  58091. void PropertyPanel::updatePropHolderLayout() const
  58092. {
  58093. const int maxWidth = viewport.getMaximumVisibleWidth();
  58094. propertyHolderComponent->updateLayout (maxWidth);
  58095. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58096. if (maxWidth != newMaxWidth)
  58097. {
  58098. // need to do this twice because of scrollbars changing the size, etc.
  58099. propertyHolderComponent->updateLayout (newMaxWidth);
  58100. }
  58101. }
  58102. void PropertyPanel::refreshAll() const
  58103. {
  58104. propertyHolderComponent->refreshAll();
  58105. }
  58106. const StringArray PropertyPanel::getSectionNames() const
  58107. {
  58108. StringArray s;
  58109. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58110. {
  58111. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58112. if (section->getName().isNotEmpty())
  58113. s.add (section->getName());
  58114. }
  58115. return s;
  58116. }
  58117. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58118. {
  58119. int index = 0;
  58120. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58121. {
  58122. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58123. if (section->getName().isNotEmpty())
  58124. {
  58125. if (index == sectionIndex)
  58126. return section->isOpen();
  58127. ++index;
  58128. }
  58129. }
  58130. return false;
  58131. }
  58132. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58133. {
  58134. int index = 0;
  58135. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58136. {
  58137. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58138. if (section->getName().isNotEmpty())
  58139. {
  58140. if (index == sectionIndex)
  58141. {
  58142. section->setOpen (shouldBeOpen);
  58143. break;
  58144. }
  58145. ++index;
  58146. }
  58147. }
  58148. }
  58149. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58150. {
  58151. int index = 0;
  58152. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58153. {
  58154. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58155. if (section->getName().isNotEmpty())
  58156. {
  58157. if (index == sectionIndex)
  58158. {
  58159. section->setEnabled (shouldBeEnabled);
  58160. break;
  58161. }
  58162. ++index;
  58163. }
  58164. }
  58165. }
  58166. XmlElement* PropertyPanel::getOpennessState() const
  58167. {
  58168. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58169. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58170. const StringArray sections (getSectionNames());
  58171. for (int i = 0; i < sections.size(); ++i)
  58172. {
  58173. if (sections[i].isNotEmpty())
  58174. {
  58175. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58176. e->setAttribute ("name", sections[i]);
  58177. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58178. }
  58179. }
  58180. return xml;
  58181. }
  58182. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58183. {
  58184. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58185. {
  58186. const StringArray sections (getSectionNames());
  58187. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58188. {
  58189. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58190. e->getBoolAttribute ("open"));
  58191. }
  58192. viewport.setViewPosition (viewport.getViewPositionX(),
  58193. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58194. }
  58195. }
  58196. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58197. {
  58198. if (messageWhenEmpty != newMessage)
  58199. {
  58200. messageWhenEmpty = newMessage;
  58201. repaint();
  58202. }
  58203. }
  58204. const String& PropertyPanel::getMessageWhenEmpty() const
  58205. {
  58206. return messageWhenEmpty;
  58207. }
  58208. END_JUCE_NAMESPACE
  58209. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58210. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58211. BEGIN_JUCE_NAMESPACE
  58212. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58213. const double rangeMin,
  58214. const double rangeMax,
  58215. const double interval,
  58216. const double skewFactor)
  58217. : PropertyComponent (name)
  58218. {
  58219. addAndMakeVisible (&slider);
  58220. slider.setRange (rangeMin, rangeMax, interval);
  58221. slider.setSkewFactor (skewFactor);
  58222. slider.setSliderStyle (Slider::LinearBar);
  58223. slider.addListener (this);
  58224. }
  58225. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58226. const String& name,
  58227. const double rangeMin,
  58228. const double rangeMax,
  58229. const double interval,
  58230. const double skewFactor)
  58231. : PropertyComponent (name)
  58232. {
  58233. addAndMakeVisible (&slider);
  58234. slider.setRange (rangeMin, rangeMax, interval);
  58235. slider.setSkewFactor (skewFactor);
  58236. slider.setSliderStyle (Slider::LinearBar);
  58237. slider.getValueObject().referTo (valueToControl);
  58238. }
  58239. SliderPropertyComponent::~SliderPropertyComponent()
  58240. {
  58241. }
  58242. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58243. {
  58244. }
  58245. double SliderPropertyComponent::getValue() const
  58246. {
  58247. return slider.getValue();
  58248. }
  58249. void SliderPropertyComponent::refresh()
  58250. {
  58251. slider.setValue (getValue(), false);
  58252. }
  58253. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58254. {
  58255. if (getValue() != slider.getValue())
  58256. setValue (slider.getValue());
  58257. }
  58258. END_JUCE_NAMESPACE
  58259. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58260. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58261. BEGIN_JUCE_NAMESPACE
  58262. class TextPropLabel : public Label
  58263. {
  58264. public:
  58265. TextPropLabel (TextPropertyComponent& owner_,
  58266. const int maxChars_, const bool isMultiline_)
  58267. : Label (String::empty, String::empty),
  58268. owner (owner_),
  58269. maxChars (maxChars_),
  58270. isMultiline (isMultiline_)
  58271. {
  58272. setEditable (true, true, false);
  58273. setColour (backgroundColourId, Colours::white);
  58274. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58275. }
  58276. TextEditor* createEditorComponent()
  58277. {
  58278. TextEditor* const textEditor = Label::createEditorComponent();
  58279. textEditor->setInputRestrictions (maxChars);
  58280. if (isMultiline)
  58281. {
  58282. textEditor->setMultiLine (true, true);
  58283. textEditor->setReturnKeyStartsNewLine (true);
  58284. }
  58285. return textEditor;
  58286. }
  58287. void textWasEdited()
  58288. {
  58289. owner.textWasEdited();
  58290. }
  58291. private:
  58292. TextPropertyComponent& owner;
  58293. int maxChars;
  58294. bool isMultiline;
  58295. };
  58296. TextPropertyComponent::TextPropertyComponent (const String& name,
  58297. const int maxNumChars,
  58298. const bool isMultiLine)
  58299. : PropertyComponent (name)
  58300. {
  58301. createEditor (maxNumChars, isMultiLine);
  58302. }
  58303. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58304. const String& name,
  58305. const int maxNumChars,
  58306. const bool isMultiLine)
  58307. : PropertyComponent (name)
  58308. {
  58309. createEditor (maxNumChars, isMultiLine);
  58310. textEditor->getTextValue().referTo (valueToControl);
  58311. }
  58312. TextPropertyComponent::~TextPropertyComponent()
  58313. {
  58314. }
  58315. void TextPropertyComponent::setText (const String& newText)
  58316. {
  58317. textEditor->setText (newText, true);
  58318. }
  58319. const String TextPropertyComponent::getText() const
  58320. {
  58321. return textEditor->getText();
  58322. }
  58323. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58324. {
  58325. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58326. if (isMultiLine)
  58327. {
  58328. textEditor->setJustificationType (Justification::topLeft);
  58329. preferredHeight = 120;
  58330. }
  58331. }
  58332. void TextPropertyComponent::refresh()
  58333. {
  58334. textEditor->setText (getText(), false);
  58335. }
  58336. void TextPropertyComponent::textWasEdited()
  58337. {
  58338. const String newText (textEditor->getText());
  58339. if (getText() != newText)
  58340. setText (newText);
  58341. }
  58342. END_JUCE_NAMESPACE
  58343. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58344. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58345. BEGIN_JUCE_NAMESPACE
  58346. class SimpleDeviceManagerInputLevelMeter : public Component,
  58347. public Timer
  58348. {
  58349. public:
  58350. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58351. : manager (manager_),
  58352. level (0)
  58353. {
  58354. startTimer (50);
  58355. manager->enableInputLevelMeasurement (true);
  58356. }
  58357. ~SimpleDeviceManagerInputLevelMeter()
  58358. {
  58359. manager->enableInputLevelMeasurement (false);
  58360. }
  58361. void timerCallback()
  58362. {
  58363. const float newLevel = (float) manager->getCurrentInputLevel();
  58364. if (std::abs (level - newLevel) > 0.005f)
  58365. {
  58366. level = newLevel;
  58367. repaint();
  58368. }
  58369. }
  58370. void paint (Graphics& g)
  58371. {
  58372. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58373. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58374. }
  58375. private:
  58376. AudioDeviceManager* const manager;
  58377. float level;
  58378. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58379. };
  58380. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58381. public ListBoxModel
  58382. {
  58383. public:
  58384. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58385. const String& noItemsMessage_,
  58386. const int minNumber_,
  58387. const int maxNumber_)
  58388. : ListBox (String::empty, 0),
  58389. deviceManager (deviceManager_),
  58390. noItemsMessage (noItemsMessage_),
  58391. minNumber (minNumber_),
  58392. maxNumber (maxNumber_)
  58393. {
  58394. items = MidiInput::getDevices();
  58395. setModel (this);
  58396. setOutlineThickness (1);
  58397. }
  58398. ~MidiInputSelectorComponentListBox()
  58399. {
  58400. }
  58401. int getNumRows()
  58402. {
  58403. return items.size();
  58404. }
  58405. void paintListBoxItem (int row,
  58406. Graphics& g,
  58407. int width, int height,
  58408. bool rowIsSelected)
  58409. {
  58410. if (isPositiveAndBelow (row, items.size()))
  58411. {
  58412. if (rowIsSelected)
  58413. g.fillAll (findColour (TextEditor::highlightColourId)
  58414. .withMultipliedAlpha (0.3f));
  58415. const String item (items [row]);
  58416. bool enabled = deviceManager.isMidiInputEnabled (item);
  58417. const int x = getTickX();
  58418. const float tickW = height * 0.75f;
  58419. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58420. enabled, true, true, false);
  58421. g.setFont (height * 0.6f);
  58422. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58423. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58424. }
  58425. }
  58426. void listBoxItemClicked (int row, const MouseEvent& e)
  58427. {
  58428. selectRow (row);
  58429. if (e.x < getTickX())
  58430. flipEnablement (row);
  58431. }
  58432. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58433. {
  58434. flipEnablement (row);
  58435. }
  58436. void returnKeyPressed (int row)
  58437. {
  58438. flipEnablement (row);
  58439. }
  58440. void paint (Graphics& g)
  58441. {
  58442. ListBox::paint (g);
  58443. if (items.size() == 0)
  58444. {
  58445. g.setColour (Colours::grey);
  58446. g.setFont (13.0f);
  58447. g.drawText (noItemsMessage,
  58448. 0, 0, getWidth(), getHeight() / 2,
  58449. Justification::centred, true);
  58450. }
  58451. }
  58452. int getBestHeight (const int preferredHeight)
  58453. {
  58454. const int extra = getOutlineThickness() * 2;
  58455. return jmax (getRowHeight() * 2 + extra,
  58456. jmin (getRowHeight() * getNumRows() + extra,
  58457. preferredHeight));
  58458. }
  58459. private:
  58460. AudioDeviceManager& deviceManager;
  58461. const String noItemsMessage;
  58462. StringArray items;
  58463. int minNumber, maxNumber;
  58464. void flipEnablement (const int row)
  58465. {
  58466. if (isPositiveAndBelow (row, items.size()))
  58467. {
  58468. const String item (items [row]);
  58469. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58470. }
  58471. }
  58472. int getTickX() const
  58473. {
  58474. return getRowHeight() + 5;
  58475. }
  58476. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58477. };
  58478. class AudioDeviceSettingsPanel : public Component,
  58479. public ChangeListener,
  58480. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58481. public ButtonListener
  58482. {
  58483. public:
  58484. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58485. AudioIODeviceType::DeviceSetupDetails& setup_,
  58486. const bool hideAdvancedOptionsWithButton)
  58487. : type (type_),
  58488. setup (setup_)
  58489. {
  58490. if (hideAdvancedOptionsWithButton)
  58491. {
  58492. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58493. showAdvancedSettingsButton->addListener (this);
  58494. }
  58495. type->scanForDevices();
  58496. setup.manager->addChangeListener (this);
  58497. changeListenerCallback (0);
  58498. }
  58499. ~AudioDeviceSettingsPanel()
  58500. {
  58501. setup.manager->removeChangeListener (this);
  58502. }
  58503. void resized()
  58504. {
  58505. const int lx = proportionOfWidth (0.35f);
  58506. const int w = proportionOfWidth (0.4f);
  58507. const int h = 24;
  58508. const int space = 6;
  58509. const int dh = h + space;
  58510. int y = 0;
  58511. if (outputDeviceDropDown != 0)
  58512. {
  58513. outputDeviceDropDown->setBounds (lx, y, w, h);
  58514. if (testButton != 0)
  58515. testButton->setBounds (proportionOfWidth (0.77f),
  58516. outputDeviceDropDown->getY(),
  58517. proportionOfWidth (0.18f),
  58518. h);
  58519. y += dh;
  58520. }
  58521. if (inputDeviceDropDown != 0)
  58522. {
  58523. inputDeviceDropDown->setBounds (lx, y, w, h);
  58524. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58525. inputDeviceDropDown->getY(),
  58526. proportionOfWidth (0.18f),
  58527. h);
  58528. y += dh;
  58529. }
  58530. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58531. if (outputChanList != 0)
  58532. {
  58533. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58534. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58535. y += bh + space;
  58536. }
  58537. if (inputChanList != 0)
  58538. {
  58539. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58540. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58541. y += bh + space;
  58542. }
  58543. y += space * 2;
  58544. if (showAdvancedSettingsButton != 0)
  58545. {
  58546. showAdvancedSettingsButton->changeWidthToFitText (h);
  58547. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58548. }
  58549. if (sampleRateDropDown != 0)
  58550. {
  58551. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58552. || ! showAdvancedSettingsButton->isVisible());
  58553. sampleRateDropDown->setBounds (lx, y, w, h);
  58554. y += dh;
  58555. }
  58556. if (bufferSizeDropDown != 0)
  58557. {
  58558. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58559. || ! showAdvancedSettingsButton->isVisible());
  58560. bufferSizeDropDown->setBounds (lx, y, w, h);
  58561. y += dh;
  58562. }
  58563. if (showUIButton != 0)
  58564. {
  58565. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58566. || ! showAdvancedSettingsButton->isVisible());
  58567. showUIButton->changeWidthToFitText (h);
  58568. showUIButton->setTopLeftPosition (lx, y);
  58569. }
  58570. }
  58571. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58572. {
  58573. if (comboBoxThatHasChanged == 0)
  58574. return;
  58575. AudioDeviceManager::AudioDeviceSetup config;
  58576. setup.manager->getAudioDeviceSetup (config);
  58577. String error;
  58578. if (comboBoxThatHasChanged == outputDeviceDropDown
  58579. || comboBoxThatHasChanged == inputDeviceDropDown)
  58580. {
  58581. if (outputDeviceDropDown != 0)
  58582. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58583. : outputDeviceDropDown->getText();
  58584. if (inputDeviceDropDown != 0)
  58585. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58586. : inputDeviceDropDown->getText();
  58587. if (! type->hasSeparateInputsAndOutputs())
  58588. config.inputDeviceName = config.outputDeviceName;
  58589. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58590. config.useDefaultInputChannels = true;
  58591. else
  58592. config.useDefaultOutputChannels = true;
  58593. error = setup.manager->setAudioDeviceSetup (config, true);
  58594. showCorrectDeviceName (inputDeviceDropDown, true);
  58595. showCorrectDeviceName (outputDeviceDropDown, false);
  58596. updateControlPanelButton();
  58597. resized();
  58598. }
  58599. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58600. {
  58601. if (sampleRateDropDown->getSelectedId() > 0)
  58602. {
  58603. config.sampleRate = sampleRateDropDown->getSelectedId();
  58604. error = setup.manager->setAudioDeviceSetup (config, true);
  58605. }
  58606. }
  58607. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58608. {
  58609. if (bufferSizeDropDown->getSelectedId() > 0)
  58610. {
  58611. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58612. error = setup.manager->setAudioDeviceSetup (config, true);
  58613. }
  58614. }
  58615. if (error.isNotEmpty())
  58616. {
  58617. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58618. "Error when trying to open audio device!",
  58619. error);
  58620. }
  58621. }
  58622. void buttonClicked (Button* button)
  58623. {
  58624. if (button == showAdvancedSettingsButton)
  58625. {
  58626. showAdvancedSettingsButton->setVisible (false);
  58627. resized();
  58628. }
  58629. else if (button == showUIButton)
  58630. {
  58631. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58632. if (device != 0 && device->showControlPanel())
  58633. {
  58634. setup.manager->closeAudioDevice();
  58635. setup.manager->restartLastAudioDevice();
  58636. getTopLevelComponent()->toFront (true);
  58637. }
  58638. }
  58639. else if (button == testButton && testButton != 0)
  58640. {
  58641. setup.manager->playTestSound();
  58642. }
  58643. }
  58644. void updateControlPanelButton()
  58645. {
  58646. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58647. showUIButton = 0;
  58648. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58649. {
  58650. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58651. TRANS ("opens the device's own control panel")));
  58652. showUIButton->addListener (this);
  58653. }
  58654. resized();
  58655. }
  58656. void changeListenerCallback (ChangeBroadcaster*)
  58657. {
  58658. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58659. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58660. {
  58661. if (outputDeviceDropDown == 0)
  58662. {
  58663. outputDeviceDropDown = new ComboBox (String::empty);
  58664. outputDeviceDropDown->addListener (this);
  58665. addAndMakeVisible (outputDeviceDropDown);
  58666. outputDeviceLabel = new Label (String::empty,
  58667. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58668. : TRANS ("device:"));
  58669. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58670. if (setup.maxNumOutputChannels > 0)
  58671. {
  58672. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58673. testButton->addListener (this);
  58674. }
  58675. }
  58676. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58677. }
  58678. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58679. {
  58680. if (inputDeviceDropDown == 0)
  58681. {
  58682. inputDeviceDropDown = new ComboBox (String::empty);
  58683. inputDeviceDropDown->addListener (this);
  58684. addAndMakeVisible (inputDeviceDropDown);
  58685. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58686. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58687. addAndMakeVisible (inputLevelMeter
  58688. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58689. }
  58690. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58691. }
  58692. updateControlPanelButton();
  58693. showCorrectDeviceName (inputDeviceDropDown, true);
  58694. showCorrectDeviceName (outputDeviceDropDown, false);
  58695. if (currentDevice != 0)
  58696. {
  58697. if (setup.maxNumOutputChannels > 0
  58698. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58699. {
  58700. if (outputChanList == 0)
  58701. {
  58702. addAndMakeVisible (outputChanList
  58703. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58704. TRANS ("(no audio output channels found)")));
  58705. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58706. outputChanLabel->attachToComponent (outputChanList, true);
  58707. }
  58708. outputChanList->refresh();
  58709. }
  58710. else
  58711. {
  58712. outputChanLabel = 0;
  58713. outputChanList = 0;
  58714. }
  58715. if (setup.maxNumInputChannels > 0
  58716. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58717. {
  58718. if (inputChanList == 0)
  58719. {
  58720. addAndMakeVisible (inputChanList
  58721. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58722. TRANS ("(no audio input channels found)")));
  58723. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58724. inputChanLabel->attachToComponent (inputChanList, true);
  58725. }
  58726. inputChanList->refresh();
  58727. }
  58728. else
  58729. {
  58730. inputChanLabel = 0;
  58731. inputChanList = 0;
  58732. }
  58733. // sample rate..
  58734. {
  58735. if (sampleRateDropDown == 0)
  58736. {
  58737. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58738. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58739. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58740. }
  58741. else
  58742. {
  58743. sampleRateDropDown->clear();
  58744. sampleRateDropDown->removeListener (this);
  58745. }
  58746. const int numRates = currentDevice->getNumSampleRates();
  58747. for (int i = 0; i < numRates; ++i)
  58748. {
  58749. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58750. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58751. }
  58752. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58753. sampleRateDropDown->addListener (this);
  58754. }
  58755. // buffer size
  58756. {
  58757. if (bufferSizeDropDown == 0)
  58758. {
  58759. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58760. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58761. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58762. }
  58763. else
  58764. {
  58765. bufferSizeDropDown->clear();
  58766. bufferSizeDropDown->removeListener (this);
  58767. }
  58768. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58769. double currentRate = currentDevice->getCurrentSampleRate();
  58770. if (currentRate == 0)
  58771. currentRate = 48000.0;
  58772. for (int i = 0; i < numBufferSizes; ++i)
  58773. {
  58774. const int bs = currentDevice->getBufferSizeSamples (i);
  58775. bufferSizeDropDown->addItem (String (bs)
  58776. + " samples ("
  58777. + String (bs * 1000.0 / currentRate, 1)
  58778. + " ms)",
  58779. bs);
  58780. }
  58781. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58782. bufferSizeDropDown->addListener (this);
  58783. }
  58784. }
  58785. else
  58786. {
  58787. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58788. sampleRateLabel = 0;
  58789. bufferSizeLabel = 0;
  58790. sampleRateDropDown = 0;
  58791. bufferSizeDropDown = 0;
  58792. if (outputDeviceDropDown != 0)
  58793. outputDeviceDropDown->setSelectedId (-1, true);
  58794. if (inputDeviceDropDown != 0)
  58795. inputDeviceDropDown->setSelectedId (-1, true);
  58796. }
  58797. resized();
  58798. setSize (getWidth(), getLowestY() + 4);
  58799. }
  58800. private:
  58801. AudioIODeviceType* const type;
  58802. const AudioIODeviceType::DeviceSetupDetails setup;
  58803. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58804. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58805. ScopedPointer<TextButton> testButton;
  58806. ScopedPointer<Component> inputLevelMeter;
  58807. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58808. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58809. {
  58810. if (box != 0)
  58811. {
  58812. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58813. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58814. box->setSelectedId (index + 1, true);
  58815. if (testButton != 0 && ! isInput)
  58816. testButton->setEnabled (index >= 0);
  58817. }
  58818. }
  58819. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58820. {
  58821. const StringArray devs (type->getDeviceNames (isInputs));
  58822. combo.clear (true);
  58823. for (int i = 0; i < devs.size(); ++i)
  58824. combo.addItem (devs[i], i + 1);
  58825. combo.addItem (TRANS("<< none >>"), -1);
  58826. combo.setSelectedId (-1, true);
  58827. }
  58828. int getLowestY() const
  58829. {
  58830. int y = 0;
  58831. for (int i = getNumChildComponents(); --i >= 0;)
  58832. y = jmax (y, getChildComponent (i)->getBottom());
  58833. return y;
  58834. }
  58835. public:
  58836. class ChannelSelectorListBox : public ListBox,
  58837. public ListBoxModel
  58838. {
  58839. public:
  58840. enum BoxType
  58841. {
  58842. audioInputType,
  58843. audioOutputType
  58844. };
  58845. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58846. const BoxType type_,
  58847. const String& noItemsMessage_)
  58848. : ListBox (String::empty, 0),
  58849. setup (setup_),
  58850. type (type_),
  58851. noItemsMessage (noItemsMessage_)
  58852. {
  58853. refresh();
  58854. setModel (this);
  58855. setOutlineThickness (1);
  58856. }
  58857. ~ChannelSelectorListBox()
  58858. {
  58859. }
  58860. void refresh()
  58861. {
  58862. items.clear();
  58863. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58864. if (currentDevice != 0)
  58865. {
  58866. if (type == audioInputType)
  58867. items = currentDevice->getInputChannelNames();
  58868. else if (type == audioOutputType)
  58869. items = currentDevice->getOutputChannelNames();
  58870. if (setup.useStereoPairs)
  58871. {
  58872. StringArray pairs;
  58873. for (int i = 0; i < items.size(); i += 2)
  58874. {
  58875. const String name (items[i]);
  58876. const String name2 (items[i + 1]);
  58877. String commonBit;
  58878. for (int j = 0; j < name.length(); ++j)
  58879. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58880. commonBit = name.substring (0, j);
  58881. // Make sure we only split the name at a space, because otherwise, things
  58882. // like "input 11" + "input 12" would become "input 11 + 2"
  58883. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58884. commonBit = commonBit.dropLastCharacters (1);
  58885. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58886. }
  58887. items = pairs;
  58888. }
  58889. }
  58890. updateContent();
  58891. repaint();
  58892. }
  58893. int getNumRows()
  58894. {
  58895. return items.size();
  58896. }
  58897. void paintListBoxItem (int row,
  58898. Graphics& g,
  58899. int width, int height,
  58900. bool rowIsSelected)
  58901. {
  58902. if (isPositiveAndBelow (row, items.size()))
  58903. {
  58904. if (rowIsSelected)
  58905. g.fillAll (findColour (TextEditor::highlightColourId)
  58906. .withMultipliedAlpha (0.3f));
  58907. const String item (items [row]);
  58908. bool enabled = false;
  58909. AudioDeviceManager::AudioDeviceSetup config;
  58910. setup.manager->getAudioDeviceSetup (config);
  58911. if (setup.useStereoPairs)
  58912. {
  58913. if (type == audioInputType)
  58914. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58915. else if (type == audioOutputType)
  58916. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58917. }
  58918. else
  58919. {
  58920. if (type == audioInputType)
  58921. enabled = config.inputChannels [row];
  58922. else if (type == audioOutputType)
  58923. enabled = config.outputChannels [row];
  58924. }
  58925. const int x = getTickX();
  58926. const float tickW = height * 0.75f;
  58927. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58928. enabled, true, true, false);
  58929. g.setFont (height * 0.6f);
  58930. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58931. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58932. }
  58933. }
  58934. void listBoxItemClicked (int row, const MouseEvent& e)
  58935. {
  58936. selectRow (row);
  58937. if (e.x < getTickX())
  58938. flipEnablement (row);
  58939. }
  58940. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58941. {
  58942. flipEnablement (row);
  58943. }
  58944. void returnKeyPressed (int row)
  58945. {
  58946. flipEnablement (row);
  58947. }
  58948. void paint (Graphics& g)
  58949. {
  58950. ListBox::paint (g);
  58951. if (items.size() == 0)
  58952. {
  58953. g.setColour (Colours::grey);
  58954. g.setFont (13.0f);
  58955. g.drawText (noItemsMessage,
  58956. 0, 0, getWidth(), getHeight() / 2,
  58957. Justification::centred, true);
  58958. }
  58959. }
  58960. int getBestHeight (int maxHeight)
  58961. {
  58962. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58963. getNumRows())
  58964. + getOutlineThickness() * 2;
  58965. }
  58966. private:
  58967. const AudioIODeviceType::DeviceSetupDetails setup;
  58968. const BoxType type;
  58969. const String noItemsMessage;
  58970. StringArray items;
  58971. void flipEnablement (const int row)
  58972. {
  58973. jassert (type == audioInputType || type == audioOutputType);
  58974. if (isPositiveAndBelow (row, items.size()))
  58975. {
  58976. AudioDeviceManager::AudioDeviceSetup config;
  58977. setup.manager->getAudioDeviceSetup (config);
  58978. if (setup.useStereoPairs)
  58979. {
  58980. BigInteger bits;
  58981. BigInteger& original = (type == audioInputType ? config.inputChannels
  58982. : config.outputChannels);
  58983. int i;
  58984. for (i = 0; i < 256; i += 2)
  58985. bits.setBit (i / 2, original [i] || original [i + 1]);
  58986. if (type == audioInputType)
  58987. {
  58988. config.useDefaultInputChannels = false;
  58989. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58990. }
  58991. else
  58992. {
  58993. config.useDefaultOutputChannels = false;
  58994. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58995. }
  58996. for (i = 0; i < 256; ++i)
  58997. original.setBit (i, bits [i / 2]);
  58998. }
  58999. else
  59000. {
  59001. if (type == audioInputType)
  59002. {
  59003. config.useDefaultInputChannels = false;
  59004. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59005. }
  59006. else
  59007. {
  59008. config.useDefaultOutputChannels = false;
  59009. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59010. }
  59011. }
  59012. String error (setup.manager->setAudioDeviceSetup (config, true));
  59013. if (! error.isEmpty())
  59014. {
  59015. //xxx
  59016. }
  59017. }
  59018. }
  59019. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59020. {
  59021. const int numActive = chans.countNumberOfSetBits();
  59022. if (chans [index])
  59023. {
  59024. if (numActive > minNumber)
  59025. chans.setBit (index, false);
  59026. }
  59027. else
  59028. {
  59029. if (numActive >= maxNumber)
  59030. {
  59031. const int firstActiveChan = chans.findNextSetBit();
  59032. chans.setBit (index > firstActiveChan
  59033. ? firstActiveChan : chans.getHighestBit(),
  59034. false);
  59035. }
  59036. chans.setBit (index, true);
  59037. }
  59038. }
  59039. int getTickX() const
  59040. {
  59041. return getRowHeight() + 5;
  59042. }
  59043. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59044. };
  59045. private:
  59046. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59047. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59048. };
  59049. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59050. const int minInputChannels_,
  59051. const int maxInputChannels_,
  59052. const int minOutputChannels_,
  59053. const int maxOutputChannels_,
  59054. const bool showMidiInputOptions,
  59055. const bool showMidiOutputSelector,
  59056. const bool showChannelsAsStereoPairs_,
  59057. const bool hideAdvancedOptionsWithButton_)
  59058. : deviceManager (deviceManager_),
  59059. deviceTypeDropDown (0),
  59060. deviceTypeDropDownLabel (0),
  59061. minOutputChannels (minOutputChannels_),
  59062. maxOutputChannels (maxOutputChannels_),
  59063. minInputChannels (minInputChannels_),
  59064. maxInputChannels (maxInputChannels_),
  59065. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59066. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59067. {
  59068. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59069. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59070. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59071. {
  59072. deviceTypeDropDown = new ComboBox (String::empty);
  59073. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59074. {
  59075. deviceTypeDropDown
  59076. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59077. i + 1);
  59078. }
  59079. addAndMakeVisible (deviceTypeDropDown);
  59080. deviceTypeDropDown->addListener (this);
  59081. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59082. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59083. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59084. }
  59085. if (showMidiInputOptions)
  59086. {
  59087. addAndMakeVisible (midiInputsList
  59088. = new MidiInputSelectorComponentListBox (deviceManager,
  59089. TRANS("(no midi inputs available)"),
  59090. 0, 0));
  59091. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59092. midiInputsLabel->setJustificationType (Justification::topRight);
  59093. midiInputsLabel->attachToComponent (midiInputsList, true);
  59094. }
  59095. else
  59096. {
  59097. midiInputsList = 0;
  59098. midiInputsLabel = 0;
  59099. }
  59100. if (showMidiOutputSelector)
  59101. {
  59102. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59103. midiOutputSelector->addListener (this);
  59104. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59105. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59106. }
  59107. else
  59108. {
  59109. midiOutputSelector = 0;
  59110. midiOutputLabel = 0;
  59111. }
  59112. deviceManager_.addChangeListener (this);
  59113. changeListenerCallback (0);
  59114. }
  59115. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59116. {
  59117. deviceManager.removeChangeListener (this);
  59118. }
  59119. void AudioDeviceSelectorComponent::resized()
  59120. {
  59121. const int lx = proportionOfWidth (0.35f);
  59122. const int w = proportionOfWidth (0.4f);
  59123. const int h = 24;
  59124. const int space = 6;
  59125. const int dh = h + space;
  59126. int y = 15;
  59127. if (deviceTypeDropDown != 0)
  59128. {
  59129. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59130. y += dh + space * 2;
  59131. }
  59132. if (audioDeviceSettingsComp != 0)
  59133. {
  59134. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59135. y += audioDeviceSettingsComp->getHeight() + space;
  59136. }
  59137. if (midiInputsList != 0)
  59138. {
  59139. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59140. midiInputsList->setBounds (lx, y, w, bh);
  59141. y += bh + space;
  59142. }
  59143. if (midiOutputSelector != 0)
  59144. midiOutputSelector->setBounds (lx, y, w, h);
  59145. }
  59146. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59147. {
  59148. if (child == audioDeviceSettingsComp)
  59149. resized();
  59150. }
  59151. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59152. {
  59153. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59154. if (device != 0 && device->hasControlPanel())
  59155. {
  59156. if (device->showControlPanel())
  59157. deviceManager.restartLastAudioDevice();
  59158. getTopLevelComponent()->toFront (true);
  59159. }
  59160. }
  59161. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59162. {
  59163. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59164. {
  59165. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59166. if (type != 0)
  59167. {
  59168. audioDeviceSettingsComp = 0;
  59169. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59170. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59171. }
  59172. }
  59173. else if (comboBoxThatHasChanged == midiOutputSelector)
  59174. {
  59175. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59176. }
  59177. }
  59178. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59179. {
  59180. if (deviceTypeDropDown != 0)
  59181. {
  59182. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59183. }
  59184. if (audioDeviceSettingsComp == 0
  59185. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59186. {
  59187. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59188. audioDeviceSettingsComp = 0;
  59189. AudioIODeviceType* const type
  59190. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59191. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59192. if (type != 0)
  59193. {
  59194. AudioIODeviceType::DeviceSetupDetails details;
  59195. details.manager = &deviceManager;
  59196. details.minNumInputChannels = minInputChannels;
  59197. details.maxNumInputChannels = maxInputChannels;
  59198. details.minNumOutputChannels = minOutputChannels;
  59199. details.maxNumOutputChannels = maxOutputChannels;
  59200. details.useStereoPairs = showChannelsAsStereoPairs;
  59201. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59202. if (audioDeviceSettingsComp != 0)
  59203. {
  59204. addAndMakeVisible (audioDeviceSettingsComp);
  59205. audioDeviceSettingsComp->resized();
  59206. }
  59207. }
  59208. }
  59209. if (midiInputsList != 0)
  59210. {
  59211. midiInputsList->updateContent();
  59212. midiInputsList->repaint();
  59213. }
  59214. if (midiOutputSelector != 0)
  59215. {
  59216. midiOutputSelector->clear();
  59217. const StringArray midiOuts (MidiOutput::getDevices());
  59218. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59219. midiOutputSelector->addSeparator();
  59220. for (int i = 0; i < midiOuts.size(); ++i)
  59221. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59222. int current = -1;
  59223. if (deviceManager.getDefaultMidiOutput() != 0)
  59224. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59225. midiOutputSelector->setSelectedId (current, true);
  59226. }
  59227. resized();
  59228. }
  59229. END_JUCE_NAMESPACE
  59230. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59231. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59232. BEGIN_JUCE_NAMESPACE
  59233. BubbleComponent::BubbleComponent()
  59234. : side (0),
  59235. allowablePlacements (above | below | left | right),
  59236. arrowTipX (0.0f),
  59237. arrowTipY (0.0f)
  59238. {
  59239. setInterceptsMouseClicks (false, false);
  59240. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59241. setComponentEffect (&shadow);
  59242. }
  59243. BubbleComponent::~BubbleComponent()
  59244. {
  59245. }
  59246. void BubbleComponent::paint (Graphics& g)
  59247. {
  59248. int x = content.getX();
  59249. int y = content.getY();
  59250. int w = content.getWidth();
  59251. int h = content.getHeight();
  59252. int cw, ch;
  59253. getContentSize (cw, ch);
  59254. if (side == 3)
  59255. x += w - cw;
  59256. else if (side != 1)
  59257. x += (w - cw) / 2;
  59258. w = cw;
  59259. if (side == 2)
  59260. y += h - ch;
  59261. else if (side != 0)
  59262. y += (h - ch) / 2;
  59263. h = ch;
  59264. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59265. (float) x, (float) y,
  59266. (float) w, (float) h);
  59267. const int cx = x + (w - cw) / 2;
  59268. const int cy = y + (h - ch) / 2;
  59269. const int indent = 3;
  59270. g.setOrigin (cx + indent, cy + indent);
  59271. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59272. paintContent (g, cw - indent * 2, ch - indent * 2);
  59273. }
  59274. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59275. {
  59276. allowablePlacements = newPlacement;
  59277. }
  59278. void BubbleComponent::setPosition (Component* componentToPointTo)
  59279. {
  59280. jassert (componentToPointTo != 0);
  59281. Point<int> pos;
  59282. if (getParentComponent() != 0)
  59283. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59284. else
  59285. pos = componentToPointTo->localPointToGlobal (pos);
  59286. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59287. }
  59288. void BubbleComponent::setPosition (const int arrowTipX_,
  59289. const int arrowTipY_)
  59290. {
  59291. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59292. }
  59293. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59294. {
  59295. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59296. : getParentMonitorArea());
  59297. int x = 0;
  59298. int y = 0;
  59299. int w = 150;
  59300. int h = 30;
  59301. getContentSize (w, h);
  59302. w += 30;
  59303. h += 30;
  59304. const float edgeIndent = 2.0f;
  59305. const int arrowLength = jmin (10, h / 3, w / 3);
  59306. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59307. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59308. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59309. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59310. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59311. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59312. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59313. {
  59314. spaceLeft = spaceRight = 0;
  59315. }
  59316. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59317. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59318. {
  59319. spaceAbove = spaceBelow = 0;
  59320. }
  59321. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59322. {
  59323. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59324. arrowTipX = w * 0.5f;
  59325. content.setSize (w, h - arrowLength);
  59326. if (spaceAbove >= spaceBelow)
  59327. {
  59328. // above
  59329. y = rectangleToPointTo.getY() - h;
  59330. content.setPosition (0, 0);
  59331. arrowTipY = h - edgeIndent;
  59332. side = 2;
  59333. }
  59334. else
  59335. {
  59336. // below
  59337. y = rectangleToPointTo.getBottom();
  59338. content.setPosition (0, arrowLength);
  59339. arrowTipY = edgeIndent;
  59340. side = 0;
  59341. }
  59342. }
  59343. else
  59344. {
  59345. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59346. arrowTipY = h * 0.5f;
  59347. content.setSize (w - arrowLength, h);
  59348. if (spaceLeft > spaceRight)
  59349. {
  59350. // on the left
  59351. x = rectangleToPointTo.getX() - w;
  59352. content.setPosition (0, 0);
  59353. arrowTipX = w - edgeIndent;
  59354. side = 3;
  59355. }
  59356. else
  59357. {
  59358. // on the right
  59359. x = rectangleToPointTo.getRight();
  59360. content.setPosition (arrowLength, 0);
  59361. arrowTipX = edgeIndent;
  59362. side = 1;
  59363. }
  59364. }
  59365. setBounds (x, y, w, h);
  59366. }
  59367. END_JUCE_NAMESPACE
  59368. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59369. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59370. BEGIN_JUCE_NAMESPACE
  59371. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59372. : fadeOutLength (fadeOutLengthMs),
  59373. deleteAfterUse (false)
  59374. {
  59375. }
  59376. BubbleMessageComponent::~BubbleMessageComponent()
  59377. {
  59378. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59379. }
  59380. void BubbleMessageComponent::showAt (int x, int y,
  59381. const String& text,
  59382. const int numMillisecondsBeforeRemoving,
  59383. const bool removeWhenMouseClicked,
  59384. const bool deleteSelfAfterUse)
  59385. {
  59386. textLayout.clear();
  59387. textLayout.setText (text, Font (14.0f));
  59388. textLayout.layout (256, Justification::centredLeft, true);
  59389. setPosition (x, y);
  59390. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59391. }
  59392. void BubbleMessageComponent::showAt (Component* const component,
  59393. const String& text,
  59394. const int numMillisecondsBeforeRemoving,
  59395. const bool removeWhenMouseClicked,
  59396. const bool deleteSelfAfterUse)
  59397. {
  59398. textLayout.clear();
  59399. textLayout.setText (text, Font (14.0f));
  59400. textLayout.layout (256, Justification::centredLeft, true);
  59401. setPosition (component);
  59402. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59403. }
  59404. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59405. const bool removeWhenMouseClicked,
  59406. const bool deleteSelfAfterUse)
  59407. {
  59408. setVisible (true);
  59409. deleteAfterUse = deleteSelfAfterUse;
  59410. if (numMillisecondsBeforeRemoving > 0)
  59411. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59412. else
  59413. expiryTime = 0;
  59414. startTimer (77);
  59415. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59416. if (! (removeWhenMouseClicked && isShowing()))
  59417. mouseClickCounter += 0xfffff;
  59418. repaint();
  59419. }
  59420. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59421. {
  59422. w = textLayout.getWidth() + 16;
  59423. h = textLayout.getHeight() + 16;
  59424. }
  59425. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59426. {
  59427. g.setColour (findColour (TooltipWindow::textColourId));
  59428. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59429. }
  59430. void BubbleMessageComponent::timerCallback()
  59431. {
  59432. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59433. {
  59434. stopTimer();
  59435. setVisible (false);
  59436. if (deleteAfterUse)
  59437. delete this;
  59438. }
  59439. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59440. {
  59441. stopTimer();
  59442. if (deleteAfterUse)
  59443. delete this;
  59444. else
  59445. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59446. }
  59447. }
  59448. END_JUCE_NAMESPACE
  59449. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59450. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59451. BEGIN_JUCE_NAMESPACE
  59452. class ColourComponentSlider : public Slider
  59453. {
  59454. public:
  59455. ColourComponentSlider (const String& name)
  59456. : Slider (name)
  59457. {
  59458. setRange (0.0, 255.0, 1.0);
  59459. }
  59460. const String getTextFromValue (double value)
  59461. {
  59462. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59463. }
  59464. double getValueFromText (const String& text)
  59465. {
  59466. return (double) text.getHexValue32();
  59467. }
  59468. private:
  59469. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59470. };
  59471. class ColourSpaceMarker : public Component
  59472. {
  59473. public:
  59474. ColourSpaceMarker()
  59475. {
  59476. setInterceptsMouseClicks (false, false);
  59477. }
  59478. void paint (Graphics& g)
  59479. {
  59480. g.setColour (Colour::greyLevel (0.1f));
  59481. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59482. g.setColour (Colour::greyLevel (0.9f));
  59483. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59484. }
  59485. private:
  59486. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59487. };
  59488. class ColourSelector::ColourSpaceView : public Component
  59489. {
  59490. public:
  59491. ColourSpaceView (ColourSelector& owner_,
  59492. float& h_, float& s_, float& v_,
  59493. const int edgeSize)
  59494. : owner (owner_),
  59495. h (h_), s (s_), v (v_),
  59496. lastHue (0.0f),
  59497. edge (edgeSize)
  59498. {
  59499. addAndMakeVisible (&marker);
  59500. setMouseCursor (MouseCursor::CrosshairCursor);
  59501. }
  59502. void paint (Graphics& g)
  59503. {
  59504. if (colours.isNull())
  59505. {
  59506. const int width = getWidth() / 2;
  59507. const int height = getHeight() / 2;
  59508. colours = Image (Image::RGB, width, height, false);
  59509. Image::BitmapData pixels (colours, true);
  59510. for (int y = 0; y < height; ++y)
  59511. {
  59512. const float val = 1.0f - y / (float) height;
  59513. for (int x = 0; x < width; ++x)
  59514. {
  59515. const float sat = x / (float) width;
  59516. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59517. }
  59518. }
  59519. }
  59520. g.setOpacity (1.0f);
  59521. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59522. 0, 0, colours.getWidth(), colours.getHeight());
  59523. }
  59524. void mouseDown (const MouseEvent& e)
  59525. {
  59526. mouseDrag (e);
  59527. }
  59528. void mouseDrag (const MouseEvent& e)
  59529. {
  59530. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59531. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59532. owner.setSV (sat, val);
  59533. }
  59534. void updateIfNeeded()
  59535. {
  59536. if (lastHue != h)
  59537. {
  59538. lastHue = h;
  59539. colours = Image::null;
  59540. repaint();
  59541. }
  59542. updateMarker();
  59543. }
  59544. void resized()
  59545. {
  59546. colours = Image::null;
  59547. updateMarker();
  59548. }
  59549. private:
  59550. ColourSelector& owner;
  59551. float& h;
  59552. float& s;
  59553. float& v;
  59554. float lastHue;
  59555. ColourSpaceMarker marker;
  59556. const int edge;
  59557. Image colours;
  59558. void updateMarker()
  59559. {
  59560. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59561. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59562. edge * 2, edge * 2);
  59563. }
  59564. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59565. };
  59566. class HueSelectorMarker : public Component
  59567. {
  59568. public:
  59569. HueSelectorMarker()
  59570. {
  59571. setInterceptsMouseClicks (false, false);
  59572. }
  59573. void paint (Graphics& g)
  59574. {
  59575. Path p;
  59576. p.addTriangle (1.0f, 1.0f,
  59577. getWidth() * 0.3f, getHeight() * 0.5f,
  59578. 1.0f, getHeight() - 1.0f);
  59579. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59580. getWidth() * 0.7f, getHeight() * 0.5f,
  59581. getWidth() - 1.0f, getHeight() - 1.0f);
  59582. g.setColour (Colours::white.withAlpha (0.75f));
  59583. g.fillPath (p);
  59584. g.setColour (Colours::black.withAlpha (0.75f));
  59585. g.strokePath (p, PathStrokeType (1.2f));
  59586. }
  59587. private:
  59588. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59589. };
  59590. class ColourSelector::HueSelectorComp : public Component
  59591. {
  59592. public:
  59593. HueSelectorComp (ColourSelector& owner_,
  59594. float& h_, float& s_, float& v_,
  59595. const int edgeSize)
  59596. : owner (owner_),
  59597. h (h_), s (s_), v (v_),
  59598. lastHue (0.0f),
  59599. edge (edgeSize)
  59600. {
  59601. addAndMakeVisible (&marker);
  59602. }
  59603. void paint (Graphics& g)
  59604. {
  59605. const float yScale = 1.0f / (getHeight() - edge * 2);
  59606. const Rectangle<int> clip (g.getClipBounds());
  59607. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59608. {
  59609. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59610. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59611. }
  59612. }
  59613. void resized()
  59614. {
  59615. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59616. getWidth(), edge * 2);
  59617. }
  59618. void mouseDown (const MouseEvent& e)
  59619. {
  59620. mouseDrag (e);
  59621. }
  59622. void mouseDrag (const MouseEvent& e)
  59623. {
  59624. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59625. }
  59626. void updateIfNeeded()
  59627. {
  59628. resized();
  59629. }
  59630. private:
  59631. ColourSelector& owner;
  59632. float& h;
  59633. float& s;
  59634. float& v;
  59635. float lastHue;
  59636. HueSelectorMarker marker;
  59637. const int edge;
  59638. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59639. };
  59640. class ColourSelector::SwatchComponent : public Component
  59641. {
  59642. public:
  59643. SwatchComponent (ColourSelector& owner_, int index_)
  59644. : owner (owner_), index (index_)
  59645. {
  59646. }
  59647. void paint (Graphics& g)
  59648. {
  59649. const Colour colour (owner.getSwatchColour (index));
  59650. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59651. Colour (0xffdddddd).overlaidWith (colour),
  59652. Colour (0xffffffff).overlaidWith (colour));
  59653. }
  59654. void mouseDown (const MouseEvent&)
  59655. {
  59656. PopupMenu m;
  59657. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59658. m.addSeparator();
  59659. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59660. const int r = m.showAt (this);
  59661. if (r == 1)
  59662. {
  59663. owner.setCurrentColour (owner.getSwatchColour (index));
  59664. }
  59665. else if (r == 2)
  59666. {
  59667. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59668. {
  59669. owner.setSwatchColour (index, owner.getCurrentColour());
  59670. repaint();
  59671. }
  59672. }
  59673. }
  59674. private:
  59675. ColourSelector& owner;
  59676. const int index;
  59677. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59678. };
  59679. ColourSelector::ColourSelector (const int flags_,
  59680. const int edgeGap_,
  59681. const int gapAroundColourSpaceComponent)
  59682. : colour (Colours::white),
  59683. flags (flags_),
  59684. edgeGap (edgeGap_)
  59685. {
  59686. // not much point having a selector with no components in it!
  59687. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59688. updateHSV();
  59689. if ((flags & showSliders) != 0)
  59690. {
  59691. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59692. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59693. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59694. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59695. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59696. for (int i = 4; --i >= 0;)
  59697. sliders[i]->addListener (this);
  59698. }
  59699. if ((flags & showColourspace) != 0)
  59700. {
  59701. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59702. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59703. }
  59704. update();
  59705. }
  59706. ColourSelector::~ColourSelector()
  59707. {
  59708. dispatchPendingMessages();
  59709. swatchComponents.clear();
  59710. }
  59711. const Colour ColourSelector::getCurrentColour() const
  59712. {
  59713. return ((flags & showAlphaChannel) != 0) ? colour
  59714. : colour.withAlpha ((uint8) 0xff);
  59715. }
  59716. void ColourSelector::setCurrentColour (const Colour& c)
  59717. {
  59718. if (c != colour)
  59719. {
  59720. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59721. updateHSV();
  59722. update();
  59723. }
  59724. }
  59725. void ColourSelector::setHue (float newH)
  59726. {
  59727. newH = jlimit (0.0f, 1.0f, newH);
  59728. if (h != newH)
  59729. {
  59730. h = newH;
  59731. colour = Colour (h, s, v, colour.getFloatAlpha());
  59732. update();
  59733. }
  59734. }
  59735. void ColourSelector::setSV (float newS, float newV)
  59736. {
  59737. newS = jlimit (0.0f, 1.0f, newS);
  59738. newV = jlimit (0.0f, 1.0f, newV);
  59739. if (s != newS || v != newV)
  59740. {
  59741. s = newS;
  59742. v = newV;
  59743. colour = Colour (h, s, v, colour.getFloatAlpha());
  59744. update();
  59745. }
  59746. }
  59747. void ColourSelector::updateHSV()
  59748. {
  59749. colour.getHSB (h, s, v);
  59750. }
  59751. void ColourSelector::update()
  59752. {
  59753. if (sliders[0] != 0)
  59754. {
  59755. sliders[0]->setValue ((int) colour.getRed());
  59756. sliders[1]->setValue ((int) colour.getGreen());
  59757. sliders[2]->setValue ((int) colour.getBlue());
  59758. sliders[3]->setValue ((int) colour.getAlpha());
  59759. }
  59760. if (colourSpace != 0)
  59761. {
  59762. colourSpace->updateIfNeeded();
  59763. hueSelector->updateIfNeeded();
  59764. }
  59765. if ((flags & showColourAtTop) != 0)
  59766. repaint (previewArea);
  59767. sendChangeMessage();
  59768. }
  59769. void ColourSelector::paint (Graphics& g)
  59770. {
  59771. g.fillAll (findColour (backgroundColourId));
  59772. if ((flags & showColourAtTop) != 0)
  59773. {
  59774. const Colour currentColour (getCurrentColour());
  59775. g.fillCheckerBoard (previewArea, 10, 10,
  59776. Colour (0xffdddddd).overlaidWith (currentColour),
  59777. Colour (0xffffffff).overlaidWith (currentColour));
  59778. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59779. g.setFont (14.0f, true);
  59780. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59781. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59782. Justification::centred, false);
  59783. }
  59784. if ((flags & showSliders) != 0)
  59785. {
  59786. g.setColour (findColour (labelTextColourId));
  59787. g.setFont (11.0f);
  59788. for (int i = 4; --i >= 0;)
  59789. {
  59790. if (sliders[i]->isVisible())
  59791. g.drawText (sliders[i]->getName() + ":",
  59792. 0, sliders[i]->getY(),
  59793. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59794. Justification::centredRight, false);
  59795. }
  59796. }
  59797. }
  59798. void ColourSelector::resized()
  59799. {
  59800. const int swatchesPerRow = 8;
  59801. const int swatchHeight = 22;
  59802. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59803. const int numSwatches = getNumSwatches();
  59804. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59805. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59806. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59807. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59808. int y = topSpace;
  59809. if ((flags & showColourspace) != 0)
  59810. {
  59811. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59812. colourSpace->setBounds (edgeGap, y,
  59813. getWidth() - hueWidth - edgeGap - 4,
  59814. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59815. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59816. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59817. colourSpace->getHeight());
  59818. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59819. }
  59820. if ((flags & showSliders) != 0)
  59821. {
  59822. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59823. for (int i = 0; i < numSliders; ++i)
  59824. {
  59825. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59826. proportionOfWidth (0.72f), sliderHeight - 2);
  59827. y += sliderHeight;
  59828. }
  59829. }
  59830. if (numSwatches > 0)
  59831. {
  59832. const int startX = 8;
  59833. const int xGap = 4;
  59834. const int yGap = 4;
  59835. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59836. y += edgeGap;
  59837. if (swatchComponents.size() != numSwatches)
  59838. {
  59839. swatchComponents.clear();
  59840. for (int i = 0; i < numSwatches; ++i)
  59841. {
  59842. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59843. swatchComponents.add (sc);
  59844. addAndMakeVisible (sc);
  59845. }
  59846. }
  59847. int x = startX;
  59848. for (int i = 0; i < swatchComponents.size(); ++i)
  59849. {
  59850. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59851. sc->setBounds (x + xGap / 2,
  59852. y + yGap / 2,
  59853. swatchWidth - xGap,
  59854. swatchHeight - yGap);
  59855. if (((i + 1) % swatchesPerRow) == 0)
  59856. {
  59857. x = startX;
  59858. y += swatchHeight;
  59859. }
  59860. else
  59861. {
  59862. x += swatchWidth;
  59863. }
  59864. }
  59865. }
  59866. }
  59867. void ColourSelector::sliderValueChanged (Slider*)
  59868. {
  59869. if (sliders[0] != 0)
  59870. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59871. (uint8) sliders[1]->getValue(),
  59872. (uint8) sliders[2]->getValue(),
  59873. (uint8) sliders[3]->getValue()));
  59874. }
  59875. int ColourSelector::getNumSwatches() const
  59876. {
  59877. return 0;
  59878. }
  59879. const Colour ColourSelector::getSwatchColour (const int) const
  59880. {
  59881. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59882. return Colours::black;
  59883. }
  59884. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59885. {
  59886. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59887. }
  59888. END_JUCE_NAMESPACE
  59889. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59890. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59891. BEGIN_JUCE_NAMESPACE
  59892. class ShadowWindow : public Component
  59893. {
  59894. public:
  59895. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  59896. : topLeft (shadowImageSections [type_ * 3]),
  59897. bottomRight (shadowImageSections [type_ * 3 + 1]),
  59898. filler (shadowImageSections [type_ * 3 + 2]),
  59899. type (type_)
  59900. {
  59901. setInterceptsMouseClicks (false, false);
  59902. if (owner.isOnDesktop())
  59903. {
  59904. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59905. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59906. | ComponentPeer::windowIsTemporary
  59907. | ComponentPeer::windowIgnoresKeyPresses);
  59908. }
  59909. else if (owner.getParentComponent() != 0)
  59910. {
  59911. owner.getParentComponent()->addChildComponent (this);
  59912. }
  59913. }
  59914. void paint (Graphics& g)
  59915. {
  59916. g.setOpacity (1.0f);
  59917. if (type < 2)
  59918. {
  59919. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59920. g.drawImage (topLeft,
  59921. 0, 0, topLeft.getWidth(), imH,
  59922. 0, 0, topLeft.getWidth(), imH);
  59923. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59924. g.drawImage (bottomRight,
  59925. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59926. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59927. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59928. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59929. }
  59930. else
  59931. {
  59932. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59933. g.drawImage (topLeft,
  59934. 0, 0, imW, topLeft.getHeight(),
  59935. 0, 0, imW, topLeft.getHeight());
  59936. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59937. g.drawImage (bottomRight,
  59938. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59939. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59940. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59941. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59942. }
  59943. }
  59944. void resized()
  59945. {
  59946. repaint(); // (needed for correct repainting)
  59947. }
  59948. private:
  59949. const Image topLeft, bottomRight, filler;
  59950. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59951. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  59952. };
  59953. DropShadower::DropShadower (const float alpha_,
  59954. const int xOffset_,
  59955. const int yOffset_,
  59956. const float blurRadius_)
  59957. : owner (0),
  59958. xOffset (xOffset_),
  59959. yOffset (yOffset_),
  59960. alpha (alpha_),
  59961. blurRadius (blurRadius_),
  59962. reentrant (false)
  59963. {
  59964. }
  59965. DropShadower::~DropShadower()
  59966. {
  59967. if (owner != 0)
  59968. owner->removeComponentListener (this);
  59969. reentrant = true;
  59970. shadowWindows.clear();
  59971. }
  59972. void DropShadower::setOwner (Component* componentToFollow)
  59973. {
  59974. if (componentToFollow != owner)
  59975. {
  59976. if (owner != 0)
  59977. owner->removeComponentListener (this);
  59978. // (the component can't be null)
  59979. jassert (componentToFollow != 0);
  59980. owner = componentToFollow;
  59981. jassert (owner != 0);
  59982. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59983. owner->addComponentListener (this);
  59984. updateShadows();
  59985. }
  59986. }
  59987. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59988. {
  59989. updateShadows();
  59990. }
  59991. void DropShadower::componentBroughtToFront (Component&)
  59992. {
  59993. bringShadowWindowsToFront();
  59994. }
  59995. void DropShadower::componentParentHierarchyChanged (Component&)
  59996. {
  59997. shadowWindows.clear();
  59998. updateShadows();
  59999. }
  60000. void DropShadower::componentVisibilityChanged (Component&)
  60001. {
  60002. updateShadows();
  60003. }
  60004. void DropShadower::updateShadows()
  60005. {
  60006. if (reentrant || owner == 0)
  60007. return;
  60008. ComponentPeer* const peer = owner->getPeer();
  60009. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60010. const bool createShadowWindows = shadowWindows.size() == 0
  60011. && owner->getWidth() > 0
  60012. && owner->getHeight() > 0
  60013. && isOwnerVisible
  60014. && (Desktop::canUseSemiTransparentWindows()
  60015. || owner->getParentComponent() != 0);
  60016. {
  60017. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60018. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60019. if (createShadowWindows)
  60020. {
  60021. // keep a cached version of the image to save doing the gaussian too often
  60022. String imageId;
  60023. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60024. const int hash = imageId.hashCode();
  60025. Image bigIm (ImageCache::getFromHashCode (hash));
  60026. if (bigIm.isNull())
  60027. {
  60028. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60029. Graphics bigG (bigIm);
  60030. bigG.setColour (Colours::black.withAlpha (alpha));
  60031. bigG.fillRect (shadowEdge + xOffset,
  60032. shadowEdge + yOffset,
  60033. bigIm.getWidth() - (shadowEdge * 2),
  60034. bigIm.getHeight() - (shadowEdge * 2));
  60035. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60036. blurKernel.createGaussianBlur (blurRadius);
  60037. blurKernel.applyToImage (bigIm, bigIm,
  60038. Rectangle<int> (xOffset, yOffset,
  60039. bigIm.getWidth(), bigIm.getHeight()));
  60040. ImageCache::addImageToCache (bigIm, hash);
  60041. }
  60042. const int iw = bigIm.getWidth();
  60043. const int ih = bigIm.getHeight();
  60044. const int shadowEdge2 = shadowEdge * 2;
  60045. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60046. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60047. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60048. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60049. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60050. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60051. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60052. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60053. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60054. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60055. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60056. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60057. for (int i = 0; i < 4; ++i)
  60058. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60059. }
  60060. if (shadowWindows.size() >= 4)
  60061. {
  60062. for (int i = shadowWindows.size(); --i >= 0;)
  60063. {
  60064. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60065. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60066. }
  60067. const int x = owner->getX();
  60068. const int y = owner->getY() - shadowEdge;
  60069. const int w = owner->getWidth();
  60070. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60071. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60072. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60073. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60074. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60075. }
  60076. }
  60077. if (createShadowWindows)
  60078. bringShadowWindowsToFront();
  60079. }
  60080. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60081. const int sx, const int sy)
  60082. {
  60083. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60084. Graphics g (shadowImageSections[num]);
  60085. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60086. }
  60087. void DropShadower::bringShadowWindowsToFront()
  60088. {
  60089. if (! reentrant)
  60090. {
  60091. updateShadows();
  60092. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60093. for (int i = shadowWindows.size(); --i >= 0;)
  60094. shadowWindows.getUnchecked(i)->toBehind (owner);
  60095. }
  60096. }
  60097. END_JUCE_NAMESPACE
  60098. /*** End of inlined file: juce_DropShadower.cpp ***/
  60099. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60100. BEGIN_JUCE_NAMESPACE
  60101. class MidiKeyboardUpDownButton : public Button
  60102. {
  60103. public:
  60104. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60105. : Button (String::empty),
  60106. owner (owner_),
  60107. delta (delta_)
  60108. {
  60109. setOpaque (true);
  60110. }
  60111. void clicked()
  60112. {
  60113. int note = owner.getLowestVisibleKey();
  60114. if (delta < 0)
  60115. note = (note - 1) / 12;
  60116. else
  60117. note = note / 12 + 1;
  60118. owner.setLowestVisibleKey (note * 12);
  60119. }
  60120. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60121. {
  60122. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60123. isMouseOverButton, isButtonDown,
  60124. delta > 0);
  60125. }
  60126. private:
  60127. MidiKeyboardComponent& owner;
  60128. const int delta;
  60129. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60130. };
  60131. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60132. const Orientation orientation_)
  60133. : state (state_),
  60134. xOffset (0),
  60135. blackNoteLength (1),
  60136. keyWidth (16.0f),
  60137. orientation (orientation_),
  60138. midiChannel (1),
  60139. midiInChannelMask (0xffff),
  60140. velocity (1.0f),
  60141. noteUnderMouse (-1),
  60142. mouseDownNote (-1),
  60143. rangeStart (0),
  60144. rangeEnd (127),
  60145. firstKey (12 * 4),
  60146. canScroll (true),
  60147. mouseDragging (false),
  60148. useMousePositionForVelocity (true),
  60149. keyMappingOctave (6),
  60150. octaveNumForMiddleC (3)
  60151. {
  60152. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60153. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60154. // initialise with a default set of querty key-mappings..
  60155. const char* const keymap = "awsedftgyhujkolp;";
  60156. for (int i = String (keymap).length(); --i >= 0;)
  60157. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60158. setOpaque (true);
  60159. setWantsKeyboardFocus (true);
  60160. state.addListener (this);
  60161. }
  60162. MidiKeyboardComponent::~MidiKeyboardComponent()
  60163. {
  60164. state.removeListener (this);
  60165. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60166. }
  60167. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60168. {
  60169. keyWidth = widthInPixels;
  60170. resized();
  60171. }
  60172. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60173. {
  60174. if (orientation != newOrientation)
  60175. {
  60176. orientation = newOrientation;
  60177. resized();
  60178. }
  60179. }
  60180. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60181. const int highestNote)
  60182. {
  60183. jassert (lowestNote >= 0 && lowestNote <= 127);
  60184. jassert (highestNote >= 0 && highestNote <= 127);
  60185. jassert (lowestNote <= highestNote);
  60186. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60187. {
  60188. rangeStart = jlimit (0, 127, lowestNote);
  60189. rangeEnd = jlimit (0, 127, highestNote);
  60190. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60191. resized();
  60192. }
  60193. }
  60194. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60195. {
  60196. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60197. if (noteNumber != firstKey)
  60198. {
  60199. firstKey = noteNumber;
  60200. sendChangeMessage();
  60201. resized();
  60202. }
  60203. }
  60204. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60205. {
  60206. if (canScroll != canScroll_)
  60207. {
  60208. canScroll = canScroll_;
  60209. resized();
  60210. }
  60211. }
  60212. void MidiKeyboardComponent::colourChanged()
  60213. {
  60214. repaint();
  60215. }
  60216. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60217. {
  60218. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60219. if (midiChannel != midiChannelNumber)
  60220. {
  60221. resetAnyKeysInUse();
  60222. midiChannel = jlimit (1, 16, midiChannelNumber);
  60223. }
  60224. }
  60225. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60226. {
  60227. midiInChannelMask = midiChannelMask;
  60228. triggerAsyncUpdate();
  60229. }
  60230. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60231. {
  60232. velocity = jlimit (0.0f, 1.0f, velocity_);
  60233. useMousePositionForVelocity = useMousePositionForVelocity_;
  60234. }
  60235. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60236. {
  60237. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60238. static const float blackNoteWidth = 0.7f;
  60239. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60240. 1.0f, 2 - blackNoteWidth * 0.4f,
  60241. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60242. 4.0f, 5 - blackNoteWidth * 0.5f,
  60243. 5.0f, 6 - blackNoteWidth * 0.3f,
  60244. 6.0f };
  60245. static const float widths[] = { 1.0f, blackNoteWidth,
  60246. 1.0f, blackNoteWidth,
  60247. 1.0f, 1.0f, blackNoteWidth,
  60248. 1.0f, blackNoteWidth,
  60249. 1.0f, blackNoteWidth,
  60250. 1.0f };
  60251. const int octave = midiNoteNumber / 12;
  60252. const int note = midiNoteNumber % 12;
  60253. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60254. w = roundToInt (widths [note] * keyWidth_);
  60255. }
  60256. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60257. {
  60258. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60259. int rx, rw;
  60260. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60261. x -= xOffset + rx;
  60262. }
  60263. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60264. {
  60265. int x, y;
  60266. getKeyPos (midiNoteNumber, x, y);
  60267. return x;
  60268. }
  60269. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60270. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60271. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60272. {
  60273. if (! reallyContains (pos, false))
  60274. return -1;
  60275. Point<int> p (pos);
  60276. if (orientation != horizontalKeyboard)
  60277. {
  60278. p = Point<int> (p.getY(), p.getX());
  60279. if (orientation == verticalKeyboardFacingLeft)
  60280. p = Point<int> (p.getX(), getWidth() - p.getY());
  60281. else
  60282. p = Point<int> (getHeight() - p.getX(), p.getY());
  60283. }
  60284. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60285. }
  60286. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60287. {
  60288. if (pos.getY() < blackNoteLength)
  60289. {
  60290. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60291. {
  60292. for (int i = 0; i < 5; ++i)
  60293. {
  60294. const int note = octaveStart + blackNotes [i];
  60295. if (note >= rangeStart && note <= rangeEnd)
  60296. {
  60297. int kx, kw;
  60298. getKeyPos (note, kx, kw);
  60299. kx += xOffset;
  60300. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60301. {
  60302. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60303. return note;
  60304. }
  60305. }
  60306. }
  60307. }
  60308. }
  60309. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60310. {
  60311. for (int i = 0; i < 7; ++i)
  60312. {
  60313. const int note = octaveStart + whiteNotes [i];
  60314. if (note >= rangeStart && note <= rangeEnd)
  60315. {
  60316. int kx, kw;
  60317. getKeyPos (note, kx, kw);
  60318. kx += xOffset;
  60319. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60320. {
  60321. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60322. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60323. return note;
  60324. }
  60325. }
  60326. }
  60327. }
  60328. mousePositionVelocity = 0;
  60329. return -1;
  60330. }
  60331. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60332. {
  60333. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60334. {
  60335. int x, w;
  60336. getKeyPos (noteNum, x, w);
  60337. if (orientation == horizontalKeyboard)
  60338. repaint (x, 0, w, getHeight());
  60339. else if (orientation == verticalKeyboardFacingLeft)
  60340. repaint (0, x, getWidth(), w);
  60341. else if (orientation == verticalKeyboardFacingRight)
  60342. repaint (0, getHeight() - x - w, getWidth(), w);
  60343. }
  60344. }
  60345. void MidiKeyboardComponent::paint (Graphics& g)
  60346. {
  60347. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60348. const Colour lineColour (findColour (keySeparatorLineColourId));
  60349. const Colour textColour (findColour (textLabelColourId));
  60350. int x, w, octave;
  60351. for (octave = 0; octave < 128; octave += 12)
  60352. {
  60353. for (int white = 0; white < 7; ++white)
  60354. {
  60355. const int noteNum = octave + whiteNotes [white];
  60356. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60357. {
  60358. getKeyPos (noteNum, x, w);
  60359. if (orientation == horizontalKeyboard)
  60360. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60361. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60362. noteUnderMouse == noteNum,
  60363. lineColour, textColour);
  60364. else if (orientation == verticalKeyboardFacingLeft)
  60365. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60366. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60367. noteUnderMouse == noteNum,
  60368. lineColour, textColour);
  60369. else if (orientation == verticalKeyboardFacingRight)
  60370. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60371. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60372. noteUnderMouse == noteNum,
  60373. lineColour, textColour);
  60374. }
  60375. }
  60376. }
  60377. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60378. if (orientation == verticalKeyboardFacingLeft)
  60379. {
  60380. x1 = getWidth() - 1.0f;
  60381. x2 = getWidth() - 5.0f;
  60382. }
  60383. else if (orientation == verticalKeyboardFacingRight)
  60384. x2 = 5.0f;
  60385. else
  60386. y2 = 5.0f;
  60387. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60388. Colours::transparentBlack, x2, y2, false));
  60389. getKeyPos (rangeEnd, x, w);
  60390. x += w;
  60391. if (orientation == verticalKeyboardFacingLeft)
  60392. g.fillRect (getWidth() - 5, 0, 5, x);
  60393. else if (orientation == verticalKeyboardFacingRight)
  60394. g.fillRect (0, 0, 5, x);
  60395. else
  60396. g.fillRect (0, 0, x, 5);
  60397. g.setColour (lineColour);
  60398. if (orientation == verticalKeyboardFacingLeft)
  60399. g.fillRect (0, 0, 1, x);
  60400. else if (orientation == verticalKeyboardFacingRight)
  60401. g.fillRect (getWidth() - 1, 0, 1, x);
  60402. else
  60403. g.fillRect (0, getHeight() - 1, x, 1);
  60404. const Colour blackNoteColour (findColour (blackNoteColourId));
  60405. for (octave = 0; octave < 128; octave += 12)
  60406. {
  60407. for (int black = 0; black < 5; ++black)
  60408. {
  60409. const int noteNum = octave + blackNotes [black];
  60410. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60411. {
  60412. getKeyPos (noteNum, x, w);
  60413. if (orientation == horizontalKeyboard)
  60414. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60415. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60416. noteUnderMouse == noteNum,
  60417. blackNoteColour);
  60418. else if (orientation == verticalKeyboardFacingLeft)
  60419. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60420. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60421. noteUnderMouse == noteNum,
  60422. blackNoteColour);
  60423. else if (orientation == verticalKeyboardFacingRight)
  60424. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60425. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60426. noteUnderMouse == noteNum,
  60427. blackNoteColour);
  60428. }
  60429. }
  60430. }
  60431. }
  60432. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60433. Graphics& g, int x, int y, int w, int h,
  60434. bool isDown, bool isOver,
  60435. const Colour& lineColour,
  60436. const Colour& textColour)
  60437. {
  60438. Colour c (Colours::transparentWhite);
  60439. if (isDown)
  60440. c = findColour (keyDownOverlayColourId);
  60441. if (isOver)
  60442. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60443. g.setColour (c);
  60444. g.fillRect (x, y, w, h);
  60445. const String text (getWhiteNoteText (midiNoteNumber));
  60446. if (! text.isEmpty())
  60447. {
  60448. g.setColour (textColour);
  60449. Font f (jmin (12.0f, keyWidth * 0.9f));
  60450. f.setHorizontalScale (0.8f);
  60451. g.setFont (f);
  60452. Justification justification (Justification::centredBottom);
  60453. if (orientation == verticalKeyboardFacingLeft)
  60454. justification = Justification::centredLeft;
  60455. else if (orientation == verticalKeyboardFacingRight)
  60456. justification = Justification::centredRight;
  60457. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60458. }
  60459. g.setColour (lineColour);
  60460. if (orientation == horizontalKeyboard)
  60461. g.fillRect (x, y, 1, h);
  60462. else if (orientation == verticalKeyboardFacingLeft)
  60463. g.fillRect (x, y, w, 1);
  60464. else if (orientation == verticalKeyboardFacingRight)
  60465. g.fillRect (x, y + h - 1, w, 1);
  60466. if (midiNoteNumber == rangeEnd)
  60467. {
  60468. if (orientation == horizontalKeyboard)
  60469. g.fillRect (x + w, y, 1, h);
  60470. else if (orientation == verticalKeyboardFacingLeft)
  60471. g.fillRect (x, y + h, w, 1);
  60472. else if (orientation == verticalKeyboardFacingRight)
  60473. g.fillRect (x, y - 1, w, 1);
  60474. }
  60475. }
  60476. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60477. Graphics& g, int x, int y, int w, int h,
  60478. bool isDown, bool isOver,
  60479. const Colour& noteFillColour)
  60480. {
  60481. Colour c (noteFillColour);
  60482. if (isDown)
  60483. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60484. if (isOver)
  60485. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60486. g.setColour (c);
  60487. g.fillRect (x, y, w, h);
  60488. if (isDown)
  60489. {
  60490. g.setColour (noteFillColour);
  60491. g.drawRect (x, y, w, h);
  60492. }
  60493. else
  60494. {
  60495. const int xIndent = jmax (1, jmin (w, h) / 8);
  60496. g.setColour (c.brighter());
  60497. if (orientation == horizontalKeyboard)
  60498. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60499. else if (orientation == verticalKeyboardFacingLeft)
  60500. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60501. else if (orientation == verticalKeyboardFacingRight)
  60502. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60503. }
  60504. }
  60505. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60506. {
  60507. octaveNumForMiddleC = octaveNumForMiddleC_;
  60508. repaint();
  60509. }
  60510. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60511. {
  60512. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60513. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60514. return String::empty;
  60515. }
  60516. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60517. const bool isMouseOver_,
  60518. const bool isButtonDown,
  60519. const bool movesOctavesUp)
  60520. {
  60521. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60522. float angle;
  60523. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60524. angle = movesOctavesUp ? 0.0f : 0.5f;
  60525. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60526. angle = movesOctavesUp ? 0.25f : 0.75f;
  60527. else
  60528. angle = movesOctavesUp ? 0.75f : 0.25f;
  60529. Path path;
  60530. path.lineTo (0.0f, 1.0f);
  60531. path.lineTo (1.0f, 0.5f);
  60532. path.closeSubPath();
  60533. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60534. g.setColour (findColour (upDownButtonArrowColourId)
  60535. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60536. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60537. w - 2.0f,
  60538. h - 2.0f,
  60539. true));
  60540. }
  60541. void MidiKeyboardComponent::resized()
  60542. {
  60543. int w = getWidth();
  60544. int h = getHeight();
  60545. if (w > 0 && h > 0)
  60546. {
  60547. if (orientation != horizontalKeyboard)
  60548. swapVariables (w, h);
  60549. blackNoteLength = roundToInt (h * 0.7f);
  60550. int kx2, kw2;
  60551. getKeyPos (rangeEnd, kx2, kw2);
  60552. kx2 += kw2;
  60553. if (firstKey != rangeStart)
  60554. {
  60555. int kx1, kw1;
  60556. getKeyPos (rangeStart, kx1, kw1);
  60557. if (kx2 - kx1 <= w)
  60558. {
  60559. firstKey = rangeStart;
  60560. sendChangeMessage();
  60561. repaint();
  60562. }
  60563. }
  60564. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60565. scrollDown->setVisible (showScrollButtons);
  60566. scrollUp->setVisible (showScrollButtons);
  60567. xOffset = 0;
  60568. if (showScrollButtons)
  60569. {
  60570. const int scrollButtonW = jmin (12, w / 2);
  60571. if (orientation == horizontalKeyboard)
  60572. {
  60573. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60574. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60575. }
  60576. else if (orientation == verticalKeyboardFacingLeft)
  60577. {
  60578. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60579. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60580. }
  60581. else if (orientation == verticalKeyboardFacingRight)
  60582. {
  60583. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60584. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60585. }
  60586. int endOfLastKey, kw;
  60587. getKeyPos (rangeEnd, endOfLastKey, kw);
  60588. endOfLastKey += kw;
  60589. float mousePositionVelocity;
  60590. const int spaceAvailable = w - scrollButtonW * 2;
  60591. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60592. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60593. {
  60594. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60595. sendChangeMessage();
  60596. }
  60597. int newOffset = 0;
  60598. getKeyPos (firstKey, newOffset, kw);
  60599. xOffset = newOffset - scrollButtonW;
  60600. }
  60601. else
  60602. {
  60603. firstKey = rangeStart;
  60604. }
  60605. timerCallback();
  60606. repaint();
  60607. }
  60608. }
  60609. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60610. {
  60611. triggerAsyncUpdate();
  60612. }
  60613. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60614. {
  60615. triggerAsyncUpdate();
  60616. }
  60617. void MidiKeyboardComponent::handleAsyncUpdate()
  60618. {
  60619. for (int i = rangeStart; i <= rangeEnd; ++i)
  60620. {
  60621. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60622. {
  60623. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60624. repaintNote (i);
  60625. }
  60626. }
  60627. }
  60628. void MidiKeyboardComponent::resetAnyKeysInUse()
  60629. {
  60630. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60631. {
  60632. state.allNotesOff (midiChannel);
  60633. keysPressed.clear();
  60634. mouseDownNote = -1;
  60635. }
  60636. }
  60637. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60638. {
  60639. float mousePositionVelocity = 0.0f;
  60640. const int newNote = (mouseDragging || isMouseOver())
  60641. ? xyToNote (pos, mousePositionVelocity) : -1;
  60642. if (noteUnderMouse != newNote)
  60643. {
  60644. if (mouseDownNote >= 0)
  60645. {
  60646. state.noteOff (midiChannel, mouseDownNote);
  60647. mouseDownNote = -1;
  60648. }
  60649. if (mouseDragging && newNote >= 0)
  60650. {
  60651. if (! useMousePositionForVelocity)
  60652. mousePositionVelocity = 1.0f;
  60653. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60654. mouseDownNote = newNote;
  60655. }
  60656. repaintNote (noteUnderMouse);
  60657. noteUnderMouse = newNote;
  60658. repaintNote (noteUnderMouse);
  60659. }
  60660. else if (mouseDownNote >= 0 && ! mouseDragging)
  60661. {
  60662. state.noteOff (midiChannel, mouseDownNote);
  60663. mouseDownNote = -1;
  60664. }
  60665. }
  60666. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60667. {
  60668. updateNoteUnderMouse (e.getPosition());
  60669. stopTimer();
  60670. }
  60671. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60672. {
  60673. float mousePositionVelocity;
  60674. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60675. if (newNote >= 0)
  60676. mouseDraggedToKey (newNote, e);
  60677. updateNoteUnderMouse (e.getPosition());
  60678. }
  60679. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60680. {
  60681. return true;
  60682. }
  60683. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60684. {
  60685. }
  60686. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60687. {
  60688. float mousePositionVelocity;
  60689. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60690. mouseDragging = false;
  60691. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60692. {
  60693. repaintNote (noteUnderMouse);
  60694. noteUnderMouse = -1;
  60695. mouseDragging = true;
  60696. updateNoteUnderMouse (e.getPosition());
  60697. startTimer (500);
  60698. }
  60699. }
  60700. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60701. {
  60702. mouseDragging = false;
  60703. updateNoteUnderMouse (e.getPosition());
  60704. stopTimer();
  60705. }
  60706. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60707. {
  60708. updateNoteUnderMouse (e.getPosition());
  60709. }
  60710. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60711. {
  60712. updateNoteUnderMouse (e.getPosition());
  60713. }
  60714. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60715. {
  60716. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60717. }
  60718. void MidiKeyboardComponent::timerCallback()
  60719. {
  60720. updateNoteUnderMouse (getMouseXYRelative());
  60721. }
  60722. void MidiKeyboardComponent::clearKeyMappings()
  60723. {
  60724. resetAnyKeysInUse();
  60725. keyPressNotes.clear();
  60726. keyPresses.clear();
  60727. }
  60728. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60729. const int midiNoteOffsetFromC)
  60730. {
  60731. removeKeyPressForNote (midiNoteOffsetFromC);
  60732. keyPressNotes.add (midiNoteOffsetFromC);
  60733. keyPresses.add (key);
  60734. }
  60735. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60736. {
  60737. for (int i = keyPressNotes.size(); --i >= 0;)
  60738. {
  60739. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60740. {
  60741. keyPressNotes.remove (i);
  60742. keyPresses.remove (i);
  60743. }
  60744. }
  60745. }
  60746. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60747. {
  60748. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60749. keyMappingOctave = newOctaveNumber;
  60750. }
  60751. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60752. {
  60753. bool keyPressUsed = false;
  60754. for (int i = keyPresses.size(); --i >= 0;)
  60755. {
  60756. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60757. if (keyPresses.getReference(i).isCurrentlyDown())
  60758. {
  60759. if (! keysPressed [note])
  60760. {
  60761. keysPressed.setBit (note);
  60762. state.noteOn (midiChannel, note, velocity);
  60763. keyPressUsed = true;
  60764. }
  60765. }
  60766. else
  60767. {
  60768. if (keysPressed [note])
  60769. {
  60770. keysPressed.clearBit (note);
  60771. state.noteOff (midiChannel, note);
  60772. keyPressUsed = true;
  60773. }
  60774. }
  60775. }
  60776. return keyPressUsed;
  60777. }
  60778. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60779. {
  60780. resetAnyKeysInUse();
  60781. }
  60782. END_JUCE_NAMESPACE
  60783. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60784. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60785. #if JUCE_OPENGL
  60786. BEGIN_JUCE_NAMESPACE
  60787. extern void juce_glViewport (const int w, const int h);
  60788. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60789. const int alphaBits_,
  60790. const int depthBufferBits_,
  60791. const int stencilBufferBits_)
  60792. : redBits (bitsPerRGBComponent),
  60793. greenBits (bitsPerRGBComponent),
  60794. blueBits (bitsPerRGBComponent),
  60795. alphaBits (alphaBits_),
  60796. depthBufferBits (depthBufferBits_),
  60797. stencilBufferBits (stencilBufferBits_),
  60798. accumulationBufferRedBits (0),
  60799. accumulationBufferGreenBits (0),
  60800. accumulationBufferBlueBits (0),
  60801. accumulationBufferAlphaBits (0),
  60802. fullSceneAntiAliasingNumSamples (0)
  60803. {
  60804. }
  60805. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60806. : redBits (other.redBits),
  60807. greenBits (other.greenBits),
  60808. blueBits (other.blueBits),
  60809. alphaBits (other.alphaBits),
  60810. depthBufferBits (other.depthBufferBits),
  60811. stencilBufferBits (other.stencilBufferBits),
  60812. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60813. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60814. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60815. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60816. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60817. {
  60818. }
  60819. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60820. {
  60821. redBits = other.redBits;
  60822. greenBits = other.greenBits;
  60823. blueBits = other.blueBits;
  60824. alphaBits = other.alphaBits;
  60825. depthBufferBits = other.depthBufferBits;
  60826. stencilBufferBits = other.stencilBufferBits;
  60827. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60828. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60829. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60830. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60831. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60832. return *this;
  60833. }
  60834. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60835. {
  60836. return redBits == other.redBits
  60837. && greenBits == other.greenBits
  60838. && blueBits == other.blueBits
  60839. && alphaBits == other.alphaBits
  60840. && depthBufferBits == other.depthBufferBits
  60841. && stencilBufferBits == other.stencilBufferBits
  60842. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60843. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60844. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60845. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60846. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60847. }
  60848. static Array<OpenGLContext*> knownContexts;
  60849. OpenGLContext::OpenGLContext() throw()
  60850. {
  60851. knownContexts.add (this);
  60852. }
  60853. OpenGLContext::~OpenGLContext()
  60854. {
  60855. knownContexts.removeValue (this);
  60856. }
  60857. OpenGLContext* OpenGLContext::getCurrentContext()
  60858. {
  60859. for (int i = knownContexts.size(); --i >= 0;)
  60860. {
  60861. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60862. if (oglc->isActive())
  60863. return oglc;
  60864. }
  60865. return 0;
  60866. }
  60867. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60868. {
  60869. public:
  60870. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60871. : ComponentMovementWatcher (owner_),
  60872. owner (owner_)
  60873. {
  60874. }
  60875. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60876. {
  60877. owner->updateContextPosition();
  60878. }
  60879. void componentPeerChanged()
  60880. {
  60881. const ScopedLock sl (owner->getContextLock());
  60882. owner->deleteContext();
  60883. }
  60884. void componentVisibilityChanged()
  60885. {
  60886. if (! owner->isShowing())
  60887. {
  60888. const ScopedLock sl (owner->getContextLock());
  60889. owner->deleteContext();
  60890. }
  60891. }
  60892. private:
  60893. OpenGLComponent* const owner;
  60894. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  60895. };
  60896. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60897. : type (type_),
  60898. contextToShareListsWith (0),
  60899. needToUpdateViewport (true)
  60900. {
  60901. setOpaque (true);
  60902. componentWatcher = new OpenGLComponentWatcher (this);
  60903. }
  60904. OpenGLComponent::~OpenGLComponent()
  60905. {
  60906. deleteContext();
  60907. componentWatcher = 0;
  60908. }
  60909. void OpenGLComponent::deleteContext()
  60910. {
  60911. const ScopedLock sl (contextLock);
  60912. context = 0;
  60913. }
  60914. void OpenGLComponent::updateContextPosition()
  60915. {
  60916. needToUpdateViewport = true;
  60917. if (getWidth() > 0 && getHeight() > 0)
  60918. {
  60919. Component* const topComp = getTopLevelComponent();
  60920. if (topComp->getPeer() != 0)
  60921. {
  60922. const ScopedLock sl (contextLock);
  60923. if (context != 0)
  60924. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60925. getScreenY() - topComp->getScreenY(),
  60926. getWidth(),
  60927. getHeight(),
  60928. topComp->getHeight());
  60929. }
  60930. }
  60931. }
  60932. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60933. {
  60934. OpenGLPixelFormat pf;
  60935. const ScopedLock sl (contextLock);
  60936. if (context != 0)
  60937. pf = context->getPixelFormat();
  60938. return pf;
  60939. }
  60940. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60941. {
  60942. if (! (preferredPixelFormat == formatToUse))
  60943. {
  60944. const ScopedLock sl (contextLock);
  60945. deleteContext();
  60946. preferredPixelFormat = formatToUse;
  60947. }
  60948. }
  60949. void OpenGLComponent::shareWith (OpenGLContext* c)
  60950. {
  60951. if (contextToShareListsWith != c)
  60952. {
  60953. const ScopedLock sl (contextLock);
  60954. deleteContext();
  60955. contextToShareListsWith = c;
  60956. }
  60957. }
  60958. bool OpenGLComponent::makeCurrentContextActive()
  60959. {
  60960. if (context == 0)
  60961. {
  60962. const ScopedLock sl (contextLock);
  60963. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60964. {
  60965. context = createContext();
  60966. if (context != 0)
  60967. {
  60968. updateContextPosition();
  60969. if (context->makeActive())
  60970. newOpenGLContextCreated();
  60971. }
  60972. }
  60973. }
  60974. return context != 0 && context->makeActive();
  60975. }
  60976. void OpenGLComponent::makeCurrentContextInactive()
  60977. {
  60978. if (context != 0)
  60979. context->makeInactive();
  60980. }
  60981. bool OpenGLComponent::isActiveContext() const throw()
  60982. {
  60983. return context != 0 && context->isActive();
  60984. }
  60985. void OpenGLComponent::swapBuffers()
  60986. {
  60987. if (context != 0)
  60988. context->swapBuffers();
  60989. }
  60990. void OpenGLComponent::paint (Graphics&)
  60991. {
  60992. if (renderAndSwapBuffers())
  60993. {
  60994. ComponentPeer* const peer = getPeer();
  60995. if (peer != 0)
  60996. {
  60997. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60998. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60999. }
  61000. }
  61001. }
  61002. bool OpenGLComponent::renderAndSwapBuffers()
  61003. {
  61004. const ScopedLock sl (contextLock);
  61005. if (! makeCurrentContextActive())
  61006. return false;
  61007. if (needToUpdateViewport)
  61008. {
  61009. needToUpdateViewport = false;
  61010. juce_glViewport (getWidth(), getHeight());
  61011. }
  61012. renderOpenGL();
  61013. swapBuffers();
  61014. return true;
  61015. }
  61016. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61017. {
  61018. Component::internalRepaint (x, y, w, h);
  61019. if (context != 0)
  61020. context->repaint();
  61021. }
  61022. END_JUCE_NAMESPACE
  61023. #endif
  61024. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61025. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61026. BEGIN_JUCE_NAMESPACE
  61027. PreferencesPanel::PreferencesPanel()
  61028. : buttonSize (70)
  61029. {
  61030. }
  61031. PreferencesPanel::~PreferencesPanel()
  61032. {
  61033. }
  61034. void PreferencesPanel::addSettingsPage (const String& title,
  61035. const Drawable* icon,
  61036. const Drawable* overIcon,
  61037. const Drawable* downIcon)
  61038. {
  61039. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61040. buttons.add (button);
  61041. button->setImages (icon, overIcon, downIcon);
  61042. button->setRadioGroupId (1);
  61043. button->addListener (this);
  61044. button->setClickingTogglesState (true);
  61045. button->setWantsKeyboardFocus (false);
  61046. addAndMakeVisible (button);
  61047. resized();
  61048. if (currentPage == 0)
  61049. setCurrentPage (title);
  61050. }
  61051. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61052. {
  61053. DrawableImage icon, iconOver, iconDown;
  61054. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61055. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61056. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61057. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61058. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61059. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61060. }
  61061. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61062. {
  61063. setSize (dialogWidth, dialogHeight);
  61064. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61065. }
  61066. void PreferencesPanel::resized()
  61067. {
  61068. for (int i = 0; i < buttons.size(); ++i)
  61069. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61070. if (currentPage != 0)
  61071. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61072. }
  61073. void PreferencesPanel::paint (Graphics& g)
  61074. {
  61075. g.setColour (Colours::grey);
  61076. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61077. }
  61078. void PreferencesPanel::setCurrentPage (const String& pageName)
  61079. {
  61080. if (currentPageName != pageName)
  61081. {
  61082. currentPageName = pageName;
  61083. currentPage = 0;
  61084. currentPage = createComponentForPage (pageName);
  61085. if (currentPage != 0)
  61086. {
  61087. addAndMakeVisible (currentPage);
  61088. currentPage->toBack();
  61089. resized();
  61090. }
  61091. for (int i = 0; i < buttons.size(); ++i)
  61092. {
  61093. if (buttons.getUnchecked(i)->getName() == pageName)
  61094. {
  61095. buttons.getUnchecked(i)->setToggleState (true, false);
  61096. break;
  61097. }
  61098. }
  61099. }
  61100. }
  61101. void PreferencesPanel::buttonClicked (Button*)
  61102. {
  61103. for (int i = 0; i < buttons.size(); ++i)
  61104. {
  61105. if (buttons.getUnchecked(i)->getToggleState())
  61106. {
  61107. setCurrentPage (buttons.getUnchecked(i)->getName());
  61108. break;
  61109. }
  61110. }
  61111. }
  61112. END_JUCE_NAMESPACE
  61113. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61114. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61115. #if JUCE_WINDOWS || JUCE_LINUX
  61116. BEGIN_JUCE_NAMESPACE
  61117. SystemTrayIconComponent::SystemTrayIconComponent()
  61118. {
  61119. addToDesktop (0);
  61120. }
  61121. SystemTrayIconComponent::~SystemTrayIconComponent()
  61122. {
  61123. }
  61124. END_JUCE_NAMESPACE
  61125. #endif
  61126. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61127. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61128. BEGIN_JUCE_NAMESPACE
  61129. class AlertWindowTextEditor : public TextEditor
  61130. {
  61131. public:
  61132. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61133. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61134. {
  61135. setSelectAllWhenFocused (true);
  61136. }
  61137. void returnPressed()
  61138. {
  61139. // pass these up the component hierarchy to be trigger the buttons
  61140. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61141. }
  61142. void escapePressed()
  61143. {
  61144. // pass these up the component hierarchy to be trigger the buttons
  61145. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61146. }
  61147. private:
  61148. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61149. static juce_wchar getDefaultPasswordChar() throw()
  61150. {
  61151. #if JUCE_LINUX
  61152. return 0x2022;
  61153. #else
  61154. return 0x25cf;
  61155. #endif
  61156. }
  61157. };
  61158. AlertWindow::AlertWindow (const String& title,
  61159. const String& message,
  61160. AlertIconType iconType,
  61161. Component* associatedComponent_)
  61162. : TopLevelWindow (title, true),
  61163. alertIconType (iconType),
  61164. associatedComponent (associatedComponent_)
  61165. {
  61166. if (message.isEmpty())
  61167. text = " "; // to force an update if the message is empty
  61168. setMessage (message);
  61169. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61170. {
  61171. Component* const c = Desktop::getInstance().getComponent (i);
  61172. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61173. {
  61174. setAlwaysOnTop (true);
  61175. break;
  61176. }
  61177. }
  61178. if (! JUCEApplication::isStandaloneApp())
  61179. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61180. lookAndFeelChanged();
  61181. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61182. }
  61183. AlertWindow::~AlertWindow()
  61184. {
  61185. removeAllChildren();
  61186. }
  61187. void AlertWindow::userTriedToCloseWindow()
  61188. {
  61189. exitModalState (0);
  61190. }
  61191. void AlertWindow::setMessage (const String& message)
  61192. {
  61193. const String newMessage (message.substring (0, 2048));
  61194. if (text != newMessage)
  61195. {
  61196. text = newMessage;
  61197. font = getLookAndFeel().getAlertWindowMessageFont();
  61198. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61199. textLayout.setText (getName() + "\n\n", titleFont);
  61200. textLayout.appendText (text, font);
  61201. updateLayout (true);
  61202. repaint();
  61203. }
  61204. }
  61205. void AlertWindow::buttonClicked (Button* button)
  61206. {
  61207. if (button->getParentComponent() != 0)
  61208. button->getParentComponent()->exitModalState (button->getCommandID());
  61209. }
  61210. void AlertWindow::addButton (const String& name,
  61211. const int returnValue,
  61212. const KeyPress& shortcutKey1,
  61213. const KeyPress& shortcutKey2)
  61214. {
  61215. TextButton* const b = new TextButton (name, String::empty);
  61216. buttons.add (b);
  61217. b->setWantsKeyboardFocus (true);
  61218. b->setMouseClickGrabsKeyboardFocus (false);
  61219. b->setCommandToTrigger (0, returnValue, false);
  61220. b->addShortcut (shortcutKey1);
  61221. b->addShortcut (shortcutKey2);
  61222. b->addListener (this);
  61223. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61224. addAndMakeVisible (b, 0);
  61225. updateLayout (false);
  61226. }
  61227. int AlertWindow::getNumButtons() const
  61228. {
  61229. return buttons.size();
  61230. }
  61231. void AlertWindow::triggerButtonClick (const String& buttonName)
  61232. {
  61233. for (int i = buttons.size(); --i >= 0;)
  61234. {
  61235. TextButton* const b = buttons.getUnchecked(i);
  61236. if (buttonName == b->getName())
  61237. {
  61238. b->triggerClick();
  61239. break;
  61240. }
  61241. }
  61242. }
  61243. void AlertWindow::addTextEditor (const String& name,
  61244. const String& initialContents,
  61245. const String& onScreenLabel,
  61246. const bool isPasswordBox)
  61247. {
  61248. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61249. textBoxes.add (tc);
  61250. allComps.add (tc);
  61251. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61252. tc->setFont (font);
  61253. tc->setText (initialContents);
  61254. tc->setCaretPosition (initialContents.length());
  61255. addAndMakeVisible (tc);
  61256. textboxNames.add (onScreenLabel);
  61257. updateLayout (false);
  61258. }
  61259. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61260. {
  61261. for (int i = textBoxes.size(); --i >= 0;)
  61262. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61263. return textBoxes.getUnchecked(i);
  61264. return 0;
  61265. }
  61266. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61267. {
  61268. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61269. return t != 0 ? t->getText() : String::empty;
  61270. }
  61271. void AlertWindow::addComboBox (const String& name,
  61272. const StringArray& items,
  61273. const String& onScreenLabel)
  61274. {
  61275. ComboBox* const cb = new ComboBox (name);
  61276. comboBoxes.add (cb);
  61277. allComps.add (cb);
  61278. for (int i = 0; i < items.size(); ++i)
  61279. cb->addItem (items[i], i + 1);
  61280. addAndMakeVisible (cb);
  61281. cb->setSelectedItemIndex (0);
  61282. comboBoxNames.add (onScreenLabel);
  61283. updateLayout (false);
  61284. }
  61285. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61286. {
  61287. for (int i = comboBoxes.size(); --i >= 0;)
  61288. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61289. return comboBoxes.getUnchecked(i);
  61290. return 0;
  61291. }
  61292. class AlertTextComp : public TextEditor
  61293. {
  61294. public:
  61295. AlertTextComp (const String& message,
  61296. const Font& font)
  61297. {
  61298. setReadOnly (true);
  61299. setMultiLine (true, true);
  61300. setCaretVisible (false);
  61301. setScrollbarsShown (true);
  61302. lookAndFeelChanged();
  61303. setWantsKeyboardFocus (false);
  61304. setFont (font);
  61305. setText (message, false);
  61306. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61307. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61308. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61309. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61310. }
  61311. ~AlertTextComp()
  61312. {
  61313. }
  61314. int getPreferredWidth() const throw() { return bestWidth; }
  61315. void updateLayout (const int width)
  61316. {
  61317. TextLayout text;
  61318. text.appendText (getText(), getFont());
  61319. text.layout (width - 8, Justification::topLeft, true);
  61320. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61321. }
  61322. private:
  61323. int bestWidth;
  61324. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61325. };
  61326. void AlertWindow::addTextBlock (const String& textBlock)
  61327. {
  61328. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61329. textBlocks.add (c);
  61330. allComps.add (c);
  61331. addAndMakeVisible (c);
  61332. updateLayout (false);
  61333. }
  61334. void AlertWindow::addProgressBarComponent (double& progressValue)
  61335. {
  61336. ProgressBar* const pb = new ProgressBar (progressValue);
  61337. progressBars.add (pb);
  61338. allComps.add (pb);
  61339. addAndMakeVisible (pb);
  61340. updateLayout (false);
  61341. }
  61342. void AlertWindow::addCustomComponent (Component* const component)
  61343. {
  61344. customComps.add (component);
  61345. allComps.add (component);
  61346. addAndMakeVisible (component);
  61347. updateLayout (false);
  61348. }
  61349. int AlertWindow::getNumCustomComponents() const
  61350. {
  61351. return customComps.size();
  61352. }
  61353. Component* AlertWindow::getCustomComponent (const int index) const
  61354. {
  61355. return customComps [index];
  61356. }
  61357. Component* AlertWindow::removeCustomComponent (const int index)
  61358. {
  61359. Component* const c = getCustomComponent (index);
  61360. if (c != 0)
  61361. {
  61362. customComps.removeValue (c);
  61363. allComps.removeValue (c);
  61364. removeChildComponent (c);
  61365. updateLayout (false);
  61366. }
  61367. return c;
  61368. }
  61369. void AlertWindow::paint (Graphics& g)
  61370. {
  61371. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61372. g.setColour (findColour (textColourId));
  61373. g.setFont (getLookAndFeel().getAlertWindowFont());
  61374. int i;
  61375. for (i = textBoxes.size(); --i >= 0;)
  61376. {
  61377. const TextEditor* const te = textBoxes.getUnchecked(i);
  61378. g.drawFittedText (textboxNames[i],
  61379. te->getX(), te->getY() - 14,
  61380. te->getWidth(), 14,
  61381. Justification::centredLeft, 1);
  61382. }
  61383. for (i = comboBoxNames.size(); --i >= 0;)
  61384. {
  61385. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61386. g.drawFittedText (comboBoxNames[i],
  61387. cb->getX(), cb->getY() - 14,
  61388. cb->getWidth(), 14,
  61389. Justification::centredLeft, 1);
  61390. }
  61391. for (i = customComps.size(); --i >= 0;)
  61392. {
  61393. const Component* const c = customComps.getUnchecked(i);
  61394. g.drawFittedText (c->getName(),
  61395. c->getX(), c->getY() - 14,
  61396. c->getWidth(), 14,
  61397. Justification::centredLeft, 1);
  61398. }
  61399. }
  61400. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61401. {
  61402. const int titleH = 24;
  61403. const int iconWidth = 80;
  61404. const int wid = jmax (font.getStringWidth (text),
  61405. font.getStringWidth (getName()));
  61406. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61407. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61408. const int edgeGap = 10;
  61409. const int labelHeight = 18;
  61410. int iconSpace;
  61411. if (alertIconType == NoIcon)
  61412. {
  61413. textLayout.layout (w, Justification::horizontallyCentred, true);
  61414. iconSpace = 0;
  61415. }
  61416. else
  61417. {
  61418. textLayout.layout (w, Justification::left, true);
  61419. iconSpace = iconWidth;
  61420. }
  61421. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61422. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61423. const int textLayoutH = textLayout.getHeight();
  61424. const int textBottom = 16 + titleH + textLayoutH;
  61425. int h = textBottom;
  61426. int buttonW = 40;
  61427. int i;
  61428. for (i = 0; i < buttons.size(); ++i)
  61429. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61430. w = jmax (buttonW, w);
  61431. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61432. if (buttons.size() > 0)
  61433. h += 20 + buttons.getUnchecked(0)->getHeight();
  61434. for (i = customComps.size(); --i >= 0;)
  61435. {
  61436. Component* c = customComps.getUnchecked(i);
  61437. w = jmax (w, (c->getWidth() * 100) / 80);
  61438. h += 10 + c->getHeight();
  61439. if (c->getName().isNotEmpty())
  61440. h += labelHeight;
  61441. }
  61442. for (i = textBlocks.size(); --i >= 0;)
  61443. {
  61444. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61445. w = jmax (w, ac->getPreferredWidth());
  61446. }
  61447. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61448. for (i = textBlocks.size(); --i >= 0;)
  61449. {
  61450. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61451. ac->updateLayout ((int) (w * 0.8f));
  61452. h += ac->getHeight() + 10;
  61453. }
  61454. h = jmin (getParentHeight() - 50, h);
  61455. if (onlyIncreaseSize)
  61456. {
  61457. w = jmax (w, getWidth());
  61458. h = jmax (h, getHeight());
  61459. }
  61460. if (! isVisible())
  61461. {
  61462. centreAroundComponent (associatedComponent, w, h);
  61463. }
  61464. else
  61465. {
  61466. const int cx = getX() + getWidth() / 2;
  61467. const int cy = getY() + getHeight() / 2;
  61468. setBounds (cx - w / 2,
  61469. cy - h / 2,
  61470. w, h);
  61471. }
  61472. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61473. const int spacer = 16;
  61474. int totalWidth = -spacer;
  61475. for (i = buttons.size(); --i >= 0;)
  61476. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61477. int x = (w - totalWidth) / 2;
  61478. int y = (int) (getHeight() * 0.95f);
  61479. for (i = 0; i < buttons.size(); ++i)
  61480. {
  61481. TextButton* const c = buttons.getUnchecked(i);
  61482. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61483. c->setTopLeftPosition (x, ny);
  61484. if (ny < y)
  61485. y = ny;
  61486. x += c->getWidth() + spacer;
  61487. c->toFront (false);
  61488. }
  61489. y = textBottom;
  61490. for (i = 0; i < allComps.size(); ++i)
  61491. {
  61492. Component* const c = allComps.getUnchecked(i);
  61493. h = 22;
  61494. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61495. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61496. y += labelHeight;
  61497. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61498. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61499. y += labelHeight;
  61500. if (customComps.contains (c))
  61501. {
  61502. if (c->getName().isNotEmpty())
  61503. y += labelHeight;
  61504. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61505. h = c->getHeight();
  61506. }
  61507. else if (textBlocks.contains (c))
  61508. {
  61509. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61510. h = c->getHeight();
  61511. }
  61512. else
  61513. {
  61514. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61515. }
  61516. y += h + 10;
  61517. }
  61518. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61519. }
  61520. bool AlertWindow::containsAnyExtraComponents() const
  61521. {
  61522. return allComps.size() > 0;
  61523. }
  61524. void AlertWindow::mouseDown (const MouseEvent& e)
  61525. {
  61526. dragger.startDraggingComponent (this, e);
  61527. }
  61528. void AlertWindow::mouseDrag (const MouseEvent& e)
  61529. {
  61530. dragger.dragComponent (this, e, &constrainer);
  61531. }
  61532. bool AlertWindow::keyPressed (const KeyPress& key)
  61533. {
  61534. for (int i = buttons.size(); --i >= 0;)
  61535. {
  61536. TextButton* const b = buttons.getUnchecked(i);
  61537. if (b->isRegisteredForShortcut (key))
  61538. {
  61539. b->triggerClick();
  61540. return true;
  61541. }
  61542. }
  61543. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61544. {
  61545. exitModalState (0);
  61546. return true;
  61547. }
  61548. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61549. {
  61550. buttons.getUnchecked(0)->triggerClick();
  61551. return true;
  61552. }
  61553. return false;
  61554. }
  61555. void AlertWindow::lookAndFeelChanged()
  61556. {
  61557. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61558. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61559. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61560. }
  61561. int AlertWindow::getDesktopWindowStyleFlags() const
  61562. {
  61563. return getLookAndFeel().getAlertBoxWindowFlags();
  61564. }
  61565. class AlertWindowInfo
  61566. {
  61567. public:
  61568. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61569. AlertWindow::AlertIconType iconType_, int numButtons_)
  61570. : title (title_), message (message_), iconType (iconType_),
  61571. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61572. {
  61573. }
  61574. String title, message, button1, button2, button3;
  61575. AlertWindow::AlertIconType iconType;
  61576. int numButtons, returnValue;
  61577. WeakReference<Component> associatedComponent;
  61578. int showModal() const
  61579. {
  61580. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61581. return returnValue;
  61582. }
  61583. private:
  61584. void show()
  61585. {
  61586. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61587. : LookAndFeel::getDefaultLookAndFeel();
  61588. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61589. iconType, numButtons, associatedComponent));
  61590. jassert (alertBox != 0); // you have to return one of these!
  61591. returnValue = alertBox->runModalLoop();
  61592. }
  61593. static void* showCallback (void* userData)
  61594. {
  61595. static_cast <AlertWindowInfo*> (userData)->show();
  61596. return 0;
  61597. }
  61598. };
  61599. void AlertWindow::showMessageBox (AlertIconType iconType,
  61600. const String& title,
  61601. const String& message,
  61602. const String& buttonText,
  61603. Component* associatedComponent)
  61604. {
  61605. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  61606. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61607. info.showModal();
  61608. }
  61609. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61610. const String& title,
  61611. const String& message,
  61612. const String& button1Text,
  61613. const String& button2Text,
  61614. Component* associatedComponent)
  61615. {
  61616. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  61617. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61618. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61619. return info.showModal() != 0;
  61620. }
  61621. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61622. const String& title,
  61623. const String& message,
  61624. const String& button1Text,
  61625. const String& button2Text,
  61626. const String& button3Text,
  61627. Component* associatedComponent)
  61628. {
  61629. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  61630. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61631. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61632. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61633. return info.showModal();
  61634. }
  61635. END_JUCE_NAMESPACE
  61636. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61637. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61638. BEGIN_JUCE_NAMESPACE
  61639. CallOutBox::CallOutBox (Component& contentComponent,
  61640. Component& componentToPointTo,
  61641. Component* const parentComponent)
  61642. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61643. {
  61644. addAndMakeVisible (&content);
  61645. if (parentComponent != 0)
  61646. {
  61647. parentComponent->addChildComponent (this);
  61648. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  61649. parentComponent->getLocalBounds());
  61650. setVisible (true);
  61651. }
  61652. else
  61653. {
  61654. if (! JUCEApplication::isStandaloneApp())
  61655. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61656. updatePosition (componentToPointTo.getScreenBounds(),
  61657. componentToPointTo.getParentMonitorArea());
  61658. addToDesktop (ComponentPeer::windowIsTemporary);
  61659. }
  61660. }
  61661. CallOutBox::~CallOutBox()
  61662. {
  61663. }
  61664. void CallOutBox::setArrowSize (const float newSize)
  61665. {
  61666. arrowSize = newSize;
  61667. borderSpace = jmax (20, (int) arrowSize);
  61668. refreshPath();
  61669. }
  61670. void CallOutBox::paint (Graphics& g)
  61671. {
  61672. if (background.isNull())
  61673. {
  61674. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61675. Graphics g2 (background);
  61676. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  61677. }
  61678. g.setColour (Colours::black);
  61679. g.drawImageAt (background, 0, 0);
  61680. }
  61681. void CallOutBox::resized()
  61682. {
  61683. content.setTopLeftPosition (borderSpace, borderSpace);
  61684. refreshPath();
  61685. }
  61686. void CallOutBox::moved()
  61687. {
  61688. refreshPath();
  61689. }
  61690. void CallOutBox::childBoundsChanged (Component*)
  61691. {
  61692. updatePosition (targetArea, availableArea);
  61693. }
  61694. bool CallOutBox::hitTest (int x, int y)
  61695. {
  61696. return outline.contains ((float) x, (float) y);
  61697. }
  61698. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61699. void CallOutBox::inputAttemptWhenModal()
  61700. {
  61701. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61702. if (targetArea.contains (mousePos))
  61703. {
  61704. // if you click on the area that originally popped-up the callout, you expect it
  61705. // to get rid of the box, but deleting the box here allows the click to pass through and
  61706. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61707. postCommandMessage (callOutBoxDismissCommandId);
  61708. }
  61709. else
  61710. {
  61711. exitModalState (0);
  61712. setVisible (false);
  61713. }
  61714. }
  61715. void CallOutBox::handleCommandMessage (int commandId)
  61716. {
  61717. Component::handleCommandMessage (commandId);
  61718. if (commandId == callOutBoxDismissCommandId)
  61719. {
  61720. exitModalState (0);
  61721. setVisible (false);
  61722. }
  61723. }
  61724. bool CallOutBox::keyPressed (const KeyPress& key)
  61725. {
  61726. if (key.isKeyCode (KeyPress::escapeKey))
  61727. {
  61728. inputAttemptWhenModal();
  61729. return true;
  61730. }
  61731. return false;
  61732. }
  61733. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61734. {
  61735. targetArea = newAreaToPointTo;
  61736. availableArea = newAreaToFitIn;
  61737. Rectangle<int> bounds (0, 0,
  61738. content.getWidth() + borderSpace * 2,
  61739. content.getHeight() + borderSpace * 2);
  61740. const int hw = bounds.getWidth() / 2;
  61741. const int hh = bounds.getHeight() / 2;
  61742. const float hwReduced = (float) (hw - borderSpace * 3);
  61743. const float hhReduced = (float) (hh - borderSpace * 3);
  61744. const float arrowIndent = borderSpace - arrowSize;
  61745. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61746. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61747. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61748. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61749. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61750. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61751. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61752. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61753. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61754. float nearest = 1.0e9f;
  61755. for (int i = 0; i < 4; ++i)
  61756. {
  61757. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61758. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61759. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61760. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61761. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61762. distanceFromCentre *= 2.0f;
  61763. if (distanceFromCentre < nearest)
  61764. {
  61765. nearest = distanceFromCentre;
  61766. targetPoint = targets[i];
  61767. bounds.setPosition ((int) (centre.getX() - hw),
  61768. (int) (centre.getY() - hh));
  61769. }
  61770. }
  61771. setBounds (bounds);
  61772. }
  61773. void CallOutBox::refreshPath()
  61774. {
  61775. repaint();
  61776. background = Image::null;
  61777. outline.clear();
  61778. const float gap = 4.5f;
  61779. const float cornerSize = 9.0f;
  61780. const float cornerSize2 = 2.0f * cornerSize;
  61781. const float arrowBaseWidth = arrowSize * 0.7f;
  61782. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61783. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61784. outline.startNewSubPath (left + cornerSize, top);
  61785. if (targetY <= top)
  61786. {
  61787. outline.lineTo (targetX - arrowBaseWidth, top);
  61788. outline.lineTo (targetX, targetY);
  61789. outline.lineTo (targetX + arrowBaseWidth, top);
  61790. }
  61791. outline.lineTo (right - cornerSize, top);
  61792. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61793. if (targetX >= right)
  61794. {
  61795. outline.lineTo (right, targetY - arrowBaseWidth);
  61796. outline.lineTo (targetX, targetY);
  61797. outline.lineTo (right, targetY + arrowBaseWidth);
  61798. }
  61799. outline.lineTo (right, bottom - cornerSize);
  61800. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61801. if (targetY >= bottom)
  61802. {
  61803. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61804. outline.lineTo (targetX, targetY);
  61805. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61806. }
  61807. outline.lineTo (left + cornerSize, bottom);
  61808. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61809. if (targetX <= left)
  61810. {
  61811. outline.lineTo (left, targetY + arrowBaseWidth);
  61812. outline.lineTo (targetX, targetY);
  61813. outline.lineTo (left, targetY - arrowBaseWidth);
  61814. }
  61815. outline.lineTo (left, top + cornerSize);
  61816. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61817. outline.closeSubPath();
  61818. }
  61819. END_JUCE_NAMESPACE
  61820. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61821. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61822. BEGIN_JUCE_NAMESPACE
  61823. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61824. static Array <ComponentPeer*> heavyweightPeers;
  61825. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61826. : component (component_),
  61827. styleFlags (styleFlags_),
  61828. lastPaintTime (0),
  61829. constrainer (0),
  61830. lastDragAndDropCompUnderMouse (0),
  61831. fakeMouseMessageSent (false),
  61832. isWindowMinimised (false)
  61833. {
  61834. heavyweightPeers.add (this);
  61835. }
  61836. ComponentPeer::~ComponentPeer()
  61837. {
  61838. heavyweightPeers.removeValue (this);
  61839. Desktop::getInstance().triggerFocusCallback();
  61840. }
  61841. int ComponentPeer::getNumPeers() throw()
  61842. {
  61843. return heavyweightPeers.size();
  61844. }
  61845. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61846. {
  61847. return heavyweightPeers [index];
  61848. }
  61849. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61850. {
  61851. for (int i = heavyweightPeers.size(); --i >= 0;)
  61852. {
  61853. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61854. if (peer->getComponent() == component)
  61855. return peer;
  61856. }
  61857. return 0;
  61858. }
  61859. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61860. {
  61861. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61862. }
  61863. void ComponentPeer::updateCurrentModifiers() throw()
  61864. {
  61865. ModifierKeys::updateCurrentModifiers();
  61866. }
  61867. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61868. {
  61869. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61870. jassert (mouse != 0); // not enough sources!
  61871. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61872. }
  61873. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61874. {
  61875. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61876. jassert (mouse != 0); // not enough sources!
  61877. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61878. }
  61879. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61880. {
  61881. Graphics g (&contextToPaintTo);
  61882. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61883. g.saveState();
  61884. #endif
  61885. JUCE_TRY
  61886. {
  61887. component->paintEntireComponent (g, true);
  61888. }
  61889. JUCE_CATCH_EXCEPTION
  61890. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61891. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61892. // clearly when things are being repainted.
  61893. g.restoreState();
  61894. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61895. (uint8) Random::getSystemRandom().nextInt (255),
  61896. (uint8) Random::getSystemRandom().nextInt (255),
  61897. (uint8) 0x50));
  61898. #endif
  61899. /** If this fails, it's probably be because your CPU floating-point precision mode has
  61900. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  61901. mess up a lot of the calculations that the library needs to do.
  61902. */
  61903. jassert (roundToInt (10.1f) == 10);
  61904. }
  61905. bool ComponentPeer::handleKeyPress (const int keyCode,
  61906. const juce_wchar textCharacter)
  61907. {
  61908. updateCurrentModifiers();
  61909. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61910. ? Component::getCurrentlyFocusedComponent()
  61911. : component;
  61912. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61913. {
  61914. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61915. if (currentModalComp != 0)
  61916. target = currentModalComp;
  61917. }
  61918. const KeyPress keyInfo (keyCode,
  61919. ModifierKeys::getCurrentModifiers().getRawFlags()
  61920. & ModifierKeys::allKeyboardModifiers,
  61921. textCharacter);
  61922. bool keyWasUsed = false;
  61923. while (target != 0)
  61924. {
  61925. const WeakReference<Component> deletionChecker (target);
  61926. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61927. if (keyListeners != 0)
  61928. {
  61929. for (int i = keyListeners->size(); --i >= 0;)
  61930. {
  61931. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  61932. if (keyWasUsed || deletionChecker == 0)
  61933. return keyWasUsed;
  61934. i = jmin (i, keyListeners->size());
  61935. }
  61936. }
  61937. keyWasUsed = target->keyPressed (keyInfo);
  61938. if (keyWasUsed || deletionChecker == 0)
  61939. break;
  61940. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61941. {
  61942. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61943. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61944. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61945. break;
  61946. }
  61947. target = target->getParentComponent();
  61948. }
  61949. return keyWasUsed;
  61950. }
  61951. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61952. {
  61953. updateCurrentModifiers();
  61954. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61955. ? Component::getCurrentlyFocusedComponent()
  61956. : component;
  61957. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61958. {
  61959. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61960. if (currentModalComp != 0)
  61961. target = currentModalComp;
  61962. }
  61963. bool keyWasUsed = false;
  61964. while (target != 0)
  61965. {
  61966. const WeakReference<Component> deletionChecker (target);
  61967. keyWasUsed = target->keyStateChanged (isKeyDown);
  61968. if (keyWasUsed || deletionChecker == 0)
  61969. break;
  61970. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61971. if (keyListeners != 0)
  61972. {
  61973. for (int i = keyListeners->size(); --i >= 0;)
  61974. {
  61975. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  61976. if (keyWasUsed || deletionChecker == 0)
  61977. return keyWasUsed;
  61978. i = jmin (i, keyListeners->size());
  61979. }
  61980. }
  61981. target = target->getParentComponent();
  61982. }
  61983. return keyWasUsed;
  61984. }
  61985. void ComponentPeer::handleModifierKeysChange()
  61986. {
  61987. updateCurrentModifiers();
  61988. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61989. if (target == 0)
  61990. target = Component::getCurrentlyFocusedComponent();
  61991. if (target == 0)
  61992. target = component;
  61993. if (target != 0)
  61994. target->internalModifierKeysChanged();
  61995. }
  61996. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61997. {
  61998. Component* const c = Component::getCurrentlyFocusedComponent();
  61999. if (component->isParentOf (c))
  62000. {
  62001. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62002. if (ti != 0 && ti->isTextInputActive())
  62003. return ti;
  62004. }
  62005. return 0;
  62006. }
  62007. void ComponentPeer::handleBroughtToFront()
  62008. {
  62009. updateCurrentModifiers();
  62010. if (component != 0)
  62011. component->internalBroughtToFront();
  62012. }
  62013. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62014. {
  62015. constrainer = newConstrainer;
  62016. }
  62017. void ComponentPeer::handleMovedOrResized()
  62018. {
  62019. updateCurrentModifiers();
  62020. const bool nowMinimised = isMinimised();
  62021. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62022. {
  62023. const WeakReference<Component> deletionChecker (component);
  62024. const Rectangle<int> newBounds (getBounds());
  62025. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62026. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62027. if (wasMoved || wasResized)
  62028. {
  62029. component->bounds = newBounds;
  62030. if (wasResized)
  62031. component->repaint();
  62032. component->sendMovedResizedMessages (wasMoved, wasResized);
  62033. if (deletionChecker == 0)
  62034. return;
  62035. }
  62036. }
  62037. if (isWindowMinimised != nowMinimised)
  62038. {
  62039. isWindowMinimised = nowMinimised;
  62040. component->minimisationStateChanged (nowMinimised);
  62041. component->sendVisibilityChangeMessage();
  62042. }
  62043. if (! isFullScreen())
  62044. lastNonFullscreenBounds = component->getBounds();
  62045. }
  62046. void ComponentPeer::handleFocusGain()
  62047. {
  62048. updateCurrentModifiers();
  62049. if (component->isParentOf (lastFocusedComponent))
  62050. {
  62051. Component::currentlyFocusedComponent = lastFocusedComponent;
  62052. Desktop::getInstance().triggerFocusCallback();
  62053. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62054. }
  62055. else
  62056. {
  62057. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62058. component->grabKeyboardFocus();
  62059. else
  62060. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62061. }
  62062. }
  62063. void ComponentPeer::handleFocusLoss()
  62064. {
  62065. updateCurrentModifiers();
  62066. if (component->hasKeyboardFocus (true))
  62067. {
  62068. lastFocusedComponent = Component::currentlyFocusedComponent;
  62069. if (lastFocusedComponent != 0)
  62070. {
  62071. Component::currentlyFocusedComponent = 0;
  62072. Desktop::getInstance().triggerFocusCallback();
  62073. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62074. }
  62075. }
  62076. }
  62077. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62078. {
  62079. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62080. ? static_cast <Component*> (lastFocusedComponent)
  62081. : component;
  62082. }
  62083. void ComponentPeer::handleScreenSizeChange()
  62084. {
  62085. updateCurrentModifiers();
  62086. component->parentSizeChanged();
  62087. handleMovedOrResized();
  62088. }
  62089. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62090. {
  62091. lastNonFullscreenBounds = newBounds;
  62092. }
  62093. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62094. {
  62095. return lastNonFullscreenBounds;
  62096. }
  62097. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62098. {
  62099. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62100. }
  62101. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62102. {
  62103. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62104. }
  62105. namespace ComponentPeerHelpers
  62106. {
  62107. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62108. const StringArray& files,
  62109. FileDragAndDropTarget* const lastOne)
  62110. {
  62111. while (c != 0)
  62112. {
  62113. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62114. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62115. return t;
  62116. c = c->getParentComponent();
  62117. }
  62118. return 0;
  62119. }
  62120. }
  62121. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62122. {
  62123. updateCurrentModifiers();
  62124. FileDragAndDropTarget* lastTarget
  62125. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62126. FileDragAndDropTarget* newTarget = 0;
  62127. Component* const compUnderMouse = component->getComponentAt (position);
  62128. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62129. {
  62130. lastDragAndDropCompUnderMouse = compUnderMouse;
  62131. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62132. if (newTarget != lastTarget)
  62133. {
  62134. if (lastTarget != 0)
  62135. lastTarget->fileDragExit (files);
  62136. dragAndDropTargetComponent = 0;
  62137. if (newTarget != 0)
  62138. {
  62139. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62140. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62141. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62142. }
  62143. }
  62144. }
  62145. else
  62146. {
  62147. newTarget = lastTarget;
  62148. }
  62149. if (newTarget != 0)
  62150. {
  62151. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62152. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62153. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62154. }
  62155. }
  62156. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62157. {
  62158. handleFileDragMove (files, Point<int> (-1, -1));
  62159. jassert (dragAndDropTargetComponent == 0);
  62160. lastDragAndDropCompUnderMouse = 0;
  62161. }
  62162. // We'll use an async message to deliver the drop, because if the target decides
  62163. // to run a modal loop, it can gum-up the operating system..
  62164. class AsyncFileDropMessage : public CallbackMessage
  62165. {
  62166. public:
  62167. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62168. const Point<int>& position_, const StringArray& files_)
  62169. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62170. {
  62171. }
  62172. void messageCallback()
  62173. {
  62174. if (target != 0)
  62175. dropTarget->filesDropped (files, position.getX(), position.getY());
  62176. }
  62177. private:
  62178. WeakReference<Component> target;
  62179. FileDragAndDropTarget* const dropTarget;
  62180. const Point<int> position;
  62181. const StringArray files;
  62182. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62183. };
  62184. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62185. {
  62186. handleFileDragMove (files, position);
  62187. if (dragAndDropTargetComponent != 0)
  62188. {
  62189. FileDragAndDropTarget* const target
  62190. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62191. dragAndDropTargetComponent = 0;
  62192. lastDragAndDropCompUnderMouse = 0;
  62193. if (target != 0)
  62194. {
  62195. Component* const targetComp = dynamic_cast <Component*> (target);
  62196. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62197. {
  62198. targetComp->internalModalInputAttempt();
  62199. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62200. return;
  62201. }
  62202. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62203. }
  62204. }
  62205. }
  62206. void ComponentPeer::handleUserClosingWindow()
  62207. {
  62208. updateCurrentModifiers();
  62209. component->userTriedToCloseWindow();
  62210. }
  62211. void ComponentPeer::clearMaskedRegion()
  62212. {
  62213. maskedRegion.clear();
  62214. }
  62215. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62216. {
  62217. maskedRegion.add (x, y, w, h);
  62218. }
  62219. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62220. {
  62221. StringArray s;
  62222. s.add ("Software Renderer");
  62223. return s;
  62224. }
  62225. int ComponentPeer::getCurrentRenderingEngine() throw()
  62226. {
  62227. return 0;
  62228. }
  62229. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62230. {
  62231. }
  62232. END_JUCE_NAMESPACE
  62233. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62234. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62235. BEGIN_JUCE_NAMESPACE
  62236. DialogWindow::DialogWindow (const String& name,
  62237. const Colour& backgroundColour_,
  62238. const bool escapeKeyTriggersCloseButton_,
  62239. const bool addToDesktop_)
  62240. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62241. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62242. {
  62243. }
  62244. DialogWindow::~DialogWindow()
  62245. {
  62246. }
  62247. void DialogWindow::resized()
  62248. {
  62249. DocumentWindow::resized();
  62250. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62251. if (escapeKeyTriggersCloseButton
  62252. && getCloseButton() != 0
  62253. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62254. {
  62255. getCloseButton()->addShortcut (esc);
  62256. }
  62257. }
  62258. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62259. // VC compiler complains about the undefined copy constructor)
  62260. class TempDialogWindow : public DialogWindow
  62261. {
  62262. public:
  62263. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62264. : DialogWindow (title, colour, escapeCloses, true)
  62265. {
  62266. if (! JUCEApplication::isStandaloneApp())
  62267. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62268. }
  62269. void closeButtonPressed()
  62270. {
  62271. setVisible (false);
  62272. }
  62273. private:
  62274. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62275. };
  62276. int DialogWindow::showModalDialog (const String& dialogTitle,
  62277. Component* contentComponent,
  62278. Component* componentToCentreAround,
  62279. const Colour& colour,
  62280. const bool escapeKeyTriggersCloseButton,
  62281. const bool shouldBeResizable,
  62282. const bool useBottomRightCornerResizer)
  62283. {
  62284. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62285. dw.setContentComponent (contentComponent, true, true);
  62286. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62287. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62288. const int result = dw.runModalLoop();
  62289. dw.setContentComponent (0, false);
  62290. return result;
  62291. }
  62292. END_JUCE_NAMESPACE
  62293. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62294. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62295. BEGIN_JUCE_NAMESPACE
  62296. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62297. {
  62298. public:
  62299. ButtonListenerProxy (DocumentWindow& owner_)
  62300. : owner (owner_)
  62301. {
  62302. }
  62303. void buttonClicked (Button* button)
  62304. {
  62305. if (button == owner.getMinimiseButton())
  62306. owner.minimiseButtonPressed();
  62307. else if (button == owner.getMaximiseButton())
  62308. owner.maximiseButtonPressed();
  62309. else if (button == owner.getCloseButton())
  62310. owner.closeButtonPressed();
  62311. }
  62312. private:
  62313. DocumentWindow& owner;
  62314. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62315. };
  62316. DocumentWindow::DocumentWindow (const String& title,
  62317. const Colour& backgroundColour,
  62318. const int requiredButtons_,
  62319. const bool addToDesktop_)
  62320. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62321. titleBarHeight (26),
  62322. menuBarHeight (24),
  62323. requiredButtons (requiredButtons_),
  62324. #if JUCE_MAC
  62325. positionTitleBarButtonsOnLeft (true),
  62326. #else
  62327. positionTitleBarButtonsOnLeft (false),
  62328. #endif
  62329. drawTitleTextCentred (true),
  62330. menuBarModel (0)
  62331. {
  62332. setResizeLimits (128, 128, 32768, 32768);
  62333. lookAndFeelChanged();
  62334. }
  62335. DocumentWindow::~DocumentWindow()
  62336. {
  62337. // Don't delete or remove the resizer components yourself! They're managed by the
  62338. // DocumentWindow, and you should leave them alone! You may have deleted them
  62339. // accidentally by careless use of deleteAllChildren()..?
  62340. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62341. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62342. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62343. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62344. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62345. titleBarButtons[i] = 0;
  62346. menuBar = 0;
  62347. }
  62348. void DocumentWindow::repaintTitleBar()
  62349. {
  62350. repaint (getTitleBarArea());
  62351. }
  62352. void DocumentWindow::setName (const String& newName)
  62353. {
  62354. if (newName != getName())
  62355. {
  62356. Component::setName (newName);
  62357. repaintTitleBar();
  62358. }
  62359. }
  62360. void DocumentWindow::setIcon (const Image& imageToUse)
  62361. {
  62362. titleBarIcon = imageToUse;
  62363. repaintTitleBar();
  62364. }
  62365. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62366. {
  62367. titleBarHeight = newHeight;
  62368. resized();
  62369. repaintTitleBar();
  62370. }
  62371. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62372. const bool positionTitleBarButtonsOnLeft_)
  62373. {
  62374. requiredButtons = requiredButtons_;
  62375. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62376. lookAndFeelChanged();
  62377. }
  62378. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62379. {
  62380. drawTitleTextCentred = textShouldBeCentred;
  62381. repaintTitleBar();
  62382. }
  62383. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62384. {
  62385. if (menuBarModel != newMenuBarModel)
  62386. {
  62387. menuBar = 0;
  62388. menuBarModel = newMenuBarModel;
  62389. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62390. : getLookAndFeel().getDefaultMenuBarHeight();
  62391. if (menuBarModel != 0)
  62392. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62393. resized();
  62394. }
  62395. }
  62396. Component* DocumentWindow::getMenuBarComponent() const throw()
  62397. {
  62398. return menuBar;
  62399. }
  62400. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62401. {
  62402. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62403. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62404. if (menuBar != 0)
  62405. menuBar->setEnabled (isActiveWindow());
  62406. resized();
  62407. }
  62408. void DocumentWindow::closeButtonPressed()
  62409. {
  62410. /* If you've got a close button, you have to override this method to get
  62411. rid of your window!
  62412. If the window is just a pop-up, you should override this method and make
  62413. it delete the window in whatever way is appropriate for your app. E.g. you
  62414. might just want to call "delete this".
  62415. If your app is centred around this window such that the whole app should quit when
  62416. the window is closed, then you will probably want to use this method as an opportunity
  62417. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62418. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62419. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62420. or closing it via the taskbar icon on Windows).
  62421. */
  62422. jassertfalse;
  62423. }
  62424. void DocumentWindow::minimiseButtonPressed()
  62425. {
  62426. setMinimised (true);
  62427. }
  62428. void DocumentWindow::maximiseButtonPressed()
  62429. {
  62430. setFullScreen (! isFullScreen());
  62431. }
  62432. void DocumentWindow::paint (Graphics& g)
  62433. {
  62434. ResizableWindow::paint (g);
  62435. if (resizableBorder == 0)
  62436. {
  62437. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62438. const BorderSize<int> border (getBorderThickness());
  62439. g.fillRect (0, 0, getWidth(), border.getTop());
  62440. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62441. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62442. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62443. }
  62444. const Rectangle<int> titleBarArea (getTitleBarArea());
  62445. g.reduceClipRegion (titleBarArea);
  62446. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62447. int titleSpaceX1 = 6;
  62448. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62449. for (int i = 0; i < 3; ++i)
  62450. {
  62451. if (titleBarButtons[i] != 0)
  62452. {
  62453. if (positionTitleBarButtonsOnLeft)
  62454. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62455. else
  62456. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62457. }
  62458. }
  62459. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62460. titleBarArea.getWidth(),
  62461. titleBarArea.getHeight(),
  62462. titleSpaceX1,
  62463. jmax (1, titleSpaceX2 - titleSpaceX1),
  62464. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62465. ! drawTitleTextCentred);
  62466. }
  62467. void DocumentWindow::resized()
  62468. {
  62469. ResizableWindow::resized();
  62470. if (titleBarButtons[1] != 0)
  62471. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62472. const Rectangle<int> titleBarArea (getTitleBarArea());
  62473. getLookAndFeel()
  62474. .positionDocumentWindowButtons (*this,
  62475. titleBarArea.getX(), titleBarArea.getY(),
  62476. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62477. titleBarButtons[0],
  62478. titleBarButtons[1],
  62479. titleBarButtons[2],
  62480. positionTitleBarButtonsOnLeft);
  62481. if (menuBar != 0)
  62482. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62483. titleBarArea.getWidth(), menuBarHeight);
  62484. }
  62485. const BorderSize<int> DocumentWindow::getBorderThickness()
  62486. {
  62487. return BorderSize<int> ((isFullScreen() || isUsingNativeTitleBar())
  62488. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62489. }
  62490. const BorderSize<int> DocumentWindow::getContentComponentBorder()
  62491. {
  62492. BorderSize<int> border (getBorderThickness());
  62493. border.setTop (border.getTop()
  62494. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62495. + (menuBar != 0 ? menuBarHeight : 0));
  62496. return border;
  62497. }
  62498. int DocumentWindow::getTitleBarHeight() const
  62499. {
  62500. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62501. }
  62502. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62503. {
  62504. const BorderSize<int> border (getBorderThickness());
  62505. return Rectangle<int> (border.getLeft(), border.getTop(),
  62506. getWidth() - border.getLeftAndRight(),
  62507. getTitleBarHeight());
  62508. }
  62509. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62510. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62511. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62512. int DocumentWindow::getDesktopWindowStyleFlags() const
  62513. {
  62514. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62515. if ((requiredButtons & minimiseButton) != 0)
  62516. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62517. if ((requiredButtons & maximiseButton) != 0)
  62518. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62519. if ((requiredButtons & closeButton) != 0)
  62520. styleFlags |= ComponentPeer::windowHasCloseButton;
  62521. return styleFlags;
  62522. }
  62523. void DocumentWindow::lookAndFeelChanged()
  62524. {
  62525. int i;
  62526. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62527. titleBarButtons[i] = 0;
  62528. if (! isUsingNativeTitleBar())
  62529. {
  62530. LookAndFeel& lf = getLookAndFeel();
  62531. if ((requiredButtons & minimiseButton) != 0)
  62532. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62533. if ((requiredButtons & maximiseButton) != 0)
  62534. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62535. if ((requiredButtons & closeButton) != 0)
  62536. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62537. for (i = 0; i < 3; ++i)
  62538. {
  62539. if (titleBarButtons[i] != 0)
  62540. {
  62541. if (buttonListener == 0)
  62542. buttonListener = new ButtonListenerProxy (*this);
  62543. titleBarButtons[i]->addListener (buttonListener);
  62544. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62545. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62546. Component::addAndMakeVisible (titleBarButtons[i]);
  62547. }
  62548. }
  62549. if (getCloseButton() != 0)
  62550. {
  62551. #if JUCE_MAC
  62552. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62553. #else
  62554. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62555. #endif
  62556. }
  62557. }
  62558. activeWindowStatusChanged();
  62559. ResizableWindow::lookAndFeelChanged();
  62560. }
  62561. void DocumentWindow::parentHierarchyChanged()
  62562. {
  62563. lookAndFeelChanged();
  62564. }
  62565. void DocumentWindow::activeWindowStatusChanged()
  62566. {
  62567. ResizableWindow::activeWindowStatusChanged();
  62568. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62569. if (titleBarButtons[i] != 0)
  62570. titleBarButtons[i]->setEnabled (isActiveWindow());
  62571. if (menuBar != 0)
  62572. menuBar->setEnabled (isActiveWindow());
  62573. }
  62574. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62575. {
  62576. if (getTitleBarArea().contains (e.x, e.y)
  62577. && getMaximiseButton() != 0)
  62578. {
  62579. getMaximiseButton()->triggerClick();
  62580. }
  62581. }
  62582. void DocumentWindow::userTriedToCloseWindow()
  62583. {
  62584. closeButtonPressed();
  62585. }
  62586. END_JUCE_NAMESPACE
  62587. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62588. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62589. BEGIN_JUCE_NAMESPACE
  62590. ResizableWindow::ResizableWindow (const String& name,
  62591. const bool addToDesktop_)
  62592. : TopLevelWindow (name, addToDesktop_),
  62593. resizeToFitContent (false),
  62594. fullscreen (false),
  62595. lastNonFullScreenPos (50, 50, 256, 256),
  62596. constrainer (0)
  62597. #if JUCE_DEBUG
  62598. , hasBeenResized (false)
  62599. #endif
  62600. {
  62601. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62602. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62603. if (addToDesktop_)
  62604. Component::addToDesktop (getDesktopWindowStyleFlags());
  62605. }
  62606. ResizableWindow::ResizableWindow (const String& name,
  62607. const Colour& backgroundColour_,
  62608. const bool addToDesktop_)
  62609. : TopLevelWindow (name, addToDesktop_),
  62610. resizeToFitContent (false),
  62611. fullscreen (false),
  62612. lastNonFullScreenPos (50, 50, 256, 256),
  62613. constrainer (0)
  62614. #if JUCE_DEBUG
  62615. , hasBeenResized (false)
  62616. #endif
  62617. {
  62618. setBackgroundColour (backgroundColour_);
  62619. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62620. if (addToDesktop_)
  62621. Component::addToDesktop (getDesktopWindowStyleFlags());
  62622. }
  62623. ResizableWindow::~ResizableWindow()
  62624. {
  62625. // Don't delete or remove the resizer components yourself! They're managed by the
  62626. // ResizableWindow, and you should leave them alone! You may have deleted them
  62627. // accidentally by careless use of deleteAllChildren()..?
  62628. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  62629. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  62630. resizableCorner = 0;
  62631. resizableBorder = 0;
  62632. contentComponent.deleteAndZero();
  62633. // have you been adding your own components directly to this window..? tut tut tut.
  62634. // Read the instructions for using a ResizableWindow!
  62635. jassert (getNumChildComponents() == 0);
  62636. }
  62637. int ResizableWindow::getDesktopWindowStyleFlags() const
  62638. {
  62639. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62640. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62641. styleFlags |= ComponentPeer::windowIsResizable;
  62642. return styleFlags;
  62643. }
  62644. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62645. const bool deleteOldOne,
  62646. const bool resizeToFit)
  62647. {
  62648. resizeToFitContent = resizeToFit;
  62649. if (newContentComponent != static_cast <Component*> (contentComponent))
  62650. {
  62651. if (deleteOldOne)
  62652. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  62653. // external deletion of the content comp)
  62654. else
  62655. removeChildComponent (contentComponent);
  62656. contentComponent = newContentComponent;
  62657. Component::addAndMakeVisible (contentComponent);
  62658. }
  62659. if (resizeToFit)
  62660. childBoundsChanged (contentComponent);
  62661. resized(); // must always be called to position the new content comp
  62662. }
  62663. void ResizableWindow::setContentComponentSize (int width, int height)
  62664. {
  62665. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62666. const BorderSize<int> border (getContentComponentBorder());
  62667. setSize (width + border.getLeftAndRight(),
  62668. height + border.getTopAndBottom());
  62669. }
  62670. const BorderSize<int> ResizableWindow::getBorderThickness()
  62671. {
  62672. return BorderSize<int> (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62673. }
  62674. const BorderSize<int> ResizableWindow::getContentComponentBorder()
  62675. {
  62676. return getBorderThickness();
  62677. }
  62678. void ResizableWindow::moved()
  62679. {
  62680. updateLastPos();
  62681. }
  62682. void ResizableWindow::visibilityChanged()
  62683. {
  62684. TopLevelWindow::visibilityChanged();
  62685. updateLastPos();
  62686. }
  62687. void ResizableWindow::resized()
  62688. {
  62689. if (resizableBorder != 0)
  62690. {
  62691. #if JUCE_WINDOWS || JUCE_LINUX
  62692. // hide the resizable border if the OS already provides one..
  62693. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62694. #else
  62695. resizableBorder->setVisible (! isFullScreen());
  62696. #endif
  62697. resizableBorder->setBorderThickness (getBorderThickness());
  62698. resizableBorder->setSize (getWidth(), getHeight());
  62699. resizableBorder->toBack();
  62700. }
  62701. if (resizableCorner != 0)
  62702. {
  62703. #if JUCE_MAC
  62704. // hide the resizable border if the OS already provides one..
  62705. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62706. #else
  62707. resizableCorner->setVisible (! isFullScreen());
  62708. #endif
  62709. const int resizerSize = 18;
  62710. resizableCorner->setBounds (getWidth() - resizerSize,
  62711. getHeight() - resizerSize,
  62712. resizerSize, resizerSize);
  62713. }
  62714. if (contentComponent != 0)
  62715. contentComponent->setBoundsInset (getContentComponentBorder());
  62716. updateLastPos();
  62717. #if JUCE_DEBUG
  62718. hasBeenResized = true;
  62719. #endif
  62720. }
  62721. void ResizableWindow::childBoundsChanged (Component* child)
  62722. {
  62723. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62724. {
  62725. // not going to look very good if this component has a zero size..
  62726. jassert (child->getWidth() > 0);
  62727. jassert (child->getHeight() > 0);
  62728. const BorderSize<int> borders (getContentComponentBorder());
  62729. setSize (child->getWidth() + borders.getLeftAndRight(),
  62730. child->getHeight() + borders.getTopAndBottom());
  62731. }
  62732. }
  62733. void ResizableWindow::activeWindowStatusChanged()
  62734. {
  62735. const BorderSize<int> border (getContentComponentBorder());
  62736. Rectangle<int> area (getLocalBounds());
  62737. repaint (area.removeFromTop (border.getTop()));
  62738. repaint (area.removeFromLeft (border.getLeft()));
  62739. repaint (area.removeFromRight (border.getRight()));
  62740. repaint (area.removeFromBottom (border.getBottom()));
  62741. }
  62742. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62743. const bool useBottomRightCornerResizer)
  62744. {
  62745. if (shouldBeResizable)
  62746. {
  62747. if (useBottomRightCornerResizer)
  62748. {
  62749. resizableBorder = 0;
  62750. if (resizableCorner == 0)
  62751. {
  62752. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62753. resizableCorner->setAlwaysOnTop (true);
  62754. }
  62755. }
  62756. else
  62757. {
  62758. resizableCorner = 0;
  62759. if (resizableBorder == 0)
  62760. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62761. }
  62762. }
  62763. else
  62764. {
  62765. resizableCorner = 0;
  62766. resizableBorder = 0;
  62767. }
  62768. if (isUsingNativeTitleBar())
  62769. recreateDesktopWindow();
  62770. childBoundsChanged (contentComponent);
  62771. resized();
  62772. }
  62773. bool ResizableWindow::isResizable() const throw()
  62774. {
  62775. return resizableCorner != 0
  62776. || resizableBorder != 0;
  62777. }
  62778. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62779. const int newMinimumHeight,
  62780. const int newMaximumWidth,
  62781. const int newMaximumHeight) throw()
  62782. {
  62783. // if you've set up a custom constrainer then these settings won't have any effect..
  62784. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62785. if (constrainer == 0)
  62786. setConstrainer (&defaultConstrainer);
  62787. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62788. newMaximumWidth, newMaximumHeight);
  62789. setBoundsConstrained (getBounds());
  62790. }
  62791. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62792. {
  62793. if (constrainer != newConstrainer)
  62794. {
  62795. constrainer = newConstrainer;
  62796. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62797. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62798. resizableCorner = 0;
  62799. resizableBorder = 0;
  62800. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62801. ComponentPeer* const peer = getPeer();
  62802. if (peer != 0)
  62803. peer->setConstrainer (newConstrainer);
  62804. }
  62805. }
  62806. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62807. {
  62808. if (constrainer != 0)
  62809. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62810. else
  62811. setBounds (bounds);
  62812. }
  62813. void ResizableWindow::paint (Graphics& g)
  62814. {
  62815. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62816. getBorderThickness(), *this);
  62817. if (! isFullScreen())
  62818. {
  62819. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62820. getBorderThickness(), *this);
  62821. }
  62822. #if JUCE_DEBUG
  62823. /* If this fails, then you've probably written a subclass with a resized()
  62824. callback but forgotten to make it call its parent class's resized() method.
  62825. It's important when you override methods like resized(), moved(),
  62826. etc., that you make sure the base class methods also get called.
  62827. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62828. because your content should all be inside the content component - and it's the
  62829. content component's resized() method that you should be using to do your
  62830. layout.
  62831. */
  62832. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62833. #endif
  62834. }
  62835. void ResizableWindow::lookAndFeelChanged()
  62836. {
  62837. resized();
  62838. if (isOnDesktop())
  62839. {
  62840. Component::addToDesktop (getDesktopWindowStyleFlags());
  62841. ComponentPeer* const peer = getPeer();
  62842. if (peer != 0)
  62843. peer->setConstrainer (constrainer);
  62844. }
  62845. }
  62846. const Colour ResizableWindow::getBackgroundColour() const throw()
  62847. {
  62848. return findColour (backgroundColourId, false);
  62849. }
  62850. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62851. {
  62852. Colour backgroundColour (newColour);
  62853. if (! Desktop::canUseSemiTransparentWindows())
  62854. backgroundColour = newColour.withAlpha (1.0f);
  62855. setColour (backgroundColourId, backgroundColour);
  62856. setOpaque (backgroundColour.isOpaque());
  62857. repaint();
  62858. }
  62859. bool ResizableWindow::isFullScreen() const
  62860. {
  62861. if (isOnDesktop())
  62862. {
  62863. ComponentPeer* const peer = getPeer();
  62864. return peer != 0 && peer->isFullScreen();
  62865. }
  62866. return fullscreen;
  62867. }
  62868. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62869. {
  62870. if (shouldBeFullScreen != isFullScreen())
  62871. {
  62872. updateLastPos();
  62873. fullscreen = shouldBeFullScreen;
  62874. if (isOnDesktop())
  62875. {
  62876. ComponentPeer* const peer = getPeer();
  62877. if (peer != 0)
  62878. {
  62879. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62880. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62881. peer->setFullScreen (shouldBeFullScreen);
  62882. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  62883. setBounds (lastPos);
  62884. }
  62885. else
  62886. {
  62887. jassertfalse;
  62888. }
  62889. }
  62890. else
  62891. {
  62892. if (shouldBeFullScreen)
  62893. setBounds (0, 0, getParentWidth(), getParentHeight());
  62894. else
  62895. setBounds (lastNonFullScreenPos);
  62896. }
  62897. resized();
  62898. }
  62899. }
  62900. bool ResizableWindow::isMinimised() const
  62901. {
  62902. ComponentPeer* const peer = getPeer();
  62903. return (peer != 0) && peer->isMinimised();
  62904. }
  62905. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62906. {
  62907. if (shouldMinimise != isMinimised())
  62908. {
  62909. ComponentPeer* const peer = getPeer();
  62910. if (peer != 0)
  62911. {
  62912. updateLastPos();
  62913. peer->setMinimised (shouldMinimise);
  62914. }
  62915. else
  62916. {
  62917. jassertfalse;
  62918. }
  62919. }
  62920. }
  62921. void ResizableWindow::updateLastPos()
  62922. {
  62923. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62924. {
  62925. lastNonFullScreenPos = getBounds();
  62926. }
  62927. }
  62928. void ResizableWindow::parentSizeChanged()
  62929. {
  62930. if (isFullScreen() && getParentComponent() != 0)
  62931. {
  62932. setBounds (0, 0, getParentWidth(), getParentHeight());
  62933. }
  62934. }
  62935. const String ResizableWindow::getWindowStateAsString()
  62936. {
  62937. updateLastPos();
  62938. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62939. }
  62940. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62941. {
  62942. StringArray tokens;
  62943. tokens.addTokens (s, false);
  62944. tokens.removeEmptyStrings();
  62945. tokens.trim();
  62946. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62947. const int firstCoord = fs ? 1 : 0;
  62948. if (tokens.size() != firstCoord + 4)
  62949. return false;
  62950. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62951. tokens[firstCoord + 1].getIntValue(),
  62952. tokens[firstCoord + 2].getIntValue(),
  62953. tokens[firstCoord + 3].getIntValue());
  62954. if (newPos.isEmpty())
  62955. return false;
  62956. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62957. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62958. if (peer != 0)
  62959. peer->getFrameSize().addTo (newPos);
  62960. if (! screen.contains (newPos))
  62961. {
  62962. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62963. jmin (newPos.getHeight(), screen.getHeight()));
  62964. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62965. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62966. }
  62967. if (peer != 0)
  62968. {
  62969. peer->getFrameSize().subtractFrom (newPos);
  62970. peer->setNonFullScreenBounds (newPos);
  62971. }
  62972. lastNonFullScreenPos = newPos;
  62973. setFullScreen (fs);
  62974. if (! fs)
  62975. setBoundsConstrained (newPos);
  62976. return true;
  62977. }
  62978. void ResizableWindow::mouseDown (const MouseEvent& e)
  62979. {
  62980. if (! isFullScreen())
  62981. dragger.startDraggingComponent (this, e);
  62982. }
  62983. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62984. {
  62985. if (! isFullScreen())
  62986. dragger.dragComponent (this, e, constrainer);
  62987. }
  62988. #if JUCE_DEBUG
  62989. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62990. {
  62991. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62992. manages its child components automatically, and if you add your own it'll cause
  62993. trouble. Instead, use setContentComponent() to give it a component which
  62994. will be automatically resized and kept in the right place - then you can add
  62995. subcomponents to the content comp. See the notes for the ResizableWindow class
  62996. for more info.
  62997. If you really know what you're doing and want to avoid this assertion, just call
  62998. Component::addChildComponent directly.
  62999. */
  63000. jassertfalse;
  63001. Component::addChildComponent (child, zOrder);
  63002. }
  63003. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63004. {
  63005. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63006. manages its child components automatically, and if you add your own it'll cause
  63007. trouble. Instead, use setContentComponent() to give it a component which
  63008. will be automatically resized and kept in the right place - then you can add
  63009. subcomponents to the content comp. See the notes for the ResizableWindow class
  63010. for more info.
  63011. If you really know what you're doing and want to avoid this assertion, just call
  63012. Component::addAndMakeVisible directly.
  63013. */
  63014. jassertfalse;
  63015. Component::addAndMakeVisible (child, zOrder);
  63016. }
  63017. #endif
  63018. END_JUCE_NAMESPACE
  63019. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63020. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63021. BEGIN_JUCE_NAMESPACE
  63022. SplashScreen::SplashScreen()
  63023. {
  63024. setOpaque (true);
  63025. }
  63026. SplashScreen::~SplashScreen()
  63027. {
  63028. }
  63029. void SplashScreen::show (const String& title,
  63030. const Image& backgroundImage_,
  63031. const int minimumTimeToDisplayFor,
  63032. const bool useDropShadow,
  63033. const bool removeOnMouseClick)
  63034. {
  63035. backgroundImage = backgroundImage_;
  63036. jassert (backgroundImage_.isValid());
  63037. if (backgroundImage_.isValid())
  63038. {
  63039. setOpaque (! backgroundImage_.hasAlphaChannel());
  63040. show (title,
  63041. backgroundImage_.getWidth(),
  63042. backgroundImage_.getHeight(),
  63043. minimumTimeToDisplayFor,
  63044. useDropShadow,
  63045. removeOnMouseClick);
  63046. }
  63047. }
  63048. void SplashScreen::show (const String& title,
  63049. const int width,
  63050. const int height,
  63051. const int minimumTimeToDisplayFor,
  63052. const bool useDropShadow,
  63053. const bool removeOnMouseClick)
  63054. {
  63055. setName (title);
  63056. setAlwaysOnTop (true);
  63057. setVisible (true);
  63058. centreWithSize (width, height);
  63059. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63060. toFront (false);
  63061. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63062. repaint();
  63063. originalClickCounter = removeOnMouseClick
  63064. ? Desktop::getMouseButtonClickCounter()
  63065. : std::numeric_limits<int>::max();
  63066. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63067. startTimer (50);
  63068. }
  63069. void SplashScreen::paint (Graphics& g)
  63070. {
  63071. g.setOpacity (1.0f);
  63072. g.drawImage (backgroundImage,
  63073. 0, 0, getWidth(), getHeight(),
  63074. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63075. }
  63076. void SplashScreen::timerCallback()
  63077. {
  63078. if (Time::getCurrentTime() > earliestTimeToDelete
  63079. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63080. {
  63081. delete this;
  63082. }
  63083. }
  63084. END_JUCE_NAMESPACE
  63085. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63086. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63087. BEGIN_JUCE_NAMESPACE
  63088. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63089. const bool hasProgressBar,
  63090. const bool hasCancelButton,
  63091. const int timeOutMsWhenCancelling_,
  63092. const String& cancelButtonText)
  63093. : Thread ("Juce Progress Window"),
  63094. progress (0.0),
  63095. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63096. {
  63097. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63098. .createAlertWindow (title, String::empty, cancelButtonText,
  63099. String::empty, String::empty,
  63100. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63101. if (hasProgressBar)
  63102. alertWindow->addProgressBarComponent (progress);
  63103. }
  63104. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63105. {
  63106. stopThread (timeOutMsWhenCancelling);
  63107. }
  63108. bool ThreadWithProgressWindow::runThread (const int priority)
  63109. {
  63110. startThread (priority);
  63111. startTimer (100);
  63112. {
  63113. const ScopedLock sl (messageLock);
  63114. alertWindow->setMessage (message);
  63115. }
  63116. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63117. stopThread (timeOutMsWhenCancelling);
  63118. alertWindow->setVisible (false);
  63119. return finishedNaturally;
  63120. }
  63121. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63122. {
  63123. progress = newProgress;
  63124. }
  63125. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63126. {
  63127. const ScopedLock sl (messageLock);
  63128. message = newStatusMessage;
  63129. }
  63130. void ThreadWithProgressWindow::timerCallback()
  63131. {
  63132. if (! isThreadRunning())
  63133. {
  63134. // thread has finished normally..
  63135. alertWindow->exitModalState (1);
  63136. alertWindow->setVisible (false);
  63137. }
  63138. else
  63139. {
  63140. const ScopedLock sl (messageLock);
  63141. alertWindow->setMessage (message);
  63142. }
  63143. }
  63144. END_JUCE_NAMESPACE
  63145. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63146. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63147. BEGIN_JUCE_NAMESPACE
  63148. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63149. const int millisecondsBeforeTipAppears_)
  63150. : Component ("tooltip"),
  63151. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63152. mouseClicks (0),
  63153. lastHideTime (0),
  63154. lastComponentUnderMouse (0),
  63155. changedCompsSinceShown (true)
  63156. {
  63157. if (Desktop::getInstance().getMainMouseSource().canHover())
  63158. startTimer (123);
  63159. setAlwaysOnTop (true);
  63160. setOpaque (true);
  63161. if (parentComponent != 0)
  63162. parentComponent->addChildComponent (this);
  63163. }
  63164. TooltipWindow::~TooltipWindow()
  63165. {
  63166. hide();
  63167. }
  63168. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63169. {
  63170. millisecondsBeforeTipAppears = newTimeMs;
  63171. }
  63172. void TooltipWindow::paint (Graphics& g)
  63173. {
  63174. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63175. }
  63176. void TooltipWindow::mouseEnter (const MouseEvent&)
  63177. {
  63178. hide();
  63179. }
  63180. void TooltipWindow::showFor (const String& tip)
  63181. {
  63182. jassert (tip.isNotEmpty());
  63183. if (tipShowing != tip)
  63184. repaint();
  63185. tipShowing = tip;
  63186. Point<int> mousePos (Desktop::getMousePosition());
  63187. if (getParentComponent() != 0)
  63188. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63189. int x, y, w, h;
  63190. getLookAndFeel().getTooltipSize (tip, w, h);
  63191. if (mousePos.getX() > getParentWidth() / 2)
  63192. x = mousePos.getX() - (w + 12);
  63193. else
  63194. x = mousePos.getX() + 24;
  63195. if (mousePos.getY() > getParentHeight() / 2)
  63196. y = mousePos.getY() - (h + 6);
  63197. else
  63198. y = mousePos.getY() + 6;
  63199. setBounds (x, y, w, h);
  63200. setVisible (true);
  63201. if (getParentComponent() == 0)
  63202. {
  63203. addToDesktop (ComponentPeer::windowHasDropShadow
  63204. | ComponentPeer::windowIsTemporary
  63205. | ComponentPeer::windowIgnoresKeyPresses);
  63206. }
  63207. toFront (false);
  63208. }
  63209. const String TooltipWindow::getTipFor (Component* const c)
  63210. {
  63211. if (c != 0
  63212. && Process::isForegroundProcess()
  63213. && ! Component::isMouseButtonDownAnywhere())
  63214. {
  63215. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63216. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63217. return ttc->getTooltip();
  63218. }
  63219. return String::empty;
  63220. }
  63221. void TooltipWindow::hide()
  63222. {
  63223. tipShowing = String::empty;
  63224. removeFromDesktop();
  63225. setVisible (false);
  63226. }
  63227. void TooltipWindow::timerCallback()
  63228. {
  63229. const unsigned int now = Time::getApproximateMillisecondCounter();
  63230. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63231. const String newTip (getTipFor (newComp));
  63232. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63233. lastComponentUnderMouse = newComp;
  63234. lastTipUnderMouse = newTip;
  63235. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63236. const bool mouseWasClicked = clickCount > mouseClicks;
  63237. mouseClicks = clickCount;
  63238. const Point<int> mousePos (Desktop::getMousePosition());
  63239. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63240. lastMousePos = mousePos;
  63241. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63242. lastCompChangeTime = now;
  63243. if (isVisible() || now < lastHideTime + 500)
  63244. {
  63245. // if a tip is currently visible (or has just disappeared), update to a new one
  63246. // immediately if needed..
  63247. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63248. {
  63249. if (isVisible())
  63250. {
  63251. lastHideTime = now;
  63252. hide();
  63253. }
  63254. }
  63255. else if (tipChanged)
  63256. {
  63257. showFor (newTip);
  63258. }
  63259. }
  63260. else
  63261. {
  63262. // if there isn't currently a tip, but one is needed, only let it
  63263. // appear after a timeout..
  63264. if (newTip.isNotEmpty()
  63265. && newTip != tipShowing
  63266. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63267. {
  63268. showFor (newTip);
  63269. }
  63270. }
  63271. }
  63272. END_JUCE_NAMESPACE
  63273. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63274. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63275. BEGIN_JUCE_NAMESPACE
  63276. /** Keeps track of the active top level window.
  63277. */
  63278. class TopLevelWindowManager : public Timer,
  63279. public DeletedAtShutdown
  63280. {
  63281. public:
  63282. TopLevelWindowManager()
  63283. : currentActive (0)
  63284. {
  63285. }
  63286. ~TopLevelWindowManager()
  63287. {
  63288. clearSingletonInstance();
  63289. }
  63290. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63291. void timerCallback()
  63292. {
  63293. startTimer (jmin (1731, getTimerInterval() * 2));
  63294. TopLevelWindow* active = 0;
  63295. if (Process::isForegroundProcess())
  63296. {
  63297. active = currentActive;
  63298. Component* const c = Component::getCurrentlyFocusedComponent();
  63299. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63300. if (tlw == 0 && c != 0)
  63301. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63302. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63303. if (tlw != 0)
  63304. active = tlw;
  63305. }
  63306. if (active != currentActive)
  63307. {
  63308. currentActive = active;
  63309. for (int i = windows.size(); --i >= 0;)
  63310. {
  63311. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63312. tlw->setWindowActive (isWindowActive (tlw));
  63313. i = jmin (i, windows.size() - 1);
  63314. }
  63315. Desktop::getInstance().triggerFocusCallback();
  63316. }
  63317. }
  63318. bool addWindow (TopLevelWindow* const w)
  63319. {
  63320. windows.add (w);
  63321. startTimer (10);
  63322. return isWindowActive (w);
  63323. }
  63324. void removeWindow (TopLevelWindow* const w)
  63325. {
  63326. startTimer (10);
  63327. if (currentActive == w)
  63328. currentActive = 0;
  63329. windows.removeValue (w);
  63330. if (windows.size() == 0)
  63331. deleteInstance();
  63332. }
  63333. Array <TopLevelWindow*> windows;
  63334. private:
  63335. TopLevelWindow* currentActive;
  63336. bool isWindowActive (TopLevelWindow* const tlw) const
  63337. {
  63338. return (tlw == currentActive
  63339. || tlw->isParentOf (currentActive)
  63340. || tlw->hasKeyboardFocus (true))
  63341. && tlw->isShowing();
  63342. }
  63343. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63344. };
  63345. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63346. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63347. {
  63348. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63349. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63350. }
  63351. TopLevelWindow::TopLevelWindow (const String& name,
  63352. const bool addToDesktop_)
  63353. : Component (name),
  63354. useDropShadow (true),
  63355. useNativeTitleBar (false),
  63356. windowIsActive_ (false)
  63357. {
  63358. setOpaque (true);
  63359. if (addToDesktop_)
  63360. Component::addToDesktop (getDesktopWindowStyleFlags());
  63361. else
  63362. setDropShadowEnabled (true);
  63363. setWantsKeyboardFocus (true);
  63364. setBroughtToFrontOnMouseClick (true);
  63365. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63366. }
  63367. TopLevelWindow::~TopLevelWindow()
  63368. {
  63369. shadower = 0;
  63370. TopLevelWindowManager::getInstance()->removeWindow (this);
  63371. }
  63372. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63373. {
  63374. if (hasKeyboardFocus (true))
  63375. TopLevelWindowManager::getInstance()->timerCallback();
  63376. else
  63377. TopLevelWindowManager::getInstance()->startTimer (10);
  63378. }
  63379. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63380. {
  63381. if (windowIsActive_ != isNowActive)
  63382. {
  63383. windowIsActive_ = isNowActive;
  63384. activeWindowStatusChanged();
  63385. }
  63386. }
  63387. void TopLevelWindow::activeWindowStatusChanged()
  63388. {
  63389. }
  63390. void TopLevelWindow::visibilityChanged()
  63391. {
  63392. if (isShowing()
  63393. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63394. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63395. {
  63396. toFront (true);
  63397. }
  63398. }
  63399. void TopLevelWindow::parentHierarchyChanged()
  63400. {
  63401. setDropShadowEnabled (useDropShadow);
  63402. }
  63403. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63404. {
  63405. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63406. if (useDropShadow)
  63407. styleFlags |= ComponentPeer::windowHasDropShadow;
  63408. if (useNativeTitleBar)
  63409. styleFlags |= ComponentPeer::windowHasTitleBar;
  63410. return styleFlags;
  63411. }
  63412. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63413. {
  63414. useDropShadow = useShadow;
  63415. if (isOnDesktop())
  63416. {
  63417. shadower = 0;
  63418. Component::addToDesktop (getDesktopWindowStyleFlags());
  63419. }
  63420. else
  63421. {
  63422. if (useShadow && isOpaque())
  63423. {
  63424. if (shadower == 0)
  63425. {
  63426. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63427. if (shadower != 0)
  63428. shadower->setOwner (this);
  63429. }
  63430. }
  63431. else
  63432. {
  63433. shadower = 0;
  63434. }
  63435. }
  63436. }
  63437. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63438. {
  63439. if (useNativeTitleBar != useNativeTitleBar_)
  63440. {
  63441. useNativeTitleBar = useNativeTitleBar_;
  63442. recreateDesktopWindow();
  63443. sendLookAndFeelChange();
  63444. }
  63445. }
  63446. void TopLevelWindow::recreateDesktopWindow()
  63447. {
  63448. if (isOnDesktop())
  63449. {
  63450. Component::addToDesktop (getDesktopWindowStyleFlags());
  63451. toFront (true);
  63452. }
  63453. }
  63454. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63455. {
  63456. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63457. because this class needs to make sure its layout corresponds with settings like whether
  63458. it's got a native title bar or not.
  63459. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63460. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63461. method, then add or remove whatever flags are necessary from this value before returning it.
  63462. */
  63463. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63464. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63465. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63466. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63467. sendLookAndFeelChange();
  63468. }
  63469. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63470. {
  63471. if (c == 0)
  63472. c = TopLevelWindow::getActiveTopLevelWindow();
  63473. if (c == 0)
  63474. {
  63475. centreWithSize (width, height);
  63476. }
  63477. else
  63478. {
  63479. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63480. Rectangle<int> parentArea (c->getParentMonitorArea());
  63481. if (getParentComponent() != 0)
  63482. {
  63483. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63484. parentArea = getParentComponent()->getLocalBounds();
  63485. }
  63486. parentArea.reduce (12, 12);
  63487. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63488. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63489. width, height);
  63490. }
  63491. }
  63492. int TopLevelWindow::getNumTopLevelWindows() throw()
  63493. {
  63494. return TopLevelWindowManager::getInstance()->windows.size();
  63495. }
  63496. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63497. {
  63498. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63499. }
  63500. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63501. {
  63502. TopLevelWindow* best = 0;
  63503. int bestNumTWLParents = -1;
  63504. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63505. {
  63506. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63507. if (tlw->isActiveWindow())
  63508. {
  63509. int numTWLParents = 0;
  63510. const Component* c = tlw->getParentComponent();
  63511. while (c != 0)
  63512. {
  63513. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63514. ++numTWLParents;
  63515. c = c->getParentComponent();
  63516. }
  63517. if (bestNumTWLParents < numTWLParents)
  63518. {
  63519. best = tlw;
  63520. bestNumTWLParents = numTWLParents;
  63521. }
  63522. }
  63523. }
  63524. return best;
  63525. }
  63526. END_JUCE_NAMESPACE
  63527. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63528. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63529. BEGIN_JUCE_NAMESPACE
  63530. MarkerList::MarkerList()
  63531. {
  63532. }
  63533. MarkerList::MarkerList (const MarkerList& other)
  63534. {
  63535. operator= (other);
  63536. }
  63537. MarkerList& MarkerList::operator= (const MarkerList& other)
  63538. {
  63539. if (other != *this)
  63540. {
  63541. markers.clear();
  63542. markers.addCopiesOf (other.markers);
  63543. markersHaveChanged();
  63544. }
  63545. return *this;
  63546. }
  63547. MarkerList::~MarkerList()
  63548. {
  63549. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  63550. }
  63551. bool MarkerList::operator== (const MarkerList& other) const throw()
  63552. {
  63553. if (other.markers.size() != markers.size())
  63554. return false;
  63555. for (int i = markers.size(); --i >= 0;)
  63556. {
  63557. const Marker* const m1 = markers.getUnchecked(i);
  63558. jassert (m1 != 0);
  63559. const Marker* const m2 = other.getMarker (m1->name);
  63560. if (m2 == 0 || *m1 != *m2)
  63561. return false;
  63562. }
  63563. return true;
  63564. }
  63565. bool MarkerList::operator!= (const MarkerList& other) const throw()
  63566. {
  63567. return ! operator== (other);
  63568. }
  63569. int MarkerList::getNumMarkers() const throw()
  63570. {
  63571. return markers.size();
  63572. }
  63573. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  63574. {
  63575. return markers [index];
  63576. }
  63577. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  63578. {
  63579. for (int i = 0; i < markers.size(); ++i)
  63580. {
  63581. const Marker* const m = markers.getUnchecked(i);
  63582. if (m->name == name)
  63583. return m;
  63584. }
  63585. return 0;
  63586. }
  63587. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  63588. {
  63589. Marker* const m = const_cast <Marker*> (getMarker (name));
  63590. if (m != 0)
  63591. {
  63592. if (m->position != position)
  63593. {
  63594. m->position = position;
  63595. markersHaveChanged();
  63596. }
  63597. return;
  63598. }
  63599. markers.add (new Marker (name, position));
  63600. markersHaveChanged();
  63601. }
  63602. void MarkerList::removeMarker (const int index)
  63603. {
  63604. if (isPositiveAndBelow (index, markers.size()))
  63605. {
  63606. markers.remove (index);
  63607. markersHaveChanged();
  63608. }
  63609. }
  63610. void MarkerList::removeMarker (const String& name)
  63611. {
  63612. for (int i = 0; i < markers.size(); ++i)
  63613. {
  63614. const Marker* const m = markers.getUnchecked(i);
  63615. if (m->name == name)
  63616. {
  63617. markers.remove (i);
  63618. markersHaveChanged();
  63619. }
  63620. }
  63621. }
  63622. void MarkerList::markersHaveChanged()
  63623. {
  63624. listeners.call (&MarkerList::Listener::markersChanged, this);
  63625. }
  63626. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  63627. {
  63628. }
  63629. void MarkerList::addListener (Listener* listener)
  63630. {
  63631. listeners.add (listener);
  63632. }
  63633. void MarkerList::removeListener (Listener* listener)
  63634. {
  63635. listeners.remove (listener);
  63636. }
  63637. MarkerList::Marker::Marker (const Marker& other)
  63638. : name (other.name), position (other.position)
  63639. {
  63640. }
  63641. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  63642. : name (name_), position (position_)
  63643. {
  63644. }
  63645. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  63646. {
  63647. return name == other.name && position == other.position;
  63648. }
  63649. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  63650. {
  63651. return ! operator== (other);
  63652. }
  63653. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  63654. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  63655. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  63656. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  63657. : state (state_)
  63658. {
  63659. }
  63660. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  63661. {
  63662. return state.getNumChildren();
  63663. }
  63664. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  63665. {
  63666. return state.getChild (index);
  63667. }
  63668. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  63669. {
  63670. return state.getChildWithProperty (nameProperty, name);
  63671. }
  63672. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  63673. {
  63674. return marker.isAChildOf (state);
  63675. }
  63676. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  63677. {
  63678. jassert (containsMarker (marker));
  63679. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  63680. }
  63681. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  63682. {
  63683. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  63684. if (marker.isValid())
  63685. {
  63686. marker.setProperty (posProperty, m.position.toString(), undoManager);
  63687. }
  63688. else
  63689. {
  63690. marker = ValueTree (markerTag);
  63691. marker.setProperty (nameProperty, m.name, 0);
  63692. marker.setProperty (posProperty, m.position.toString(), 0);
  63693. state.addChild (marker, -1, undoManager);
  63694. }
  63695. }
  63696. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  63697. {
  63698. state.removeChild (marker, undoManager);
  63699. }
  63700. double MarkerList::getMarkerPosition (const Marker& marker, Component* parentComponent) const
  63701. {
  63702. if (parentComponent != 0)
  63703. {
  63704. RelativeCoordinatePositionerBase::ComponentScope scope (*parentComponent);
  63705. return marker.position.resolve (&scope);
  63706. }
  63707. else
  63708. {
  63709. return marker.position.resolve (0);
  63710. }
  63711. }
  63712. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  63713. {
  63714. const int numMarkers = getNumMarkers();
  63715. StringArray updatedMarkers;
  63716. int i;
  63717. for (i = 0; i < numMarkers; ++i)
  63718. {
  63719. const ValueTree marker (state.getChild (i));
  63720. const String name (marker [nameProperty].toString());
  63721. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  63722. updatedMarkers.add (name);
  63723. }
  63724. for (i = markerList.getNumMarkers(); --i >= 0;)
  63725. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  63726. markerList.removeMarker (i);
  63727. }
  63728. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  63729. {
  63730. state.removeAllChildren (undoManager);
  63731. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  63732. setMarker (*markerList.getMarker(i), undoManager);
  63733. }
  63734. END_JUCE_NAMESPACE
  63735. /*** End of inlined file: juce_MarkerList.cpp ***/
  63736. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63737. BEGIN_JUCE_NAMESPACE
  63738. const String RelativeCoordinate::Strings::parent ("parent");
  63739. const String RelativeCoordinate::Strings::left ("left");
  63740. const String RelativeCoordinate::Strings::right ("right");
  63741. const String RelativeCoordinate::Strings::top ("top");
  63742. const String RelativeCoordinate::Strings::bottom ("bottom");
  63743. const String RelativeCoordinate::Strings::x ("x");
  63744. const String RelativeCoordinate::Strings::y ("y");
  63745. const String RelativeCoordinate::Strings::width ("width");
  63746. const String RelativeCoordinate::Strings::height ("height");
  63747. RelativeCoordinate::StandardStrings::Type RelativeCoordinate::StandardStrings::getTypeOf (const String& s) throw()
  63748. {
  63749. if (s == Strings::left) return left;
  63750. if (s == Strings::right) return right;
  63751. if (s == Strings::top) return top;
  63752. if (s == Strings::bottom) return bottom;
  63753. if (s == Strings::x) return x;
  63754. if (s == Strings::y) return y;
  63755. if (s == Strings::width) return width;
  63756. if (s == Strings::height) return height;
  63757. if (s == Strings::parent) return parent;
  63758. return unknown;
  63759. }
  63760. RelativeCoordinate::RelativeCoordinate()
  63761. {
  63762. }
  63763. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63764. : term (term_)
  63765. {
  63766. }
  63767. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63768. : term (other.term)
  63769. {
  63770. }
  63771. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63772. {
  63773. term = other.term;
  63774. return *this;
  63775. }
  63776. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63777. : term (absoluteDistanceFromOrigin)
  63778. {
  63779. }
  63780. RelativeCoordinate::RelativeCoordinate (const String& s)
  63781. {
  63782. try
  63783. {
  63784. term = Expression (s);
  63785. }
  63786. catch (...)
  63787. {}
  63788. }
  63789. RelativeCoordinate::~RelativeCoordinate()
  63790. {
  63791. }
  63792. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63793. {
  63794. return term.toString() == other.term.toString();
  63795. }
  63796. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63797. {
  63798. return ! operator== (other);
  63799. }
  63800. double RelativeCoordinate::resolve (const Expression::Scope* scope) const
  63801. {
  63802. try
  63803. {
  63804. if (scope != 0)
  63805. return term.evaluate (*scope);
  63806. else
  63807. return term.evaluate();
  63808. }
  63809. catch (...)
  63810. {}
  63811. return 0.0;
  63812. }
  63813. bool RelativeCoordinate::isRecursive (const Expression::Scope* scope) const
  63814. {
  63815. try
  63816. {
  63817. if (scope != 0)
  63818. term.evaluate (*scope);
  63819. else
  63820. term.evaluate();
  63821. }
  63822. catch (...)
  63823. {
  63824. return true;
  63825. }
  63826. return false;
  63827. }
  63828. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::Scope* scope)
  63829. {
  63830. try
  63831. {
  63832. if (scope != 0)
  63833. {
  63834. term = term.adjustedToGiveNewResult (newPos, *scope);
  63835. }
  63836. else
  63837. {
  63838. Expression::Scope defaultScope;
  63839. term = term.adjustedToGiveNewResult (newPos, defaultScope);
  63840. }
  63841. }
  63842. catch (...)
  63843. {}
  63844. }
  63845. bool RelativeCoordinate::isDynamic() const
  63846. {
  63847. return term.usesAnySymbols();
  63848. }
  63849. const String RelativeCoordinate::toString() const
  63850. {
  63851. return term.toString();
  63852. }
  63853. END_JUCE_NAMESPACE
  63854. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  63855. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  63856. BEGIN_JUCE_NAMESPACE
  63857. namespace RelativePointHelpers
  63858. {
  63859. inline void skipComma (String::CharPointerType& s)
  63860. {
  63861. s = s.findEndOfWhitespace();
  63862. if (*s == ',')
  63863. ++s;
  63864. }
  63865. }
  63866. RelativePoint::RelativePoint()
  63867. {
  63868. }
  63869. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  63870. : x (absolutePoint.getX()), y (absolutePoint.getY())
  63871. {
  63872. }
  63873. RelativePoint::RelativePoint (const float x_, const float y_)
  63874. : x (x_), y (y_)
  63875. {
  63876. }
  63877. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  63878. : x (x_), y (y_)
  63879. {
  63880. }
  63881. RelativePoint::RelativePoint (const String& s)
  63882. {
  63883. String::CharPointerType text (s.getCharPointer());
  63884. x = RelativeCoordinate (Expression::parse (text));
  63885. RelativePointHelpers::skipComma (text);
  63886. y = RelativeCoordinate (Expression::parse (text));
  63887. }
  63888. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  63889. {
  63890. return x == other.x && y == other.y;
  63891. }
  63892. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  63893. {
  63894. return ! operator== (other);
  63895. }
  63896. const Point<float> RelativePoint::resolve (const Expression::Scope* scope) const
  63897. {
  63898. return Point<float> ((float) x.resolve (scope),
  63899. (float) y.resolve (scope));
  63900. }
  63901. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::Scope* scope)
  63902. {
  63903. x.moveToAbsolute (newPos.getX(), scope);
  63904. y.moveToAbsolute (newPos.getY(), scope);
  63905. }
  63906. const String RelativePoint::toString() const
  63907. {
  63908. return x.toString() + ", " + y.toString();
  63909. }
  63910. bool RelativePoint::isDynamic() const
  63911. {
  63912. return x.isDynamic() || y.isDynamic();
  63913. }
  63914. END_JUCE_NAMESPACE
  63915. /*** End of inlined file: juce_RelativePoint.cpp ***/
  63916. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  63917. BEGIN_JUCE_NAMESPACE
  63918. namespace RelativeRectangleHelpers
  63919. {
  63920. inline void skipComma (String::CharPointerType& s)
  63921. {
  63922. s = s.findEndOfWhitespace();
  63923. if (*s == ',')
  63924. ++s;
  63925. }
  63926. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  63927. {
  63928. if (e.getType() == Expression::operatorType && e.getSymbolOrFunction() == ".")
  63929. return true;
  63930. if (e.getType() == Expression::symbolType)
  63931. {
  63932. switch (RelativeCoordinate::StandardStrings::getTypeOf (e.getSymbolOrFunction()))
  63933. {
  63934. case RelativeCoordinate::StandardStrings::x:
  63935. case RelativeCoordinate::StandardStrings::y:
  63936. case RelativeCoordinate::StandardStrings::left:
  63937. case RelativeCoordinate::StandardStrings::right:
  63938. case RelativeCoordinate::StandardStrings::top:
  63939. case RelativeCoordinate::StandardStrings::bottom: return false;
  63940. default: break;
  63941. }
  63942. return true;
  63943. }
  63944. else
  63945. {
  63946. for (int i = e.getNumInputs(); --i >= 0;)
  63947. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  63948. return true;
  63949. }
  63950. return false;
  63951. }
  63952. }
  63953. RelativeRectangle::RelativeRectangle()
  63954. {
  63955. }
  63956. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  63957. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  63958. : left (left_), right (right_), top (top_), bottom (bottom_)
  63959. {
  63960. }
  63961. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  63962. : left (rect.getX()),
  63963. right (Expression::symbol (RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  63964. top (rect.getY()),
  63965. bottom (Expression::symbol (RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  63966. {
  63967. }
  63968. RelativeRectangle::RelativeRectangle (const String& s)
  63969. {
  63970. String::CharPointerType text (s.getCharPointer());
  63971. left = RelativeCoordinate (Expression::parse (text));
  63972. RelativeRectangleHelpers::skipComma (text);
  63973. top = RelativeCoordinate (Expression::parse (text));
  63974. RelativeRectangleHelpers::skipComma (text);
  63975. right = RelativeCoordinate (Expression::parse (text));
  63976. RelativeRectangleHelpers::skipComma (text);
  63977. bottom = RelativeCoordinate (Expression::parse (text));
  63978. }
  63979. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  63980. {
  63981. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  63982. }
  63983. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  63984. {
  63985. return ! operator== (other);
  63986. }
  63987. // An expression context that can evaluate expressions using "this"
  63988. class RelativeRectangleLocalScope : public Expression::Scope
  63989. {
  63990. public:
  63991. RelativeRectangleLocalScope (const RelativeRectangle& rect_) : rect (rect_) {}
  63992. const Expression getSymbolValue (const String& symbol) const
  63993. {
  63994. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  63995. {
  63996. case RelativeCoordinate::StandardStrings::x:
  63997. case RelativeCoordinate::StandardStrings::left: return rect.left.getExpression();
  63998. case RelativeCoordinate::StandardStrings::y:
  63999. case RelativeCoordinate::StandardStrings::top: return rect.top.getExpression();
  64000. case RelativeCoordinate::StandardStrings::right: return rect.right.getExpression();
  64001. case RelativeCoordinate::StandardStrings::bottom: return rect.bottom.getExpression();
  64002. default: break;
  64003. }
  64004. return Expression::Scope::getSymbolValue (symbol);
  64005. }
  64006. private:
  64007. const RelativeRectangle& rect;
  64008. JUCE_DECLARE_NON_COPYABLE (RelativeRectangleLocalScope);
  64009. };
  64010. const Rectangle<float> RelativeRectangle::resolve (const Expression::Scope* scope) const
  64011. {
  64012. if (scope == 0)
  64013. {
  64014. RelativeRectangleLocalScope scope (*this);
  64015. return resolve (&scope);
  64016. }
  64017. else
  64018. {
  64019. const double l = left.resolve (scope);
  64020. const double r = right.resolve (scope);
  64021. const double t = top.resolve (scope);
  64022. const double b = bottom.resolve (scope);
  64023. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64024. }
  64025. }
  64026. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope)
  64027. {
  64028. left.moveToAbsolute (newPos.getX(), scope);
  64029. right.moveToAbsolute (newPos.getRight(), scope);
  64030. top.moveToAbsolute (newPos.getY(), scope);
  64031. bottom.moveToAbsolute (newPos.getBottom(), scope);
  64032. }
  64033. bool RelativeRectangle::isDynamic() const
  64034. {
  64035. using namespace RelativeRectangleHelpers;
  64036. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64037. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64038. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64039. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64040. }
  64041. const String RelativeRectangle::toString() const
  64042. {
  64043. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64044. }
  64045. void RelativeRectangle::renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope)
  64046. {
  64047. left = left.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64048. right = right.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64049. top = top.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64050. bottom = bottom.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64051. }
  64052. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64053. {
  64054. public:
  64055. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64056. : RelativeCoordinatePositionerBase (component_),
  64057. rectangle (rectangle_)
  64058. {
  64059. }
  64060. bool registerCoordinates()
  64061. {
  64062. bool ok = addCoordinate (rectangle.left);
  64063. ok = addCoordinate (rectangle.right) && ok;
  64064. ok = addCoordinate (rectangle.top) && ok;
  64065. ok = addCoordinate (rectangle.bottom) && ok;
  64066. return ok;
  64067. }
  64068. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64069. {
  64070. return rectangle == other;
  64071. }
  64072. void applyToComponentBounds()
  64073. {
  64074. for (int i = 4; --i >= 0;)
  64075. {
  64076. ComponentScope scope (getComponent());
  64077. const Rectangle<int> newBounds (rectangle.resolve (&scope).getSmallestIntegerContainer());
  64078. if (newBounds == getComponent().getBounds())
  64079. return;
  64080. getComponent().setBounds (newBounds);
  64081. }
  64082. jassertfalse; // must be a recursive reference!
  64083. }
  64084. private:
  64085. const RelativeRectangle rectangle;
  64086. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64087. };
  64088. void RelativeRectangle::applyToComponent (Component& component) const
  64089. {
  64090. if (isDynamic())
  64091. {
  64092. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64093. if (current == 0 || ! current->isUsingRectangle (*this))
  64094. {
  64095. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64096. component.setPositioner (p);
  64097. p->apply();
  64098. }
  64099. }
  64100. else
  64101. {
  64102. component.setPositioner (0);
  64103. component.setBounds (resolve (0).getSmallestIntegerContainer());
  64104. }
  64105. }
  64106. END_JUCE_NAMESPACE
  64107. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64108. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64109. BEGIN_JUCE_NAMESPACE
  64110. RelativePointPath::RelativePointPath()
  64111. : usesNonZeroWinding (true),
  64112. containsDynamicPoints (false)
  64113. {
  64114. }
  64115. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64116. : usesNonZeroWinding (true),
  64117. containsDynamicPoints (false)
  64118. {
  64119. for (int i = 0; i < other.elements.size(); ++i)
  64120. elements.add (other.elements.getUnchecked(i)->clone());
  64121. }
  64122. RelativePointPath::RelativePointPath (const Path& path)
  64123. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64124. containsDynamicPoints (false)
  64125. {
  64126. for (Path::Iterator i (path); i.next();)
  64127. {
  64128. switch (i.elementType)
  64129. {
  64130. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64131. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64132. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64133. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64134. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64135. default: jassertfalse; break;
  64136. }
  64137. }
  64138. }
  64139. RelativePointPath::~RelativePointPath()
  64140. {
  64141. }
  64142. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64143. {
  64144. if (elements.size() != other.elements.size()
  64145. || usesNonZeroWinding != other.usesNonZeroWinding
  64146. || containsDynamicPoints != other.containsDynamicPoints)
  64147. return false;
  64148. for (int i = 0; i < elements.size(); ++i)
  64149. {
  64150. ElementBase* const e1 = elements.getUnchecked(i);
  64151. ElementBase* const e2 = other.elements.getUnchecked(i);
  64152. if (e1->type != e2->type)
  64153. return false;
  64154. int numPoints1, numPoints2;
  64155. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64156. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64157. jassert (numPoints1 == numPoints2);
  64158. for (int j = numPoints1; --j >= 0;)
  64159. if (points1[j] != points2[j])
  64160. return false;
  64161. }
  64162. return true;
  64163. }
  64164. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64165. {
  64166. return ! operator== (other);
  64167. }
  64168. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64169. {
  64170. elements.swapWithArray (other.elements);
  64171. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64172. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64173. }
  64174. void RelativePointPath::createPath (Path& path, Expression::Scope* scope) const
  64175. {
  64176. for (int i = 0; i < elements.size(); ++i)
  64177. elements.getUnchecked(i)->addToPath (path, scope);
  64178. }
  64179. bool RelativePointPath::containsAnyDynamicPoints() const
  64180. {
  64181. return containsDynamicPoints;
  64182. }
  64183. void RelativePointPath::addElement (ElementBase* newElement)
  64184. {
  64185. if (newElement != 0)
  64186. {
  64187. elements.add (newElement);
  64188. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64189. }
  64190. }
  64191. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64192. {
  64193. }
  64194. bool RelativePointPath::ElementBase::isDynamic()
  64195. {
  64196. int numPoints;
  64197. const RelativePoint* const points = getControlPoints (numPoints);
  64198. for (int i = numPoints; --i >= 0;)
  64199. if (points[i].isDynamic())
  64200. return true;
  64201. return false;
  64202. }
  64203. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64204. : ElementBase (startSubPathElement), startPos (pos)
  64205. {
  64206. }
  64207. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64208. {
  64209. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64210. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64211. return v;
  64212. }
  64213. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::Scope* scope) const
  64214. {
  64215. path.startNewSubPath (startPos.resolve (scope));
  64216. }
  64217. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64218. {
  64219. numPoints = 1;
  64220. return &startPos;
  64221. }
  64222. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64223. {
  64224. return new StartSubPath (startPos);
  64225. }
  64226. RelativePointPath::CloseSubPath::CloseSubPath()
  64227. : ElementBase (closeSubPathElement)
  64228. {
  64229. }
  64230. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64231. {
  64232. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64233. }
  64234. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::Scope*) const
  64235. {
  64236. path.closeSubPath();
  64237. }
  64238. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64239. {
  64240. numPoints = 0;
  64241. return 0;
  64242. }
  64243. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64244. {
  64245. return new CloseSubPath();
  64246. }
  64247. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64248. : ElementBase (lineToElement), endPoint (endPoint_)
  64249. {
  64250. }
  64251. const ValueTree RelativePointPath::LineTo::createTree() const
  64252. {
  64253. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64254. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64255. return v;
  64256. }
  64257. void RelativePointPath::LineTo::addToPath (Path& path, Expression::Scope* scope) const
  64258. {
  64259. path.lineTo (endPoint.resolve (scope));
  64260. }
  64261. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64262. {
  64263. numPoints = 1;
  64264. return &endPoint;
  64265. }
  64266. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64267. {
  64268. return new LineTo (endPoint);
  64269. }
  64270. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64271. : ElementBase (quadraticToElement)
  64272. {
  64273. controlPoints[0] = controlPoint;
  64274. controlPoints[1] = endPoint;
  64275. }
  64276. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64277. {
  64278. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64279. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64280. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64281. return v;
  64282. }
  64283. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::Scope* scope) const
  64284. {
  64285. path.quadraticTo (controlPoints[0].resolve (scope),
  64286. controlPoints[1].resolve (scope));
  64287. }
  64288. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64289. {
  64290. numPoints = 2;
  64291. return controlPoints;
  64292. }
  64293. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64294. {
  64295. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64296. }
  64297. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64298. : ElementBase (cubicToElement)
  64299. {
  64300. controlPoints[0] = controlPoint1;
  64301. controlPoints[1] = controlPoint2;
  64302. controlPoints[2] = endPoint;
  64303. }
  64304. const ValueTree RelativePointPath::CubicTo::createTree() const
  64305. {
  64306. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64307. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64308. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64309. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64310. return v;
  64311. }
  64312. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::Scope* scope) const
  64313. {
  64314. path.cubicTo (controlPoints[0].resolve (scope),
  64315. controlPoints[1].resolve (scope),
  64316. controlPoints[2].resolve (scope));
  64317. }
  64318. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64319. {
  64320. numPoints = 3;
  64321. return controlPoints;
  64322. }
  64323. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64324. {
  64325. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64326. }
  64327. END_JUCE_NAMESPACE
  64328. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64329. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64330. BEGIN_JUCE_NAMESPACE
  64331. RelativeParallelogram::RelativeParallelogram()
  64332. {
  64333. }
  64334. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64335. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64336. {
  64337. }
  64338. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64339. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64340. {
  64341. }
  64342. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64343. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64344. {
  64345. }
  64346. RelativeParallelogram::~RelativeParallelogram()
  64347. {
  64348. }
  64349. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::Scope* const scope) const
  64350. {
  64351. points[0] = topLeft.resolve (scope);
  64352. points[1] = topRight.resolve (scope);
  64353. points[2] = bottomLeft.resolve (scope);
  64354. }
  64355. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::Scope* const scope) const
  64356. {
  64357. resolveThreePoints (points, scope);
  64358. points[3] = points[1] + (points[2] - points[0]);
  64359. }
  64360. const Rectangle<float> RelativeParallelogram::getBounds (Expression::Scope* const scope) const
  64361. {
  64362. Point<float> points[4];
  64363. resolveFourCorners (points, scope);
  64364. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64365. }
  64366. void RelativeParallelogram::getPath (Path& path, Expression::Scope* const scope) const
  64367. {
  64368. Point<float> points[4];
  64369. resolveFourCorners (points, scope);
  64370. path.startNewSubPath (points[0]);
  64371. path.lineTo (points[1]);
  64372. path.lineTo (points[3]);
  64373. path.lineTo (points[2]);
  64374. path.closeSubPath();
  64375. }
  64376. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::Scope* const scope)
  64377. {
  64378. Point<float> corners[3];
  64379. resolveThreePoints (corners, scope);
  64380. const Line<float> top (corners[0], corners[1]);
  64381. const Line<float> left (corners[0], corners[2]);
  64382. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64383. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64384. topRight.moveToAbsolute (newTopRight, scope);
  64385. bottomLeft.moveToAbsolute (newBottomLeft, scope);
  64386. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64387. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64388. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64389. }
  64390. bool RelativeParallelogram::isDynamic() const
  64391. {
  64392. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64393. }
  64394. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64395. {
  64396. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64397. }
  64398. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64399. {
  64400. return ! operator== (other);
  64401. }
  64402. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64403. {
  64404. const Point<float> tr (corners[1] - corners[0]);
  64405. const Point<float> bl (corners[2] - corners[0]);
  64406. target -= corners[0];
  64407. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64408. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64409. }
  64410. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64411. {
  64412. return corners[0]
  64413. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64414. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64415. }
  64416. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64417. {
  64418. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64419. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64420. }
  64421. END_JUCE_NAMESPACE
  64422. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64423. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64424. BEGIN_JUCE_NAMESPACE
  64425. RelativeCoordinatePositionerBase::ComponentScope::ComponentScope (Component& component_)
  64426. : component (component_)
  64427. {
  64428. }
  64429. const Expression RelativeCoordinatePositionerBase::ComponentScope::getSymbolValue (const String& symbol) const
  64430. {
  64431. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64432. {
  64433. case RelativeCoordinate::StandardStrings::x:
  64434. case RelativeCoordinate::StandardStrings::left: return Expression ((double) component.getX());
  64435. case RelativeCoordinate::StandardStrings::y:
  64436. case RelativeCoordinate::StandardStrings::top: return Expression ((double) component.getY());
  64437. case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth());
  64438. case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight());
  64439. case RelativeCoordinate::StandardStrings::right: return Expression ((double) component.getRight());
  64440. case RelativeCoordinate::StandardStrings::bottom: return Expression ((double) component.getBottom());
  64441. default: break;
  64442. }
  64443. MarkerList* list;
  64444. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64445. if (marker != 0)
  64446. return marker->position.getExpression();
  64447. return Expression::Scope::getSymbolValue (symbol);
  64448. }
  64449. void RelativeCoordinatePositionerBase::ComponentScope::visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64450. {
  64451. Component* targetComp = 0;
  64452. if (scopeName == RelativeCoordinate::Strings::parent)
  64453. targetComp = component.getParentComponent();
  64454. else
  64455. targetComp = findSiblingComponent (scopeName);
  64456. if (targetComp != 0)
  64457. visitor.visit (ComponentScope (*targetComp));
  64458. else
  64459. Expression::Scope::visitRelativeScope (scopeName, visitor);
  64460. }
  64461. const String RelativeCoordinatePositionerBase::ComponentScope::getScopeUID() const
  64462. {
  64463. return String::toHexString ((int) (pointer_sized_int) (void*) &component);
  64464. }
  64465. Component* RelativeCoordinatePositionerBase::ComponentScope::findSiblingComponent (const String& componentID) const
  64466. {
  64467. Component* const parent = component.getParentComponent();
  64468. if (parent != 0)
  64469. {
  64470. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64471. {
  64472. Component* const c = parent->getChildComponent(i);
  64473. if (c->getComponentID() == componentID)
  64474. return c;
  64475. }
  64476. }
  64477. return 0;
  64478. }
  64479. const MarkerList::Marker* RelativeCoordinatePositionerBase::ComponentScope::findMarker (const String& name, MarkerList*& list) const
  64480. {
  64481. const MarkerList::Marker* marker = 0;
  64482. Component* const parent = component.getParentComponent();
  64483. if (parent != 0)
  64484. {
  64485. list = parent->getMarkers (true);
  64486. if (list != 0)
  64487. marker = list->getMarker (name);
  64488. if (marker == 0)
  64489. {
  64490. list = parent->getMarkers (false);
  64491. if (list != 0)
  64492. marker = list->getMarker (name);
  64493. }
  64494. }
  64495. return marker;
  64496. }
  64497. class RelativeCoordinatePositionerBase::DependencyFinderScope : public ComponentScope
  64498. {
  64499. public:
  64500. DependencyFinderScope (Component& component_, RelativeCoordinatePositionerBase& positioner_, bool& ok_)
  64501. : ComponentScope (component_), positioner (positioner_), ok (ok_)
  64502. {
  64503. }
  64504. const Expression getSymbolValue (const String& symbol) const
  64505. {
  64506. if (symbol == RelativeCoordinate::Strings::left || symbol == RelativeCoordinate::Strings::x
  64507. || symbol == RelativeCoordinate::Strings::width || symbol == RelativeCoordinate::Strings::right
  64508. || symbol == RelativeCoordinate::Strings::top || symbol == RelativeCoordinate::Strings::y
  64509. || symbol == RelativeCoordinate::Strings::height || symbol == RelativeCoordinate::Strings::bottom)
  64510. {
  64511. positioner.registerComponentListener (component);
  64512. }
  64513. else
  64514. {
  64515. MarkerList* list;
  64516. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64517. if (marker != 0)
  64518. {
  64519. positioner.registerMarkerListListener (list);
  64520. }
  64521. else
  64522. {
  64523. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64524. positioner.registerMarkerListListener (component.getMarkers (true));
  64525. positioner.registerMarkerListListener (component.getMarkers (false));
  64526. ok = false;
  64527. }
  64528. }
  64529. return ComponentScope::getSymbolValue (symbol);
  64530. }
  64531. void visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64532. {
  64533. Component* targetComp = 0;
  64534. if (scopeName == RelativeCoordinate::Strings::parent)
  64535. targetComp = component.getParentComponent();
  64536. else
  64537. targetComp = findSiblingComponent (scopeName);
  64538. if (targetComp != 0)
  64539. {
  64540. visitor.visit (DependencyFinderScope (*targetComp, positioner, ok));
  64541. }
  64542. else
  64543. {
  64544. // The named component doesn't exist, so we'll watch the parent for changes in case it appears later..
  64545. Component* const parent = component.getParentComponent();
  64546. if (parent != 0)
  64547. positioner.registerComponentListener (*parent);
  64548. positioner.registerComponentListener (component);
  64549. ok = false;
  64550. }
  64551. }
  64552. private:
  64553. RelativeCoordinatePositionerBase& positioner;
  64554. bool& ok;
  64555. JUCE_DECLARE_NON_COPYABLE (DependencyFinderScope);
  64556. };
  64557. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  64558. : Component::Positioner (component_), registeredOk (false)
  64559. {
  64560. }
  64561. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  64562. {
  64563. unregisterListeners();
  64564. }
  64565. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  64566. {
  64567. apply();
  64568. }
  64569. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  64570. {
  64571. apply();
  64572. }
  64573. void RelativeCoordinatePositionerBase::componentChildrenChanged (Component& changed)
  64574. {
  64575. if (getComponent().getParentComponent() == &changed && ! registeredOk)
  64576. apply();
  64577. }
  64578. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  64579. {
  64580. jassert (sourceComponents.contains (&component));
  64581. sourceComponents.removeValue (&component);
  64582. registeredOk = false;
  64583. }
  64584. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  64585. {
  64586. apply();
  64587. }
  64588. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  64589. {
  64590. jassert (sourceMarkerLists.contains (markerList));
  64591. sourceMarkerLists.removeValue (markerList);
  64592. }
  64593. void RelativeCoordinatePositionerBase::apply()
  64594. {
  64595. if (! registeredOk)
  64596. {
  64597. unregisterListeners();
  64598. registeredOk = registerCoordinates();
  64599. }
  64600. applyToComponentBounds();
  64601. }
  64602. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  64603. {
  64604. bool ok = true;
  64605. DependencyFinderScope finderScope (getComponent(), *this, ok);
  64606. coord.getExpression().evaluate (finderScope);
  64607. return ok;
  64608. }
  64609. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  64610. {
  64611. const bool ok = addCoordinate (point.x);
  64612. return addCoordinate (point.y) && ok;
  64613. }
  64614. void RelativeCoordinatePositionerBase::registerComponentListener (Component& comp)
  64615. {
  64616. if (! sourceComponents.contains (&comp))
  64617. {
  64618. comp.addComponentListener (this);
  64619. sourceComponents.add (&comp);
  64620. }
  64621. }
  64622. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  64623. {
  64624. if (list != 0 && ! sourceMarkerLists.contains (list))
  64625. {
  64626. list->addListener (this);
  64627. sourceMarkerLists.add (list);
  64628. }
  64629. }
  64630. void RelativeCoordinatePositionerBase::unregisterListeners()
  64631. {
  64632. int i;
  64633. for (i = sourceComponents.size(); --i >= 0;)
  64634. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  64635. for (i = sourceMarkerLists.size(); --i >= 0;)
  64636. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  64637. sourceComponents.clear();
  64638. sourceMarkerLists.clear();
  64639. }
  64640. END_JUCE_NAMESPACE
  64641. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64642. #endif
  64643. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64644. /*** Start of inlined file: juce_Colour.cpp ***/
  64645. BEGIN_JUCE_NAMESPACE
  64646. namespace ColourHelpers
  64647. {
  64648. uint8 floatAlphaToInt (const float alpha) throw()
  64649. {
  64650. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64651. }
  64652. void convertHSBtoRGB (float h, float s, float v,
  64653. uint8& r, uint8& g, uint8& b) throw()
  64654. {
  64655. v = jlimit (0.0f, 1.0f, v);
  64656. v *= 255.0f;
  64657. const uint8 intV = (uint8) roundToInt (v);
  64658. if (s <= 0)
  64659. {
  64660. r = intV;
  64661. g = intV;
  64662. b = intV;
  64663. }
  64664. else
  64665. {
  64666. s = jmin (1.0f, s);
  64667. h = jlimit (0.0f, 1.0f, h);
  64668. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64669. const float f = h - std::floor (h);
  64670. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64671. const float y = v * (1.0f - s * f);
  64672. const float z = v * (1.0f - (s * (1.0f - f)));
  64673. if (h < 1.0f)
  64674. {
  64675. r = intV;
  64676. g = (uint8) roundToInt (z);
  64677. b = x;
  64678. }
  64679. else if (h < 2.0f)
  64680. {
  64681. r = (uint8) roundToInt (y);
  64682. g = intV;
  64683. b = x;
  64684. }
  64685. else if (h < 3.0f)
  64686. {
  64687. r = x;
  64688. g = intV;
  64689. b = (uint8) roundToInt (z);
  64690. }
  64691. else if (h < 4.0f)
  64692. {
  64693. r = x;
  64694. g = (uint8) roundToInt (y);
  64695. b = intV;
  64696. }
  64697. else if (h < 5.0f)
  64698. {
  64699. r = (uint8) roundToInt (z);
  64700. g = x;
  64701. b = intV;
  64702. }
  64703. else if (h < 6.0f)
  64704. {
  64705. r = intV;
  64706. g = x;
  64707. b = (uint8) roundToInt (y);
  64708. }
  64709. else
  64710. {
  64711. r = 0;
  64712. g = 0;
  64713. b = 0;
  64714. }
  64715. }
  64716. }
  64717. }
  64718. Colour::Colour() throw()
  64719. : argb (0)
  64720. {
  64721. }
  64722. Colour::Colour (const Colour& other) throw()
  64723. : argb (other.argb)
  64724. {
  64725. }
  64726. Colour& Colour::operator= (const Colour& other) throw()
  64727. {
  64728. argb = other.argb;
  64729. return *this;
  64730. }
  64731. bool Colour::operator== (const Colour& other) const throw()
  64732. {
  64733. return argb.getARGB() == other.argb.getARGB();
  64734. }
  64735. bool Colour::operator!= (const Colour& other) const throw()
  64736. {
  64737. return argb.getARGB() != other.argb.getARGB();
  64738. }
  64739. Colour::Colour (const uint32 argb_) throw()
  64740. : argb (argb_)
  64741. {
  64742. }
  64743. Colour::Colour (const uint8 red,
  64744. const uint8 green,
  64745. const uint8 blue) throw()
  64746. {
  64747. argb.setARGB (0xff, red, green, blue);
  64748. }
  64749. const Colour Colour::fromRGB (const uint8 red,
  64750. const uint8 green,
  64751. const uint8 blue) throw()
  64752. {
  64753. return Colour (red, green, blue);
  64754. }
  64755. Colour::Colour (const uint8 red,
  64756. const uint8 green,
  64757. const uint8 blue,
  64758. const uint8 alpha) throw()
  64759. {
  64760. argb.setARGB (alpha, red, green, blue);
  64761. }
  64762. const Colour Colour::fromRGBA (const uint8 red,
  64763. const uint8 green,
  64764. const uint8 blue,
  64765. const uint8 alpha) throw()
  64766. {
  64767. return Colour (red, green, blue, alpha);
  64768. }
  64769. Colour::Colour (const uint8 red,
  64770. const uint8 green,
  64771. const uint8 blue,
  64772. const float alpha) throw()
  64773. {
  64774. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64775. }
  64776. const Colour Colour::fromRGBAFloat (const uint8 red,
  64777. const uint8 green,
  64778. const uint8 blue,
  64779. const float alpha) throw()
  64780. {
  64781. return Colour (red, green, blue, alpha);
  64782. }
  64783. Colour::Colour (const float hue,
  64784. const float saturation,
  64785. const float brightness,
  64786. const float alpha) throw()
  64787. {
  64788. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64789. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64790. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64791. }
  64792. const Colour Colour::fromHSV (const float hue,
  64793. const float saturation,
  64794. const float brightness,
  64795. const float alpha) throw()
  64796. {
  64797. return Colour (hue, saturation, brightness, alpha);
  64798. }
  64799. Colour::Colour (const float hue,
  64800. const float saturation,
  64801. const float brightness,
  64802. const uint8 alpha) throw()
  64803. {
  64804. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64805. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64806. argb.setARGB (alpha, r, g, b);
  64807. }
  64808. Colour::~Colour() throw()
  64809. {
  64810. }
  64811. const PixelARGB Colour::getPixelARGB() const throw()
  64812. {
  64813. PixelARGB p (argb);
  64814. p.premultiply();
  64815. return p;
  64816. }
  64817. uint32 Colour::getARGB() const throw()
  64818. {
  64819. return argb.getARGB();
  64820. }
  64821. bool Colour::isTransparent() const throw()
  64822. {
  64823. return getAlpha() == 0;
  64824. }
  64825. bool Colour::isOpaque() const throw()
  64826. {
  64827. return getAlpha() == 0xff;
  64828. }
  64829. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64830. {
  64831. PixelARGB newCol (argb);
  64832. newCol.setAlpha (newAlpha);
  64833. return Colour (newCol.getARGB());
  64834. }
  64835. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64836. {
  64837. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64838. PixelARGB newCol (argb);
  64839. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64840. return Colour (newCol.getARGB());
  64841. }
  64842. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64843. {
  64844. jassert (alphaMultiplier >= 0);
  64845. PixelARGB newCol (argb);
  64846. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64847. return Colour (newCol.getARGB());
  64848. }
  64849. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64850. {
  64851. const int destAlpha = getAlpha();
  64852. if (destAlpha > 0)
  64853. {
  64854. const int invA = 0xff - (int) src.getAlpha();
  64855. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64856. if (resA > 0)
  64857. {
  64858. const int da = (invA * destAlpha) / resA;
  64859. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64860. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64861. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64862. (uint8) resA);
  64863. }
  64864. return *this;
  64865. }
  64866. else
  64867. {
  64868. return src;
  64869. }
  64870. }
  64871. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64872. {
  64873. if (proportionOfOther <= 0)
  64874. return *this;
  64875. if (proportionOfOther >= 1.0f)
  64876. return other;
  64877. PixelARGB c1 (getPixelARGB());
  64878. const PixelARGB c2 (other.getPixelARGB());
  64879. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64880. c1.unpremultiply();
  64881. return Colour (c1.getARGB());
  64882. }
  64883. float Colour::getFloatRed() const throw()
  64884. {
  64885. return getRed() / 255.0f;
  64886. }
  64887. float Colour::getFloatGreen() const throw()
  64888. {
  64889. return getGreen() / 255.0f;
  64890. }
  64891. float Colour::getFloatBlue() const throw()
  64892. {
  64893. return getBlue() / 255.0f;
  64894. }
  64895. float Colour::getFloatAlpha() const throw()
  64896. {
  64897. return getAlpha() / 255.0f;
  64898. }
  64899. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64900. {
  64901. const int r = getRed();
  64902. const int g = getGreen();
  64903. const int b = getBlue();
  64904. const int hi = jmax (r, g, b);
  64905. const int lo = jmin (r, g, b);
  64906. if (hi != 0)
  64907. {
  64908. s = (hi - lo) / (float) hi;
  64909. if (s != 0)
  64910. {
  64911. const float invDiff = 1.0f / (hi - lo);
  64912. const float red = (hi - r) * invDiff;
  64913. const float green = (hi - g) * invDiff;
  64914. const float blue = (hi - b) * invDiff;
  64915. if (r == hi)
  64916. h = blue - green;
  64917. else if (g == hi)
  64918. h = 2.0f + red - blue;
  64919. else
  64920. h = 4.0f + green - red;
  64921. h *= 1.0f / 6.0f;
  64922. if (h < 0)
  64923. ++h;
  64924. }
  64925. else
  64926. {
  64927. h = 0;
  64928. }
  64929. }
  64930. else
  64931. {
  64932. s = 0;
  64933. h = 0;
  64934. }
  64935. v = hi / 255.0f;
  64936. }
  64937. float Colour::getHue() const throw()
  64938. {
  64939. float h, s, b;
  64940. getHSB (h, s, b);
  64941. return h;
  64942. }
  64943. const Colour Colour::withHue (const float hue) const throw()
  64944. {
  64945. float h, s, b;
  64946. getHSB (h, s, b);
  64947. return Colour (hue, s, b, getAlpha());
  64948. }
  64949. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64950. {
  64951. float h, s, b;
  64952. getHSB (h, s, b);
  64953. h += amountToRotate;
  64954. h -= std::floor (h);
  64955. return Colour (h, s, b, getAlpha());
  64956. }
  64957. float Colour::getSaturation() const throw()
  64958. {
  64959. float h, s, b;
  64960. getHSB (h, s, b);
  64961. return s;
  64962. }
  64963. const Colour Colour::withSaturation (const float saturation) const throw()
  64964. {
  64965. float h, s, b;
  64966. getHSB (h, s, b);
  64967. return Colour (h, saturation, b, getAlpha());
  64968. }
  64969. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64970. {
  64971. float h, s, b;
  64972. getHSB (h, s, b);
  64973. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64974. }
  64975. float Colour::getBrightness() const throw()
  64976. {
  64977. float h, s, b;
  64978. getHSB (h, s, b);
  64979. return b;
  64980. }
  64981. const Colour Colour::withBrightness (const float brightness) const throw()
  64982. {
  64983. float h, s, b;
  64984. getHSB (h, s, b);
  64985. return Colour (h, s, brightness, getAlpha());
  64986. }
  64987. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64988. {
  64989. float h, s, b;
  64990. getHSB (h, s, b);
  64991. b *= amount;
  64992. if (b > 1.0f)
  64993. b = 1.0f;
  64994. return Colour (h, s, b, getAlpha());
  64995. }
  64996. const Colour Colour::brighter (float amount) const throw()
  64997. {
  64998. amount = 1.0f / (1.0f + amount);
  64999. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65000. (uint8) (255 - (amount * (255 - getGreen()))),
  65001. (uint8) (255 - (amount * (255 - getBlue()))),
  65002. getAlpha());
  65003. }
  65004. const Colour Colour::darker (float amount) const throw()
  65005. {
  65006. amount = 1.0f / (1.0f + amount);
  65007. return Colour ((uint8) (amount * getRed()),
  65008. (uint8) (amount * getGreen()),
  65009. (uint8) (amount * getBlue()),
  65010. getAlpha());
  65011. }
  65012. const Colour Colour::greyLevel (const float brightness) throw()
  65013. {
  65014. const uint8 level
  65015. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65016. return Colour (level, level, level);
  65017. }
  65018. const Colour Colour::contrasting (const float amount) const throw()
  65019. {
  65020. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65021. ? Colours::black
  65022. : Colours::white).withAlpha (amount));
  65023. }
  65024. const Colour Colour::contrasting (const Colour& colour1,
  65025. const Colour& colour2) throw()
  65026. {
  65027. const float b1 = colour1.getBrightness();
  65028. const float b2 = colour2.getBrightness();
  65029. float best = 0.0f;
  65030. float bestDist = 0.0f;
  65031. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65032. {
  65033. const float d1 = std::abs (i - b1);
  65034. const float d2 = std::abs (i - b2);
  65035. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65036. if (dist > bestDist)
  65037. {
  65038. best = i;
  65039. bestDist = dist;
  65040. }
  65041. }
  65042. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65043. .withBrightness (best);
  65044. }
  65045. const String Colour::toString() const
  65046. {
  65047. return String::toHexString ((int) argb.getARGB());
  65048. }
  65049. const Colour Colour::fromString (const String& encodedColourString)
  65050. {
  65051. return Colour ((uint32) encodedColourString.getHexValue32());
  65052. }
  65053. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65054. {
  65055. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65056. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65057. .toUpperCase();
  65058. }
  65059. END_JUCE_NAMESPACE
  65060. /*** End of inlined file: juce_Colour.cpp ***/
  65061. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65062. BEGIN_JUCE_NAMESPACE
  65063. ColourGradient::ColourGradient() throw()
  65064. {
  65065. #if JUCE_DEBUG
  65066. point1.setX (987654.0f);
  65067. #endif
  65068. }
  65069. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65070. const Colour& colour2, const float x2_, const float y2_,
  65071. const bool isRadial_)
  65072. : point1 (x1_, y1_),
  65073. point2 (x2_, y2_),
  65074. isRadial (isRadial_)
  65075. {
  65076. colours.add (ColourPoint (0.0, colour1));
  65077. colours.add (ColourPoint (1.0, colour2));
  65078. }
  65079. ColourGradient::~ColourGradient()
  65080. {
  65081. }
  65082. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65083. {
  65084. return point1 == other.point1 && point2 == other.point2
  65085. && isRadial == other.isRadial
  65086. && colours == other.colours;
  65087. }
  65088. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65089. {
  65090. return ! operator== (other);
  65091. }
  65092. void ColourGradient::clearColours()
  65093. {
  65094. colours.clear();
  65095. }
  65096. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65097. {
  65098. // must be within the two end-points
  65099. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65100. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65101. int i;
  65102. for (i = 0; i < colours.size(); ++i)
  65103. if (colours.getReference(i).position > pos)
  65104. break;
  65105. colours.insert (i, ColourPoint (pos, colour));
  65106. return i;
  65107. }
  65108. void ColourGradient::removeColour (int index)
  65109. {
  65110. jassert (index > 0 && index < colours.size() - 1);
  65111. colours.remove (index);
  65112. }
  65113. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65114. {
  65115. for (int i = 0; i < colours.size(); ++i)
  65116. {
  65117. Colour& c = colours.getReference(i).colour;
  65118. c = c.withMultipliedAlpha (multiplier);
  65119. }
  65120. }
  65121. int ColourGradient::getNumColours() const throw()
  65122. {
  65123. return colours.size();
  65124. }
  65125. double ColourGradient::getColourPosition (const int index) const throw()
  65126. {
  65127. if (isPositiveAndBelow (index, colours.size()))
  65128. return colours.getReference (index).position;
  65129. return 0;
  65130. }
  65131. const Colour ColourGradient::getColour (const int index) const throw()
  65132. {
  65133. if (isPositiveAndBelow (index, colours.size()))
  65134. return colours.getReference (index).colour;
  65135. return Colour();
  65136. }
  65137. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65138. {
  65139. if (isPositiveAndBelow (index, colours.size()))
  65140. colours.getReference (index).colour = newColour;
  65141. }
  65142. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65143. {
  65144. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65145. if (position <= 0 || colours.size() <= 1)
  65146. return colours.getReference(0).colour;
  65147. int i = colours.size() - 1;
  65148. while (position < colours.getReference(i).position)
  65149. --i;
  65150. const ColourPoint& p1 = colours.getReference (i);
  65151. if (i >= colours.size() - 1)
  65152. return p1.colour;
  65153. const ColourPoint& p2 = colours.getReference (i + 1);
  65154. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65155. }
  65156. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65157. {
  65158. #if JUCE_DEBUG
  65159. // trying to use the object without setting its co-ordinates? Have a careful read of
  65160. // the comments for the constructors.
  65161. jassert (point1.getX() != 987654.0f);
  65162. #endif
  65163. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65164. 3 * (int) point1.transformedBy (transform)
  65165. .getDistanceFrom (point2.transformedBy (transform)));
  65166. lookupTable.malloc (numEntries);
  65167. if (colours.size() >= 2)
  65168. {
  65169. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65170. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65171. int index = 0;
  65172. for (int j = 1; j < colours.size(); ++j)
  65173. {
  65174. const ColourPoint& p = colours.getReference (j);
  65175. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65176. const PixelARGB pix2 (p.colour.getPixelARGB());
  65177. for (int i = 0; i < numToDo; ++i)
  65178. {
  65179. jassert (index >= 0 && index < numEntries);
  65180. lookupTable[index] = pix1;
  65181. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65182. ++index;
  65183. }
  65184. pix1 = pix2;
  65185. }
  65186. while (index < numEntries)
  65187. lookupTable [index++] = pix1;
  65188. }
  65189. else
  65190. {
  65191. jassertfalse; // no colours specified!
  65192. }
  65193. return numEntries;
  65194. }
  65195. bool ColourGradient::isOpaque() const throw()
  65196. {
  65197. for (int i = 0; i < colours.size(); ++i)
  65198. if (! colours.getReference(i).colour.isOpaque())
  65199. return false;
  65200. return true;
  65201. }
  65202. bool ColourGradient::isInvisible() const throw()
  65203. {
  65204. for (int i = 0; i < colours.size(); ++i)
  65205. if (! colours.getReference(i).colour.isTransparent())
  65206. return false;
  65207. return true;
  65208. }
  65209. END_JUCE_NAMESPACE
  65210. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65211. /*** Start of inlined file: juce_Colours.cpp ***/
  65212. BEGIN_JUCE_NAMESPACE
  65213. const Colour Colours::transparentBlack (0);
  65214. const Colour Colours::transparentWhite (0x00ffffff);
  65215. const Colour Colours::aliceblue (0xfff0f8ff);
  65216. const Colour Colours::antiquewhite (0xfffaebd7);
  65217. const Colour Colours::aqua (0xff00ffff);
  65218. const Colour Colours::aquamarine (0xff7fffd4);
  65219. const Colour Colours::azure (0xfff0ffff);
  65220. const Colour Colours::beige (0xfff5f5dc);
  65221. const Colour Colours::bisque (0xffffe4c4);
  65222. const Colour Colours::black (0xff000000);
  65223. const Colour Colours::blanchedalmond (0xffffebcd);
  65224. const Colour Colours::blue (0xff0000ff);
  65225. const Colour Colours::blueviolet (0xff8a2be2);
  65226. const Colour Colours::brown (0xffa52a2a);
  65227. const Colour Colours::burlywood (0xffdeb887);
  65228. const Colour Colours::cadetblue (0xff5f9ea0);
  65229. const Colour Colours::chartreuse (0xff7fff00);
  65230. const Colour Colours::chocolate (0xffd2691e);
  65231. const Colour Colours::coral (0xffff7f50);
  65232. const Colour Colours::cornflowerblue (0xff6495ed);
  65233. const Colour Colours::cornsilk (0xfffff8dc);
  65234. const Colour Colours::crimson (0xffdc143c);
  65235. const Colour Colours::cyan (0xff00ffff);
  65236. const Colour Colours::darkblue (0xff00008b);
  65237. const Colour Colours::darkcyan (0xff008b8b);
  65238. const Colour Colours::darkgoldenrod (0xffb8860b);
  65239. const Colour Colours::darkgrey (0xff555555);
  65240. const Colour Colours::darkgreen (0xff006400);
  65241. const Colour Colours::darkkhaki (0xffbdb76b);
  65242. const Colour Colours::darkmagenta (0xff8b008b);
  65243. const Colour Colours::darkolivegreen (0xff556b2f);
  65244. const Colour Colours::darkorange (0xffff8c00);
  65245. const Colour Colours::darkorchid (0xff9932cc);
  65246. const Colour Colours::darkred (0xff8b0000);
  65247. const Colour Colours::darksalmon (0xffe9967a);
  65248. const Colour Colours::darkseagreen (0xff8fbc8f);
  65249. const Colour Colours::darkslateblue (0xff483d8b);
  65250. const Colour Colours::darkslategrey (0xff2f4f4f);
  65251. const Colour Colours::darkturquoise (0xff00ced1);
  65252. const Colour Colours::darkviolet (0xff9400d3);
  65253. const Colour Colours::deeppink (0xffff1493);
  65254. const Colour Colours::deepskyblue (0xff00bfff);
  65255. const Colour Colours::dimgrey (0xff696969);
  65256. const Colour Colours::dodgerblue (0xff1e90ff);
  65257. const Colour Colours::firebrick (0xffb22222);
  65258. const Colour Colours::floralwhite (0xfffffaf0);
  65259. const Colour Colours::forestgreen (0xff228b22);
  65260. const Colour Colours::fuchsia (0xffff00ff);
  65261. const Colour Colours::gainsboro (0xffdcdcdc);
  65262. const Colour Colours::gold (0xffffd700);
  65263. const Colour Colours::goldenrod (0xffdaa520);
  65264. const Colour Colours::grey (0xff808080);
  65265. const Colour Colours::green (0xff008000);
  65266. const Colour Colours::greenyellow (0xffadff2f);
  65267. const Colour Colours::honeydew (0xfff0fff0);
  65268. const Colour Colours::hotpink (0xffff69b4);
  65269. const Colour Colours::indianred (0xffcd5c5c);
  65270. const Colour Colours::indigo (0xff4b0082);
  65271. const Colour Colours::ivory (0xfffffff0);
  65272. const Colour Colours::khaki (0xfff0e68c);
  65273. const Colour Colours::lavender (0xffe6e6fa);
  65274. const Colour Colours::lavenderblush (0xfffff0f5);
  65275. const Colour Colours::lemonchiffon (0xfffffacd);
  65276. const Colour Colours::lightblue (0xffadd8e6);
  65277. const Colour Colours::lightcoral (0xfff08080);
  65278. const Colour Colours::lightcyan (0xffe0ffff);
  65279. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65280. const Colour Colours::lightgreen (0xff90ee90);
  65281. const Colour Colours::lightgrey (0xffd3d3d3);
  65282. const Colour Colours::lightpink (0xffffb6c1);
  65283. const Colour Colours::lightsalmon (0xffffa07a);
  65284. const Colour Colours::lightseagreen (0xff20b2aa);
  65285. const Colour Colours::lightskyblue (0xff87cefa);
  65286. const Colour Colours::lightslategrey (0xff778899);
  65287. const Colour Colours::lightsteelblue (0xffb0c4de);
  65288. const Colour Colours::lightyellow (0xffffffe0);
  65289. const Colour Colours::lime (0xff00ff00);
  65290. const Colour Colours::limegreen (0xff32cd32);
  65291. const Colour Colours::linen (0xfffaf0e6);
  65292. const Colour Colours::magenta (0xffff00ff);
  65293. const Colour Colours::maroon (0xff800000);
  65294. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65295. const Colour Colours::mediumblue (0xff0000cd);
  65296. const Colour Colours::mediumorchid (0xffba55d3);
  65297. const Colour Colours::mediumpurple (0xff9370db);
  65298. const Colour Colours::mediumseagreen (0xff3cb371);
  65299. const Colour Colours::mediumslateblue (0xff7b68ee);
  65300. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65301. const Colour Colours::mediumturquoise (0xff48d1cc);
  65302. const Colour Colours::mediumvioletred (0xffc71585);
  65303. const Colour Colours::midnightblue (0xff191970);
  65304. const Colour Colours::mintcream (0xfff5fffa);
  65305. const Colour Colours::mistyrose (0xffffe4e1);
  65306. const Colour Colours::navajowhite (0xffffdead);
  65307. const Colour Colours::navy (0xff000080);
  65308. const Colour Colours::oldlace (0xfffdf5e6);
  65309. const Colour Colours::olive (0xff808000);
  65310. const Colour Colours::olivedrab (0xff6b8e23);
  65311. const Colour Colours::orange (0xffffa500);
  65312. const Colour Colours::orangered (0xffff4500);
  65313. const Colour Colours::orchid (0xffda70d6);
  65314. const Colour Colours::palegoldenrod (0xffeee8aa);
  65315. const Colour Colours::palegreen (0xff98fb98);
  65316. const Colour Colours::paleturquoise (0xffafeeee);
  65317. const Colour Colours::palevioletred (0xffdb7093);
  65318. const Colour Colours::papayawhip (0xffffefd5);
  65319. const Colour Colours::peachpuff (0xffffdab9);
  65320. const Colour Colours::peru (0xffcd853f);
  65321. const Colour Colours::pink (0xffffc0cb);
  65322. const Colour Colours::plum (0xffdda0dd);
  65323. const Colour Colours::powderblue (0xffb0e0e6);
  65324. const Colour Colours::purple (0xff800080);
  65325. const Colour Colours::red (0xffff0000);
  65326. const Colour Colours::rosybrown (0xffbc8f8f);
  65327. const Colour Colours::royalblue (0xff4169e1);
  65328. const Colour Colours::saddlebrown (0xff8b4513);
  65329. const Colour Colours::salmon (0xfffa8072);
  65330. const Colour Colours::sandybrown (0xfff4a460);
  65331. const Colour Colours::seagreen (0xff2e8b57);
  65332. const Colour Colours::seashell (0xfffff5ee);
  65333. const Colour Colours::sienna (0xffa0522d);
  65334. const Colour Colours::silver (0xffc0c0c0);
  65335. const Colour Colours::skyblue (0xff87ceeb);
  65336. const Colour Colours::slateblue (0xff6a5acd);
  65337. const Colour Colours::slategrey (0xff708090);
  65338. const Colour Colours::snow (0xfffffafa);
  65339. const Colour Colours::springgreen (0xff00ff7f);
  65340. const Colour Colours::steelblue (0xff4682b4);
  65341. const Colour Colours::tan (0xffd2b48c);
  65342. const Colour Colours::teal (0xff008080);
  65343. const Colour Colours::thistle (0xffd8bfd8);
  65344. const Colour Colours::tomato (0xffff6347);
  65345. const Colour Colours::turquoise (0xff40e0d0);
  65346. const Colour Colours::violet (0xffee82ee);
  65347. const Colour Colours::wheat (0xfff5deb3);
  65348. const Colour Colours::white (0xffffffff);
  65349. const Colour Colours::whitesmoke (0xfff5f5f5);
  65350. const Colour Colours::yellow (0xffffff00);
  65351. const Colour Colours::yellowgreen (0xff9acd32);
  65352. const Colour Colours::findColourForName (const String& colourName,
  65353. const Colour& defaultColour)
  65354. {
  65355. static const int presets[] =
  65356. {
  65357. // (first value is the string's hashcode, second is ARGB)
  65358. 0x05978fff, 0xff000000, /* black */
  65359. 0x06bdcc29, 0xffffffff, /* white */
  65360. 0x002e305a, 0xff0000ff, /* blue */
  65361. 0x00308adf, 0xff808080, /* grey */
  65362. 0x05e0cf03, 0xff008000, /* green */
  65363. 0x0001b891, 0xffff0000, /* red */
  65364. 0xd43c6474, 0xffffff00, /* yellow */
  65365. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65366. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65367. 0x002dcebc, 0xff00ffff, /* aqua */
  65368. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65369. 0x0590228f, 0xfff0ffff, /* azure */
  65370. 0x05947fe4, 0xfff5f5dc, /* beige */
  65371. 0xad388e35, 0xffffe4c4, /* bisque */
  65372. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65373. 0x39129959, 0xff8a2be2, /* blueviolet */
  65374. 0x059a8136, 0xffa52a2a, /* brown */
  65375. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65376. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65377. 0x6b748956, 0xff7fff00, /* chartreuse */
  65378. 0x2903623c, 0xffd2691e, /* chocolate */
  65379. 0x05a74431, 0xffff7f50, /* coral */
  65380. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65381. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65382. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65383. 0x002ed323, 0xff00ffff, /* cyan */
  65384. 0x67cc74d0, 0xff00008b, /* darkblue */
  65385. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65386. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65387. 0x67cecf55, 0xff555555, /* darkgrey */
  65388. 0x920b194d, 0xff006400, /* darkgreen */
  65389. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65390. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65391. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65392. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65393. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65394. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65395. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65396. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65397. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65398. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65399. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65400. 0xc8769375, 0xff9400d3, /* darkviolet */
  65401. 0x25832862, 0xffff1493, /* deeppink */
  65402. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65403. 0x634c8b67, 0xff696969, /* dimgrey */
  65404. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65405. 0xef19e3cb, 0xffb22222, /* firebrick */
  65406. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65407. 0xd086fd06, 0xff228b22, /* forestgreen */
  65408. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65409. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65410. 0x00308060, 0xffffd700, /* gold */
  65411. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65412. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65413. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65414. 0x41892743, 0xffff69b4, /* hotpink */
  65415. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65416. 0xb969fed2, 0xff4b0082, /* indigo */
  65417. 0x05fef6a9, 0xfffffff0, /* ivory */
  65418. 0x06149302, 0xfff0e68c, /* khaki */
  65419. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65420. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65421. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65422. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65423. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65424. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65425. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65426. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65427. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65428. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65429. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65430. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65431. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65432. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65433. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65434. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65435. 0x0032afd5, 0xff00ff00, /* lime */
  65436. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65437. 0x06234efa, 0xfffaf0e6, /* linen */
  65438. 0x316858a9, 0xffff00ff, /* magenta */
  65439. 0xbf8ca470, 0xff800000, /* maroon */
  65440. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65441. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65442. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65443. 0x07556b71, 0xff9370db, /* mediumpurple */
  65444. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65445. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65446. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65447. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65448. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65449. 0x168eb32a, 0xff191970, /* midnightblue */
  65450. 0x4306b960, 0xfff5fffa, /* mintcream */
  65451. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65452. 0xe97218a6, 0xffffdead, /* navajowhite */
  65453. 0x00337bb6, 0xff000080, /* navy */
  65454. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65455. 0x064ee1db, 0xff808000, /* olive */
  65456. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65457. 0xc3de262e, 0xffffa500, /* orange */
  65458. 0x58bebba3, 0xffff4500, /* orangered */
  65459. 0xc3def8a3, 0xffda70d6, /* orchid */
  65460. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65461. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65462. 0x74022737, 0xffafeeee, /* paleturquoise */
  65463. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65464. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65465. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65466. 0x003472f8, 0xffcd853f, /* peru */
  65467. 0x00348176, 0xffffc0cb, /* pink */
  65468. 0x00348d94, 0xffdda0dd, /* plum */
  65469. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65470. 0xc5c507bc, 0xff800080, /* purple */
  65471. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65472. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65473. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65474. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65475. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65476. 0x34636c14, 0xff2e8b57, /* seagreen */
  65477. 0x3507fb41, 0xfffff5ee, /* seashell */
  65478. 0xca348772, 0xffa0522d, /* sienna */
  65479. 0xca37d30d, 0xffc0c0c0, /* silver */
  65480. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65481. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65482. 0x44ab37f8, 0xff708090, /* slategrey */
  65483. 0x0035f183, 0xfffffafa, /* snow */
  65484. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65485. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65486. 0x0001bfa1, 0xffd2b48c, /* tan */
  65487. 0x0036425c, 0xff008080, /* teal */
  65488. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65489. 0xcc41600a, 0xffff6347, /* tomato */
  65490. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65491. 0xcf57947f, 0xffee82ee, /* violet */
  65492. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65493. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65494. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65495. };
  65496. const int hash = colourName.trim().toLowerCase().hashCode();
  65497. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65498. if (presets [i] == hash)
  65499. return Colour (presets [i + 1]);
  65500. return defaultColour;
  65501. }
  65502. END_JUCE_NAMESPACE
  65503. /*** End of inlined file: juce_Colours.cpp ***/
  65504. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65505. BEGIN_JUCE_NAMESPACE
  65506. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65507. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65508. const Path& path, const AffineTransform& transform)
  65509. : bounds (bounds_),
  65510. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65511. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65512. needToCheckEmptinesss (true)
  65513. {
  65514. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65515. int* t = table;
  65516. for (int i = bounds.getHeight(); --i >= 0;)
  65517. {
  65518. *t = 0;
  65519. t += lineStrideElements;
  65520. }
  65521. const int topLimit = bounds.getY() << 8;
  65522. const int heightLimit = bounds.getHeight() << 8;
  65523. const int leftLimit = bounds.getX() << 8;
  65524. const int rightLimit = bounds.getRight() << 8;
  65525. PathFlatteningIterator iter (path, transform);
  65526. while (iter.next())
  65527. {
  65528. int y1 = roundToInt (iter.y1 * 256.0f);
  65529. int y2 = roundToInt (iter.y2 * 256.0f);
  65530. if (y1 != y2)
  65531. {
  65532. y1 -= topLimit;
  65533. y2 -= topLimit;
  65534. const int startY = y1;
  65535. int direction = -1;
  65536. if (y1 > y2)
  65537. {
  65538. swapVariables (y1, y2);
  65539. direction = 1;
  65540. }
  65541. if (y1 < 0)
  65542. y1 = 0;
  65543. if (y2 > heightLimit)
  65544. y2 = heightLimit;
  65545. if (y1 < y2)
  65546. {
  65547. const double startX = 256.0f * iter.x1;
  65548. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65549. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65550. do
  65551. {
  65552. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65553. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65554. if (x < leftLimit)
  65555. x = leftLimit;
  65556. else if (x >= rightLimit)
  65557. x = rightLimit - 1;
  65558. addEdgePoint (x, y1 >> 8, direction * step);
  65559. y1 += step;
  65560. }
  65561. while (y1 < y2);
  65562. }
  65563. }
  65564. }
  65565. sanitiseLevels (path.isUsingNonZeroWinding());
  65566. }
  65567. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65568. : bounds (rectangleToAdd),
  65569. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65570. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65571. needToCheckEmptinesss (true)
  65572. {
  65573. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65574. table[0] = 0;
  65575. const int x1 = rectangleToAdd.getX() << 8;
  65576. const int x2 = rectangleToAdd.getRight() << 8;
  65577. int* t = table;
  65578. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65579. {
  65580. t[0] = 2;
  65581. t[1] = x1;
  65582. t[2] = 255;
  65583. t[3] = x2;
  65584. t[4] = 0;
  65585. t += lineStrideElements;
  65586. }
  65587. }
  65588. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65589. : bounds (rectanglesToAdd.getBounds()),
  65590. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65591. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65592. needToCheckEmptinesss (true)
  65593. {
  65594. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65595. int* t = table;
  65596. for (int i = bounds.getHeight(); --i >= 0;)
  65597. {
  65598. *t = 0;
  65599. t += lineStrideElements;
  65600. }
  65601. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65602. {
  65603. const Rectangle<int>* const r = iter.getRectangle();
  65604. const int x1 = r->getX() << 8;
  65605. const int x2 = r->getRight() << 8;
  65606. int y = r->getY() - bounds.getY();
  65607. for (int j = r->getHeight(); --j >= 0;)
  65608. {
  65609. addEdgePoint (x1, y, 255);
  65610. addEdgePoint (x2, y, -255);
  65611. ++y;
  65612. }
  65613. }
  65614. sanitiseLevels (true);
  65615. }
  65616. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65617. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65618. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65619. 2 + (int) rectangleToAdd.getWidth(),
  65620. 2 + (int) rectangleToAdd.getHeight())),
  65621. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65622. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65623. needToCheckEmptinesss (true)
  65624. {
  65625. jassert (! rectangleToAdd.isEmpty());
  65626. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65627. table[0] = 0;
  65628. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65629. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65630. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65631. jassert (y1 < 256);
  65632. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65633. if (x2 <= x1 || y2 <= y1)
  65634. {
  65635. bounds.setHeight (0);
  65636. return;
  65637. }
  65638. int lineY = 0;
  65639. int* t = table;
  65640. if ((y1 >> 8) == (y2 >> 8))
  65641. {
  65642. t[0] = 2;
  65643. t[1] = x1;
  65644. t[2] = y2 - y1;
  65645. t[3] = x2;
  65646. t[4] = 0;
  65647. ++lineY;
  65648. t += lineStrideElements;
  65649. }
  65650. else
  65651. {
  65652. t[0] = 2;
  65653. t[1] = x1;
  65654. t[2] = 255 - (y1 & 255);
  65655. t[3] = x2;
  65656. t[4] = 0;
  65657. ++lineY;
  65658. t += lineStrideElements;
  65659. while (lineY < (y2 >> 8))
  65660. {
  65661. t[0] = 2;
  65662. t[1] = x1;
  65663. t[2] = 255;
  65664. t[3] = x2;
  65665. t[4] = 0;
  65666. ++lineY;
  65667. t += lineStrideElements;
  65668. }
  65669. jassert (lineY < bounds.getHeight());
  65670. t[0] = 2;
  65671. t[1] = x1;
  65672. t[2] = y2 & 255;
  65673. t[3] = x2;
  65674. t[4] = 0;
  65675. ++lineY;
  65676. t += lineStrideElements;
  65677. }
  65678. while (lineY < bounds.getHeight())
  65679. {
  65680. t[0] = 0;
  65681. t += lineStrideElements;
  65682. ++lineY;
  65683. }
  65684. }
  65685. EdgeTable::EdgeTable (const EdgeTable& other)
  65686. {
  65687. operator= (other);
  65688. }
  65689. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65690. {
  65691. bounds = other.bounds;
  65692. maxEdgesPerLine = other.maxEdgesPerLine;
  65693. lineStrideElements = other.lineStrideElements;
  65694. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65695. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65696. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65697. return *this;
  65698. }
  65699. EdgeTable::~EdgeTable()
  65700. {
  65701. }
  65702. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65703. {
  65704. while (--numLines >= 0)
  65705. {
  65706. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65707. src += srcLineStride;
  65708. dest += destLineStride;
  65709. }
  65710. }
  65711. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65712. {
  65713. // Convert the table from relative windings to absolute levels..
  65714. int* lineStart = table;
  65715. for (int i = bounds.getHeight(); --i >= 0;)
  65716. {
  65717. int* line = lineStart;
  65718. lineStart += lineStrideElements;
  65719. int num = *line;
  65720. if (num == 0)
  65721. continue;
  65722. int level = 0;
  65723. if (useNonZeroWinding)
  65724. {
  65725. while (--num > 0)
  65726. {
  65727. line += 2;
  65728. level += *line;
  65729. int corrected = abs (level);
  65730. if (corrected >> 8)
  65731. corrected = 255;
  65732. *line = corrected;
  65733. }
  65734. }
  65735. else
  65736. {
  65737. while (--num > 0)
  65738. {
  65739. line += 2;
  65740. level += *line;
  65741. int corrected = abs (level);
  65742. if (corrected >> 8)
  65743. {
  65744. corrected &= 511;
  65745. if (corrected >> 8)
  65746. corrected = 511 - corrected;
  65747. }
  65748. *line = corrected;
  65749. }
  65750. }
  65751. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65752. }
  65753. }
  65754. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65755. {
  65756. if (newNumEdgesPerLine != maxEdgesPerLine)
  65757. {
  65758. maxEdgesPerLine = newNumEdgesPerLine;
  65759. jassert (bounds.getHeight() > 0);
  65760. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65761. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65762. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65763. table.swapWith (newTable);
  65764. lineStrideElements = newLineStrideElements;
  65765. }
  65766. }
  65767. void EdgeTable::optimiseTable()
  65768. {
  65769. int maxLineElements = 0;
  65770. for (int i = bounds.getHeight(); --i >= 0;)
  65771. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65772. remapTableForNumEdges (maxLineElements);
  65773. }
  65774. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65775. {
  65776. jassert (y >= 0 && y < bounds.getHeight());
  65777. int* line = table + lineStrideElements * y;
  65778. const int numPoints = line[0];
  65779. int n = numPoints << 1;
  65780. if (n > 0)
  65781. {
  65782. while (n > 0)
  65783. {
  65784. const int cx = line [n - 1];
  65785. if (cx <= x)
  65786. {
  65787. if (cx == x)
  65788. {
  65789. line [n] += winding;
  65790. return;
  65791. }
  65792. break;
  65793. }
  65794. n -= 2;
  65795. }
  65796. if (numPoints >= maxEdgesPerLine)
  65797. {
  65798. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65799. jassert (numPoints < maxEdgesPerLine);
  65800. line = table + lineStrideElements * y;
  65801. }
  65802. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65803. }
  65804. line [n + 1] = x;
  65805. line [n + 2] = winding;
  65806. line[0]++;
  65807. }
  65808. void EdgeTable::translate (float dx, const int dy) throw()
  65809. {
  65810. bounds.translate ((int) std::floor (dx), dy);
  65811. int* lineStart = table;
  65812. const int intDx = (int) (dx * 256.0f);
  65813. for (int i = bounds.getHeight(); --i >= 0;)
  65814. {
  65815. int* line = lineStart;
  65816. lineStart += lineStrideElements;
  65817. int num = *line++;
  65818. while (--num >= 0)
  65819. {
  65820. *line += intDx;
  65821. line += 2;
  65822. }
  65823. }
  65824. }
  65825. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65826. {
  65827. jassert (y >= 0 && y < bounds.getHeight());
  65828. int* dest = table + lineStrideElements * y;
  65829. if (dest[0] == 0)
  65830. return;
  65831. int otherNumPoints = *otherLine;
  65832. if (otherNumPoints == 0)
  65833. {
  65834. *dest = 0;
  65835. return;
  65836. }
  65837. const int right = bounds.getRight() << 8;
  65838. // optimise for the common case where our line lies entirely within a
  65839. // single pair of points, as happens when clipping to a simple rect.
  65840. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65841. {
  65842. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65843. return;
  65844. }
  65845. ++otherLine;
  65846. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65847. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65848. memcpy (temp, dest, lineSizeBytes);
  65849. const int* src1 = temp;
  65850. int srcNum1 = *src1++;
  65851. int x1 = *src1++;
  65852. const int* src2 = otherLine;
  65853. int srcNum2 = otherNumPoints;
  65854. int x2 = *src2++;
  65855. int destIndex = 0, destTotal = 0;
  65856. int level1 = 0, level2 = 0;
  65857. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65858. while (srcNum1 > 0 && srcNum2 > 0)
  65859. {
  65860. int nextX;
  65861. if (x1 < x2)
  65862. {
  65863. nextX = x1;
  65864. level1 = *src1++;
  65865. x1 = *src1++;
  65866. --srcNum1;
  65867. }
  65868. else if (x1 == x2)
  65869. {
  65870. nextX = x1;
  65871. level1 = *src1++;
  65872. level2 = *src2++;
  65873. x1 = *src1++;
  65874. x2 = *src2++;
  65875. --srcNum1;
  65876. --srcNum2;
  65877. }
  65878. else
  65879. {
  65880. nextX = x2;
  65881. level2 = *src2++;
  65882. x2 = *src2++;
  65883. --srcNum2;
  65884. }
  65885. if (nextX > lastX)
  65886. {
  65887. if (nextX >= right)
  65888. break;
  65889. lastX = nextX;
  65890. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65891. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  65892. if (nextLevel != lastLevel)
  65893. {
  65894. if (destTotal >= maxEdgesPerLine)
  65895. {
  65896. dest[0] = destTotal;
  65897. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65898. dest = table + lineStrideElements * y;
  65899. }
  65900. ++destTotal;
  65901. lastLevel = nextLevel;
  65902. dest[++destIndex] = nextX;
  65903. dest[++destIndex] = nextLevel;
  65904. }
  65905. }
  65906. }
  65907. if (lastLevel > 0)
  65908. {
  65909. if (destTotal >= maxEdgesPerLine)
  65910. {
  65911. dest[0] = destTotal;
  65912. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65913. dest = table + lineStrideElements * y;
  65914. }
  65915. ++destTotal;
  65916. dest[++destIndex] = right;
  65917. dest[++destIndex] = 0;
  65918. }
  65919. dest[0] = destTotal;
  65920. #if JUCE_DEBUG
  65921. int last = std::numeric_limits<int>::min();
  65922. for (int i = 0; i < dest[0]; ++i)
  65923. {
  65924. jassert (dest[i * 2 + 1] > last);
  65925. last = dest[i * 2 + 1];
  65926. }
  65927. jassert (dest [dest[0] * 2] == 0);
  65928. #endif
  65929. }
  65930. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65931. {
  65932. int* lastItem = dest + (dest[0] * 2 - 1);
  65933. if (x2 < lastItem[0])
  65934. {
  65935. if (x2 <= dest[1])
  65936. {
  65937. dest[0] = 0;
  65938. return;
  65939. }
  65940. while (x2 < lastItem[-2])
  65941. {
  65942. --(dest[0]);
  65943. lastItem -= 2;
  65944. }
  65945. lastItem[0] = x2;
  65946. lastItem[1] = 0;
  65947. }
  65948. if (x1 > dest[1])
  65949. {
  65950. while (lastItem[0] > x1)
  65951. lastItem -= 2;
  65952. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65953. if (itemsRemoved > 0)
  65954. {
  65955. dest[0] -= itemsRemoved;
  65956. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65957. }
  65958. dest[1] = x1;
  65959. }
  65960. }
  65961. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  65962. {
  65963. const Rectangle<int> clipped (r.getIntersection (bounds));
  65964. if (clipped.isEmpty())
  65965. {
  65966. needToCheckEmptinesss = false;
  65967. bounds.setHeight (0);
  65968. }
  65969. else
  65970. {
  65971. const int top = clipped.getY() - bounds.getY();
  65972. const int bottom = clipped.getBottom() - bounds.getY();
  65973. if (bottom < bounds.getHeight())
  65974. bounds.setHeight (bottom);
  65975. if (clipped.getRight() < bounds.getRight())
  65976. bounds.setRight (clipped.getRight());
  65977. for (int i = top; --i >= 0;)
  65978. table [lineStrideElements * i] = 0;
  65979. if (clipped.getX() > bounds.getX())
  65980. {
  65981. const int x1 = clipped.getX() << 8;
  65982. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65983. int* line = table + lineStrideElements * top;
  65984. for (int i = bottom - top; --i >= 0;)
  65985. {
  65986. if (line[0] != 0)
  65987. clipEdgeTableLineToRange (line, x1, x2);
  65988. line += lineStrideElements;
  65989. }
  65990. }
  65991. needToCheckEmptinesss = true;
  65992. }
  65993. }
  65994. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  65995. {
  65996. const Rectangle<int> clipped (r.getIntersection (bounds));
  65997. if (! clipped.isEmpty())
  65998. {
  65999. const int top = clipped.getY() - bounds.getY();
  66000. const int bottom = clipped.getBottom() - bounds.getY();
  66001. //XXX optimise here by shortening the table if it fills top or bottom
  66002. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66003. clipped.getX() << 8, 0,
  66004. clipped.getRight() << 8, 255,
  66005. std::numeric_limits<int>::max(), 0 };
  66006. for (int i = top; i < bottom; ++i)
  66007. intersectWithEdgeTableLine (i, rectLine);
  66008. needToCheckEmptinesss = true;
  66009. }
  66010. }
  66011. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66012. {
  66013. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66014. if (clipped.isEmpty())
  66015. {
  66016. needToCheckEmptinesss = false;
  66017. bounds.setHeight (0);
  66018. }
  66019. else
  66020. {
  66021. const int top = clipped.getY() - bounds.getY();
  66022. const int bottom = clipped.getBottom() - bounds.getY();
  66023. if (bottom < bounds.getHeight())
  66024. bounds.setHeight (bottom);
  66025. if (clipped.getRight() < bounds.getRight())
  66026. bounds.setRight (clipped.getRight());
  66027. int i = 0;
  66028. for (i = top; --i >= 0;)
  66029. table [lineStrideElements * i] = 0;
  66030. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66031. for (i = top; i < bottom; ++i)
  66032. {
  66033. intersectWithEdgeTableLine (i, otherLine);
  66034. otherLine += other.lineStrideElements;
  66035. }
  66036. needToCheckEmptinesss = true;
  66037. }
  66038. }
  66039. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66040. {
  66041. y -= bounds.getY();
  66042. if (y < 0 || y >= bounds.getHeight())
  66043. return;
  66044. needToCheckEmptinesss = true;
  66045. if (numPixels <= 0)
  66046. {
  66047. table [lineStrideElements * y] = 0;
  66048. return;
  66049. }
  66050. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66051. int destIndex = 0, lastLevel = 0;
  66052. while (--numPixels >= 0)
  66053. {
  66054. const int alpha = *mask;
  66055. mask += maskStride;
  66056. if (alpha != lastLevel)
  66057. {
  66058. tempLine[++destIndex] = (x << 8);
  66059. tempLine[++destIndex] = alpha;
  66060. lastLevel = alpha;
  66061. }
  66062. ++x;
  66063. }
  66064. if (lastLevel > 0)
  66065. {
  66066. tempLine[++destIndex] = (x << 8);
  66067. tempLine[++destIndex] = 0;
  66068. }
  66069. tempLine[0] = destIndex >> 1;
  66070. intersectWithEdgeTableLine (y, tempLine);
  66071. }
  66072. bool EdgeTable::isEmpty() throw()
  66073. {
  66074. if (needToCheckEmptinesss)
  66075. {
  66076. needToCheckEmptinesss = false;
  66077. int* t = table;
  66078. for (int i = bounds.getHeight(); --i >= 0;)
  66079. {
  66080. if (t[0] > 1)
  66081. return false;
  66082. t += lineStrideElements;
  66083. }
  66084. bounds.setHeight (0);
  66085. }
  66086. return bounds.getHeight() == 0;
  66087. }
  66088. END_JUCE_NAMESPACE
  66089. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66090. /*** Start of inlined file: juce_FillType.cpp ***/
  66091. BEGIN_JUCE_NAMESPACE
  66092. FillType::FillType() throw()
  66093. : colour (0xff000000), image (0)
  66094. {
  66095. }
  66096. FillType::FillType (const Colour& colour_) throw()
  66097. : colour (colour_), image (0)
  66098. {
  66099. }
  66100. FillType::FillType (const ColourGradient& gradient_)
  66101. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66102. {
  66103. }
  66104. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66105. : colour (0xff000000), image (image_), transform (transform_)
  66106. {
  66107. }
  66108. FillType::FillType (const FillType& other)
  66109. : colour (other.colour),
  66110. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66111. image (other.image), transform (other.transform)
  66112. {
  66113. }
  66114. FillType& FillType::operator= (const FillType& other)
  66115. {
  66116. if (this != &other)
  66117. {
  66118. colour = other.colour;
  66119. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66120. image = other.image;
  66121. transform = other.transform;
  66122. }
  66123. return *this;
  66124. }
  66125. FillType::~FillType() throw()
  66126. {
  66127. }
  66128. bool FillType::operator== (const FillType& other) const
  66129. {
  66130. return colour == other.colour && image == other.image
  66131. && transform == other.transform
  66132. && (gradient == other.gradient
  66133. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66134. }
  66135. bool FillType::operator!= (const FillType& other) const
  66136. {
  66137. return ! operator== (other);
  66138. }
  66139. void FillType::setColour (const Colour& newColour) throw()
  66140. {
  66141. gradient = 0;
  66142. image = Image::null;
  66143. colour = newColour;
  66144. }
  66145. void FillType::setGradient (const ColourGradient& newGradient)
  66146. {
  66147. if (gradient != 0)
  66148. {
  66149. *gradient = newGradient;
  66150. }
  66151. else
  66152. {
  66153. image = Image::null;
  66154. gradient = new ColourGradient (newGradient);
  66155. colour = Colours::black;
  66156. }
  66157. }
  66158. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66159. {
  66160. gradient = 0;
  66161. image = image_;
  66162. transform = transform_;
  66163. colour = Colours::black;
  66164. }
  66165. void FillType::setOpacity (const float newOpacity) throw()
  66166. {
  66167. colour = colour.withAlpha (newOpacity);
  66168. }
  66169. bool FillType::isInvisible() const throw()
  66170. {
  66171. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66172. }
  66173. END_JUCE_NAMESPACE
  66174. /*** End of inlined file: juce_FillType.cpp ***/
  66175. /*** Start of inlined file: juce_Graphics.cpp ***/
  66176. BEGIN_JUCE_NAMESPACE
  66177. namespace
  66178. {
  66179. template <typename Type>
  66180. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66181. {
  66182. const int maxVal = 0x3fffffff;
  66183. return (int) x >= -maxVal && (int) x <= maxVal
  66184. && (int) y >= -maxVal && (int) y <= maxVal
  66185. && (int) w >= -maxVal && (int) w <= maxVal
  66186. && (int) h >= -maxVal && (int) h <= maxVal;
  66187. }
  66188. }
  66189. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66190. {
  66191. }
  66192. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66193. {
  66194. }
  66195. Graphics::Graphics (const Image& imageToDrawOnto)
  66196. : context (imageToDrawOnto.createLowLevelContext()),
  66197. contextToDelete (context),
  66198. saveStatePending (false)
  66199. {
  66200. }
  66201. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66202. : context (internalContext),
  66203. saveStatePending (false)
  66204. {
  66205. }
  66206. Graphics::~Graphics()
  66207. {
  66208. }
  66209. void Graphics::resetToDefaultState()
  66210. {
  66211. saveStateIfPending();
  66212. context->setFill (FillType());
  66213. context->setFont (Font());
  66214. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66215. }
  66216. bool Graphics::isVectorDevice() const
  66217. {
  66218. return context->isVectorDevice();
  66219. }
  66220. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66221. {
  66222. saveStateIfPending();
  66223. return context->clipToRectangle (area);
  66224. }
  66225. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66226. {
  66227. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66228. }
  66229. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66230. {
  66231. saveStateIfPending();
  66232. return context->clipToRectangleList (clipRegion);
  66233. }
  66234. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66235. {
  66236. saveStateIfPending();
  66237. context->clipToPath (path, transform);
  66238. return ! context->isClipEmpty();
  66239. }
  66240. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66241. {
  66242. saveStateIfPending();
  66243. context->clipToImageAlpha (image, transform);
  66244. return ! context->isClipEmpty();
  66245. }
  66246. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66247. {
  66248. saveStateIfPending();
  66249. context->excludeClipRectangle (rectangleToExclude);
  66250. }
  66251. bool Graphics::isClipEmpty() const
  66252. {
  66253. return context->isClipEmpty();
  66254. }
  66255. const Rectangle<int> Graphics::getClipBounds() const
  66256. {
  66257. return context->getClipBounds();
  66258. }
  66259. void Graphics::saveState()
  66260. {
  66261. saveStateIfPending();
  66262. saveStatePending = true;
  66263. }
  66264. void Graphics::restoreState()
  66265. {
  66266. if (saveStatePending)
  66267. saveStatePending = false;
  66268. else
  66269. context->restoreState();
  66270. }
  66271. void Graphics::saveStateIfPending()
  66272. {
  66273. if (saveStatePending)
  66274. {
  66275. saveStatePending = false;
  66276. context->saveState();
  66277. }
  66278. }
  66279. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66280. {
  66281. saveStateIfPending();
  66282. context->setOrigin (newOriginX, newOriginY);
  66283. }
  66284. void Graphics::addTransform (const AffineTransform& transform)
  66285. {
  66286. saveStateIfPending();
  66287. context->addTransform (transform);
  66288. }
  66289. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66290. {
  66291. return context->clipRegionIntersects (area);
  66292. }
  66293. void Graphics::beginTransparencyLayer (float layerOpacity)
  66294. {
  66295. saveStateIfPending();
  66296. context->beginTransparencyLayer (layerOpacity);
  66297. }
  66298. void Graphics::endTransparencyLayer()
  66299. {
  66300. context->endTransparencyLayer();
  66301. }
  66302. void Graphics::setColour (const Colour& newColour)
  66303. {
  66304. saveStateIfPending();
  66305. context->setFill (newColour);
  66306. }
  66307. void Graphics::setOpacity (const float newOpacity)
  66308. {
  66309. saveStateIfPending();
  66310. context->setOpacity (newOpacity);
  66311. }
  66312. void Graphics::setGradientFill (const ColourGradient& gradient)
  66313. {
  66314. setFillType (gradient);
  66315. }
  66316. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66317. {
  66318. saveStateIfPending();
  66319. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66320. context->setOpacity (opacity);
  66321. }
  66322. void Graphics::setFillType (const FillType& newFill)
  66323. {
  66324. saveStateIfPending();
  66325. context->setFill (newFill);
  66326. }
  66327. void Graphics::setFont (const Font& newFont)
  66328. {
  66329. saveStateIfPending();
  66330. context->setFont (newFont);
  66331. }
  66332. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66333. {
  66334. saveStateIfPending();
  66335. Font f (context->getFont());
  66336. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66337. context->setFont (f);
  66338. }
  66339. const Font Graphics::getCurrentFont() const
  66340. {
  66341. return context->getFont();
  66342. }
  66343. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66344. {
  66345. if (text.isNotEmpty()
  66346. && startX < context->getClipBounds().getRight())
  66347. {
  66348. GlyphArrangement arr;
  66349. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66350. arr.draw (*this);
  66351. }
  66352. }
  66353. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66354. {
  66355. if (text.isNotEmpty())
  66356. {
  66357. GlyphArrangement arr;
  66358. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66359. arr.draw (*this, transform);
  66360. }
  66361. }
  66362. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66363. {
  66364. if (text.isNotEmpty()
  66365. && startX < context->getClipBounds().getRight())
  66366. {
  66367. GlyphArrangement arr;
  66368. arr.addJustifiedText (context->getFont(), text,
  66369. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66370. Justification::left);
  66371. arr.draw (*this);
  66372. }
  66373. }
  66374. void Graphics::drawText (const String& text,
  66375. const int x, const int y, const int width, const int height,
  66376. const Justification& justificationType,
  66377. const bool useEllipsesIfTooBig) const
  66378. {
  66379. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66380. {
  66381. GlyphArrangement arr;
  66382. arr.addCurtailedLineOfText (context->getFont(), text,
  66383. 0.0f, 0.0f, (float) width,
  66384. useEllipsesIfTooBig);
  66385. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66386. (float) x, (float) y, (float) width, (float) height,
  66387. justificationType);
  66388. arr.draw (*this);
  66389. }
  66390. }
  66391. void Graphics::drawFittedText (const String& text,
  66392. const int x, const int y, const int width, const int height,
  66393. const Justification& justification,
  66394. const int maximumNumberOfLines,
  66395. const float minimumHorizontalScale) const
  66396. {
  66397. if (text.isNotEmpty()
  66398. && width > 0 && height > 0
  66399. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66400. {
  66401. GlyphArrangement arr;
  66402. arr.addFittedText (context->getFont(), text,
  66403. (float) x, (float) y, (float) width, (float) height,
  66404. justification,
  66405. maximumNumberOfLines,
  66406. minimumHorizontalScale);
  66407. arr.draw (*this);
  66408. }
  66409. }
  66410. void Graphics::fillRect (int x, int y, int width, int height) const
  66411. {
  66412. // passing in a silly number can cause maths problems in rendering!
  66413. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66414. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66415. }
  66416. void Graphics::fillRect (const Rectangle<int>& r) const
  66417. {
  66418. context->fillRect (r, false);
  66419. }
  66420. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66421. {
  66422. // passing in a silly number can cause maths problems in rendering!
  66423. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66424. Path p;
  66425. p.addRectangle (x, y, width, height);
  66426. fillPath (p);
  66427. }
  66428. void Graphics::setPixel (int x, int y) const
  66429. {
  66430. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66431. }
  66432. void Graphics::fillAll() const
  66433. {
  66434. fillRect (context->getClipBounds());
  66435. }
  66436. void Graphics::fillAll (const Colour& colourToUse) const
  66437. {
  66438. if (! colourToUse.isTransparent())
  66439. {
  66440. const Rectangle<int> clip (context->getClipBounds());
  66441. context->saveState();
  66442. context->setFill (colourToUse);
  66443. context->fillRect (clip, false);
  66444. context->restoreState();
  66445. }
  66446. }
  66447. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66448. {
  66449. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66450. context->fillPath (path, transform);
  66451. }
  66452. void Graphics::strokePath (const Path& path,
  66453. const PathStrokeType& strokeType,
  66454. const AffineTransform& transform) const
  66455. {
  66456. Path stroke;
  66457. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66458. fillPath (stroke);
  66459. }
  66460. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66461. const int lineThickness) const
  66462. {
  66463. // passing in a silly number can cause maths problems in rendering!
  66464. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66465. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66466. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66467. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66468. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66469. }
  66470. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66471. {
  66472. // passing in a silly number can cause maths problems in rendering!
  66473. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66474. Path p;
  66475. p.addRectangle (x, y, width, lineThickness);
  66476. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66477. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66478. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66479. fillPath (p);
  66480. }
  66481. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66482. {
  66483. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66484. }
  66485. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66486. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66487. const bool useGradient, const bool sharpEdgeOnOutside) const
  66488. {
  66489. // passing in a silly number can cause maths problems in rendering!
  66490. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66491. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66492. {
  66493. context->saveState();
  66494. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66495. const float ramp = oldOpacity / bevelThickness;
  66496. for (int i = bevelThickness; --i >= 0;)
  66497. {
  66498. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66499. : oldOpacity;
  66500. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66501. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66502. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66503. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66504. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66505. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66506. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66507. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66508. }
  66509. context->restoreState();
  66510. }
  66511. }
  66512. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66513. {
  66514. // passing in a silly number can cause maths problems in rendering!
  66515. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66516. Path p;
  66517. p.addEllipse (x, y, width, height);
  66518. fillPath (p);
  66519. }
  66520. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66521. const float lineThickness) const
  66522. {
  66523. // passing in a silly number can cause maths problems in rendering!
  66524. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66525. Path p;
  66526. p.addEllipse (x, y, width, height);
  66527. strokePath (p, PathStrokeType (lineThickness));
  66528. }
  66529. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66530. {
  66531. // passing in a silly number can cause maths problems in rendering!
  66532. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66533. Path p;
  66534. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66535. fillPath (p);
  66536. }
  66537. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66538. {
  66539. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66540. }
  66541. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66542. const float cornerSize, const float lineThickness) const
  66543. {
  66544. // passing in a silly number can cause maths problems in rendering!
  66545. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66546. Path p;
  66547. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66548. strokePath (p, PathStrokeType (lineThickness));
  66549. }
  66550. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66551. {
  66552. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66553. }
  66554. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66555. {
  66556. Path p;
  66557. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66558. fillPath (p);
  66559. }
  66560. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66561. const int checkWidth, const int checkHeight,
  66562. const Colour& colour1, const Colour& colour2) const
  66563. {
  66564. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66565. if (checkWidth > 0 && checkHeight > 0)
  66566. {
  66567. context->saveState();
  66568. if (colour1 == colour2)
  66569. {
  66570. context->setFill (colour1);
  66571. context->fillRect (area, false);
  66572. }
  66573. else
  66574. {
  66575. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66576. if (! clipped.isEmpty())
  66577. {
  66578. context->clipToRectangle (clipped);
  66579. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66580. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66581. const int startX = area.getX() + checkNumX * checkWidth;
  66582. const int startY = area.getY() + checkNumY * checkHeight;
  66583. const int right = clipped.getRight();
  66584. const int bottom = clipped.getBottom();
  66585. for (int i = 0; i < 2; ++i)
  66586. {
  66587. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66588. int cy = i;
  66589. for (int y = startY; y < bottom; y += checkHeight)
  66590. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66591. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66592. }
  66593. }
  66594. }
  66595. context->restoreState();
  66596. }
  66597. }
  66598. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66599. {
  66600. context->drawVerticalLine (x, top, bottom);
  66601. }
  66602. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66603. {
  66604. context->drawHorizontalLine (y, left, right);
  66605. }
  66606. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2) const
  66607. {
  66608. context->drawLine (Line<float> (x1, y1, x2, y2));
  66609. }
  66610. void Graphics::drawLine (const Line<float>& line) const
  66611. {
  66612. context->drawLine (line);
  66613. }
  66614. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2, const float lineThickness) const
  66615. {
  66616. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  66617. }
  66618. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66619. {
  66620. Path p;
  66621. p.addLineSegment (line, lineThickness);
  66622. fillPath (p);
  66623. }
  66624. void Graphics::drawDashedLine (const Line<float>& line, const float* const dashLengths,
  66625. const int numDashLengths, const float lineThickness, int n) const
  66626. {
  66627. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  66628. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  66629. const double totalLen = delta.getDistanceFromOrigin();
  66630. if (totalLen >= 0.1)
  66631. {
  66632. const double onePixAlpha = 1.0 / totalLen;
  66633. for (double alpha = 0.0; alpha < 1.0;)
  66634. {
  66635. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  66636. const double lastAlpha = alpha;
  66637. alpha = jmin (1.0, alpha + dashLengths [n] * onePixAlpha);
  66638. n = (n + 1) % numDashLengths;
  66639. if ((n & 1) != 0)
  66640. {
  66641. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  66642. line.getStart() + (delta * alpha).toFloat());
  66643. if (lineThickness != 1.0f)
  66644. drawLine (segment, lineThickness);
  66645. else
  66646. context->drawLine (segment);
  66647. }
  66648. }
  66649. }
  66650. }
  66651. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66652. {
  66653. saveStateIfPending();
  66654. context->setInterpolationQuality (newQuality);
  66655. }
  66656. void Graphics::drawImageAt (const Image& imageToDraw,
  66657. const int topLeftX, const int topLeftY,
  66658. const bool fillAlphaChannelWithCurrentBrush) const
  66659. {
  66660. const int imageW = imageToDraw.getWidth();
  66661. const int imageH = imageToDraw.getHeight();
  66662. drawImage (imageToDraw,
  66663. topLeftX, topLeftY, imageW, imageH,
  66664. 0, 0, imageW, imageH,
  66665. fillAlphaChannelWithCurrentBrush);
  66666. }
  66667. void Graphics::drawImageWithin (const Image& imageToDraw,
  66668. const int destX, const int destY,
  66669. const int destW, const int destH,
  66670. const RectanglePlacement& placementWithinTarget,
  66671. const bool fillAlphaChannelWithCurrentBrush) const
  66672. {
  66673. // passing in a silly number can cause maths problems in rendering!
  66674. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66675. if (imageToDraw.isValid())
  66676. {
  66677. const int imageW = imageToDraw.getWidth();
  66678. const int imageH = imageToDraw.getHeight();
  66679. if (imageW > 0 && imageH > 0)
  66680. {
  66681. double newX = 0.0, newY = 0.0;
  66682. double newW = imageW;
  66683. double newH = imageH;
  66684. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66685. destX, destY, destW, destH);
  66686. if (newW > 0 && newH > 0)
  66687. {
  66688. drawImage (imageToDraw,
  66689. roundToInt (newX), roundToInt (newY),
  66690. roundToInt (newW), roundToInt (newH),
  66691. 0, 0, imageW, imageH,
  66692. fillAlphaChannelWithCurrentBrush);
  66693. }
  66694. }
  66695. }
  66696. }
  66697. void Graphics::drawImage (const Image& imageToDraw,
  66698. int dx, int dy, int dw, int dh,
  66699. int sx, int sy, int sw, int sh,
  66700. const bool fillAlphaChannelWithCurrentBrush) const
  66701. {
  66702. // passing in a silly number can cause maths problems in rendering!
  66703. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66704. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66705. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66706. {
  66707. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66708. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66709. .translated ((float) dx, (float) dy),
  66710. fillAlphaChannelWithCurrentBrush);
  66711. }
  66712. }
  66713. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66714. const AffineTransform& transform,
  66715. const bool fillAlphaChannelWithCurrentBrush) const
  66716. {
  66717. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66718. {
  66719. if (fillAlphaChannelWithCurrentBrush)
  66720. {
  66721. context->saveState();
  66722. context->clipToImageAlpha (imageToDraw, transform);
  66723. fillAll();
  66724. context->restoreState();
  66725. }
  66726. else
  66727. {
  66728. context->drawImage (imageToDraw, transform, false);
  66729. }
  66730. }
  66731. }
  66732. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66733. : context (g)
  66734. {
  66735. context.saveState();
  66736. }
  66737. Graphics::ScopedSaveState::~ScopedSaveState()
  66738. {
  66739. context.restoreState();
  66740. }
  66741. END_JUCE_NAMESPACE
  66742. /*** End of inlined file: juce_Graphics.cpp ***/
  66743. /*** Start of inlined file: juce_Justification.cpp ***/
  66744. BEGIN_JUCE_NAMESPACE
  66745. Justification::Justification (const Justification& other) throw()
  66746. : flags (other.flags)
  66747. {
  66748. }
  66749. Justification& Justification::operator= (const Justification& other) throw()
  66750. {
  66751. flags = other.flags;
  66752. return *this;
  66753. }
  66754. int Justification::getOnlyVerticalFlags() const throw()
  66755. {
  66756. return flags & (top | bottom | verticallyCentred);
  66757. }
  66758. int Justification::getOnlyHorizontalFlags() const throw()
  66759. {
  66760. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66761. }
  66762. END_JUCE_NAMESPACE
  66763. /*** End of inlined file: juce_Justification.cpp ***/
  66764. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66765. BEGIN_JUCE_NAMESPACE
  66766. // this will throw an assertion if you try to draw something that's not
  66767. // possible in postscript
  66768. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66769. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66770. #define notPossibleInPostscriptAssert jassertfalse
  66771. #else
  66772. #define notPossibleInPostscriptAssert
  66773. #endif
  66774. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66775. const String& documentTitle,
  66776. const int totalWidth_,
  66777. const int totalHeight_)
  66778. : out (resultingPostScript),
  66779. totalWidth (totalWidth_),
  66780. totalHeight (totalHeight_),
  66781. needToClip (true)
  66782. {
  66783. stateStack.add (new SavedState());
  66784. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66785. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66786. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66787. "\n%%BoundingBox: 0 0 600 824"
  66788. "\n%%Pages: 0"
  66789. "\n%%Creator: Raw Material Software JUCE"
  66790. "\n%%Title: " << documentTitle <<
  66791. "\n%%CreationDate: none"
  66792. "\n%%LanguageLevel: 2"
  66793. "\n%%EndComments"
  66794. "\n%%BeginProlog"
  66795. "\n%%BeginResource: JRes"
  66796. "\n/bd {bind def} bind def"
  66797. "\n/c {setrgbcolor} bd"
  66798. "\n/m {moveto} bd"
  66799. "\n/l {lineto} bd"
  66800. "\n/rl {rlineto} bd"
  66801. "\n/ct {curveto} bd"
  66802. "\n/cp {closepath} bd"
  66803. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66804. "\n/doclip {initclip newpath} bd"
  66805. "\n/endclip {clip newpath} bd"
  66806. "\n%%EndResource"
  66807. "\n%%EndProlog"
  66808. "\n%%BeginSetup"
  66809. "\n%%EndSetup"
  66810. "\n%%Page: 1 1"
  66811. "\n%%BeginPageSetup"
  66812. "\n%%EndPageSetup\n\n"
  66813. << "40 800 translate\n"
  66814. << scale << ' ' << scale << " scale\n\n";
  66815. }
  66816. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66817. {
  66818. }
  66819. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66820. {
  66821. return true;
  66822. }
  66823. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66824. {
  66825. if (x != 0 || y != 0)
  66826. {
  66827. stateStack.getLast()->xOffset += x;
  66828. stateStack.getLast()->yOffset += y;
  66829. needToClip = true;
  66830. }
  66831. }
  66832. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66833. {
  66834. //xxx
  66835. jassertfalse;
  66836. }
  66837. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66838. {
  66839. jassertfalse; //xxx
  66840. return 1.0f;
  66841. }
  66842. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66843. {
  66844. needToClip = true;
  66845. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66846. }
  66847. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66848. {
  66849. needToClip = true;
  66850. return stateStack.getLast()->clip.clipTo (clipRegion);
  66851. }
  66852. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66853. {
  66854. needToClip = true;
  66855. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66856. }
  66857. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66858. {
  66859. writeClip();
  66860. Path p (path);
  66861. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66862. writePath (p);
  66863. out << "clip\n";
  66864. }
  66865. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66866. {
  66867. needToClip = true;
  66868. jassertfalse; // xxx
  66869. }
  66870. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66871. {
  66872. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66873. }
  66874. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66875. {
  66876. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66877. -stateStack.getLast()->yOffset);
  66878. }
  66879. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66880. {
  66881. return stateStack.getLast()->clip.isEmpty();
  66882. }
  66883. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66884. : xOffset (0),
  66885. yOffset (0)
  66886. {
  66887. }
  66888. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66889. {
  66890. }
  66891. void LowLevelGraphicsPostScriptRenderer::saveState()
  66892. {
  66893. stateStack.add (new SavedState (*stateStack.getLast()));
  66894. }
  66895. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66896. {
  66897. jassert (stateStack.size() > 0);
  66898. if (stateStack.size() > 0)
  66899. stateStack.removeLast();
  66900. }
  66901. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  66902. {
  66903. }
  66904. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  66905. {
  66906. }
  66907. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66908. {
  66909. if (needToClip)
  66910. {
  66911. needToClip = false;
  66912. out << "doclip ";
  66913. int itemsOnLine = 0;
  66914. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66915. {
  66916. if (++itemsOnLine == 6)
  66917. {
  66918. itemsOnLine = 0;
  66919. out << '\n';
  66920. }
  66921. const Rectangle<int>& r = *i.getRectangle();
  66922. out << r.getX() << ' ' << -r.getY() << ' '
  66923. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66924. }
  66925. out << "endclip\n";
  66926. }
  66927. }
  66928. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66929. {
  66930. Colour c (Colours::white.overlaidWith (colour));
  66931. if (lastColour != c)
  66932. {
  66933. lastColour = c;
  66934. out << String (c.getFloatRed(), 3) << ' '
  66935. << String (c.getFloatGreen(), 3) << ' '
  66936. << String (c.getFloatBlue(), 3) << " c\n";
  66937. }
  66938. }
  66939. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66940. {
  66941. out << String (x, 2) << ' '
  66942. << String (-y, 2) << ' ';
  66943. }
  66944. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66945. {
  66946. out << "newpath ";
  66947. float lastX = 0.0f;
  66948. float lastY = 0.0f;
  66949. int itemsOnLine = 0;
  66950. Path::Iterator i (path);
  66951. while (i.next())
  66952. {
  66953. if (++itemsOnLine == 4)
  66954. {
  66955. itemsOnLine = 0;
  66956. out << '\n';
  66957. }
  66958. switch (i.elementType)
  66959. {
  66960. case Path::Iterator::startNewSubPath:
  66961. writeXY (i.x1, i.y1);
  66962. lastX = i.x1;
  66963. lastY = i.y1;
  66964. out << "m ";
  66965. break;
  66966. case Path::Iterator::lineTo:
  66967. writeXY (i.x1, i.y1);
  66968. lastX = i.x1;
  66969. lastY = i.y1;
  66970. out << "l ";
  66971. break;
  66972. case Path::Iterator::quadraticTo:
  66973. {
  66974. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66975. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66976. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66977. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66978. writeXY (cp1x, cp1y);
  66979. writeXY (cp2x, cp2y);
  66980. writeXY (i.x2, i.y2);
  66981. out << "ct ";
  66982. lastX = i.x2;
  66983. lastY = i.y2;
  66984. }
  66985. break;
  66986. case Path::Iterator::cubicTo:
  66987. writeXY (i.x1, i.y1);
  66988. writeXY (i.x2, i.y2);
  66989. writeXY (i.x3, i.y3);
  66990. out << "ct ";
  66991. lastX = i.x3;
  66992. lastY = i.y3;
  66993. break;
  66994. case Path::Iterator::closePath:
  66995. out << "cp ";
  66996. break;
  66997. default:
  66998. jassertfalse;
  66999. break;
  67000. }
  67001. }
  67002. out << '\n';
  67003. }
  67004. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67005. {
  67006. out << "[ "
  67007. << trans.mat00 << ' '
  67008. << trans.mat10 << ' '
  67009. << trans.mat01 << ' '
  67010. << trans.mat11 << ' '
  67011. << trans.mat02 << ' '
  67012. << trans.mat12 << " ] concat ";
  67013. }
  67014. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67015. {
  67016. stateStack.getLast()->fillType = fillType;
  67017. }
  67018. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67019. {
  67020. }
  67021. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67022. {
  67023. }
  67024. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67025. {
  67026. if (stateStack.getLast()->fillType.isColour())
  67027. {
  67028. writeClip();
  67029. writeColour (stateStack.getLast()->fillType.colour);
  67030. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67031. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67032. }
  67033. else
  67034. {
  67035. Path p;
  67036. p.addRectangle (r);
  67037. fillPath (p, AffineTransform::identity);
  67038. }
  67039. }
  67040. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67041. {
  67042. if (stateStack.getLast()->fillType.isColour())
  67043. {
  67044. writeClip();
  67045. Path p (path);
  67046. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67047. (float) stateStack.getLast()->yOffset));
  67048. writePath (p);
  67049. writeColour (stateStack.getLast()->fillType.colour);
  67050. out << "fill\n";
  67051. }
  67052. else if (stateStack.getLast()->fillType.isGradient())
  67053. {
  67054. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67055. // postscript can't do semi-transparent ones.
  67056. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67057. writeClip();
  67058. out << "gsave ";
  67059. {
  67060. Path p (path);
  67061. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67062. writePath (p);
  67063. out << "clip\n";
  67064. }
  67065. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67066. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67067. // time-being, this just fills it with the average colour..
  67068. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67069. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67070. out << "grestore\n";
  67071. }
  67072. }
  67073. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67074. const int sx, const int sy,
  67075. const int maxW, const int maxH) const
  67076. {
  67077. out << "{<\n";
  67078. const int w = jmin (maxW, im.getWidth());
  67079. const int h = jmin (maxH, im.getHeight());
  67080. int charsOnLine = 0;
  67081. const Image::BitmapData srcData (im, 0, 0, w, h);
  67082. Colour pixel;
  67083. for (int y = h; --y >= 0;)
  67084. {
  67085. for (int x = 0; x < w; ++x)
  67086. {
  67087. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67088. if (x >= sx && y >= sy)
  67089. {
  67090. if (im.isARGB())
  67091. {
  67092. PixelARGB p (*(const PixelARGB*) pixelData);
  67093. p.unpremultiply();
  67094. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67095. }
  67096. else if (im.isRGB())
  67097. {
  67098. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67099. }
  67100. else
  67101. {
  67102. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67103. }
  67104. }
  67105. else
  67106. {
  67107. pixel = Colours::transparentWhite;
  67108. }
  67109. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67110. out << String::toHexString (pixelValues, 3, 0);
  67111. charsOnLine += 3;
  67112. if (charsOnLine > 100)
  67113. {
  67114. out << '\n';
  67115. charsOnLine = 0;
  67116. }
  67117. }
  67118. }
  67119. out << "\n>}\n";
  67120. }
  67121. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67122. {
  67123. const int w = sourceImage.getWidth();
  67124. const int h = sourceImage.getHeight();
  67125. writeClip();
  67126. out << "gsave ";
  67127. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67128. .scaled (1.0f, -1.0f));
  67129. RectangleList imageClip;
  67130. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67131. out << "newpath ";
  67132. int itemsOnLine = 0;
  67133. for (RectangleList::Iterator i (imageClip); i.next();)
  67134. {
  67135. if (++itemsOnLine == 6)
  67136. {
  67137. out << '\n';
  67138. itemsOnLine = 0;
  67139. }
  67140. const Rectangle<int>& r = *i.getRectangle();
  67141. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67142. }
  67143. out << " clip newpath\n";
  67144. out << w << ' ' << h << " scale\n";
  67145. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67146. writeImage (sourceImage, 0, 0, w, h);
  67147. out << "false 3 colorimage grestore\n";
  67148. needToClip = true;
  67149. }
  67150. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67151. {
  67152. Path p;
  67153. p.addLineSegment (line, 1.0f);
  67154. fillPath (p, AffineTransform::identity);
  67155. }
  67156. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67157. {
  67158. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67159. }
  67160. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67161. {
  67162. drawLine (Line<float> (left, (float) y, right, (float) y));
  67163. }
  67164. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67165. {
  67166. stateStack.getLast()->font = newFont;
  67167. }
  67168. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67169. {
  67170. return stateStack.getLast()->font;
  67171. }
  67172. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67173. {
  67174. Path p;
  67175. Font& font = stateStack.getLast()->font;
  67176. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67177. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67178. }
  67179. END_JUCE_NAMESPACE
  67180. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67181. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67182. BEGIN_JUCE_NAMESPACE
  67183. #if JUCE_MSVC
  67184. #pragma warning (push)
  67185. #pragma warning (disable: 4127) // "expression is constant" warning
  67186. #if JUCE_DEBUG
  67187. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67188. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67189. #endif
  67190. #endif
  67191. namespace SoftwareRendererClasses
  67192. {
  67193. template <class PixelType, bool replaceExisting = false>
  67194. class SolidColourEdgeTableRenderer
  67195. {
  67196. public:
  67197. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67198. : data (data_),
  67199. sourceColour (colour)
  67200. {
  67201. if (sizeof (PixelType) == 3)
  67202. {
  67203. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67204. && sourceColour.getGreen() == sourceColour.getBlue();
  67205. filler[0].set (sourceColour);
  67206. filler[1].set (sourceColour);
  67207. filler[2].set (sourceColour);
  67208. filler[3].set (sourceColour);
  67209. }
  67210. }
  67211. forcedinline void setEdgeTableYPos (const int y) throw()
  67212. {
  67213. linePixels = (PixelType*) data.getLinePointer (y);
  67214. }
  67215. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67216. {
  67217. if (replaceExisting)
  67218. linePixels[x].set (sourceColour);
  67219. else
  67220. linePixels[x].blend (sourceColour, alphaLevel);
  67221. }
  67222. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67223. {
  67224. if (replaceExisting)
  67225. linePixels[x].set (sourceColour);
  67226. else
  67227. linePixels[x].blend (sourceColour);
  67228. }
  67229. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67230. {
  67231. PixelARGB p (sourceColour);
  67232. p.multiplyAlpha (alphaLevel);
  67233. PixelType* dest = linePixels + x;
  67234. if (replaceExisting || p.getAlpha() >= 0xff)
  67235. replaceLine (dest, p, width);
  67236. else
  67237. blendLine (dest, p, width);
  67238. }
  67239. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67240. {
  67241. PixelType* dest = linePixels + x;
  67242. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67243. replaceLine (dest, sourceColour, width);
  67244. else
  67245. blendLine (dest, sourceColour, width);
  67246. }
  67247. private:
  67248. const Image::BitmapData& data;
  67249. PixelType* linePixels;
  67250. PixelARGB sourceColour;
  67251. PixelRGB filler [4];
  67252. bool areRGBComponentsEqual;
  67253. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67254. {
  67255. do
  67256. {
  67257. dest->blend (colour);
  67258. ++dest;
  67259. } while (--width > 0);
  67260. }
  67261. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67262. {
  67263. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67264. {
  67265. memset (dest, colour.getRed(), width * 3);
  67266. }
  67267. else
  67268. {
  67269. if (width >> 5)
  67270. {
  67271. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67272. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67273. {
  67274. dest->set (colour);
  67275. ++dest;
  67276. --width;
  67277. }
  67278. while (width > 4)
  67279. {
  67280. int* d = reinterpret_cast<int*> (dest);
  67281. *d++ = intFiller[0];
  67282. *d++ = intFiller[1];
  67283. *d++ = intFiller[2];
  67284. dest = reinterpret_cast<PixelRGB*> (d);
  67285. width -= 4;
  67286. }
  67287. }
  67288. while (--width >= 0)
  67289. {
  67290. dest->set (colour);
  67291. ++dest;
  67292. }
  67293. }
  67294. }
  67295. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67296. {
  67297. memset (dest, colour.getAlpha(), width);
  67298. }
  67299. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67300. {
  67301. do
  67302. {
  67303. dest->set (colour);
  67304. ++dest;
  67305. } while (--width > 0);
  67306. }
  67307. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67308. };
  67309. class LinearGradientPixelGenerator
  67310. {
  67311. public:
  67312. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67313. : lookupTable (lookupTable_), numEntries (numEntries_)
  67314. {
  67315. jassert (numEntries_ >= 0);
  67316. Point<float> p1 (gradient.point1);
  67317. Point<float> p2 (gradient.point2);
  67318. if (! transform.isIdentity())
  67319. {
  67320. const Line<float> l (p2, p1);
  67321. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67322. p1.applyTransform (transform);
  67323. p2.applyTransform (transform);
  67324. p3.applyTransform (transform);
  67325. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67326. }
  67327. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67328. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67329. if (vertical)
  67330. {
  67331. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67332. start = roundToInt (p1.getY() * scale);
  67333. }
  67334. else if (horizontal)
  67335. {
  67336. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67337. start = roundToInt (p1.getX() * scale);
  67338. }
  67339. else
  67340. {
  67341. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67342. yTerm = p1.getY() - p1.getX() / grad;
  67343. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67344. grad *= scale;
  67345. }
  67346. }
  67347. forcedinline void setY (const int y) throw()
  67348. {
  67349. if (vertical)
  67350. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67351. else if (! horizontal)
  67352. start = roundToInt ((y - yTerm) * grad);
  67353. }
  67354. inline const PixelARGB getPixel (const int x) const throw()
  67355. {
  67356. return vertical ? linePix
  67357. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67358. }
  67359. private:
  67360. const PixelARGB* const lookupTable;
  67361. const int numEntries;
  67362. PixelARGB linePix;
  67363. int start, scale;
  67364. double grad, yTerm;
  67365. bool vertical, horizontal;
  67366. enum { numScaleBits = 12 };
  67367. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67368. };
  67369. class RadialGradientPixelGenerator
  67370. {
  67371. public:
  67372. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67373. const PixelARGB* const lookupTable_, const int numEntries_)
  67374. : lookupTable (lookupTable_),
  67375. numEntries (numEntries_),
  67376. gx1 (gradient.point1.getX()),
  67377. gy1 (gradient.point1.getY())
  67378. {
  67379. jassert (numEntries_ >= 0);
  67380. const Point<float> diff (gradient.point1 - gradient.point2);
  67381. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67382. invScale = numEntries / std::sqrt (maxDist);
  67383. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67384. }
  67385. forcedinline void setY (const int y) throw()
  67386. {
  67387. dy = y - gy1;
  67388. dy *= dy;
  67389. }
  67390. inline const PixelARGB getPixel (const int px) const throw()
  67391. {
  67392. double x = px - gx1;
  67393. x *= x;
  67394. x += dy;
  67395. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67396. }
  67397. protected:
  67398. const PixelARGB* const lookupTable;
  67399. const int numEntries;
  67400. const double gx1, gy1;
  67401. double maxDist, invScale, dy;
  67402. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67403. };
  67404. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67405. {
  67406. public:
  67407. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67408. const PixelARGB* const lookupTable_, const int numEntries_)
  67409. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67410. inverseTransform (transform.inverted())
  67411. {
  67412. tM10 = inverseTransform.mat10;
  67413. tM00 = inverseTransform.mat00;
  67414. }
  67415. forcedinline void setY (const int y) throw()
  67416. {
  67417. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67418. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67419. }
  67420. inline const PixelARGB getPixel (const int px) const throw()
  67421. {
  67422. double x = px;
  67423. const double y = tM10 * x + lineYM11;
  67424. x = tM00 * x + lineYM01;
  67425. x *= x;
  67426. x += y * y;
  67427. if (x >= maxDist)
  67428. return lookupTable [numEntries];
  67429. else
  67430. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67431. }
  67432. private:
  67433. double tM10, tM00, lineYM01, lineYM11;
  67434. const AffineTransform inverseTransform;
  67435. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67436. };
  67437. template <class PixelType, class GradientType>
  67438. class GradientEdgeTableRenderer : public GradientType
  67439. {
  67440. public:
  67441. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67442. const PixelARGB* const lookupTable_, const int numEntries_)
  67443. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67444. destData (destData_)
  67445. {
  67446. }
  67447. forcedinline void setEdgeTableYPos (const int y) throw()
  67448. {
  67449. linePixels = (PixelType*) destData.getLinePointer (y);
  67450. GradientType::setY (y);
  67451. }
  67452. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67453. {
  67454. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67455. }
  67456. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67457. {
  67458. linePixels[x].blend (GradientType::getPixel (x));
  67459. }
  67460. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67461. {
  67462. PixelType* dest = linePixels + x;
  67463. if (alphaLevel < 0xff)
  67464. {
  67465. do
  67466. {
  67467. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67468. } while (--width > 0);
  67469. }
  67470. else
  67471. {
  67472. do
  67473. {
  67474. (dest++)->blend (GradientType::getPixel (x++));
  67475. } while (--width > 0);
  67476. }
  67477. }
  67478. void handleEdgeTableLineFull (int x, int width) const throw()
  67479. {
  67480. PixelType* dest = linePixels + x;
  67481. do
  67482. {
  67483. (dest++)->blend (GradientType::getPixel (x++));
  67484. } while (--width > 0);
  67485. }
  67486. private:
  67487. const Image::BitmapData& destData;
  67488. PixelType* linePixels;
  67489. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67490. };
  67491. namespace RenderingHelpers
  67492. {
  67493. forcedinline int safeModulo (int n, const int divisor) throw()
  67494. {
  67495. jassert (divisor > 0);
  67496. n %= divisor;
  67497. return (n < 0) ? (n + divisor) : n;
  67498. }
  67499. }
  67500. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67501. class ImageFillEdgeTableRenderer
  67502. {
  67503. public:
  67504. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67505. const Image::BitmapData& srcData_,
  67506. const int extraAlpha_,
  67507. const int x, const int y)
  67508. : destData (destData_),
  67509. srcData (srcData_),
  67510. extraAlpha (extraAlpha_ + 1),
  67511. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67512. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67513. {
  67514. }
  67515. forcedinline void setEdgeTableYPos (int y) throw()
  67516. {
  67517. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67518. y -= yOffset;
  67519. if (repeatPattern)
  67520. {
  67521. jassert (y >= 0);
  67522. y %= srcData.height;
  67523. }
  67524. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67525. }
  67526. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67527. {
  67528. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67529. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67530. }
  67531. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67532. {
  67533. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67534. }
  67535. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67536. {
  67537. DestPixelType* dest = linePixels + x;
  67538. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67539. x -= xOffset;
  67540. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67541. if (alphaLevel < 0xfe)
  67542. {
  67543. do
  67544. {
  67545. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67546. } while (--width > 0);
  67547. }
  67548. else
  67549. {
  67550. if (repeatPattern)
  67551. {
  67552. do
  67553. {
  67554. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67555. } while (--width > 0);
  67556. }
  67557. else
  67558. {
  67559. copyRow (dest, sourceLineStart + x, width);
  67560. }
  67561. }
  67562. }
  67563. void handleEdgeTableLineFull (int x, int width) const throw()
  67564. {
  67565. DestPixelType* dest = linePixels + x;
  67566. x -= xOffset;
  67567. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67568. if (extraAlpha < 0xfe)
  67569. {
  67570. do
  67571. {
  67572. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67573. } while (--width > 0);
  67574. }
  67575. else
  67576. {
  67577. if (repeatPattern)
  67578. {
  67579. do
  67580. {
  67581. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67582. } while (--width > 0);
  67583. }
  67584. else
  67585. {
  67586. copyRow (dest, sourceLineStart + x, width);
  67587. }
  67588. }
  67589. }
  67590. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67591. {
  67592. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67593. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67594. uint8* mask = (uint8*) (s + x - xOffset);
  67595. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67596. mask += PixelARGB::indexA;
  67597. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67598. }
  67599. private:
  67600. const Image::BitmapData& destData;
  67601. const Image::BitmapData& srcData;
  67602. const int extraAlpha, xOffset, yOffset;
  67603. DestPixelType* linePixels;
  67604. SrcPixelType* sourceLineStart;
  67605. template <class PixelType1, class PixelType2>
  67606. static forcedinline void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67607. {
  67608. do
  67609. {
  67610. dest++ ->blend (*src++);
  67611. } while (--width > 0);
  67612. }
  67613. static forcedinline void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67614. {
  67615. memcpy (dest, src, width * sizeof (PixelRGB));
  67616. }
  67617. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67618. };
  67619. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67620. class TransformedImageFillEdgeTableRenderer
  67621. {
  67622. public:
  67623. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67624. const Image::BitmapData& srcData_,
  67625. const AffineTransform& transform,
  67626. const int extraAlpha_,
  67627. const bool betterQuality_)
  67628. : interpolator (transform,
  67629. betterQuality_ ? 0.5f : 0.0f,
  67630. betterQuality_ ? -128 : 0),
  67631. destData (destData_),
  67632. srcData (srcData_),
  67633. extraAlpha (extraAlpha_ + 1),
  67634. betterQuality (betterQuality_),
  67635. maxX (srcData_.width - 1),
  67636. maxY (srcData_.height - 1),
  67637. scratchSize (2048)
  67638. {
  67639. scratchBuffer.malloc (scratchSize);
  67640. }
  67641. forcedinline void setEdgeTableYPos (const int newY) throw()
  67642. {
  67643. y = newY;
  67644. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67645. }
  67646. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67647. {
  67648. SrcPixelType p;
  67649. generate (&p, x, 1);
  67650. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67651. }
  67652. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67653. {
  67654. SrcPixelType p;
  67655. generate (&p, x, 1);
  67656. linePixels[x].blend (p, extraAlpha);
  67657. }
  67658. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67659. {
  67660. if (width > scratchSize)
  67661. {
  67662. scratchSize = width;
  67663. scratchBuffer.malloc (scratchSize);
  67664. }
  67665. SrcPixelType* span = scratchBuffer;
  67666. generate (span, x, width);
  67667. DestPixelType* dest = linePixels + x;
  67668. alphaLevel *= extraAlpha;
  67669. alphaLevel >>= 8;
  67670. if (alphaLevel < 0xfe)
  67671. {
  67672. do
  67673. {
  67674. dest++ ->blend (*span++, alphaLevel);
  67675. } while (--width > 0);
  67676. }
  67677. else
  67678. {
  67679. do
  67680. {
  67681. dest++ ->blend (*span++);
  67682. } while (--width > 0);
  67683. }
  67684. }
  67685. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67686. {
  67687. handleEdgeTableLine (x, width, 255);
  67688. }
  67689. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67690. {
  67691. if (width > scratchSize)
  67692. {
  67693. scratchSize = width;
  67694. scratchBuffer.malloc (scratchSize);
  67695. }
  67696. y = y_;
  67697. generate (scratchBuffer.getData(), x, width);
  67698. et.clipLineToMask (x, y_,
  67699. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67700. sizeof (SrcPixelType), width);
  67701. }
  67702. private:
  67703. template <class PixelType>
  67704. void generate (PixelType* dest, const int x, int numPixels) throw()
  67705. {
  67706. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67707. do
  67708. {
  67709. int hiResX, hiResY;
  67710. this->interpolator.next (hiResX, hiResY);
  67711. int loResX = hiResX >> 8;
  67712. int loResY = hiResY >> 8;
  67713. if (repeatPattern)
  67714. {
  67715. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67716. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67717. }
  67718. if (betterQuality)
  67719. {
  67720. if (isPositiveAndBelow (loResX, maxX))
  67721. {
  67722. if (isPositiveAndBelow (loResY, maxY))
  67723. {
  67724. // In the centre of the image..
  67725. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67726. hiResX & 255, hiResY & 255);
  67727. ++dest;
  67728. continue;
  67729. }
  67730. else
  67731. {
  67732. // At a top or bottom edge..
  67733. if (! repeatPattern)
  67734. {
  67735. if (loResY < 0)
  67736. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67737. else
  67738. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67739. ++dest;
  67740. continue;
  67741. }
  67742. }
  67743. }
  67744. else
  67745. {
  67746. if (isPositiveAndBelow (loResY, maxY))
  67747. {
  67748. // At a left or right hand edge..
  67749. if (! repeatPattern)
  67750. {
  67751. if (loResX < 0)
  67752. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67753. else
  67754. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67755. ++dest;
  67756. continue;
  67757. }
  67758. }
  67759. }
  67760. }
  67761. if (! repeatPattern)
  67762. {
  67763. if (loResX < 0) loResX = 0;
  67764. if (loResY < 0) loResY = 0;
  67765. if (loResX > maxX) loResX = maxX;
  67766. if (loResY > maxY) loResY = maxY;
  67767. }
  67768. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67769. ++dest;
  67770. } while (--numPixels > 0);
  67771. }
  67772. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67773. {
  67774. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67775. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67776. c[0] += weight * src[0];
  67777. c[1] += weight * src[1];
  67778. c[2] += weight * src[2];
  67779. c[3] += weight * src[3];
  67780. weight = subPixelX * (256 - subPixelY);
  67781. c[0] += weight * src[4];
  67782. c[1] += weight * src[5];
  67783. c[2] += weight * src[6];
  67784. c[3] += weight * src[7];
  67785. src += this->srcData.lineStride;
  67786. weight = (256 - subPixelX) * subPixelY;
  67787. c[0] += weight * src[0];
  67788. c[1] += weight * src[1];
  67789. c[2] += weight * src[2];
  67790. c[3] += weight * src[3];
  67791. weight = subPixelX * subPixelY;
  67792. c[0] += weight * src[4];
  67793. c[1] += weight * src[5];
  67794. c[2] += weight * src[6];
  67795. c[3] += weight * src[7];
  67796. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67797. (uint8) (c[PixelARGB::indexR] >> 16),
  67798. (uint8) (c[PixelARGB::indexG] >> 16),
  67799. (uint8) (c[PixelARGB::indexB] >> 16));
  67800. }
  67801. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67802. {
  67803. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67804. uint32 weight = (256 - subPixelX) * alpha;
  67805. c[0] += weight * src[0];
  67806. c[1] += weight * src[1];
  67807. c[2] += weight * src[2];
  67808. c[3] += weight * src[3];
  67809. weight = subPixelX * alpha;
  67810. c[0] += weight * src[4];
  67811. c[1] += weight * src[5];
  67812. c[2] += weight * src[6];
  67813. c[3] += weight * src[7];
  67814. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67815. (uint8) (c[PixelARGB::indexR] >> 16),
  67816. (uint8) (c[PixelARGB::indexG] >> 16),
  67817. (uint8) (c[PixelARGB::indexB] >> 16));
  67818. }
  67819. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67820. {
  67821. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67822. uint32 weight = (256 - subPixelY) * alpha;
  67823. c[0] += weight * src[0];
  67824. c[1] += weight * src[1];
  67825. c[2] += weight * src[2];
  67826. c[3] += weight * src[3];
  67827. src += this->srcData.lineStride;
  67828. weight = subPixelY * alpha;
  67829. c[0] += weight * src[0];
  67830. c[1] += weight * src[1];
  67831. c[2] += weight * src[2];
  67832. c[3] += weight * src[3];
  67833. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67834. (uint8) (c[PixelARGB::indexR] >> 16),
  67835. (uint8) (c[PixelARGB::indexG] >> 16),
  67836. (uint8) (c[PixelARGB::indexB] >> 16));
  67837. }
  67838. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67839. {
  67840. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67841. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67842. c[0] += weight * src[0];
  67843. c[1] += weight * src[1];
  67844. c[2] += weight * src[2];
  67845. weight = subPixelX * (256 - subPixelY);
  67846. c[0] += weight * src[3];
  67847. c[1] += weight * src[4];
  67848. c[2] += weight * src[5];
  67849. src += this->srcData.lineStride;
  67850. weight = (256 - subPixelX) * subPixelY;
  67851. c[0] += weight * src[0];
  67852. c[1] += weight * src[1];
  67853. c[2] += weight * src[2];
  67854. weight = subPixelX * subPixelY;
  67855. c[0] += weight * src[3];
  67856. c[1] += weight * src[4];
  67857. c[2] += weight * src[5];
  67858. dest->setARGB ((uint8) 255,
  67859. (uint8) (c[PixelRGB::indexR] >> 16),
  67860. (uint8) (c[PixelRGB::indexG] >> 16),
  67861. (uint8) (c[PixelRGB::indexB] >> 16));
  67862. }
  67863. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67864. {
  67865. uint32 c[3] = { 128, 128, 128 };
  67866. uint32 weight = (256 - subPixelX);
  67867. c[0] += weight * src[0];
  67868. c[1] += weight * src[1];
  67869. c[2] += weight * src[2];
  67870. c[0] += subPixelX * src[3];
  67871. c[1] += subPixelX * src[4];
  67872. c[2] += subPixelX * src[5];
  67873. dest->setARGB ((uint8) 255,
  67874. (uint8) (c[PixelRGB::indexR] >> 8),
  67875. (uint8) (c[PixelRGB::indexG] >> 8),
  67876. (uint8) (c[PixelRGB::indexB] >> 8));
  67877. }
  67878. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67879. {
  67880. uint32 c[3] = { 128, 128, 128 };
  67881. uint32 weight = (256 - subPixelY);
  67882. c[0] += weight * src[0];
  67883. c[1] += weight * src[1];
  67884. c[2] += weight * src[2];
  67885. src += this->srcData.lineStride;
  67886. c[0] += subPixelY * src[0];
  67887. c[1] += subPixelY * src[1];
  67888. c[2] += subPixelY * src[2];
  67889. dest->setARGB ((uint8) 255,
  67890. (uint8) (c[PixelRGB::indexR] >> 8),
  67891. (uint8) (c[PixelRGB::indexG] >> 8),
  67892. (uint8) (c[PixelRGB::indexB] >> 8));
  67893. }
  67894. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67895. {
  67896. uint32 c = 256 * 128;
  67897. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67898. c += src[1] * (subPixelX * (256 - subPixelY));
  67899. src += this->srcData.lineStride;
  67900. c += src[0] * ((256 - subPixelX) * subPixelY);
  67901. c += src[1] * (subPixelX * subPixelY);
  67902. *((uint8*) dest) = (uint8) (c >> 16);
  67903. }
  67904. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67905. {
  67906. uint32 c = 256 * 128;
  67907. c += src[0] * (256 - subPixelX) * alpha;
  67908. c += src[1] * subPixelX * alpha;
  67909. *((uint8*) dest) = (uint8) (c >> 16);
  67910. }
  67911. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67912. {
  67913. uint32 c = 256 * 128;
  67914. c += src[0] * (256 - subPixelY) * alpha;
  67915. src += this->srcData.lineStride;
  67916. c += src[0] * subPixelY * alpha;
  67917. *((uint8*) dest) = (uint8) (c >> 16);
  67918. }
  67919. class TransformedImageSpanInterpolator
  67920. {
  67921. public:
  67922. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67923. : inverseTransform (transform.inverted()),
  67924. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67925. {}
  67926. void setStartOfLine (float x, float y, const int numPixels) throw()
  67927. {
  67928. jassert (numPixels > 0);
  67929. x += pixelOffset;
  67930. y += pixelOffset;
  67931. float x1 = x, y1 = y;
  67932. x += numPixels;
  67933. inverseTransform.transformPoints (x1, y1, x, y);
  67934. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67935. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67936. }
  67937. void next (int& x, int& y) throw()
  67938. {
  67939. x = xBresenham.n;
  67940. xBresenham.stepToNext();
  67941. y = yBresenham.n;
  67942. yBresenham.stepToNext();
  67943. }
  67944. private:
  67945. class BresenhamInterpolator
  67946. {
  67947. public:
  67948. BresenhamInterpolator() throw() {}
  67949. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67950. {
  67951. numSteps = numSteps_;
  67952. step = (n2 - n1) / numSteps;
  67953. remainder = modulo = (n2 - n1) % numSteps;
  67954. n = n1 + pixelOffsetInt;
  67955. if (modulo <= 0)
  67956. {
  67957. modulo += numSteps;
  67958. remainder += numSteps;
  67959. --step;
  67960. }
  67961. modulo -= numSteps;
  67962. }
  67963. forcedinline void stepToNext() throw()
  67964. {
  67965. modulo += remainder;
  67966. n += step;
  67967. if (modulo > 0)
  67968. {
  67969. modulo -= numSteps;
  67970. ++n;
  67971. }
  67972. }
  67973. int n;
  67974. private:
  67975. int numSteps, step, modulo, remainder;
  67976. };
  67977. const AffineTransform inverseTransform;
  67978. BresenhamInterpolator xBresenham, yBresenham;
  67979. const float pixelOffset;
  67980. const int pixelOffsetInt;
  67981. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  67982. };
  67983. TransformedImageSpanInterpolator interpolator;
  67984. const Image::BitmapData& destData;
  67985. const Image::BitmapData& srcData;
  67986. const int extraAlpha;
  67987. const bool betterQuality;
  67988. const int maxX, maxY;
  67989. int y;
  67990. DestPixelType* linePixels;
  67991. HeapBlock <SrcPixelType> scratchBuffer;
  67992. int scratchSize;
  67993. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  67994. };
  67995. class ClipRegionBase : public ReferenceCountedObject
  67996. {
  67997. public:
  67998. ClipRegionBase() {}
  67999. virtual ~ClipRegionBase() {}
  68000. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68001. virtual const Ptr clone() const = 0;
  68002. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68003. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68004. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68005. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68006. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68007. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68008. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68009. virtual const Ptr translated (const Point<int>& delta) = 0;
  68010. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68011. virtual const Rectangle<int> getClipBounds() const = 0;
  68012. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68013. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68014. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68015. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68016. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68017. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68018. protected:
  68019. template <class Iterator>
  68020. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68021. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68022. {
  68023. switch (destData.pixelFormat)
  68024. {
  68025. case Image::ARGB:
  68026. switch (srcData.pixelFormat)
  68027. {
  68028. case Image::ARGB:
  68029. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68030. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68031. break;
  68032. case Image::RGB:
  68033. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68034. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68035. break;
  68036. default:
  68037. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68038. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68039. break;
  68040. }
  68041. break;
  68042. case Image::RGB:
  68043. switch (srcData.pixelFormat)
  68044. {
  68045. case Image::ARGB:
  68046. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68047. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68048. break;
  68049. case Image::RGB:
  68050. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68051. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68052. break;
  68053. default:
  68054. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68055. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68056. break;
  68057. }
  68058. break;
  68059. default:
  68060. switch (srcData.pixelFormat)
  68061. {
  68062. case Image::ARGB:
  68063. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68064. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68065. break;
  68066. case Image::RGB:
  68067. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68068. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68069. break;
  68070. default:
  68071. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68072. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68073. break;
  68074. }
  68075. break;
  68076. }
  68077. }
  68078. template <class Iterator>
  68079. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68080. {
  68081. switch (destData.pixelFormat)
  68082. {
  68083. case Image::ARGB:
  68084. switch (srcData.pixelFormat)
  68085. {
  68086. case Image::ARGB:
  68087. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68088. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68089. break;
  68090. case Image::RGB:
  68091. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68092. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68093. break;
  68094. default:
  68095. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68096. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68097. break;
  68098. }
  68099. break;
  68100. case Image::RGB:
  68101. switch (srcData.pixelFormat)
  68102. {
  68103. case Image::ARGB:
  68104. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68105. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68106. break;
  68107. case Image::RGB:
  68108. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68109. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68110. break;
  68111. default:
  68112. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68113. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68114. break;
  68115. }
  68116. break;
  68117. default:
  68118. switch (srcData.pixelFormat)
  68119. {
  68120. case Image::ARGB:
  68121. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68122. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68123. break;
  68124. case Image::RGB:
  68125. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68126. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68127. break;
  68128. default:
  68129. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68130. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68131. break;
  68132. }
  68133. break;
  68134. }
  68135. }
  68136. template <class Iterator, class DestPixelType>
  68137. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68138. {
  68139. jassert (destData.pixelStride == sizeof (DestPixelType));
  68140. if (replaceContents)
  68141. {
  68142. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68143. iter.iterate (r);
  68144. }
  68145. else
  68146. {
  68147. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68148. iter.iterate (r);
  68149. }
  68150. }
  68151. template <class Iterator, class DestPixelType>
  68152. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68153. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68154. {
  68155. jassert (destData.pixelStride == sizeof (DestPixelType));
  68156. if (g.isRadial)
  68157. {
  68158. if (isIdentity)
  68159. {
  68160. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68161. iter.iterate (renderer);
  68162. }
  68163. else
  68164. {
  68165. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68166. iter.iterate (renderer);
  68167. }
  68168. }
  68169. else
  68170. {
  68171. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68172. iter.iterate (renderer);
  68173. }
  68174. }
  68175. };
  68176. class ClipRegion_EdgeTable : public ClipRegionBase
  68177. {
  68178. public:
  68179. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68180. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68181. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68182. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68183. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68184. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68185. ~ClipRegion_EdgeTable() {}
  68186. const Ptr clone() const
  68187. {
  68188. return new ClipRegion_EdgeTable (*this);
  68189. }
  68190. const Ptr applyClipTo (const Ptr& target) const
  68191. {
  68192. return target->clipToEdgeTable (edgeTable);
  68193. }
  68194. const Ptr clipToRectangle (const Rectangle<int>& r)
  68195. {
  68196. edgeTable.clipToRectangle (r);
  68197. return edgeTable.isEmpty() ? 0 : this;
  68198. }
  68199. const Ptr clipToRectangleList (const RectangleList& r)
  68200. {
  68201. RectangleList inverse (edgeTable.getMaximumBounds());
  68202. if (inverse.subtract (r))
  68203. for (RectangleList::Iterator iter (inverse); iter.next();)
  68204. edgeTable.excludeRectangle (*iter.getRectangle());
  68205. return edgeTable.isEmpty() ? 0 : this;
  68206. }
  68207. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68208. {
  68209. edgeTable.excludeRectangle (r);
  68210. return edgeTable.isEmpty() ? 0 : this;
  68211. }
  68212. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68213. {
  68214. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68215. edgeTable.clipToEdgeTable (et);
  68216. return edgeTable.isEmpty() ? 0 : this;
  68217. }
  68218. const Ptr clipToEdgeTable (const EdgeTable& et)
  68219. {
  68220. edgeTable.clipToEdgeTable (et);
  68221. return edgeTable.isEmpty() ? 0 : this;
  68222. }
  68223. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68224. {
  68225. const Image::BitmapData srcData (image, false);
  68226. if (transform.isOnlyTranslation())
  68227. {
  68228. // If our translation doesn't involve any distortion, just use a simple blit..
  68229. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68230. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68231. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68232. {
  68233. const int imageX = ((tx + 128) >> 8);
  68234. const int imageY = ((ty + 128) >> 8);
  68235. if (image.getFormat() == Image::ARGB)
  68236. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68237. else
  68238. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68239. return edgeTable.isEmpty() ? 0 : this;
  68240. }
  68241. }
  68242. if (transform.isSingularity())
  68243. return 0;
  68244. {
  68245. Path p;
  68246. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68247. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68248. edgeTable.clipToEdgeTable (et2);
  68249. }
  68250. if (! edgeTable.isEmpty())
  68251. {
  68252. if (image.getFormat() == Image::ARGB)
  68253. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68254. else
  68255. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68256. }
  68257. return edgeTable.isEmpty() ? 0 : this;
  68258. }
  68259. const Ptr translated (const Point<int>& delta)
  68260. {
  68261. edgeTable.translate ((float) delta.getX(), delta.getY());
  68262. return edgeTable.isEmpty() ? 0 : this;
  68263. }
  68264. bool clipRegionIntersects (const Rectangle<int>& r) const
  68265. {
  68266. return edgeTable.getMaximumBounds().intersects (r);
  68267. }
  68268. const Rectangle<int> getClipBounds() const
  68269. {
  68270. return edgeTable.getMaximumBounds();
  68271. }
  68272. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68273. {
  68274. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68275. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68276. if (! clipped.isEmpty())
  68277. {
  68278. ClipRegion_EdgeTable et (clipped);
  68279. et.edgeTable.clipToEdgeTable (edgeTable);
  68280. et.fillAllWithColour (destData, colour, replaceContents);
  68281. }
  68282. }
  68283. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68284. {
  68285. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68286. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68287. if (! clipped.isEmpty())
  68288. {
  68289. ClipRegion_EdgeTable et (clipped);
  68290. et.edgeTable.clipToEdgeTable (edgeTable);
  68291. et.fillAllWithColour (destData, colour, false);
  68292. }
  68293. }
  68294. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68295. {
  68296. switch (destData.pixelFormat)
  68297. {
  68298. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68299. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68300. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68301. }
  68302. }
  68303. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68304. {
  68305. HeapBlock <PixelARGB> lookupTable;
  68306. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68307. jassert (numLookupEntries > 0);
  68308. switch (destData.pixelFormat)
  68309. {
  68310. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68311. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68312. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68313. }
  68314. }
  68315. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68316. {
  68317. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68318. }
  68319. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68320. {
  68321. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68322. }
  68323. EdgeTable edgeTable;
  68324. private:
  68325. template <class SrcPixelType>
  68326. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68327. {
  68328. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68329. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68330. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68331. edgeTable.getMaximumBounds().getWidth());
  68332. }
  68333. template <class SrcPixelType>
  68334. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68335. {
  68336. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68337. edgeTable.clipToRectangle (r);
  68338. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68339. for (int y = 0; y < r.getHeight(); ++y)
  68340. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68341. }
  68342. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68343. };
  68344. class ClipRegion_RectangleList : public ClipRegionBase
  68345. {
  68346. public:
  68347. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68348. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68349. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68350. ~ClipRegion_RectangleList() {}
  68351. const Ptr clone() const
  68352. {
  68353. return new ClipRegion_RectangleList (*this);
  68354. }
  68355. const Ptr applyClipTo (const Ptr& target) const
  68356. {
  68357. return target->clipToRectangleList (clip);
  68358. }
  68359. const Ptr clipToRectangle (const Rectangle<int>& r)
  68360. {
  68361. clip.clipTo (r);
  68362. return clip.isEmpty() ? 0 : this;
  68363. }
  68364. const Ptr clipToRectangleList (const RectangleList& r)
  68365. {
  68366. clip.clipTo (r);
  68367. return clip.isEmpty() ? 0 : this;
  68368. }
  68369. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68370. {
  68371. clip.subtract (r);
  68372. return clip.isEmpty() ? 0 : this;
  68373. }
  68374. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68375. {
  68376. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68377. }
  68378. const Ptr clipToEdgeTable (const EdgeTable& et)
  68379. {
  68380. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68381. }
  68382. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68383. {
  68384. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68385. }
  68386. const Ptr translated (const Point<int>& delta)
  68387. {
  68388. clip.offsetAll (delta.getX(), delta.getY());
  68389. return clip.isEmpty() ? 0 : this;
  68390. }
  68391. bool clipRegionIntersects (const Rectangle<int>& r) const
  68392. {
  68393. return clip.intersects (r);
  68394. }
  68395. const Rectangle<int> getClipBounds() const
  68396. {
  68397. return clip.getBounds();
  68398. }
  68399. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68400. {
  68401. SubRectangleIterator iter (clip, area);
  68402. switch (destData.pixelFormat)
  68403. {
  68404. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68405. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68406. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68407. }
  68408. }
  68409. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68410. {
  68411. SubRectangleIteratorFloat iter (clip, area);
  68412. switch (destData.pixelFormat)
  68413. {
  68414. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68415. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68416. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68417. }
  68418. }
  68419. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68420. {
  68421. switch (destData.pixelFormat)
  68422. {
  68423. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68424. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68425. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68426. }
  68427. }
  68428. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68429. {
  68430. HeapBlock <PixelARGB> lookupTable;
  68431. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68432. jassert (numLookupEntries > 0);
  68433. switch (destData.pixelFormat)
  68434. {
  68435. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68436. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68437. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68438. }
  68439. }
  68440. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68441. {
  68442. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68443. }
  68444. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68445. {
  68446. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68447. }
  68448. RectangleList clip;
  68449. template <class Renderer>
  68450. void iterate (Renderer& r) const throw()
  68451. {
  68452. RectangleList::Iterator iter (clip);
  68453. while (iter.next())
  68454. {
  68455. const Rectangle<int> rect (*iter.getRectangle());
  68456. const int x = rect.getX();
  68457. const int w = rect.getWidth();
  68458. jassert (w > 0);
  68459. const int bottom = rect.getBottom();
  68460. for (int y = rect.getY(); y < bottom; ++y)
  68461. {
  68462. r.setEdgeTableYPos (y);
  68463. r.handleEdgeTableLineFull (x, w);
  68464. }
  68465. }
  68466. }
  68467. private:
  68468. class SubRectangleIterator
  68469. {
  68470. public:
  68471. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68472. : clip (clip_), area (area_)
  68473. {
  68474. }
  68475. template <class Renderer>
  68476. void iterate (Renderer& r) const throw()
  68477. {
  68478. RectangleList::Iterator iter (clip);
  68479. while (iter.next())
  68480. {
  68481. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68482. if (! rect.isEmpty())
  68483. {
  68484. const int x = rect.getX();
  68485. const int w = rect.getWidth();
  68486. const int bottom = rect.getBottom();
  68487. for (int y = rect.getY(); y < bottom; ++y)
  68488. {
  68489. r.setEdgeTableYPos (y);
  68490. r.handleEdgeTableLineFull (x, w);
  68491. }
  68492. }
  68493. }
  68494. }
  68495. private:
  68496. const RectangleList& clip;
  68497. const Rectangle<int> area;
  68498. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68499. };
  68500. class SubRectangleIteratorFloat
  68501. {
  68502. public:
  68503. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68504. : clip (clip_), area (area_)
  68505. {
  68506. }
  68507. template <class Renderer>
  68508. void iterate (Renderer& r) const throw()
  68509. {
  68510. int left = roundToInt (area.getX() * 256.0f);
  68511. int top = roundToInt (area.getY() * 256.0f);
  68512. int right = roundToInt (area.getRight() * 256.0f);
  68513. int bottom = roundToInt (area.getBottom() * 256.0f);
  68514. int totalTop, totalLeft, totalBottom, totalRight;
  68515. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68516. if ((top >> 8) == (bottom >> 8))
  68517. {
  68518. topAlpha = bottom - top;
  68519. bottomAlpha = 0;
  68520. totalTop = top >> 8;
  68521. totalBottom = bottom = top = totalTop + 1;
  68522. }
  68523. else
  68524. {
  68525. if ((top & 255) == 0)
  68526. {
  68527. topAlpha = 0;
  68528. top = totalTop = (top >> 8);
  68529. }
  68530. else
  68531. {
  68532. topAlpha = 255 - (top & 255);
  68533. totalTop = (top >> 8);
  68534. top = totalTop + 1;
  68535. }
  68536. bottomAlpha = bottom & 255;
  68537. bottom >>= 8;
  68538. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68539. }
  68540. if ((left >> 8) == (right >> 8))
  68541. {
  68542. leftAlpha = right - left;
  68543. rightAlpha = 0;
  68544. totalLeft = (left >> 8);
  68545. totalRight = right = left = totalLeft + 1;
  68546. }
  68547. else
  68548. {
  68549. if ((left & 255) == 0)
  68550. {
  68551. leftAlpha = 0;
  68552. left = totalLeft = (left >> 8);
  68553. }
  68554. else
  68555. {
  68556. leftAlpha = 255 - (left & 255);
  68557. totalLeft = (left >> 8);
  68558. left = totalLeft + 1;
  68559. }
  68560. rightAlpha = right & 255;
  68561. right >>= 8;
  68562. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68563. }
  68564. RectangleList::Iterator iter (clip);
  68565. while (iter.next())
  68566. {
  68567. const int clipLeft = iter.getRectangle()->getX();
  68568. const int clipRight = iter.getRectangle()->getRight();
  68569. const int clipTop = iter.getRectangle()->getY();
  68570. const int clipBottom = iter.getRectangle()->getBottom();
  68571. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68572. {
  68573. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68574. {
  68575. if (topAlpha != 0 && totalTop >= clipTop)
  68576. {
  68577. r.setEdgeTableYPos (totalTop);
  68578. r.handleEdgeTablePixel (left, topAlpha);
  68579. }
  68580. const int endY = jmin (bottom, clipBottom);
  68581. for (int y = jmax (clipTop, top); y < endY; ++y)
  68582. {
  68583. r.setEdgeTableYPos (y);
  68584. r.handleEdgeTablePixelFull (left);
  68585. }
  68586. if (bottomAlpha != 0 && bottom < clipBottom)
  68587. {
  68588. r.setEdgeTableYPos (bottom);
  68589. r.handleEdgeTablePixel (left, bottomAlpha);
  68590. }
  68591. }
  68592. else
  68593. {
  68594. const int clippedLeft = jmax (left, clipLeft);
  68595. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68596. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68597. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68598. if (topAlpha != 0 && totalTop >= clipTop)
  68599. {
  68600. r.setEdgeTableYPos (totalTop);
  68601. if (doLeftAlpha)
  68602. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68603. if (clippedWidth > 0)
  68604. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68605. if (doRightAlpha)
  68606. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68607. }
  68608. const int endY = jmin (bottom, clipBottom);
  68609. for (int y = jmax (clipTop, top); y < endY; ++y)
  68610. {
  68611. r.setEdgeTableYPos (y);
  68612. if (doLeftAlpha)
  68613. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68614. if (clippedWidth > 0)
  68615. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68616. if (doRightAlpha)
  68617. r.handleEdgeTablePixel (right, rightAlpha);
  68618. }
  68619. if (bottomAlpha != 0 && bottom < clipBottom)
  68620. {
  68621. r.setEdgeTableYPos (bottom);
  68622. if (doLeftAlpha)
  68623. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68624. if (clippedWidth > 0)
  68625. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68626. if (doRightAlpha)
  68627. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68628. }
  68629. }
  68630. }
  68631. }
  68632. }
  68633. private:
  68634. const RectangleList& clip;
  68635. const Rectangle<float>& area;
  68636. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68637. };
  68638. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68639. };
  68640. }
  68641. class LowLevelGraphicsSoftwareRenderer::SavedState
  68642. {
  68643. public:
  68644. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68645. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68646. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68647. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68648. {
  68649. }
  68650. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68651. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68652. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68653. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68654. {
  68655. }
  68656. SavedState (const SavedState& other)
  68657. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68658. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68659. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68660. interpolationQuality (other.interpolationQuality)
  68661. {
  68662. }
  68663. void setOrigin (const int x, const int y) throw()
  68664. {
  68665. if (isOnlyTranslated)
  68666. {
  68667. xOffset += x;
  68668. yOffset += y;
  68669. }
  68670. else
  68671. {
  68672. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68673. }
  68674. }
  68675. void addTransform (const AffineTransform& t)
  68676. {
  68677. if ((! isOnlyTranslated)
  68678. || (! t.isOnlyTranslation())
  68679. || (int) (t.getTranslationX() * 256.0f) != 0
  68680. || (int) (t.getTranslationY() * 256.0f) != 0)
  68681. {
  68682. complexTransform = getTransformWith (t);
  68683. isOnlyTranslated = false;
  68684. }
  68685. else
  68686. {
  68687. xOffset += (int) t.getTranslationX();
  68688. yOffset += (int) t.getTranslationY();
  68689. }
  68690. }
  68691. float getScaleFactor() const
  68692. {
  68693. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68694. }
  68695. bool clipToRectangle (const Rectangle<int>& r)
  68696. {
  68697. if (clip != 0)
  68698. {
  68699. if (isOnlyTranslated)
  68700. {
  68701. cloneClipIfMultiplyReferenced();
  68702. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68703. }
  68704. else
  68705. {
  68706. Path p;
  68707. p.addRectangle (r);
  68708. clipToPath (p, AffineTransform::identity);
  68709. }
  68710. }
  68711. return clip != 0;
  68712. }
  68713. bool clipToRectangleList (const RectangleList& r)
  68714. {
  68715. if (clip != 0)
  68716. {
  68717. if (isOnlyTranslated)
  68718. {
  68719. cloneClipIfMultiplyReferenced();
  68720. RectangleList offsetList (r);
  68721. offsetList.offsetAll (xOffset, yOffset);
  68722. clip = clip->clipToRectangleList (offsetList);
  68723. }
  68724. else
  68725. {
  68726. clipToPath (r.toPath(), AffineTransform::identity);
  68727. }
  68728. }
  68729. return clip != 0;
  68730. }
  68731. bool excludeClipRectangle (const Rectangle<int>& r)
  68732. {
  68733. if (clip != 0)
  68734. {
  68735. cloneClipIfMultiplyReferenced();
  68736. if (isOnlyTranslated)
  68737. {
  68738. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68739. }
  68740. else
  68741. {
  68742. Path p;
  68743. p.addRectangle (r.toFloat());
  68744. p.applyTransform (complexTransform);
  68745. p.addRectangle (clip->getClipBounds().toFloat());
  68746. p.setUsingNonZeroWinding (false);
  68747. clip = clip->clipToPath (p, AffineTransform::identity);
  68748. }
  68749. }
  68750. return clip != 0;
  68751. }
  68752. void clipToPath (const Path& p, const AffineTransform& transform)
  68753. {
  68754. if (clip != 0)
  68755. {
  68756. cloneClipIfMultiplyReferenced();
  68757. clip = clip->clipToPath (p, getTransformWith (transform));
  68758. }
  68759. }
  68760. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  68761. {
  68762. if (clip != 0)
  68763. {
  68764. if (sourceImage.hasAlphaChannel())
  68765. {
  68766. cloneClipIfMultiplyReferenced();
  68767. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  68768. interpolationQuality != Graphics::lowResamplingQuality);
  68769. }
  68770. else
  68771. {
  68772. Path p;
  68773. p.addRectangle (sourceImage.getBounds());
  68774. clipToPath (p, t);
  68775. }
  68776. }
  68777. }
  68778. bool clipRegionIntersects (const Rectangle<int>& r) const
  68779. {
  68780. if (clip != 0)
  68781. {
  68782. if (isOnlyTranslated)
  68783. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68784. else
  68785. return getClipBounds().intersects (r);
  68786. }
  68787. return false;
  68788. }
  68789. const Rectangle<int> getUntransformedClipBounds() const
  68790. {
  68791. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68792. }
  68793. const Rectangle<int> getClipBounds() const
  68794. {
  68795. if (clip != 0)
  68796. {
  68797. if (isOnlyTranslated)
  68798. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68799. else
  68800. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68801. }
  68802. return Rectangle<int>();
  68803. }
  68804. SavedState* beginTransparencyLayer (float opacity)
  68805. {
  68806. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68807. SavedState* s = new SavedState (*this);
  68808. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  68809. s->compositionAlpha = opacity;
  68810. if (s->isOnlyTranslated)
  68811. {
  68812. s->xOffset -= layerBounds.getX();
  68813. s->yOffset -= layerBounds.getY();
  68814. }
  68815. else
  68816. {
  68817. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  68818. (float) -layerBounds.getY()));
  68819. }
  68820. s->cloneClipIfMultiplyReferenced();
  68821. s->clip = s->clip->translated (-layerBounds.getPosition());
  68822. return s;
  68823. }
  68824. void endTransparencyLayer (SavedState& layerState)
  68825. {
  68826. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68827. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68828. g->setOpacity (layerState.compositionAlpha);
  68829. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  68830. (float) layerBounds.getY()), false);
  68831. }
  68832. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68833. {
  68834. if (clip != 0)
  68835. {
  68836. if (isOnlyTranslated)
  68837. {
  68838. if (fillType.isColour())
  68839. {
  68840. Image::BitmapData destData (image, true);
  68841. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68842. }
  68843. else
  68844. {
  68845. const Rectangle<int> totalClip (clip->getClipBounds());
  68846. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68847. if (! clipped.isEmpty())
  68848. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68849. }
  68850. }
  68851. else
  68852. {
  68853. Path p;
  68854. p.addRectangle (r);
  68855. fillPath (p, AffineTransform::identity);
  68856. }
  68857. }
  68858. }
  68859. void fillRect (const Rectangle<float>& r)
  68860. {
  68861. if (clip != 0)
  68862. {
  68863. if (isOnlyTranslated)
  68864. {
  68865. if (fillType.isColour())
  68866. {
  68867. Image::BitmapData destData (image, true);
  68868. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68869. }
  68870. else
  68871. {
  68872. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68873. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68874. if (! clipped.isEmpty())
  68875. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68876. }
  68877. }
  68878. else
  68879. {
  68880. Path p;
  68881. p.addRectangle (r);
  68882. fillPath (p, AffineTransform::identity);
  68883. }
  68884. }
  68885. }
  68886. void fillPath (const Path& path, const AffineTransform& transform)
  68887. {
  68888. if (clip != 0)
  68889. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68890. }
  68891. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  68892. {
  68893. jassert (isOnlyTranslated);
  68894. if (clip != 0)
  68895. {
  68896. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68897. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68898. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68899. fillShape (shapeToFill, false);
  68900. }
  68901. }
  68902. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68903. {
  68904. jassert (clip != 0);
  68905. shapeToFill = clip->applyClipTo (shapeToFill);
  68906. if (shapeToFill != 0)
  68907. {
  68908. Image::BitmapData destData (image, true);
  68909. if (fillType.isGradient())
  68910. {
  68911. jassert (! replaceContents); // that option is just for solid colours
  68912. ColourGradient g2 (*(fillType.gradient));
  68913. g2.multiplyOpacity (fillType.getOpacity());
  68914. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68915. const bool isIdentity = transform.isOnlyTranslation();
  68916. if (isIdentity)
  68917. {
  68918. // If our translation doesn't involve any distortion, we can speed it up..
  68919. g2.point1.applyTransform (transform);
  68920. g2.point2.applyTransform (transform);
  68921. transform = AffineTransform::identity;
  68922. }
  68923. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68924. }
  68925. else if (fillType.isTiledImage())
  68926. {
  68927. renderImage (fillType.image, fillType.transform, shapeToFill);
  68928. }
  68929. else
  68930. {
  68931. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68932. }
  68933. }
  68934. }
  68935. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68936. {
  68937. const AffineTransform transform (getTransformWith (t));
  68938. const Image::BitmapData destData (image, true);
  68939. const Image::BitmapData srcData (sourceImage, false);
  68940. const int alpha = fillType.colour.getAlpha();
  68941. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68942. if (transform.isOnlyTranslation())
  68943. {
  68944. // If our translation doesn't involve any distortion, just use a simple blit..
  68945. int tx = (int) (transform.getTranslationX() * 256.0f);
  68946. int ty = (int) (transform.getTranslationY() * 256.0f);
  68947. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68948. {
  68949. tx = ((tx + 128) >> 8);
  68950. ty = ((ty + 128) >> 8);
  68951. if (tiledFillClipRegion != 0)
  68952. {
  68953. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68954. }
  68955. else
  68956. {
  68957. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  68958. c = clip->applyClipTo (c);
  68959. if (c != 0)
  68960. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68961. }
  68962. return;
  68963. }
  68964. }
  68965. if (transform.isSingularity())
  68966. return;
  68967. if (tiledFillClipRegion != 0)
  68968. {
  68969. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68970. }
  68971. else
  68972. {
  68973. Path p;
  68974. p.addRectangle (sourceImage.getBounds());
  68975. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68976. c = c->clipToPath (p, transform);
  68977. if (c != 0)
  68978. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68979. }
  68980. }
  68981. Image image;
  68982. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68983. private:
  68984. AffineTransform complexTransform;
  68985. int xOffset, yOffset;
  68986. float compositionAlpha;
  68987. public:
  68988. bool isOnlyTranslated;
  68989. Font font;
  68990. FillType fillType;
  68991. Graphics::ResamplingQuality interpolationQuality;
  68992. private:
  68993. void cloneClipIfMultiplyReferenced()
  68994. {
  68995. if (clip->getReferenceCount() > 1)
  68996. clip = clip->clone();
  68997. }
  68998. const AffineTransform getTransform() const
  68999. {
  69000. if (isOnlyTranslated)
  69001. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  69002. return complexTransform;
  69003. }
  69004. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  69005. {
  69006. if (isOnlyTranslated)
  69007. return userTransform.translated ((float) xOffset, (float) yOffset);
  69008. return userTransform.followedBy (complexTransform);
  69009. }
  69010. SavedState& operator= (const SavedState&);
  69011. };
  69012. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69013. : image (image_),
  69014. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69015. {
  69016. }
  69017. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69018. const RectangleList& initialClip)
  69019. : image (image_),
  69020. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69021. {
  69022. }
  69023. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69024. {
  69025. }
  69026. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69027. {
  69028. return false;
  69029. }
  69030. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69031. {
  69032. currentState->setOrigin (x, y);
  69033. }
  69034. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69035. {
  69036. currentState->addTransform (transform);
  69037. }
  69038. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69039. {
  69040. return currentState->getScaleFactor();
  69041. }
  69042. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69043. {
  69044. return currentState->clipToRectangle (r);
  69045. }
  69046. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69047. {
  69048. return currentState->clipToRectangleList (clipRegion);
  69049. }
  69050. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69051. {
  69052. currentState->excludeClipRectangle (r);
  69053. }
  69054. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69055. {
  69056. currentState->clipToPath (path, transform);
  69057. }
  69058. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69059. {
  69060. currentState->clipToImageAlpha (sourceImage, transform);
  69061. }
  69062. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69063. {
  69064. return currentState->clipRegionIntersects (r);
  69065. }
  69066. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69067. {
  69068. return currentState->getClipBounds();
  69069. }
  69070. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69071. {
  69072. return currentState->clip == 0;
  69073. }
  69074. void LowLevelGraphicsSoftwareRenderer::saveState()
  69075. {
  69076. stateStack.add (new SavedState (*currentState));
  69077. }
  69078. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69079. {
  69080. SavedState* const top = stateStack.getLast();
  69081. if (top != 0)
  69082. {
  69083. currentState = top;
  69084. stateStack.removeLast (1, false);
  69085. }
  69086. else
  69087. {
  69088. jassertfalse; // trying to pop with an empty stack!
  69089. }
  69090. }
  69091. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69092. {
  69093. saveState();
  69094. currentState = currentState->beginTransparencyLayer (opacity);
  69095. }
  69096. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69097. {
  69098. const ScopedPointer<SavedState> layer (currentState);
  69099. restoreState();
  69100. currentState->endTransparencyLayer (*layer);
  69101. }
  69102. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69103. {
  69104. currentState->fillType = fillType;
  69105. }
  69106. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69107. {
  69108. currentState->fillType.setOpacity (newOpacity);
  69109. }
  69110. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69111. {
  69112. currentState->interpolationQuality = quality;
  69113. }
  69114. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69115. {
  69116. currentState->fillRect (r, replaceExistingContents);
  69117. }
  69118. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69119. {
  69120. currentState->fillPath (path, transform);
  69121. }
  69122. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69123. {
  69124. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69125. }
  69126. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69127. {
  69128. Path p;
  69129. p.addLineSegment (line, 1.0f);
  69130. fillPath (p, AffineTransform::identity);
  69131. }
  69132. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69133. {
  69134. if (bottom > top)
  69135. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69136. }
  69137. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69138. {
  69139. if (right > left)
  69140. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69141. }
  69142. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69143. {
  69144. public:
  69145. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69146. void draw (SavedState& state, float x, const float y) const
  69147. {
  69148. if (snapToIntegerCoordinate)
  69149. x = std::floor (x + 0.5f);
  69150. if (edgeTable != 0)
  69151. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69152. }
  69153. void generate (const Font& newFont, const int glyphNumber)
  69154. {
  69155. font = newFont;
  69156. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69157. glyph = glyphNumber;
  69158. edgeTable = 0;
  69159. Path glyphPath;
  69160. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69161. if (! glyphPath.isEmpty())
  69162. {
  69163. const float fontHeight = font.getHeight();
  69164. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69165. #if JUCE_MAC || JUCE_IOS
  69166. .translated (0.0f, -0.5f)
  69167. #endif
  69168. );
  69169. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69170. glyphPath, transform);
  69171. }
  69172. }
  69173. Font font;
  69174. int glyph, lastAccessCount;
  69175. bool snapToIntegerCoordinate;
  69176. private:
  69177. ScopedPointer <EdgeTable> edgeTable;
  69178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69179. };
  69180. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69181. {
  69182. public:
  69183. GlyphCache()
  69184. : accessCounter (0), hits (0), misses (0)
  69185. {
  69186. addNewGlyphSlots (120);
  69187. }
  69188. ~GlyphCache()
  69189. {
  69190. clearSingletonInstance();
  69191. }
  69192. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69193. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69194. {
  69195. ++accessCounter;
  69196. int oldestCounter = std::numeric_limits<int>::max();
  69197. CachedGlyph* oldest = 0;
  69198. for (int i = glyphs.size(); --i >= 0;)
  69199. {
  69200. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69201. if (glyph->glyph == glyphNumber && glyph->font == font)
  69202. {
  69203. ++hits;
  69204. glyph->lastAccessCount = accessCounter;
  69205. glyph->draw (state, x, y);
  69206. return;
  69207. }
  69208. if (glyph->lastAccessCount <= oldestCounter)
  69209. {
  69210. oldestCounter = glyph->lastAccessCount;
  69211. oldest = glyph;
  69212. }
  69213. }
  69214. if (hits + ++misses > (glyphs.size() << 4))
  69215. {
  69216. if (misses * 2 > hits)
  69217. addNewGlyphSlots (32);
  69218. hits = misses = 0;
  69219. oldest = glyphs.getLast();
  69220. }
  69221. jassert (oldest != 0);
  69222. oldest->lastAccessCount = accessCounter;
  69223. oldest->generate (font, glyphNumber);
  69224. oldest->draw (state, x, y);
  69225. }
  69226. private:
  69227. friend class OwnedArray <CachedGlyph>;
  69228. OwnedArray <CachedGlyph> glyphs;
  69229. int accessCounter, hits, misses;
  69230. void addNewGlyphSlots (int num)
  69231. {
  69232. while (--num >= 0)
  69233. glyphs.add (new CachedGlyph());
  69234. }
  69235. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69236. };
  69237. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69238. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69239. {
  69240. currentState->font = newFont;
  69241. }
  69242. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69243. {
  69244. return currentState->font;
  69245. }
  69246. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69247. {
  69248. Font& f = currentState->font;
  69249. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69250. {
  69251. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69252. transform.getTranslationX(),
  69253. transform.getTranslationY());
  69254. }
  69255. else
  69256. {
  69257. Path p;
  69258. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69259. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69260. }
  69261. }
  69262. #if JUCE_MSVC
  69263. #pragma warning (pop)
  69264. #if JUCE_DEBUG
  69265. #pragma optimize ("", on) // resets optimisations to the project defaults
  69266. #endif
  69267. #endif
  69268. END_JUCE_NAMESPACE
  69269. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69270. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69271. BEGIN_JUCE_NAMESPACE
  69272. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69273. : flags (other.flags)
  69274. {
  69275. }
  69276. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69277. {
  69278. flags = other.flags;
  69279. return *this;
  69280. }
  69281. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69282. const double dx, const double dy, const double dw, const double dh) const throw()
  69283. {
  69284. if (w == 0 || h == 0)
  69285. return;
  69286. if ((flags & stretchToFit) != 0)
  69287. {
  69288. x = dx;
  69289. y = dy;
  69290. w = dw;
  69291. h = dh;
  69292. }
  69293. else
  69294. {
  69295. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69296. : jmin (dw / w, dh / h);
  69297. if ((flags & onlyReduceInSize) != 0)
  69298. scale = jmin (scale, 1.0);
  69299. if ((flags & onlyIncreaseInSize) != 0)
  69300. scale = jmax (scale, 1.0);
  69301. w *= scale;
  69302. h *= scale;
  69303. if ((flags & xLeft) != 0)
  69304. x = dx;
  69305. else if ((flags & xRight) != 0)
  69306. x = dx + dw - w;
  69307. else
  69308. x = dx + (dw - w) * 0.5;
  69309. if ((flags & yTop) != 0)
  69310. y = dy;
  69311. else if ((flags & yBottom) != 0)
  69312. y = dy + dh - h;
  69313. else
  69314. y = dy + (dh - h) * 0.5;
  69315. }
  69316. }
  69317. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69318. {
  69319. if (source.isEmpty())
  69320. return AffineTransform::identity;
  69321. float newX = destination.getX();
  69322. float newY = destination.getY();
  69323. float scaleX = destination.getWidth() / source.getWidth();
  69324. float scaleY = destination.getHeight() / source.getHeight();
  69325. if ((flags & stretchToFit) == 0)
  69326. {
  69327. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69328. : jmin (scaleX, scaleY);
  69329. if ((flags & onlyReduceInSize) != 0)
  69330. scaleX = jmin (scaleX, 1.0f);
  69331. if ((flags & onlyIncreaseInSize) != 0)
  69332. scaleX = jmax (scaleX, 1.0f);
  69333. scaleY = scaleX;
  69334. if ((flags & xRight) != 0)
  69335. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69336. else if ((flags & xLeft) == 0)
  69337. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69338. if ((flags & yBottom) != 0)
  69339. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69340. else if ((flags & yTop) == 0)
  69341. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69342. }
  69343. return AffineTransform::translation (-source.getX(), -source.getY())
  69344. .scaled (scaleX, scaleY)
  69345. .translated (newX, newY);
  69346. }
  69347. END_JUCE_NAMESPACE
  69348. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69349. /*** Start of inlined file: juce_Drawable.cpp ***/
  69350. BEGIN_JUCE_NAMESPACE
  69351. Drawable::Drawable()
  69352. {
  69353. setInterceptsMouseClicks (false, false);
  69354. setPaintingIsUnclipped (true);
  69355. }
  69356. Drawable::~Drawable()
  69357. {
  69358. }
  69359. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69360. {
  69361. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69362. }
  69363. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69364. {
  69365. Graphics::ScopedSaveState ss (g);
  69366. const float oldOpacity = getAlpha();
  69367. setAlpha (opacity);
  69368. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69369. (float) -originRelativeToComponent.getY())
  69370. .followedBy (getTransform())
  69371. .followedBy (transform));
  69372. if (! g.isClipEmpty())
  69373. paintEntireComponent (g, false);
  69374. setAlpha (oldOpacity);
  69375. }
  69376. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69377. {
  69378. draw (g, opacity, AffineTransform::translation (x, y));
  69379. }
  69380. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69381. {
  69382. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69383. }
  69384. DrawableComposite* Drawable::getParent() const
  69385. {
  69386. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69387. }
  69388. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69389. {
  69390. g.setOrigin (originRelativeToComponent.getX(),
  69391. originRelativeToComponent.getY());
  69392. }
  69393. void Drawable::parentHierarchyChanged()
  69394. {
  69395. setBoundsToEnclose (getDrawableBounds());
  69396. }
  69397. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69398. {
  69399. Drawable* const parent = getParent();
  69400. Point<int> parentOrigin;
  69401. if (parent != 0)
  69402. parentOrigin = parent->originRelativeToComponent;
  69403. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69404. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69405. setBounds (newBounds);
  69406. }
  69407. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69408. {
  69409. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69410. }
  69411. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69412. {
  69413. if (! area.isEmpty())
  69414. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69415. }
  69416. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69417. {
  69418. Drawable* result = 0;
  69419. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69420. if (image.isValid())
  69421. {
  69422. DrawableImage* const di = new DrawableImage();
  69423. di->setImage (image);
  69424. result = di;
  69425. }
  69426. else
  69427. {
  69428. const String asString (String::createStringFromData (data, (int) numBytes));
  69429. XmlDocument doc (asString);
  69430. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69431. if (outer != 0 && outer->hasTagName ("svg"))
  69432. {
  69433. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69434. if (svg != 0)
  69435. result = Drawable::createFromSVG (*svg);
  69436. }
  69437. }
  69438. return result;
  69439. }
  69440. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69441. {
  69442. MemoryOutputStream mo;
  69443. mo.writeFromInputStream (dataSource, -1);
  69444. return createFromImageData (mo.getData(), mo.getDataSize());
  69445. }
  69446. Drawable* Drawable::createFromImageFile (const File& file)
  69447. {
  69448. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69449. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69450. }
  69451. template <class DrawableClass>
  69452. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69453. {
  69454. public:
  69455. DrawableTypeHandler()
  69456. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69457. {
  69458. }
  69459. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69460. {
  69461. DrawableClass* const d = new DrawableClass();
  69462. if (parent != 0)
  69463. parent->addAndMakeVisible (d);
  69464. updateComponentFromState (d, state);
  69465. return d;
  69466. }
  69467. void updateComponentFromState (Component* component, const ValueTree& state)
  69468. {
  69469. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69470. jassert (d != 0);
  69471. d->refreshFromValueTree (state, *this->getBuilder());
  69472. }
  69473. };
  69474. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69475. {
  69476. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69477. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69478. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69479. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69480. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69481. }
  69482. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69483. {
  69484. ComponentBuilder builder (tree);
  69485. builder.setImageProvider (imageProvider);
  69486. registerDrawableTypeHandlers (builder);
  69487. ScopedPointer<Component> comp (builder.createComponent());
  69488. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69489. if (d != 0)
  69490. comp.release();
  69491. return d;
  69492. }
  69493. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69494. : state (state_)
  69495. {
  69496. }
  69497. const String Drawable::ValueTreeWrapperBase::getID() const
  69498. {
  69499. return state [ComponentBuilder::idProperty];
  69500. }
  69501. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69502. {
  69503. if (newID.isEmpty())
  69504. state.removeProperty (ComponentBuilder::idProperty, 0);
  69505. else
  69506. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69507. }
  69508. END_JUCE_NAMESPACE
  69509. /*** End of inlined file: juce_Drawable.cpp ***/
  69510. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69511. BEGIN_JUCE_NAMESPACE
  69512. DrawableShape::DrawableShape()
  69513. : strokeType (0.0f),
  69514. mainFill (Colours::black),
  69515. strokeFill (Colours::black)
  69516. {
  69517. }
  69518. DrawableShape::DrawableShape (const DrawableShape& other)
  69519. : strokeType (other.strokeType),
  69520. mainFill (other.mainFill),
  69521. strokeFill (other.strokeFill)
  69522. {
  69523. }
  69524. DrawableShape::~DrawableShape()
  69525. {
  69526. }
  69527. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69528. {
  69529. public:
  69530. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  69531. : RelativeCoordinatePositionerBase (component_),
  69532. owner (component_),
  69533. fill (fill_),
  69534. isMainFill (isMainFill_)
  69535. {
  69536. }
  69537. bool registerCoordinates()
  69538. {
  69539. bool ok = addPoint (fill.gradientPoint1);
  69540. ok = addPoint (fill.gradientPoint2) && ok;
  69541. return addPoint (fill.gradientPoint3) && ok;
  69542. }
  69543. void applyToComponentBounds()
  69544. {
  69545. ComponentScope scope (owner);
  69546. if (isMainFill ? owner.mainFill.recalculateCoords (&scope)
  69547. : owner.strokeFill.recalculateCoords (&scope))
  69548. owner.repaint();
  69549. }
  69550. private:
  69551. DrawableShape& owner;
  69552. const DrawableShape::RelativeFillType fill;
  69553. const bool isMainFill;
  69554. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  69555. };
  69556. void DrawableShape::setFill (const FillType& newFill)
  69557. {
  69558. setFill (RelativeFillType (newFill));
  69559. }
  69560. void DrawableShape::setStrokeFill (const FillType& newFill)
  69561. {
  69562. setStrokeFill (RelativeFillType (newFill));
  69563. }
  69564. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  69565. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  69566. {
  69567. if (fill != newFill)
  69568. {
  69569. fill = newFill;
  69570. positioner = 0;
  69571. if (fill.isDynamic())
  69572. {
  69573. positioner = new RelativePositioner (*this, fill, true);
  69574. positioner->apply();
  69575. }
  69576. else
  69577. {
  69578. fill.recalculateCoords (0);
  69579. }
  69580. repaint();
  69581. }
  69582. }
  69583. void DrawableShape::setFill (const RelativeFillType& newFill)
  69584. {
  69585. setFillInternal (mainFill, newFill, mainFillPositioner);
  69586. }
  69587. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  69588. {
  69589. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  69590. }
  69591. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69592. {
  69593. if (strokeType != newStrokeType)
  69594. {
  69595. strokeType = newStrokeType;
  69596. strokeChanged();
  69597. }
  69598. }
  69599. void DrawableShape::setStrokeThickness (const float newThickness)
  69600. {
  69601. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69602. }
  69603. bool DrawableShape::isStrokeVisible() const throw()
  69604. {
  69605. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  69606. }
  69607. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  69608. {
  69609. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  69610. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  69611. }
  69612. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69613. {
  69614. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  69615. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  69616. state.setStrokeType (strokeType, undoManager);
  69617. }
  69618. void DrawableShape::paint (Graphics& g)
  69619. {
  69620. transformContextToCorrectOrigin (g);
  69621. g.setFillType (mainFill.fill);
  69622. g.fillPath (path);
  69623. if (isStrokeVisible())
  69624. {
  69625. g.setFillType (strokeFill.fill);
  69626. g.fillPath (strokePath);
  69627. }
  69628. }
  69629. void DrawableShape::pathChanged()
  69630. {
  69631. strokeChanged();
  69632. }
  69633. void DrawableShape::strokeChanged()
  69634. {
  69635. strokePath.clear();
  69636. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69637. setBoundsToEnclose (getDrawableBounds());
  69638. repaint();
  69639. }
  69640. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69641. {
  69642. if (isStrokeVisible())
  69643. return strokePath.getBounds();
  69644. else
  69645. return path.getBounds();
  69646. }
  69647. bool DrawableShape::hitTest (int x, int y)
  69648. {
  69649. bool allowsClicksOnThisComponent, allowsClicksOnChildComponents;
  69650. getInterceptsMouseClicks (allowsClicksOnThisComponent, allowsClicksOnChildComponents);
  69651. if (! allowsClicksOnThisComponent)
  69652. return false;
  69653. const float globalX = (float) (x - originRelativeToComponent.getX());
  69654. const float globalY = (float) (y - originRelativeToComponent.getY());
  69655. return path.contains (globalX, globalY)
  69656. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69657. }
  69658. DrawableShape::RelativeFillType::RelativeFillType()
  69659. {
  69660. }
  69661. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  69662. : fill (fill_)
  69663. {
  69664. if (fill.isGradient())
  69665. {
  69666. const ColourGradient& g = *fill.gradient;
  69667. gradientPoint1 = g.point1.transformedBy (fill.transform);
  69668. gradientPoint2 = g.point2.transformedBy (fill.transform);
  69669. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69670. g.point1.getY() + g.point1.getX() - g.point2.getX())
  69671. .transformedBy (fill.transform);
  69672. fill.transform = AffineTransform::identity;
  69673. }
  69674. }
  69675. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  69676. : fill (other.fill),
  69677. gradientPoint1 (other.gradientPoint1),
  69678. gradientPoint2 (other.gradientPoint2),
  69679. gradientPoint3 (other.gradientPoint3)
  69680. {
  69681. }
  69682. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  69683. {
  69684. fill = other.fill;
  69685. gradientPoint1 = other.gradientPoint1;
  69686. gradientPoint2 = other.gradientPoint2;
  69687. gradientPoint3 = other.gradientPoint3;
  69688. return *this;
  69689. }
  69690. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  69691. {
  69692. return fill == other.fill
  69693. && ((! fill.isGradient())
  69694. || (gradientPoint1 == other.gradientPoint1
  69695. && gradientPoint2 == other.gradientPoint2
  69696. && gradientPoint3 == other.gradientPoint3));
  69697. }
  69698. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  69699. {
  69700. return ! operator== (other);
  69701. }
  69702. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::Scope* scope)
  69703. {
  69704. if (fill.isGradient())
  69705. {
  69706. const Point<float> g1 (gradientPoint1.resolve (scope));
  69707. const Point<float> g2 (gradientPoint2.resolve (scope));
  69708. AffineTransform t;
  69709. ColourGradient& g = *fill.gradient;
  69710. if (g.isRadial)
  69711. {
  69712. const Point<float> g3 (gradientPoint3.resolve (scope));
  69713. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  69714. g1.getY() + g1.getX() - g2.getX());
  69715. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  69716. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  69717. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  69718. }
  69719. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  69720. {
  69721. g.point1 = g1;
  69722. g.point2 = g2;
  69723. fill.transform = t;
  69724. return true;
  69725. }
  69726. }
  69727. return false;
  69728. }
  69729. bool DrawableShape::RelativeFillType::isDynamic() const
  69730. {
  69731. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  69732. }
  69733. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69734. {
  69735. if (fill.isColour())
  69736. {
  69737. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  69738. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  69739. }
  69740. else if (fill.isGradient())
  69741. {
  69742. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  69743. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  69744. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  69745. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  69746. const ColourGradient& cg = *fill.gradient;
  69747. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  69748. String s;
  69749. for (int i = 0; i < cg.getNumColours(); ++i)
  69750. s << ' ' << cg.getColourPosition (i)
  69751. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  69752. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  69753. }
  69754. else if (fill.isTiledImage())
  69755. {
  69756. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  69757. if (imageProvider != 0)
  69758. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  69759. if (fill.getOpacity() < 1.0f)
  69760. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  69761. else
  69762. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  69763. }
  69764. else
  69765. {
  69766. jassertfalse;
  69767. }
  69768. }
  69769. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  69770. {
  69771. const String newType (v [FillAndStrokeState::type].toString());
  69772. if (newType == "solid")
  69773. {
  69774. const String colourString (v [FillAndStrokeState::colour].toString());
  69775. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69776. : (uint32) colourString.getHexValue32()));
  69777. return true;
  69778. }
  69779. else if (newType == "gradient")
  69780. {
  69781. ColourGradient g;
  69782. g.isRadial = v [FillAndStrokeState::radial];
  69783. StringArray colourSteps;
  69784. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  69785. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69786. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69787. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69788. fill.setGradient (g);
  69789. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  69790. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  69791. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  69792. return true;
  69793. }
  69794. else if (newType == "image")
  69795. {
  69796. Image im;
  69797. if (imageProvider != 0)
  69798. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  69799. fill.setTiledImage (im, AffineTransform::identity);
  69800. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  69801. return true;
  69802. }
  69803. jassertfalse;
  69804. return false;
  69805. }
  69806. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69807. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69808. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69809. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69810. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69811. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69812. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69813. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69814. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69815. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69816. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69817. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69818. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69819. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69820. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69821. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69822. : Drawable::ValueTreeWrapperBase (state_)
  69823. {
  69824. }
  69825. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  69826. {
  69827. DrawableShape::RelativeFillType f;
  69828. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  69829. return f;
  69830. }
  69831. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  69832. {
  69833. ValueTree v (state.getChildWithName (fillOrStrokeType));
  69834. if (v.isValid())
  69835. return v;
  69836. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  69837. return getFillState (fillOrStrokeType);
  69838. }
  69839. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  69840. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  69841. {
  69842. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  69843. newFill.writeTo (v, imageProvider, undoManager);
  69844. }
  69845. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69846. {
  69847. const String jointStyleString (state [jointStyle].toString());
  69848. const String capStyleString (state [capStyle].toString());
  69849. return PathStrokeType (state [strokeWidth],
  69850. jointStyleString == "curved" ? PathStrokeType::curved
  69851. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69852. : PathStrokeType::mitered),
  69853. capStyleString == "square" ? PathStrokeType::square
  69854. : (capStyleString == "round" ? PathStrokeType::rounded
  69855. : PathStrokeType::butt));
  69856. }
  69857. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69858. {
  69859. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69860. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69861. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69862. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69863. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69864. }
  69865. END_JUCE_NAMESPACE
  69866. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69867. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69868. BEGIN_JUCE_NAMESPACE
  69869. DrawableComposite::DrawableComposite()
  69870. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69871. updateBoundsReentrant (false)
  69872. {
  69873. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69874. RelativeCoordinate (100.0),
  69875. RelativeCoordinate (0.0),
  69876. RelativeCoordinate (100.0)));
  69877. }
  69878. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69879. : bounds (other.bounds),
  69880. markersX (other.markersX),
  69881. markersY (other.markersY),
  69882. updateBoundsReentrant (false)
  69883. {
  69884. for (int i = 0; i < other.getNumChildComponents(); ++i)
  69885. {
  69886. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  69887. if (d != 0)
  69888. addAndMakeVisible (d->createCopy());
  69889. }
  69890. }
  69891. DrawableComposite::~DrawableComposite()
  69892. {
  69893. deleteAllChildren();
  69894. }
  69895. Drawable* DrawableComposite::createCopy() const
  69896. {
  69897. return new DrawableComposite (*this);
  69898. }
  69899. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  69900. {
  69901. Rectangle<float> r;
  69902. for (int i = getNumChildComponents(); --i >= 0;)
  69903. {
  69904. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  69905. if (d != 0)
  69906. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  69907. : d->getDrawableBounds());
  69908. }
  69909. return r;
  69910. }
  69911. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  69912. {
  69913. return xAxis ? &markersX : &markersY;
  69914. }
  69915. const RelativeRectangle DrawableComposite::getContentArea() const
  69916. {
  69917. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  69918. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  69919. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  69920. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  69921. }
  69922. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69923. {
  69924. markersX.setMarker (contentLeftMarkerName, newArea.left);
  69925. markersX.setMarker (contentRightMarkerName, newArea.right);
  69926. markersY.setMarker (contentTopMarkerName, newArea.top);
  69927. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  69928. }
  69929. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  69930. {
  69931. if (bounds != newBounds)
  69932. {
  69933. bounds = newBounds;
  69934. if (bounds.isDynamic())
  69935. {
  69936. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  69937. setPositioner (p);
  69938. p->apply();
  69939. }
  69940. else
  69941. {
  69942. setPositioner (0);
  69943. recalculateCoordinates (0);
  69944. }
  69945. }
  69946. }
  69947. void DrawableComposite::resetBoundingBoxToContentArea()
  69948. {
  69949. const RelativeRectangle content (getContentArea());
  69950. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69951. RelativePoint (content.right, content.top),
  69952. RelativePoint (content.left, content.bottom)));
  69953. }
  69954. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69955. {
  69956. const Rectangle<float> activeArea (getDrawableBounds());
  69957. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  69958. RelativeCoordinate (activeArea.getRight()),
  69959. RelativeCoordinate (activeArea.getY()),
  69960. RelativeCoordinate (activeArea.getBottom())));
  69961. resetBoundingBoxToContentArea();
  69962. }
  69963. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  69964. {
  69965. bool ok = positioner.addPoint (bounds.topLeft);
  69966. ok = positioner.addPoint (bounds.topRight) && ok;
  69967. return positioner.addPoint (bounds.bottomLeft) && ok;
  69968. }
  69969. void DrawableComposite::recalculateCoordinates (Expression::Scope* scope)
  69970. {
  69971. Point<float> resolved[3];
  69972. bounds.resolveThreePoints (resolved, scope);
  69973. const Rectangle<float> content (getContentArea().resolve (scope));
  69974. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69975. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69976. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  69977. if (t.isSingularity())
  69978. t = AffineTransform::identity;
  69979. setTransform (t);
  69980. }
  69981. void DrawableComposite::parentHierarchyChanged()
  69982. {
  69983. DrawableComposite* parent = getParent();
  69984. if (parent != 0)
  69985. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  69986. }
  69987. void DrawableComposite::childBoundsChanged (Component*)
  69988. {
  69989. updateBoundsToFitChildren();
  69990. }
  69991. void DrawableComposite::childrenChanged()
  69992. {
  69993. updateBoundsToFitChildren();
  69994. }
  69995. void DrawableComposite::updateBoundsToFitChildren()
  69996. {
  69997. if (! updateBoundsReentrant)
  69998. {
  69999. const ScopedValueSetter<bool> setter (updateBoundsReentrant, true, false);
  70000. Rectangle<int> childArea;
  70001. for (int i = getNumChildComponents(); --i >= 0;)
  70002. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  70003. const Point<int> delta (childArea.getPosition());
  70004. childArea += getPosition();
  70005. if (childArea != getBounds())
  70006. {
  70007. if (! delta.isOrigin())
  70008. {
  70009. originRelativeToComponent -= delta;
  70010. for (int i = getNumChildComponents(); --i >= 0;)
  70011. {
  70012. Component* const c = getChildComponent(i);
  70013. if (c != 0)
  70014. c->setBounds (c->getBounds() - delta);
  70015. }
  70016. }
  70017. setBounds (childArea);
  70018. }
  70019. }
  70020. }
  70021. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70022. const char* const DrawableComposite::contentRightMarkerName = "right";
  70023. const char* const DrawableComposite::contentTopMarkerName = "top";
  70024. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70025. const Identifier DrawableComposite::valueTreeType ("Group");
  70026. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70027. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70028. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70029. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70030. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70031. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70032. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70033. : ValueTreeWrapperBase (state_)
  70034. {
  70035. jassert (state.hasType (valueTreeType));
  70036. }
  70037. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70038. {
  70039. return state.getChildWithName (childGroupTag);
  70040. }
  70041. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70042. {
  70043. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70044. }
  70045. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70046. {
  70047. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70048. state.getProperty (topRight, "100, 0"),
  70049. state.getProperty (bottomLeft, "0, 100"));
  70050. }
  70051. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70052. {
  70053. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70054. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70055. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70056. }
  70057. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70058. {
  70059. const RelativeRectangle content (getContentArea());
  70060. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70061. RelativePoint (content.right, content.top),
  70062. RelativePoint (content.left, content.bottom)), undoManager);
  70063. }
  70064. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70065. {
  70066. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70067. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70068. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70069. markersX.getMarker (markersX.getMarkerState (1)).position,
  70070. markersY.getMarker (markersY.getMarkerState (0)).position,
  70071. markersY.getMarker (markersY.getMarkerState (1)).position);
  70072. }
  70073. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70074. {
  70075. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70076. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70077. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70078. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70079. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70080. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70081. }
  70082. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70083. {
  70084. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70085. }
  70086. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70087. {
  70088. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70089. }
  70090. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70091. {
  70092. const ValueTreeWrapper wrapper (tree);
  70093. setComponentID (wrapper.getID());
  70094. wrapper.getMarkerList (true).applyTo (markersX);
  70095. wrapper.getMarkerList (false).applyTo (markersY);
  70096. setBoundingBox (wrapper.getBoundingBox());
  70097. builder.updateChildComponents (*this, wrapper.getChildList());
  70098. }
  70099. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70100. {
  70101. ValueTree tree (valueTreeType);
  70102. ValueTreeWrapper v (tree);
  70103. v.setID (getComponentID());
  70104. v.setBoundingBox (bounds, 0);
  70105. ValueTree childList (v.getChildListCreating (0));
  70106. for (int i = 0; i < getNumChildComponents(); ++i)
  70107. {
  70108. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70109. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70110. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70111. }
  70112. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70113. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70114. return tree;
  70115. }
  70116. END_JUCE_NAMESPACE
  70117. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70118. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70119. BEGIN_JUCE_NAMESPACE
  70120. DrawableImage::DrawableImage()
  70121. : image (0),
  70122. opacity (1.0f),
  70123. overlayColour (0x00000000)
  70124. {
  70125. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70126. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70127. }
  70128. DrawableImage::DrawableImage (const DrawableImage& other)
  70129. : image (other.image),
  70130. opacity (other.opacity),
  70131. overlayColour (other.overlayColour),
  70132. bounds (other.bounds)
  70133. {
  70134. }
  70135. DrawableImage::~DrawableImage()
  70136. {
  70137. }
  70138. void DrawableImage::setImage (const Image& imageToUse)
  70139. {
  70140. image = imageToUse;
  70141. setBounds (imageToUse.getBounds());
  70142. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70143. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70144. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70145. recalculateCoordinates (0);
  70146. repaint();
  70147. }
  70148. void DrawableImage::setOpacity (const float newOpacity)
  70149. {
  70150. opacity = newOpacity;
  70151. }
  70152. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70153. {
  70154. overlayColour = newOverlayColour;
  70155. }
  70156. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70157. {
  70158. if (bounds != newBounds)
  70159. {
  70160. bounds = newBounds;
  70161. if (bounds.isDynamic())
  70162. {
  70163. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70164. setPositioner (p);
  70165. p->apply();
  70166. }
  70167. else
  70168. {
  70169. setPositioner (0);
  70170. recalculateCoordinates (0);
  70171. }
  70172. }
  70173. }
  70174. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70175. {
  70176. bool ok = positioner.addPoint (bounds.topLeft);
  70177. ok = positioner.addPoint (bounds.topRight) && ok;
  70178. return positioner.addPoint (bounds.bottomLeft) && ok;
  70179. }
  70180. void DrawableImage::recalculateCoordinates (Expression::Scope* scope)
  70181. {
  70182. if (image.isValid())
  70183. {
  70184. Point<float> resolved[3];
  70185. bounds.resolveThreePoints (resolved, scope);
  70186. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70187. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70188. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70189. tr.getX(), tr.getY(),
  70190. bl.getX(), bl.getY()));
  70191. if (t.isSingularity())
  70192. t = AffineTransform::identity;
  70193. setTransform (t);
  70194. }
  70195. }
  70196. void DrawableImage::paint (Graphics& g)
  70197. {
  70198. if (image.isValid())
  70199. {
  70200. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70201. {
  70202. g.setOpacity (opacity);
  70203. g.drawImageAt (image, 0, 0, false);
  70204. }
  70205. if (! overlayColour.isTransparent())
  70206. {
  70207. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70208. g.drawImageAt (image, 0, 0, true);
  70209. }
  70210. }
  70211. }
  70212. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70213. {
  70214. return image.getBounds().toFloat();
  70215. }
  70216. bool DrawableImage::hitTest (int x, int y) const
  70217. {
  70218. return (! image.isNull())
  70219. && image.getPixelAt (x, y).getAlpha() >= 127;
  70220. }
  70221. Drawable* DrawableImage::createCopy() const
  70222. {
  70223. return new DrawableImage (*this);
  70224. }
  70225. const Identifier DrawableImage::valueTreeType ("Image");
  70226. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70227. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70228. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70229. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70230. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70231. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70232. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70233. : ValueTreeWrapperBase (state_)
  70234. {
  70235. jassert (state.hasType (valueTreeType));
  70236. }
  70237. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70238. {
  70239. return state [image];
  70240. }
  70241. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70242. {
  70243. return state.getPropertyAsValue (image, undoManager);
  70244. }
  70245. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70246. {
  70247. state.setProperty (image, newIdentifier, undoManager);
  70248. }
  70249. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70250. {
  70251. return (float) state.getProperty (opacity, 1.0);
  70252. }
  70253. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70254. {
  70255. if (! state.hasProperty (opacity))
  70256. state.setProperty (opacity, 1.0, undoManager);
  70257. return state.getPropertyAsValue (opacity, undoManager);
  70258. }
  70259. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70260. {
  70261. state.setProperty (opacity, newOpacity, undoManager);
  70262. }
  70263. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70264. {
  70265. return Colour (state [overlay].toString().getHexValue32());
  70266. }
  70267. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70268. {
  70269. if (newColour.isTransparent())
  70270. state.removeProperty (overlay, undoManager);
  70271. else
  70272. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70273. }
  70274. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70275. {
  70276. return state.getPropertyAsValue (overlay, undoManager);
  70277. }
  70278. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70279. {
  70280. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70281. state.getProperty (topRight, "100, 0"),
  70282. state.getProperty (bottomLeft, "0, 100"));
  70283. }
  70284. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70285. {
  70286. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70287. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70288. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70289. }
  70290. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70291. {
  70292. const ValueTreeWrapper controller (tree);
  70293. setComponentID (controller.getID());
  70294. const float newOpacity = controller.getOpacity();
  70295. const Colour newOverlayColour (controller.getOverlayColour());
  70296. Image newImage;
  70297. const var imageIdentifier (controller.getImageIdentifier());
  70298. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70299. if (builder.getImageProvider() != 0)
  70300. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70301. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70302. if (bounds != newBounds || newOpacity != opacity
  70303. || overlayColour != newOverlayColour || image != newImage)
  70304. {
  70305. repaint();
  70306. opacity = newOpacity;
  70307. overlayColour = newOverlayColour;
  70308. if (image != newImage)
  70309. setImage (newImage);
  70310. setBoundingBox (newBounds);
  70311. }
  70312. }
  70313. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70314. {
  70315. ValueTree tree (valueTreeType);
  70316. ValueTreeWrapper v (tree);
  70317. v.setID (getComponentID());
  70318. v.setOpacity (opacity, 0);
  70319. v.setOverlayColour (overlayColour, 0);
  70320. v.setBoundingBox (bounds, 0);
  70321. if (image.isValid())
  70322. {
  70323. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70324. if (imageProvider != 0)
  70325. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70326. }
  70327. return tree;
  70328. }
  70329. END_JUCE_NAMESPACE
  70330. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70331. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70332. BEGIN_JUCE_NAMESPACE
  70333. DrawablePath::DrawablePath()
  70334. {
  70335. }
  70336. DrawablePath::DrawablePath (const DrawablePath& other)
  70337. : DrawableShape (other)
  70338. {
  70339. if (other.relativePath != 0)
  70340. setPath (*other.relativePath);
  70341. else
  70342. setPath (other.path);
  70343. }
  70344. DrawablePath::~DrawablePath()
  70345. {
  70346. }
  70347. Drawable* DrawablePath::createCopy() const
  70348. {
  70349. return new DrawablePath (*this);
  70350. }
  70351. void DrawablePath::setPath (const Path& newPath)
  70352. {
  70353. path = newPath;
  70354. pathChanged();
  70355. }
  70356. const Path& DrawablePath::getPath() const
  70357. {
  70358. return path;
  70359. }
  70360. const Path& DrawablePath::getStrokePath() const
  70361. {
  70362. return strokePath;
  70363. }
  70364. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::Scope* scope)
  70365. {
  70366. Path newPath;
  70367. newRelativePath.createPath (newPath, scope);
  70368. if (path != newPath)
  70369. {
  70370. path.swapWithPath (newPath);
  70371. pathChanged();
  70372. }
  70373. }
  70374. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70375. {
  70376. public:
  70377. RelativePositioner (DrawablePath& component_)
  70378. : RelativeCoordinatePositionerBase (component_),
  70379. owner (component_)
  70380. {
  70381. }
  70382. bool registerCoordinates()
  70383. {
  70384. bool ok = true;
  70385. jassert (owner.relativePath != 0);
  70386. const RelativePointPath& path = *owner.relativePath;
  70387. for (int i = 0; i < path.elements.size(); ++i)
  70388. {
  70389. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70390. int numPoints;
  70391. RelativePoint* const points = e->getControlPoints (numPoints);
  70392. for (int j = numPoints; --j >= 0;)
  70393. ok = addPoint (points[j]) && ok;
  70394. }
  70395. return ok;
  70396. }
  70397. void applyToComponentBounds()
  70398. {
  70399. jassert (owner.relativePath != 0);
  70400. ComponentScope scope (getComponent());
  70401. owner.applyRelativePath (*owner.relativePath, &scope);
  70402. }
  70403. private:
  70404. DrawablePath& owner;
  70405. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70406. };
  70407. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70408. {
  70409. if (newRelativePath.containsAnyDynamicPoints())
  70410. {
  70411. if (relativePath == 0 || newRelativePath != *relativePath)
  70412. {
  70413. relativePath = new RelativePointPath (newRelativePath);
  70414. RelativePositioner* const p = new RelativePositioner (*this);
  70415. setPositioner (p);
  70416. p->apply();
  70417. }
  70418. }
  70419. else
  70420. {
  70421. relativePath = 0;
  70422. applyRelativePath (newRelativePath, 0);
  70423. }
  70424. }
  70425. const Identifier DrawablePath::valueTreeType ("Path");
  70426. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70427. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70428. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70429. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70430. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70431. : FillAndStrokeState (state_)
  70432. {
  70433. jassert (state.hasType (valueTreeType));
  70434. }
  70435. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70436. {
  70437. return state.getOrCreateChildWithName (path, 0);
  70438. }
  70439. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70440. {
  70441. return state [nonZeroWinding];
  70442. }
  70443. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70444. {
  70445. state.setProperty (nonZeroWinding, b, undoManager);
  70446. }
  70447. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70448. {
  70449. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70450. ValueTree pathTree (getPathState());
  70451. pathTree.removeAllChildren (undoManager);
  70452. for (int i = 0; i < relativePath.elements.size(); ++i)
  70453. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70454. }
  70455. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70456. {
  70457. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70458. RelativePoint points[3];
  70459. const ValueTree pathTree (state.getChildWithName (path));
  70460. const int num = pathTree.getNumChildren();
  70461. for (int i = 0; i < num; ++i)
  70462. {
  70463. const Element e (pathTree.getChild(i));
  70464. const int numCps = e.getNumControlPoints();
  70465. for (int j = 0; j < numCps; ++j)
  70466. points[j] = e.getControlPoint (j);
  70467. const Identifier type (e.getType());
  70468. RelativePointPath::ElementBase* newElement = 0;
  70469. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70470. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70471. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70472. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70473. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70474. else jassertfalse;
  70475. relativePath.addElement (newElement);
  70476. }
  70477. }
  70478. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70479. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70480. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70481. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70482. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70483. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70484. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70485. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70486. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70487. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70488. : state (state_)
  70489. {
  70490. }
  70491. DrawablePath::ValueTreeWrapper::Element::~Element()
  70492. {
  70493. }
  70494. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70495. {
  70496. return ValueTreeWrapper (state.getParent().getParent());
  70497. }
  70498. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70499. {
  70500. return Element (state.getSibling (-1));
  70501. }
  70502. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70503. {
  70504. const Identifier i (state.getType());
  70505. if (i == startSubPathElement || i == lineToElement) return 1;
  70506. if (i == quadraticToElement) return 2;
  70507. if (i == cubicToElement) return 3;
  70508. return 0;
  70509. }
  70510. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70511. {
  70512. jassert (index >= 0 && index < getNumControlPoints());
  70513. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70514. }
  70515. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70516. {
  70517. jassert (index >= 0 && index < getNumControlPoints());
  70518. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70519. }
  70520. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70521. {
  70522. jassert (index >= 0 && index < getNumControlPoints());
  70523. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70524. }
  70525. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70526. {
  70527. const Identifier i (state.getType());
  70528. if (i == startSubPathElement)
  70529. return getControlPoint (0);
  70530. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70531. return getPreviousElement().getEndPoint();
  70532. }
  70533. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70534. {
  70535. const Identifier i (state.getType());
  70536. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70537. if (i == quadraticToElement) return getControlPoint (1);
  70538. if (i == cubicToElement) return getControlPoint (2);
  70539. jassert (i == closeSubPathElement);
  70540. return RelativePoint();
  70541. }
  70542. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::Scope* scope) const
  70543. {
  70544. const Identifier i (state.getType());
  70545. if (i == lineToElement || i == closeSubPathElement)
  70546. return getEndPoint().resolve (scope).getDistanceFrom (getStartPoint().resolve (scope));
  70547. if (i == cubicToElement)
  70548. {
  70549. Path p;
  70550. p.startNewSubPath (getStartPoint().resolve (scope));
  70551. p.cubicTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope), getControlPoint (2).resolve (scope));
  70552. return p.getLength();
  70553. }
  70554. if (i == quadraticToElement)
  70555. {
  70556. Path p;
  70557. p.startNewSubPath (getStartPoint().resolve (scope));
  70558. p.quadraticTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope));
  70559. return p.getLength();
  70560. }
  70561. jassert (i == startSubPathElement);
  70562. return 0;
  70563. }
  70564. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70565. {
  70566. return state [mode].toString();
  70567. }
  70568. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70569. {
  70570. if (state.hasType (cubicToElement))
  70571. state.setProperty (mode, newMode, undoManager);
  70572. }
  70573. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70574. {
  70575. const Identifier i (state.getType());
  70576. if (i == quadraticToElement || i == cubicToElement)
  70577. {
  70578. ValueTree newState (lineToElement);
  70579. Element e (newState);
  70580. e.setControlPoint (0, getEndPoint(), undoManager);
  70581. state = newState;
  70582. }
  70583. }
  70584. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::Scope* scope, UndoManager* undoManager)
  70585. {
  70586. const Identifier i (state.getType());
  70587. if (i == lineToElement || i == quadraticToElement)
  70588. {
  70589. ValueTree newState (cubicToElement);
  70590. Element e (newState);
  70591. const RelativePoint start (getStartPoint());
  70592. const RelativePoint end (getEndPoint());
  70593. const Point<float> startResolved (start.resolve (scope));
  70594. const Point<float> endResolved (end.resolve (scope));
  70595. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70596. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70597. e.setControlPoint (2, end, undoManager);
  70598. state = newState;
  70599. }
  70600. }
  70601. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70602. {
  70603. const Identifier i (state.getType());
  70604. if (i != startSubPathElement)
  70605. {
  70606. ValueTree newState (startSubPathElement);
  70607. Element e (newState);
  70608. e.setControlPoint (0, getEndPoint(), undoManager);
  70609. state = newState;
  70610. }
  70611. }
  70612. namespace DrawablePathHelpers
  70613. {
  70614. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70615. {
  70616. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70617. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70618. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70619. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70620. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70621. return newCp1 + (newCp2 - newCp1) * proportion;
  70622. }
  70623. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70624. {
  70625. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70626. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70627. return mid1 + (mid2 - mid1) * proportion;
  70628. }
  70629. }
  70630. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope* scope) const
  70631. {
  70632. using namespace DrawablePathHelpers;
  70633. const Identifier type (state.getType());
  70634. float bestProp = 0;
  70635. if (type == cubicToElement)
  70636. {
  70637. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70638. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70639. float bestDistance = std::numeric_limits<float>::max();
  70640. for (int i = 110; --i >= 0;)
  70641. {
  70642. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70643. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70644. const float distance = centre.getDistanceFrom (targetPoint);
  70645. if (distance < bestDistance)
  70646. {
  70647. bestProp = prop;
  70648. bestDistance = distance;
  70649. }
  70650. }
  70651. }
  70652. else if (type == quadraticToElement)
  70653. {
  70654. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70655. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70656. float bestDistance = std::numeric_limits<float>::max();
  70657. for (int i = 110; --i >= 0;)
  70658. {
  70659. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70660. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70661. const float distance = centre.getDistanceFrom (targetPoint);
  70662. if (distance < bestDistance)
  70663. {
  70664. bestProp = prop;
  70665. bestDistance = distance;
  70666. }
  70667. }
  70668. }
  70669. else if (type == lineToElement)
  70670. {
  70671. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70672. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70673. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70674. }
  70675. return bestProp;
  70676. }
  70677. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::Scope* scope, UndoManager* undoManager)
  70678. {
  70679. ValueTree newTree;
  70680. const Identifier type (state.getType());
  70681. if (type == cubicToElement)
  70682. {
  70683. float bestProp = findProportionAlongLine (targetPoint, scope);
  70684. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70685. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70686. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70687. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70688. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70689. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70690. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70691. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70692. setControlPoint (0, mid1, undoManager);
  70693. setControlPoint (1, newCp1, undoManager);
  70694. setControlPoint (2, newCentre, undoManager);
  70695. setModeOfEndPoint (roundedMode, undoManager);
  70696. Element newElement (newTree = ValueTree (cubicToElement));
  70697. newElement.setControlPoint (0, newCp2, 0);
  70698. newElement.setControlPoint (1, mid3, 0);
  70699. newElement.setControlPoint (2, rp4, 0);
  70700. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70701. }
  70702. else if (type == quadraticToElement)
  70703. {
  70704. float bestProp = findProportionAlongLine (targetPoint, scope);
  70705. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70706. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70707. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70708. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70709. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70710. setControlPoint (0, mid1, undoManager);
  70711. setControlPoint (1, newCentre, undoManager);
  70712. setModeOfEndPoint (roundedMode, undoManager);
  70713. Element newElement (newTree = ValueTree (quadraticToElement));
  70714. newElement.setControlPoint (0, mid2, 0);
  70715. newElement.setControlPoint (1, rp3, 0);
  70716. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70717. }
  70718. else if (type == lineToElement)
  70719. {
  70720. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70721. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70722. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70723. setControlPoint (0, newPoint, undoManager);
  70724. Element newElement (newTree = ValueTree (lineToElement));
  70725. newElement.setControlPoint (0, rp2, 0);
  70726. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70727. }
  70728. else if (type == closeSubPathElement)
  70729. {
  70730. }
  70731. return newTree;
  70732. }
  70733. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70734. {
  70735. state.getParent().removeChild (state, undoManager);
  70736. }
  70737. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70738. {
  70739. ValueTreeWrapper v (tree);
  70740. setComponentID (v.getID());
  70741. refreshFillTypes (v, builder.getImageProvider());
  70742. setStrokeType (v.getStrokeType());
  70743. RelativePointPath newRelativePath;
  70744. v.writeTo (newRelativePath);
  70745. setPath (newRelativePath);
  70746. }
  70747. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70748. {
  70749. ValueTree tree (valueTreeType);
  70750. ValueTreeWrapper v (tree);
  70751. v.setID (getComponentID());
  70752. writeTo (v, imageProvider, 0);
  70753. if (relativePath != 0)
  70754. v.readFrom (*relativePath, 0);
  70755. else
  70756. v.readFrom (RelativePointPath (path), 0);
  70757. return tree;
  70758. }
  70759. END_JUCE_NAMESPACE
  70760. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70761. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70762. BEGIN_JUCE_NAMESPACE
  70763. DrawableRectangle::DrawableRectangle()
  70764. {
  70765. }
  70766. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70767. : DrawableShape (other),
  70768. bounds (other.bounds),
  70769. cornerSize (other.cornerSize)
  70770. {
  70771. }
  70772. DrawableRectangle::~DrawableRectangle()
  70773. {
  70774. }
  70775. Drawable* DrawableRectangle::createCopy() const
  70776. {
  70777. return new DrawableRectangle (*this);
  70778. }
  70779. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70780. {
  70781. if (bounds != newBounds)
  70782. {
  70783. bounds = newBounds;
  70784. rebuildPath();
  70785. }
  70786. }
  70787. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70788. {
  70789. if (cornerSize != newSize)
  70790. {
  70791. cornerSize = newSize;
  70792. rebuildPath();
  70793. }
  70794. }
  70795. void DrawableRectangle::rebuildPath()
  70796. {
  70797. if (bounds.isDynamic() || cornerSize.isDynamic())
  70798. {
  70799. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  70800. setPositioner (p);
  70801. p->apply();
  70802. }
  70803. else
  70804. {
  70805. setPositioner (0);
  70806. recalculateCoordinates (0);
  70807. }
  70808. }
  70809. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70810. {
  70811. bool ok = positioner.addPoint (bounds.topLeft);
  70812. ok = positioner.addPoint (bounds.topRight) && ok;
  70813. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70814. return positioner.addPoint (cornerSize) && ok;
  70815. }
  70816. void DrawableRectangle::recalculateCoordinates (Expression::Scope* scope)
  70817. {
  70818. Point<float> points[3];
  70819. bounds.resolveThreePoints (points, scope);
  70820. const float cornerSizeX = (float) cornerSize.x.resolve (scope);
  70821. const float cornerSizeY = (float) cornerSize.y.resolve (scope);
  70822. const float w = Line<float> (points[0], points[1]).getLength();
  70823. const float h = Line<float> (points[0], points[2]).getLength();
  70824. Path newPath;
  70825. if (cornerSizeX > 0 && cornerSizeY > 0)
  70826. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70827. else
  70828. newPath.addRectangle (0, 0, w, h);
  70829. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70830. w, 0, points[1].getX(), points[1].getY(),
  70831. 0, h, points[2].getX(), points[2].getY()));
  70832. if (path != newPath)
  70833. {
  70834. path.swapWithPath (newPath);
  70835. pathChanged();
  70836. }
  70837. }
  70838. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70839. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70840. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70841. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70842. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70843. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70844. : FillAndStrokeState (state_)
  70845. {
  70846. jassert (state.hasType (valueTreeType));
  70847. }
  70848. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70849. {
  70850. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70851. state.getProperty (topRight, "100, 0"),
  70852. state.getProperty (bottomLeft, "0, 100"));
  70853. }
  70854. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70855. {
  70856. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70857. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70858. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70859. }
  70860. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70861. {
  70862. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70863. }
  70864. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70865. {
  70866. return RelativePoint (state [cornerSize]);
  70867. }
  70868. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70869. {
  70870. return state.getPropertyAsValue (cornerSize, undoManager);
  70871. }
  70872. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70873. {
  70874. ValueTreeWrapper v (tree);
  70875. setComponentID (v.getID());
  70876. refreshFillTypes (v, builder.getImageProvider());
  70877. setStrokeType (v.getStrokeType());
  70878. setRectangle (v.getRectangle());
  70879. setCornerSize (v.getCornerSize());
  70880. }
  70881. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70882. {
  70883. ValueTree tree (valueTreeType);
  70884. ValueTreeWrapper v (tree);
  70885. v.setID (getComponentID());
  70886. writeTo (v, imageProvider, 0);
  70887. v.setRectangle (bounds, 0);
  70888. v.setCornerSize (cornerSize, 0);
  70889. return tree;
  70890. }
  70891. END_JUCE_NAMESPACE
  70892. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70893. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70894. BEGIN_JUCE_NAMESPACE
  70895. DrawableText::DrawableText()
  70896. : colour (Colours::black),
  70897. justification (Justification::centredLeft)
  70898. {
  70899. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70900. RelativePoint (50.0f, 0.0f),
  70901. RelativePoint (0.0f, 20.0f)));
  70902. setFont (Font (15.0f), true);
  70903. }
  70904. DrawableText::DrawableText (const DrawableText& other)
  70905. : bounds (other.bounds),
  70906. fontSizeControlPoint (other.fontSizeControlPoint),
  70907. font (other.font),
  70908. text (other.text),
  70909. colour (other.colour),
  70910. justification (other.justification)
  70911. {
  70912. }
  70913. DrawableText::~DrawableText()
  70914. {
  70915. }
  70916. void DrawableText::setText (const String& newText)
  70917. {
  70918. if (text != newText)
  70919. {
  70920. text = newText;
  70921. refreshBounds();
  70922. }
  70923. }
  70924. void DrawableText::setColour (const Colour& newColour)
  70925. {
  70926. if (colour != newColour)
  70927. {
  70928. colour = newColour;
  70929. repaint();
  70930. }
  70931. }
  70932. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70933. {
  70934. if (font != newFont)
  70935. {
  70936. font = newFont;
  70937. if (applySizeAndScale)
  70938. {
  70939. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  70940. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70941. }
  70942. refreshBounds();
  70943. }
  70944. }
  70945. void DrawableText::setJustification (const Justification& newJustification)
  70946. {
  70947. justification = newJustification;
  70948. repaint();
  70949. }
  70950. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70951. {
  70952. if (bounds != newBounds)
  70953. {
  70954. bounds = newBounds;
  70955. refreshBounds();
  70956. }
  70957. }
  70958. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70959. {
  70960. if (fontSizeControlPoint != newPoint)
  70961. {
  70962. fontSizeControlPoint = newPoint;
  70963. refreshBounds();
  70964. }
  70965. }
  70966. void DrawableText::refreshBounds()
  70967. {
  70968. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  70969. {
  70970. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  70971. setPositioner (p);
  70972. p->apply();
  70973. }
  70974. else
  70975. {
  70976. setPositioner (0);
  70977. recalculateCoordinates (0);
  70978. }
  70979. }
  70980. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70981. {
  70982. bool ok = positioner.addPoint (bounds.topLeft);
  70983. ok = positioner.addPoint (bounds.topRight) && ok;
  70984. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70985. return positioner.addPoint (fontSizeControlPoint) && ok;
  70986. }
  70987. void DrawableText::recalculateCoordinates (Expression::Scope* scope)
  70988. {
  70989. bounds.resolveThreePoints (resolvedPoints, scope);
  70990. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  70991. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  70992. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (scope)));
  70993. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  70994. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  70995. scaledFont = font;
  70996. scaledFont.setHeight (fontHeight);
  70997. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  70998. setBoundsToEnclose (getDrawableBounds());
  70999. repaint();
  71000. }
  71001. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  71002. {
  71003. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71004. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71005. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  71006. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  71007. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  71008. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  71009. }
  71010. void DrawableText::paint (Graphics& g)
  71011. {
  71012. transformContextToCorrectOrigin (g);
  71013. g.setColour (colour);
  71014. GlyphArrangement ga;
  71015. const AffineTransform transform (getArrangementAndTransform (ga));
  71016. ga.draw (g, transform);
  71017. }
  71018. const Rectangle<float> DrawableText::getDrawableBounds() const
  71019. {
  71020. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71021. }
  71022. Drawable* DrawableText::createCopy() const
  71023. {
  71024. return new DrawableText (*this);
  71025. }
  71026. const Identifier DrawableText::valueTreeType ("Text");
  71027. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71028. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71029. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71030. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71031. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71032. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71033. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71034. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71035. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71036. : ValueTreeWrapperBase (state_)
  71037. {
  71038. jassert (state.hasType (valueTreeType));
  71039. }
  71040. const String DrawableText::ValueTreeWrapper::getText() const
  71041. {
  71042. return state [text].toString();
  71043. }
  71044. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71045. {
  71046. state.setProperty (text, newText, undoManager);
  71047. }
  71048. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71049. {
  71050. return state.getPropertyAsValue (text, undoManager);
  71051. }
  71052. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71053. {
  71054. return Colour::fromString (state [colour].toString());
  71055. }
  71056. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71057. {
  71058. state.setProperty (colour, newColour.toString(), undoManager);
  71059. }
  71060. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71061. {
  71062. return Justification ((int) state [justification]);
  71063. }
  71064. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71065. {
  71066. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71067. }
  71068. const Font DrawableText::ValueTreeWrapper::getFont() const
  71069. {
  71070. return Font::fromString (state [font]);
  71071. }
  71072. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71073. {
  71074. state.setProperty (font, newFont.toString(), undoManager);
  71075. }
  71076. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71077. {
  71078. return state.getPropertyAsValue (font, undoManager);
  71079. }
  71080. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71081. {
  71082. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71083. }
  71084. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71085. {
  71086. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71087. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71088. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71089. }
  71090. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71091. {
  71092. return state [fontSizeAnchor].toString();
  71093. }
  71094. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71095. {
  71096. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71097. }
  71098. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71099. {
  71100. ValueTreeWrapper v (tree);
  71101. setComponentID (v.getID());
  71102. const RelativeParallelogram newBounds (v.getBoundingBox());
  71103. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71104. const Colour newColour (v.getColour());
  71105. const Justification newJustification (v.getJustification());
  71106. const String newText (v.getText());
  71107. const Font newFont (v.getFont());
  71108. if (text != newText || font != newFont || justification != newJustification
  71109. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71110. {
  71111. setBoundingBox (newBounds);
  71112. setFontSizeControlPoint (newFontPoint);
  71113. setColour (newColour);
  71114. setFont (newFont, false);
  71115. setJustification (newJustification);
  71116. setText (newText);
  71117. }
  71118. }
  71119. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71120. {
  71121. ValueTree tree (valueTreeType);
  71122. ValueTreeWrapper v (tree);
  71123. v.setID (getComponentID());
  71124. v.setText (text, 0);
  71125. v.setFont (font, 0);
  71126. v.setJustification (justification, 0);
  71127. v.setColour (colour, 0);
  71128. v.setBoundingBox (bounds, 0);
  71129. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71130. return tree;
  71131. }
  71132. END_JUCE_NAMESPACE
  71133. /*** End of inlined file: juce_DrawableText.cpp ***/
  71134. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71135. BEGIN_JUCE_NAMESPACE
  71136. class SVGState
  71137. {
  71138. public:
  71139. SVGState (const XmlElement* const topLevel)
  71140. : topLevelXml (topLevel),
  71141. elementX (0), elementY (0),
  71142. width (512), height (512),
  71143. viewBoxW (0), viewBoxH (0)
  71144. {
  71145. }
  71146. Drawable* parseSVGElement (const XmlElement& xml)
  71147. {
  71148. if (! xml.hasTagName ("svg"))
  71149. return 0;
  71150. DrawableComposite* const drawable = new DrawableComposite();
  71151. drawable->setName (xml.getStringAttribute ("id"));
  71152. SVGState newState (*this);
  71153. if (xml.hasAttribute ("transform"))
  71154. newState.addTransform (xml);
  71155. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71156. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71157. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71158. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71159. if (xml.hasAttribute ("viewBox"))
  71160. {
  71161. const String viewBoxAtt (xml.getStringAttribute ("viewBox"));
  71162. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  71163. float vx, vy, vw, vh;
  71164. if (parseCoords (viewParams, vx, vy, true)
  71165. && parseCoords (viewParams, vw, vh, true)
  71166. && vw > 0
  71167. && vh > 0)
  71168. {
  71169. newState.viewBoxW = vw;
  71170. newState.viewBoxH = vh;
  71171. int placementFlags = 0;
  71172. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71173. if (aspect.containsIgnoreCase ("none"))
  71174. {
  71175. placementFlags = RectanglePlacement::stretchToFit;
  71176. }
  71177. else
  71178. {
  71179. if (aspect.containsIgnoreCase ("slice"))
  71180. placementFlags |= RectanglePlacement::fillDestination;
  71181. if (aspect.containsIgnoreCase ("xMin"))
  71182. placementFlags |= RectanglePlacement::xLeft;
  71183. else if (aspect.containsIgnoreCase ("xMax"))
  71184. placementFlags |= RectanglePlacement::xRight;
  71185. else
  71186. placementFlags |= RectanglePlacement::xMid;
  71187. if (aspect.containsIgnoreCase ("yMin"))
  71188. placementFlags |= RectanglePlacement::yTop;
  71189. else if (aspect.containsIgnoreCase ("yMax"))
  71190. placementFlags |= RectanglePlacement::yBottom;
  71191. else
  71192. placementFlags |= RectanglePlacement::yMid;
  71193. }
  71194. const RectanglePlacement placement (placementFlags);
  71195. newState.transform
  71196. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71197. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71198. .followedBy (newState.transform);
  71199. }
  71200. }
  71201. else
  71202. {
  71203. if (viewBoxW == 0)
  71204. newState.viewBoxW = newState.width;
  71205. if (viewBoxH == 0)
  71206. newState.viewBoxH = newState.height;
  71207. }
  71208. newState.parseSubElements (xml, drawable);
  71209. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71210. return drawable;
  71211. }
  71212. private:
  71213. const XmlElement* const topLevelXml;
  71214. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71215. AffineTransform transform;
  71216. String cssStyleText;
  71217. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71218. {
  71219. forEachXmlChildElement (xml, e)
  71220. {
  71221. Drawable* d = 0;
  71222. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71223. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71224. else if (e->hasTagName ("path")) d = parsePath (*e);
  71225. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71226. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71227. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71228. else if (e->hasTagName ("line")) d = parseLine (*e);
  71229. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71230. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71231. else if (e->hasTagName ("text")) d = parseText (*e);
  71232. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71233. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71234. parentDrawable->addAndMakeVisible (d);
  71235. }
  71236. }
  71237. DrawableComposite* parseSwitch (const XmlElement& xml)
  71238. {
  71239. const XmlElement* const group = xml.getChildByName ("g");
  71240. if (group != 0)
  71241. return parseGroupElement (*group);
  71242. return 0;
  71243. }
  71244. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71245. {
  71246. DrawableComposite* const drawable = new DrawableComposite();
  71247. drawable->setName (xml.getStringAttribute ("id"));
  71248. if (xml.hasAttribute ("transform"))
  71249. {
  71250. SVGState newState (*this);
  71251. newState.addTransform (xml);
  71252. newState.parseSubElements (xml, drawable);
  71253. }
  71254. else
  71255. {
  71256. parseSubElements (xml, drawable);
  71257. }
  71258. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71259. return drawable;
  71260. }
  71261. Drawable* parsePath (const XmlElement& xml) const
  71262. {
  71263. const String dAttribute (xml.getStringAttribute ("d").trimStart());
  71264. String::CharPointerType d (dAttribute.getCharPointer());
  71265. Path path;
  71266. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71267. path.setUsingNonZeroWinding (false);
  71268. float lastX = 0, lastY = 0;
  71269. float lastX2 = 0, lastY2 = 0;
  71270. juce_wchar lastCommandChar = 0;
  71271. bool isRelative = true;
  71272. bool carryOn = true;
  71273. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71274. while (! d.isEmpty())
  71275. {
  71276. float x, y, x2, y2, x3, y3;
  71277. if (validCommandChars.indexOf (*d) >= 0)
  71278. {
  71279. lastCommandChar = d.getAndAdvance();
  71280. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71281. }
  71282. switch (lastCommandChar)
  71283. {
  71284. case 'M':
  71285. case 'm':
  71286. case 'L':
  71287. case 'l':
  71288. if (parseCoords (d, x, y, false))
  71289. {
  71290. if (isRelative)
  71291. {
  71292. x += lastX;
  71293. y += lastY;
  71294. }
  71295. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71296. {
  71297. path.startNewSubPath (x, y);
  71298. lastCommandChar = 'l';
  71299. }
  71300. else
  71301. path.lineTo (x, y);
  71302. lastX2 = lastX;
  71303. lastY2 = lastY;
  71304. lastX = x;
  71305. lastY = y;
  71306. }
  71307. else
  71308. {
  71309. ++d;
  71310. }
  71311. break;
  71312. case 'H':
  71313. case 'h':
  71314. if (parseCoord (d, x, false, true))
  71315. {
  71316. if (isRelative)
  71317. x += lastX;
  71318. path.lineTo (x, lastY);
  71319. lastX2 = lastX;
  71320. lastX = x;
  71321. }
  71322. else
  71323. {
  71324. ++d;
  71325. }
  71326. break;
  71327. case 'V':
  71328. case 'v':
  71329. if (parseCoord (d, y, false, false))
  71330. {
  71331. if (isRelative)
  71332. y += lastY;
  71333. path.lineTo (lastX, y);
  71334. lastY2 = lastY;
  71335. lastY = y;
  71336. }
  71337. else
  71338. {
  71339. ++d;
  71340. }
  71341. break;
  71342. case 'C':
  71343. case 'c':
  71344. if (parseCoords (d, x, y, false)
  71345. && parseCoords (d, x2, y2, false)
  71346. && parseCoords (d, x3, y3, false))
  71347. {
  71348. if (isRelative)
  71349. {
  71350. x += lastX;
  71351. y += lastY;
  71352. x2 += lastX;
  71353. y2 += lastY;
  71354. x3 += lastX;
  71355. y3 += lastY;
  71356. }
  71357. path.cubicTo (x, y, x2, y2, x3, y3);
  71358. lastX2 = x2;
  71359. lastY2 = y2;
  71360. lastX = x3;
  71361. lastY = y3;
  71362. }
  71363. else
  71364. {
  71365. ++d;
  71366. }
  71367. break;
  71368. case 'S':
  71369. case 's':
  71370. if (parseCoords (d, x, y, false)
  71371. && parseCoords (d, x3, y3, false))
  71372. {
  71373. if (isRelative)
  71374. {
  71375. x += lastX;
  71376. y += lastY;
  71377. x3 += lastX;
  71378. y3 += lastY;
  71379. }
  71380. x2 = lastX + (lastX - lastX2);
  71381. y2 = lastY + (lastY - lastY2);
  71382. path.cubicTo (x2, y2, x, y, x3, y3);
  71383. lastX2 = x;
  71384. lastY2 = y;
  71385. lastX = x3;
  71386. lastY = y3;
  71387. }
  71388. else
  71389. {
  71390. ++d;
  71391. }
  71392. break;
  71393. case 'Q':
  71394. case 'q':
  71395. if (parseCoords (d, x, y, false)
  71396. && parseCoords (d, x2, y2, false))
  71397. {
  71398. if (isRelative)
  71399. {
  71400. x += lastX;
  71401. y += lastY;
  71402. x2 += lastX;
  71403. y2 += lastY;
  71404. }
  71405. path.quadraticTo (x, y, x2, y2);
  71406. lastX2 = x;
  71407. lastY2 = y;
  71408. lastX = x2;
  71409. lastY = y2;
  71410. }
  71411. else
  71412. {
  71413. ++d;
  71414. }
  71415. break;
  71416. case 'T':
  71417. case 't':
  71418. if (parseCoords (d, x, y, false))
  71419. {
  71420. if (isRelative)
  71421. {
  71422. x += lastX;
  71423. y += lastY;
  71424. }
  71425. x2 = lastX + (lastX - lastX2);
  71426. y2 = lastY + (lastY - lastY2);
  71427. path.quadraticTo (x2, y2, x, y);
  71428. lastX2 = x2;
  71429. lastY2 = y2;
  71430. lastX = x;
  71431. lastY = y;
  71432. }
  71433. else
  71434. {
  71435. ++d;
  71436. }
  71437. break;
  71438. case 'A':
  71439. case 'a':
  71440. if (parseCoords (d, x, y, false))
  71441. {
  71442. String num;
  71443. if (parseNextNumber (d, num, false))
  71444. {
  71445. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71446. if (parseNextNumber (d, num, false))
  71447. {
  71448. const bool largeArc = num.getIntValue() != 0;
  71449. if (parseNextNumber (d, num, false))
  71450. {
  71451. const bool sweep = num.getIntValue() != 0;
  71452. if (parseCoords (d, x2, y2, false))
  71453. {
  71454. if (isRelative)
  71455. {
  71456. x2 += lastX;
  71457. y2 += lastY;
  71458. }
  71459. if (lastX != x2 || lastY != y2)
  71460. {
  71461. double centreX, centreY, startAngle, deltaAngle;
  71462. double rx = x, ry = y;
  71463. endpointToCentreParameters (lastX, lastY, x2, y2,
  71464. angle, largeArc, sweep,
  71465. rx, ry, centreX, centreY,
  71466. startAngle, deltaAngle);
  71467. path.addCentredArc ((float) centreX, (float) centreY,
  71468. (float) rx, (float) ry,
  71469. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71470. false);
  71471. path.lineTo (x2, y2);
  71472. }
  71473. lastX2 = lastX;
  71474. lastY2 = lastY;
  71475. lastX = x2;
  71476. lastY = y2;
  71477. }
  71478. }
  71479. }
  71480. }
  71481. }
  71482. else
  71483. {
  71484. ++d;
  71485. }
  71486. break;
  71487. case 'Z':
  71488. case 'z':
  71489. path.closeSubPath();
  71490. d = d.findEndOfWhitespace();
  71491. break;
  71492. default:
  71493. carryOn = false;
  71494. break;
  71495. }
  71496. if (! carryOn)
  71497. break;
  71498. }
  71499. return parseShape (xml, path);
  71500. }
  71501. Drawable* parseRect (const XmlElement& xml) const
  71502. {
  71503. Path rect;
  71504. const bool hasRX = xml.hasAttribute ("rx");
  71505. const bool hasRY = xml.hasAttribute ("ry");
  71506. if (hasRX || hasRY)
  71507. {
  71508. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71509. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71510. if (! hasRX)
  71511. rx = ry;
  71512. else if (! hasRY)
  71513. ry = rx;
  71514. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71515. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71516. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71517. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71518. rx, ry);
  71519. }
  71520. else
  71521. {
  71522. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71523. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71524. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71525. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71526. }
  71527. return parseShape (xml, rect);
  71528. }
  71529. Drawable* parseCircle (const XmlElement& xml) const
  71530. {
  71531. Path circle;
  71532. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71533. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71534. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71535. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71536. return parseShape (xml, circle);
  71537. }
  71538. Drawable* parseEllipse (const XmlElement& xml) const
  71539. {
  71540. Path ellipse;
  71541. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71542. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71543. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71544. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71545. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71546. return parseShape (xml, ellipse);
  71547. }
  71548. Drawable* parseLine (const XmlElement& xml) const
  71549. {
  71550. Path line;
  71551. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71552. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71553. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71554. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71555. line.startNewSubPath (x1, y1);
  71556. line.lineTo (x2, y2);
  71557. return parseShape (xml, line);
  71558. }
  71559. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71560. {
  71561. const String pointsAtt (xml.getStringAttribute ("points"));
  71562. String::CharPointerType points (pointsAtt.getCharPointer());
  71563. Path path;
  71564. float x, y;
  71565. if (parseCoords (points, x, y, true))
  71566. {
  71567. float firstX = x;
  71568. float firstY = y;
  71569. float lastX = 0, lastY = 0;
  71570. path.startNewSubPath (x, y);
  71571. while (parseCoords (points, x, y, true))
  71572. {
  71573. lastX = x;
  71574. lastY = y;
  71575. path.lineTo (x, y);
  71576. }
  71577. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71578. path.closeSubPath();
  71579. }
  71580. return parseShape (xml, path);
  71581. }
  71582. Drawable* parseShape (const XmlElement& xml, Path& path,
  71583. const bool shouldParseTransform = true) const
  71584. {
  71585. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71586. {
  71587. SVGState newState (*this);
  71588. newState.addTransform (xml);
  71589. return newState.parseShape (xml, path, false);
  71590. }
  71591. DrawablePath* dp = new DrawablePath();
  71592. dp->setName (xml.getStringAttribute ("id"));
  71593. dp->setFill (Colours::transparentBlack);
  71594. path.applyTransform (transform);
  71595. dp->setPath (path);
  71596. Path::Iterator iter (path);
  71597. bool containsClosedSubPath = false;
  71598. while (iter.next())
  71599. {
  71600. if (iter.elementType == Path::Iterator::closePath)
  71601. {
  71602. containsClosedSubPath = true;
  71603. break;
  71604. }
  71605. }
  71606. dp->setFill (getPathFillType (path,
  71607. getStyleAttribute (&xml, "fill"),
  71608. getStyleAttribute (&xml, "fill-opacity"),
  71609. getStyleAttribute (&xml, "opacity"),
  71610. containsClosedSubPath ? Colours::black
  71611. : Colours::transparentBlack));
  71612. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71613. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71614. {
  71615. dp->setStrokeFill (getPathFillType (path, strokeType,
  71616. getStyleAttribute (&xml, "stroke-opacity"),
  71617. getStyleAttribute (&xml, "opacity"),
  71618. Colours::transparentBlack));
  71619. dp->setStrokeType (getStrokeFor (&xml));
  71620. }
  71621. return dp;
  71622. }
  71623. const XmlElement* findLinkedElement (const XmlElement* e) const
  71624. {
  71625. const String id (e->getStringAttribute ("xlink:href"));
  71626. if (! id.startsWithChar ('#'))
  71627. return 0;
  71628. return findElementForId (topLevelXml, id.substring (1));
  71629. }
  71630. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71631. {
  71632. if (fillXml == 0)
  71633. return;
  71634. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71635. {
  71636. int index = 0;
  71637. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71638. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71639. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71640. double offset = e->getDoubleAttribute ("offset");
  71641. if (e->getStringAttribute ("offset").containsChar ('%'))
  71642. offset *= 0.01;
  71643. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71644. }
  71645. }
  71646. const FillType getPathFillType (const Path& path,
  71647. const String& fill,
  71648. const String& fillOpacity,
  71649. const String& overallOpacity,
  71650. const Colour& defaultColour) const
  71651. {
  71652. float opacity = 1.0f;
  71653. if (overallOpacity.isNotEmpty())
  71654. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71655. if (fillOpacity.isNotEmpty())
  71656. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71657. if (fill.startsWithIgnoreCase ("url"))
  71658. {
  71659. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71660. .upToLastOccurrenceOf (")", false, false).trim());
  71661. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71662. if (fillXml != 0
  71663. && (fillXml->hasTagName ("linearGradient")
  71664. || fillXml->hasTagName ("radialGradient")))
  71665. {
  71666. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71667. ColourGradient gradient;
  71668. addGradientStopsIn (gradient, inheritedFrom);
  71669. addGradientStopsIn (gradient, fillXml);
  71670. if (gradient.getNumColours() > 0)
  71671. {
  71672. gradient.addColour (0.0, gradient.getColour (0));
  71673. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71674. }
  71675. else
  71676. {
  71677. gradient.addColour (0.0, Colours::black);
  71678. gradient.addColour (1.0, Colours::black);
  71679. }
  71680. if (overallOpacity.isNotEmpty())
  71681. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71682. jassert (gradient.getNumColours() > 0);
  71683. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71684. float gradientWidth = viewBoxW;
  71685. float gradientHeight = viewBoxH;
  71686. float dx = 0.0f;
  71687. float dy = 0.0f;
  71688. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71689. if (! userSpace)
  71690. {
  71691. const Rectangle<float> bounds (path.getBounds());
  71692. dx = bounds.getX();
  71693. dy = bounds.getY();
  71694. gradientWidth = bounds.getWidth();
  71695. gradientHeight = bounds.getHeight();
  71696. }
  71697. if (gradient.isRadial)
  71698. {
  71699. if (userSpace)
  71700. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71701. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71702. else
  71703. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71704. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71705. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71706. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71707. //xxx (the fx, fy focal point isn't handled properly here..)
  71708. }
  71709. else
  71710. {
  71711. if (userSpace)
  71712. {
  71713. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71714. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71715. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71716. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71717. }
  71718. else
  71719. {
  71720. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71721. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71722. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71723. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71724. }
  71725. if (gradient.point1 == gradient.point2)
  71726. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71727. }
  71728. FillType type (gradient);
  71729. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71730. .followedBy (transform);
  71731. return type;
  71732. }
  71733. }
  71734. if (fill.equalsIgnoreCase ("none"))
  71735. return Colours::transparentBlack;
  71736. int i = 0;
  71737. const Colour colour (parseColour (fill, i, defaultColour));
  71738. return colour.withMultipliedAlpha (opacity);
  71739. }
  71740. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71741. {
  71742. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71743. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71744. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71745. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71746. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71747. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71748. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71749. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71750. if (join.equalsIgnoreCase ("round"))
  71751. joinStyle = PathStrokeType::curved;
  71752. else if (join.equalsIgnoreCase ("bevel"))
  71753. joinStyle = PathStrokeType::beveled;
  71754. if (cap.equalsIgnoreCase ("round"))
  71755. capStyle = PathStrokeType::rounded;
  71756. else if (cap.equalsIgnoreCase ("square"))
  71757. capStyle = PathStrokeType::square;
  71758. float ox = 0.0f, oy = 0.0f;
  71759. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71760. transform.transformPoints (ox, oy, x, y);
  71761. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71762. joinStyle, capStyle);
  71763. }
  71764. Drawable* parseText (const XmlElement& xml)
  71765. {
  71766. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71767. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71768. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71769. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71770. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71771. //xxx not done text yet!
  71772. forEachXmlChildElement (xml, e)
  71773. {
  71774. if (e->isTextElement())
  71775. {
  71776. const String text (e->getText());
  71777. Path path;
  71778. Drawable* s = parseShape (*e, path);
  71779. delete s; // xxx not finished!
  71780. }
  71781. else if (e->hasTagName ("tspan"))
  71782. {
  71783. Drawable* s = parseText (*e);
  71784. delete s; // xxx not finished!
  71785. }
  71786. }
  71787. return 0;
  71788. }
  71789. void addTransform (const XmlElement& xml)
  71790. {
  71791. transform = parseTransform (xml.getStringAttribute ("transform"))
  71792. .followedBy (transform);
  71793. }
  71794. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  71795. {
  71796. String number;
  71797. if (! parseNextNumber (s, number, allowUnits))
  71798. {
  71799. value = 0;
  71800. return false;
  71801. }
  71802. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71803. return true;
  71804. }
  71805. bool parseCoords (String::CharPointerType& s, float& x, float& y, const bool allowUnits) const
  71806. {
  71807. return parseCoord (s, x, allowUnits, true)
  71808. && parseCoord (s, y, allowUnits, false);
  71809. }
  71810. float getCoordLength (const String& s, const float sizeForProportions) const
  71811. {
  71812. float n = s.getFloatValue();
  71813. const int len = s.length();
  71814. if (len > 2)
  71815. {
  71816. const float dpi = 96.0f;
  71817. const juce_wchar n1 = s [len - 2];
  71818. const juce_wchar n2 = s [len - 1];
  71819. if (n1 == 'i' && n2 == 'n')
  71820. n *= dpi;
  71821. else if (n1 == 'm' && n2 == 'm')
  71822. n *= dpi / 25.4f;
  71823. else if (n1 == 'c' && n2 == 'm')
  71824. n *= dpi / 2.54f;
  71825. else if (n1 == 'p' && n2 == 'c')
  71826. n *= 15.0f;
  71827. else if (n2 == '%')
  71828. n *= 0.01f * sizeForProportions;
  71829. }
  71830. return n;
  71831. }
  71832. void getCoordList (Array <float>& coords, const String& list,
  71833. const bool allowUnits, const bool isX) const
  71834. {
  71835. String::CharPointerType text (list.getCharPointer());
  71836. float value;
  71837. while (parseCoord (text, value, allowUnits, isX))
  71838. coords.add (value);
  71839. }
  71840. void parseCSSStyle (const XmlElement& xml)
  71841. {
  71842. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71843. }
  71844. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71845. const String& defaultValue = String::empty) const
  71846. {
  71847. if (xml->hasAttribute (attributeName))
  71848. return xml->getStringAttribute (attributeName, defaultValue);
  71849. const String styleAtt (xml->getStringAttribute ("style"));
  71850. if (styleAtt.isNotEmpty())
  71851. {
  71852. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71853. if (value.isNotEmpty())
  71854. return value;
  71855. }
  71856. else if (xml->hasAttribute ("class"))
  71857. {
  71858. const String className ("." + xml->getStringAttribute ("class"));
  71859. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71860. if (index < 0)
  71861. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71862. if (index >= 0)
  71863. {
  71864. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71865. if (openBracket > index)
  71866. {
  71867. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71868. if (closeBracket > openBracket)
  71869. {
  71870. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71871. if (value.isNotEmpty())
  71872. return value;
  71873. }
  71874. }
  71875. }
  71876. }
  71877. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71878. if (xml != 0)
  71879. return getStyleAttribute (xml, attributeName, defaultValue);
  71880. return defaultValue;
  71881. }
  71882. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71883. {
  71884. if (xml->hasAttribute (attributeName))
  71885. return xml->getStringAttribute (attributeName);
  71886. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71887. if (xml != 0)
  71888. return getInheritedAttribute (xml, attributeName);
  71889. return String::empty;
  71890. }
  71891. static bool isIdentifierChar (const juce_wchar c)
  71892. {
  71893. return CharacterFunctions::isLetter (c) || c == '-';
  71894. }
  71895. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71896. {
  71897. int i = 0;
  71898. for (;;)
  71899. {
  71900. i = list.indexOf (i, attributeName);
  71901. if (i < 0)
  71902. break;
  71903. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71904. && ! isIdentifierChar (list [i + attributeName.length()]))
  71905. {
  71906. i = list.indexOfChar (i, ':');
  71907. if (i < 0)
  71908. break;
  71909. int end = list.indexOfChar (i, ';');
  71910. if (end < 0)
  71911. end = 0x7ffff;
  71912. return list.substring (i + 1, end).trim();
  71913. }
  71914. ++i;
  71915. }
  71916. return defaultValue;
  71917. }
  71918. static bool parseNextNumber (String::CharPointerType& s, String& value, const bool allowUnits)
  71919. {
  71920. while (s.isWhitespace() || *s == ',')
  71921. ++s;
  71922. String::CharPointerType start (s);
  71923. int numChars = 0;
  71924. if (s.isDigit() || *s == '.' || *s == '-')
  71925. {
  71926. ++numChars;
  71927. ++s;
  71928. }
  71929. while (s.isDigit() || *s == '.')
  71930. {
  71931. ++numChars;
  71932. ++s;
  71933. }
  71934. if ((*s == 'e' || *s == 'E')
  71935. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  71936. {
  71937. s += 2;
  71938. numChars += 2;
  71939. while (s.isDigit())
  71940. {
  71941. ++numChars;
  71942. ++s;
  71943. }
  71944. }
  71945. if (allowUnits)
  71946. {
  71947. while (s.isLetter())
  71948. {
  71949. ++numChars;
  71950. ++s;
  71951. }
  71952. }
  71953. if (numChars == 0)
  71954. return false;
  71955. value = String (start, numChars);
  71956. while (s.isWhitespace() || *s == ',')
  71957. ++s;
  71958. return true;
  71959. }
  71960. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71961. {
  71962. if (s [index] == '#')
  71963. {
  71964. uint32 hex [6];
  71965. zeromem (hex, sizeof (hex));
  71966. int numChars = 0;
  71967. for (int i = 6; --i >= 0;)
  71968. {
  71969. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71970. if (hexValue >= 0)
  71971. hex [numChars++] = hexValue;
  71972. else
  71973. break;
  71974. }
  71975. if (numChars <= 3)
  71976. return Colour ((uint8) (hex [0] * 0x11),
  71977. (uint8) (hex [1] * 0x11),
  71978. (uint8) (hex [2] * 0x11));
  71979. else
  71980. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71981. (uint8) ((hex [2] << 4) + hex [3]),
  71982. (uint8) ((hex [4] << 4) + hex [5]));
  71983. }
  71984. else if (s [index] == 'r'
  71985. && s [index + 1] == 'g'
  71986. && s [index + 2] == 'b')
  71987. {
  71988. const int openBracket = s.indexOfChar (index, '(');
  71989. const int closeBracket = s.indexOfChar (openBracket, ')');
  71990. if (openBracket >= 3 && closeBracket > openBracket)
  71991. {
  71992. index = closeBracket;
  71993. StringArray tokens;
  71994. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71995. tokens.trim();
  71996. tokens.removeEmptyStrings();
  71997. if (tokens[0].containsChar ('%'))
  71998. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71999. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72000. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72001. else
  72002. return Colour ((uint8) tokens[0].getIntValue(),
  72003. (uint8) tokens[1].getIntValue(),
  72004. (uint8) tokens[2].getIntValue());
  72005. }
  72006. }
  72007. return Colours::findColourForName (s, defaultColour);
  72008. }
  72009. static const AffineTransform parseTransform (String t)
  72010. {
  72011. AffineTransform result;
  72012. while (t.isNotEmpty())
  72013. {
  72014. StringArray tokens;
  72015. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72016. .upToFirstOccurrenceOf (")", false, false),
  72017. ", ", String::empty);
  72018. tokens.removeEmptyStrings (true);
  72019. float numbers [6];
  72020. for (int i = 0; i < 6; ++i)
  72021. numbers[i] = tokens[i].getFloatValue();
  72022. AffineTransform trans;
  72023. if (t.startsWithIgnoreCase ("matrix"))
  72024. {
  72025. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72026. numbers[1], numbers[3], numbers[5]);
  72027. }
  72028. else if (t.startsWithIgnoreCase ("translate"))
  72029. {
  72030. jassert (tokens.size() == 2);
  72031. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72032. }
  72033. else if (t.startsWithIgnoreCase ("scale"))
  72034. {
  72035. if (tokens.size() == 1)
  72036. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72037. else
  72038. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72039. }
  72040. else if (t.startsWithIgnoreCase ("rotate"))
  72041. {
  72042. if (tokens.size() != 3)
  72043. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72044. else
  72045. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72046. numbers[1], numbers[2]);
  72047. }
  72048. else if (t.startsWithIgnoreCase ("skewX"))
  72049. {
  72050. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72051. 0.0f, 1.0f, 0.0f);
  72052. }
  72053. else if (t.startsWithIgnoreCase ("skewY"))
  72054. {
  72055. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72056. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72057. }
  72058. result = trans.followedBy (result);
  72059. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72060. }
  72061. return result;
  72062. }
  72063. static void endpointToCentreParameters (const double x1, const double y1,
  72064. const double x2, const double y2,
  72065. const double angle,
  72066. const bool largeArc, const bool sweep,
  72067. double& rx, double& ry,
  72068. double& centreX, double& centreY,
  72069. double& startAngle, double& deltaAngle)
  72070. {
  72071. const double midX = (x1 - x2) * 0.5;
  72072. const double midY = (y1 - y2) * 0.5;
  72073. const double cosAngle = cos (angle);
  72074. const double sinAngle = sin (angle);
  72075. const double xp = cosAngle * midX + sinAngle * midY;
  72076. const double yp = cosAngle * midY - sinAngle * midX;
  72077. const double xp2 = xp * xp;
  72078. const double yp2 = yp * yp;
  72079. double rx2 = rx * rx;
  72080. double ry2 = ry * ry;
  72081. const double s = (xp2 / rx2) + (yp2 / ry2);
  72082. double c;
  72083. if (s <= 1.0)
  72084. {
  72085. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72086. / (( rx2 * yp2) + (ry2 * xp2))));
  72087. if (largeArc == sweep)
  72088. c = -c;
  72089. }
  72090. else
  72091. {
  72092. const double s2 = std::sqrt (s);
  72093. rx *= s2;
  72094. ry *= s2;
  72095. rx2 = rx * rx;
  72096. ry2 = ry * ry;
  72097. c = 0;
  72098. }
  72099. const double cpx = ((rx * yp) / ry) * c;
  72100. const double cpy = ((-ry * xp) / rx) * c;
  72101. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72102. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72103. const double ux = (xp - cpx) / rx;
  72104. const double uy = (yp - cpy) / ry;
  72105. const double vx = (-xp - cpx) / rx;
  72106. const double vy = (-yp - cpy) / ry;
  72107. const double length = juce_hypot (ux, uy);
  72108. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72109. if (uy < 0)
  72110. startAngle = -startAngle;
  72111. startAngle += double_Pi * 0.5;
  72112. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72113. / (length * juce_hypot (vx, vy))));
  72114. if ((ux * vy) - (uy * vx) < 0)
  72115. deltaAngle = -deltaAngle;
  72116. if (sweep)
  72117. {
  72118. if (deltaAngle < 0)
  72119. deltaAngle += double_Pi * 2.0;
  72120. }
  72121. else
  72122. {
  72123. if (deltaAngle > 0)
  72124. deltaAngle -= double_Pi * 2.0;
  72125. }
  72126. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72127. }
  72128. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72129. {
  72130. forEachXmlChildElement (*parent, e)
  72131. {
  72132. if (e->compareAttribute ("id", id))
  72133. return e;
  72134. const XmlElement* const found = findElementForId (e, id);
  72135. if (found != 0)
  72136. return found;
  72137. }
  72138. return 0;
  72139. }
  72140. SVGState& operator= (const SVGState&);
  72141. };
  72142. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72143. {
  72144. SVGState state (&svgDocument);
  72145. return state.parseSVGElement (svgDocument);
  72146. }
  72147. END_JUCE_NAMESPACE
  72148. /*** End of inlined file: juce_SVGParser.cpp ***/
  72149. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72150. BEGIN_JUCE_NAMESPACE
  72151. #if JUCE_MSVC && JUCE_DEBUG
  72152. #pragma optimize ("t", on)
  72153. #endif
  72154. DropShadowEffect::DropShadowEffect()
  72155. : offsetX (0),
  72156. offsetY (0),
  72157. radius (4),
  72158. opacity (0.6f)
  72159. {
  72160. }
  72161. DropShadowEffect::~DropShadowEffect()
  72162. {
  72163. }
  72164. void DropShadowEffect::setShadowProperties (const float newRadius,
  72165. const float newOpacity,
  72166. const int newShadowOffsetX,
  72167. const int newShadowOffsetY)
  72168. {
  72169. radius = jmax (1.1f, newRadius);
  72170. offsetX = newShadowOffsetX;
  72171. offsetY = newShadowOffsetY;
  72172. opacity = newOpacity;
  72173. }
  72174. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72175. {
  72176. const int w = image.getWidth();
  72177. const int h = image.getHeight();
  72178. Image shadowImage (Image::SingleChannel, w, h, false);
  72179. const Image::BitmapData srcData (image, false);
  72180. const Image::BitmapData destData (shadowImage, true);
  72181. const int filter = roundToInt (63.0f / radius);
  72182. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72183. for (int x = w; --x >= 0;)
  72184. {
  72185. int shadowAlpha = 0;
  72186. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72187. uint8* shadowPix = destData.data + x;
  72188. for (int y = h; --y >= 0;)
  72189. {
  72190. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72191. *shadowPix = (uint8) shadowAlpha;
  72192. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72193. shadowPix += destData.lineStride;
  72194. }
  72195. }
  72196. for (int y = h; --y >= 0;)
  72197. {
  72198. int shadowAlpha = 0;
  72199. uint8* shadowPix = destData.getLinePointer (y);
  72200. for (int x = w; --x >= 0;)
  72201. {
  72202. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72203. *shadowPix++ = (uint8) shadowAlpha;
  72204. }
  72205. }
  72206. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72207. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72208. g.setOpacity (alpha);
  72209. g.drawImageAt (image, 0, 0);
  72210. }
  72211. #if JUCE_MSVC && JUCE_DEBUG
  72212. #pragma optimize ("", on) // resets optimisations to the project defaults
  72213. #endif
  72214. END_JUCE_NAMESPACE
  72215. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72216. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72217. BEGIN_JUCE_NAMESPACE
  72218. GlowEffect::GlowEffect()
  72219. : radius (2.0f),
  72220. colour (Colours::white)
  72221. {
  72222. }
  72223. GlowEffect::~GlowEffect()
  72224. {
  72225. }
  72226. void GlowEffect::setGlowProperties (const float newRadius,
  72227. const Colour& newColour)
  72228. {
  72229. radius = newRadius;
  72230. colour = newColour;
  72231. }
  72232. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72233. {
  72234. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72235. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72236. blurKernel.createGaussianBlur (radius);
  72237. blurKernel.rescaleAllValues (radius);
  72238. blurKernel.applyToImage (temp, image, image.getBounds());
  72239. g.setColour (colour.withMultipliedAlpha (alpha));
  72240. g.drawImageAt (temp, 0, 0, true);
  72241. g.setOpacity (alpha);
  72242. g.drawImageAt (image, 0, 0, false);
  72243. }
  72244. END_JUCE_NAMESPACE
  72245. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72246. /*** Start of inlined file: juce_Font.cpp ***/
  72247. BEGIN_JUCE_NAMESPACE
  72248. namespace FontValues
  72249. {
  72250. float limitFontHeight (const float height) throw()
  72251. {
  72252. return jlimit (0.1f, 10000.0f, height);
  72253. }
  72254. const float defaultFontHeight = 14.0f;
  72255. String fallbackFont;
  72256. }
  72257. class TypefaceCache : public DeletedAtShutdown
  72258. {
  72259. public:
  72260. TypefaceCache()
  72261. : counter (0)
  72262. {
  72263. setSize (10);
  72264. }
  72265. ~TypefaceCache()
  72266. {
  72267. clearSingletonInstance();
  72268. }
  72269. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72270. void setSize (const int numToCache)
  72271. {
  72272. faces.clear();
  72273. faces.insertMultiple (-1, CachedFace(), numToCache);
  72274. }
  72275. const Typeface::Ptr findTypefaceFor (const Font& font)
  72276. {
  72277. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72278. const String faceName (font.getTypefaceName());
  72279. int i;
  72280. for (i = faces.size(); --i >= 0;)
  72281. {
  72282. CachedFace& face = faces.getReference(i);
  72283. if (face.flags == flags
  72284. && face.typefaceName == faceName
  72285. && face.typeface->isSuitableForFont (font))
  72286. {
  72287. face.lastUsageCount = ++counter;
  72288. return face.typeface;
  72289. }
  72290. }
  72291. int replaceIndex = 0;
  72292. int bestLastUsageCount = std::numeric_limits<int>::max();
  72293. for (i = faces.size(); --i >= 0;)
  72294. {
  72295. const int lu = faces.getReference(i).lastUsageCount;
  72296. if (bestLastUsageCount > lu)
  72297. {
  72298. bestLastUsageCount = lu;
  72299. replaceIndex = i;
  72300. }
  72301. }
  72302. CachedFace& face = faces.getReference (replaceIndex);
  72303. face.typefaceName = faceName;
  72304. face.flags = flags;
  72305. face.lastUsageCount = ++counter;
  72306. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72307. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72308. if (defaultFace == 0 && font == Font())
  72309. defaultFace = face.typeface;
  72310. return face.typeface;
  72311. }
  72312. const Typeface::Ptr getDefaultTypeface() const throw()
  72313. {
  72314. return defaultFace;
  72315. }
  72316. private:
  72317. struct CachedFace
  72318. {
  72319. CachedFace() throw()
  72320. : lastUsageCount (0), flags (-1)
  72321. {
  72322. }
  72323. // Although it seems a bit wacky to store the name here, it's because it may be a
  72324. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72325. // Since the typeface itself doesn't know that it may have this alias, the name under
  72326. // which it was fetched needs to be stored separately.
  72327. String typefaceName;
  72328. int lastUsageCount, flags;
  72329. Typeface::Ptr typeface;
  72330. };
  72331. Array <CachedFace> faces;
  72332. Typeface::Ptr defaultFace;
  72333. int counter;
  72334. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72335. };
  72336. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72337. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72338. {
  72339. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72340. }
  72341. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72342. : typefaceName (Font::getDefaultSansSerifFontName()),
  72343. height (height_),
  72344. horizontalScale (1.0f),
  72345. kerning (0),
  72346. ascent (0),
  72347. styleFlags (styleFlags_),
  72348. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72349. {
  72350. }
  72351. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72352. : typefaceName (typefaceName_),
  72353. height (height_),
  72354. horizontalScale (1.0f),
  72355. kerning (0),
  72356. ascent (0),
  72357. styleFlags (styleFlags_),
  72358. typeface (0)
  72359. {
  72360. }
  72361. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72362. : typefaceName (typeface_->getName()),
  72363. height (FontValues::defaultFontHeight),
  72364. horizontalScale (1.0f),
  72365. kerning (0),
  72366. ascent (0),
  72367. styleFlags (Font::plain),
  72368. typeface (typeface_)
  72369. {
  72370. }
  72371. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72372. : typefaceName (other.typefaceName),
  72373. height (other.height),
  72374. horizontalScale (other.horizontalScale),
  72375. kerning (other.kerning),
  72376. ascent (other.ascent),
  72377. styleFlags (other.styleFlags),
  72378. typeface (other.typeface)
  72379. {
  72380. }
  72381. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72382. {
  72383. return height == other.height
  72384. && styleFlags == other.styleFlags
  72385. && horizontalScale == other.horizontalScale
  72386. && kerning == other.kerning
  72387. && typefaceName == other.typefaceName;
  72388. }
  72389. Font::Font()
  72390. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72391. {
  72392. }
  72393. Font::Font (const float fontHeight, const int styleFlags_)
  72394. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72395. {
  72396. }
  72397. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72398. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72399. {
  72400. }
  72401. Font::Font (const Typeface::Ptr& typeface)
  72402. : font (new SharedFontInternal (typeface))
  72403. {
  72404. }
  72405. Font::Font (const Font& other) throw()
  72406. : font (other.font)
  72407. {
  72408. }
  72409. Font& Font::operator= (const Font& other) throw()
  72410. {
  72411. font = other.font;
  72412. return *this;
  72413. }
  72414. Font::~Font() throw()
  72415. {
  72416. }
  72417. bool Font::operator== (const Font& other) const throw()
  72418. {
  72419. return font == other.font
  72420. || *font == *other.font;
  72421. }
  72422. bool Font::operator!= (const Font& other) const throw()
  72423. {
  72424. return ! operator== (other);
  72425. }
  72426. void Font::dupeInternalIfShared()
  72427. {
  72428. if (font->getReferenceCount() > 1)
  72429. font = new SharedFontInternal (*font);
  72430. }
  72431. const String Font::getDefaultSansSerifFontName()
  72432. {
  72433. static const String name ("<Sans-Serif>");
  72434. return name;
  72435. }
  72436. const String Font::getDefaultSerifFontName()
  72437. {
  72438. static const String name ("<Serif>");
  72439. return name;
  72440. }
  72441. const String Font::getDefaultMonospacedFontName()
  72442. {
  72443. static const String name ("<Monospaced>");
  72444. return name;
  72445. }
  72446. void Font::setTypefaceName (const String& faceName)
  72447. {
  72448. if (faceName != font->typefaceName)
  72449. {
  72450. dupeInternalIfShared();
  72451. font->typefaceName = faceName;
  72452. font->typeface = 0;
  72453. font->ascent = 0;
  72454. }
  72455. }
  72456. const String Font::getFallbackFontName()
  72457. {
  72458. return FontValues::fallbackFont;
  72459. }
  72460. void Font::setFallbackFontName (const String& name)
  72461. {
  72462. FontValues::fallbackFont = name;
  72463. }
  72464. void Font::setHeight (float newHeight)
  72465. {
  72466. newHeight = FontValues::limitFontHeight (newHeight);
  72467. if (font->height != newHeight)
  72468. {
  72469. dupeInternalIfShared();
  72470. font->height = newHeight;
  72471. }
  72472. }
  72473. void Font::setHeightWithoutChangingWidth (float newHeight)
  72474. {
  72475. newHeight = FontValues::limitFontHeight (newHeight);
  72476. if (font->height != newHeight)
  72477. {
  72478. dupeInternalIfShared();
  72479. font->horizontalScale *= (font->height / newHeight);
  72480. font->height = newHeight;
  72481. }
  72482. }
  72483. void Font::setStyleFlags (const int newFlags)
  72484. {
  72485. if (font->styleFlags != newFlags)
  72486. {
  72487. dupeInternalIfShared();
  72488. font->styleFlags = newFlags;
  72489. font->typeface = 0;
  72490. font->ascent = 0;
  72491. }
  72492. }
  72493. void Font::setSizeAndStyle (float newHeight,
  72494. const int newStyleFlags,
  72495. const float newHorizontalScale,
  72496. const float newKerningAmount)
  72497. {
  72498. newHeight = FontValues::limitFontHeight (newHeight);
  72499. if (font->height != newHeight
  72500. || font->horizontalScale != newHorizontalScale
  72501. || font->kerning != newKerningAmount)
  72502. {
  72503. dupeInternalIfShared();
  72504. font->height = newHeight;
  72505. font->horizontalScale = newHorizontalScale;
  72506. font->kerning = newKerningAmount;
  72507. }
  72508. setStyleFlags (newStyleFlags);
  72509. }
  72510. void Font::setHorizontalScale (const float scaleFactor)
  72511. {
  72512. dupeInternalIfShared();
  72513. font->horizontalScale = scaleFactor;
  72514. }
  72515. void Font::setExtraKerningFactor (const float extraKerning)
  72516. {
  72517. dupeInternalIfShared();
  72518. font->kerning = extraKerning;
  72519. }
  72520. void Font::setBold (const bool shouldBeBold)
  72521. {
  72522. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72523. : (font->styleFlags & ~bold));
  72524. }
  72525. const Font Font::boldened() const
  72526. {
  72527. Font f (*this);
  72528. f.setBold (true);
  72529. return f;
  72530. }
  72531. bool Font::isBold() const throw()
  72532. {
  72533. return (font->styleFlags & bold) != 0;
  72534. }
  72535. void Font::setItalic (const bool shouldBeItalic)
  72536. {
  72537. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72538. : (font->styleFlags & ~italic));
  72539. }
  72540. const Font Font::italicised() const
  72541. {
  72542. Font f (*this);
  72543. f.setItalic (true);
  72544. return f;
  72545. }
  72546. bool Font::isItalic() const throw()
  72547. {
  72548. return (font->styleFlags & italic) != 0;
  72549. }
  72550. void Font::setUnderline (const bool shouldBeUnderlined)
  72551. {
  72552. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72553. : (font->styleFlags & ~underlined));
  72554. }
  72555. bool Font::isUnderlined() const throw()
  72556. {
  72557. return (font->styleFlags & underlined) != 0;
  72558. }
  72559. float Font::getAscent() const
  72560. {
  72561. if (font->ascent == 0)
  72562. font->ascent = getTypeface()->getAscent();
  72563. return font->height * font->ascent;
  72564. }
  72565. float Font::getDescent() const
  72566. {
  72567. return font->height - getAscent();
  72568. }
  72569. int Font::getStringWidth (const String& text) const
  72570. {
  72571. return roundToInt (getStringWidthFloat (text));
  72572. }
  72573. float Font::getStringWidthFloat (const String& text) const
  72574. {
  72575. float w = getTypeface()->getStringWidth (text);
  72576. if (font->kerning != 0)
  72577. w += font->kerning * text.length();
  72578. return w * font->height * font->horizontalScale;
  72579. }
  72580. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72581. {
  72582. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72583. const float scale = font->height * font->horizontalScale;
  72584. const int num = xOffsets.size();
  72585. if (num > 0)
  72586. {
  72587. float* const x = &(xOffsets.getReference(0));
  72588. if (font->kerning != 0)
  72589. {
  72590. for (int i = 0; i < num; ++i)
  72591. x[i] = (x[i] + i * font->kerning) * scale;
  72592. }
  72593. else
  72594. {
  72595. for (int i = 0; i < num; ++i)
  72596. x[i] *= scale;
  72597. }
  72598. }
  72599. }
  72600. void Font::findFonts (Array<Font>& destArray)
  72601. {
  72602. const StringArray names (findAllTypefaceNames());
  72603. for (int i = 0; i < names.size(); ++i)
  72604. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72605. }
  72606. const String Font::toString() const
  72607. {
  72608. String s (getTypefaceName());
  72609. if (s == getDefaultSansSerifFontName())
  72610. s = String::empty;
  72611. else
  72612. s += "; ";
  72613. s += String (getHeight(), 1);
  72614. if (isBold())
  72615. s += " bold";
  72616. if (isItalic())
  72617. s += " italic";
  72618. return s;
  72619. }
  72620. const Font Font::fromString (const String& fontDescription)
  72621. {
  72622. String name;
  72623. const int separator = fontDescription.indexOfChar (';');
  72624. if (separator > 0)
  72625. name = fontDescription.substring (0, separator).trim();
  72626. if (name.isEmpty())
  72627. name = getDefaultSansSerifFontName();
  72628. String sizeAndStyle (fontDescription.substring (separator + 1));
  72629. float height = sizeAndStyle.getFloatValue();
  72630. if (height <= 0)
  72631. height = 10.0f;
  72632. int flags = Font::plain;
  72633. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72634. flags |= Font::bold;
  72635. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72636. flags |= Font::italic;
  72637. return Font (name, height, flags);
  72638. }
  72639. Typeface* Font::getTypeface() const
  72640. {
  72641. if (font->typeface == 0)
  72642. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72643. return font->typeface;
  72644. }
  72645. END_JUCE_NAMESPACE
  72646. /*** End of inlined file: juce_Font.cpp ***/
  72647. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72648. BEGIN_JUCE_NAMESPACE
  72649. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72650. const juce_wchar character_, const int glyph_)
  72651. : x (x_),
  72652. y (y_),
  72653. w (w_),
  72654. font (font_),
  72655. character (character_),
  72656. glyph (glyph_)
  72657. {
  72658. }
  72659. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72660. : x (other.x),
  72661. y (other.y),
  72662. w (other.w),
  72663. font (other.font),
  72664. character (other.character),
  72665. glyph (other.glyph)
  72666. {
  72667. }
  72668. void PositionedGlyph::draw (const Graphics& g) const
  72669. {
  72670. if (! isWhitespace())
  72671. {
  72672. g.getInternalContext()->setFont (font);
  72673. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72674. }
  72675. }
  72676. void PositionedGlyph::draw (const Graphics& g,
  72677. const AffineTransform& transform) const
  72678. {
  72679. if (! isWhitespace())
  72680. {
  72681. g.getInternalContext()->setFont (font);
  72682. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72683. .followedBy (transform));
  72684. }
  72685. }
  72686. void PositionedGlyph::createPath (Path& path) const
  72687. {
  72688. if (! isWhitespace())
  72689. {
  72690. Typeface* const t = font.getTypeface();
  72691. if (t != 0)
  72692. {
  72693. Path p;
  72694. t->getOutlineForGlyph (glyph, p);
  72695. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72696. .translated (x, y));
  72697. }
  72698. }
  72699. }
  72700. bool PositionedGlyph::hitTest (float px, float py) const
  72701. {
  72702. if (getBounds().contains (px, py) && ! isWhitespace())
  72703. {
  72704. Typeface* const t = font.getTypeface();
  72705. if (t != 0)
  72706. {
  72707. Path p;
  72708. t->getOutlineForGlyph (glyph, p);
  72709. AffineTransform::translation (-x, -y)
  72710. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72711. .transformPoint (px, py);
  72712. return p.contains (px, py);
  72713. }
  72714. }
  72715. return false;
  72716. }
  72717. void PositionedGlyph::moveBy (const float deltaX,
  72718. const float deltaY)
  72719. {
  72720. x += deltaX;
  72721. y += deltaY;
  72722. }
  72723. GlyphArrangement::GlyphArrangement()
  72724. {
  72725. glyphs.ensureStorageAllocated (128);
  72726. }
  72727. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72728. {
  72729. addGlyphArrangement (other);
  72730. }
  72731. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72732. {
  72733. if (this != &other)
  72734. {
  72735. clear();
  72736. addGlyphArrangement (other);
  72737. }
  72738. return *this;
  72739. }
  72740. GlyphArrangement::~GlyphArrangement()
  72741. {
  72742. }
  72743. void GlyphArrangement::clear()
  72744. {
  72745. glyphs.clear();
  72746. }
  72747. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72748. {
  72749. jassert (isPositiveAndBelow (index, glyphs.size()));
  72750. return *glyphs [index];
  72751. }
  72752. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72753. {
  72754. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72755. glyphs.addCopiesOf (other.glyphs);
  72756. }
  72757. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72758. {
  72759. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72760. }
  72761. void GlyphArrangement::addLineOfText (const Font& font,
  72762. const String& text,
  72763. const float xOffset,
  72764. const float yOffset)
  72765. {
  72766. addCurtailedLineOfText (font, text,
  72767. xOffset, yOffset,
  72768. 1.0e10f, false);
  72769. }
  72770. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72771. const String& text,
  72772. float xOffset,
  72773. const float yOffset,
  72774. const float maxWidthPixels,
  72775. const bool useEllipsis)
  72776. {
  72777. if (text.isNotEmpty())
  72778. {
  72779. Array <int> newGlyphs;
  72780. Array <float> xOffsets;
  72781. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72782. const int textLen = newGlyphs.size();
  72783. String::CharPointerType t (text.getCharPointer());
  72784. for (int i = 0; i < textLen; ++i)
  72785. {
  72786. const float thisX = xOffsets.getUnchecked (i);
  72787. const float nextX = xOffsets.getUnchecked (i + 1);
  72788. if (nextX > maxWidthPixels + 1.0f)
  72789. {
  72790. // curtail the string if it's too wide..
  72791. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72792. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72793. break;
  72794. }
  72795. else
  72796. {
  72797. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72798. font, t.getAndAdvance(), newGlyphs.getUnchecked(i)));
  72799. }
  72800. }
  72801. }
  72802. }
  72803. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72804. const int startIndex, int endIndex)
  72805. {
  72806. int numDeleted = 0;
  72807. if (glyphs.size() > 0)
  72808. {
  72809. Array<int> dotGlyphs;
  72810. Array<float> dotXs;
  72811. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72812. const float dx = dotXs[1];
  72813. float xOffset = 0.0f, yOffset = 0.0f;
  72814. while (endIndex > startIndex)
  72815. {
  72816. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72817. xOffset = pg->x;
  72818. yOffset = pg->y;
  72819. glyphs.remove (endIndex);
  72820. ++numDeleted;
  72821. if (xOffset + dx * 3 <= maxXPos)
  72822. break;
  72823. }
  72824. for (int i = 3; --i >= 0;)
  72825. {
  72826. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72827. font, '.', dotGlyphs.getFirst()));
  72828. --numDeleted;
  72829. xOffset += dx;
  72830. if (xOffset > maxXPos)
  72831. break;
  72832. }
  72833. }
  72834. return numDeleted;
  72835. }
  72836. void GlyphArrangement::addJustifiedText (const Font& font,
  72837. const String& text,
  72838. float x, float y,
  72839. const float maxLineWidth,
  72840. const Justification& horizontalLayout)
  72841. {
  72842. int lineStartIndex = glyphs.size();
  72843. addLineOfText (font, text, x, y);
  72844. const float originalY = y;
  72845. while (lineStartIndex < glyphs.size())
  72846. {
  72847. int i = lineStartIndex;
  72848. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72849. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72850. ++i;
  72851. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72852. int lastWordBreakIndex = -1;
  72853. while (i < glyphs.size())
  72854. {
  72855. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72856. const juce_wchar c = pg->getCharacter();
  72857. if (c == '\r' || c == '\n')
  72858. {
  72859. ++i;
  72860. if (c == '\r' && i < glyphs.size()
  72861. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72862. ++i;
  72863. break;
  72864. }
  72865. else if (pg->isWhitespace())
  72866. {
  72867. lastWordBreakIndex = i + 1;
  72868. }
  72869. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72870. {
  72871. if (lastWordBreakIndex >= 0)
  72872. i = lastWordBreakIndex;
  72873. break;
  72874. }
  72875. ++i;
  72876. }
  72877. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72878. float currentLineEndX = currentLineStartX;
  72879. for (int j = i; --j >= lineStartIndex;)
  72880. {
  72881. if (! glyphs.getUnchecked (j)->isWhitespace())
  72882. {
  72883. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72884. break;
  72885. }
  72886. }
  72887. float deltaX = 0.0f;
  72888. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72889. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72890. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72891. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72892. else if (horizontalLayout.testFlags (Justification::right))
  72893. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72894. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72895. x + deltaX - currentLineStartX, y - originalY);
  72896. lineStartIndex = i;
  72897. y += font.getHeight();
  72898. }
  72899. }
  72900. void GlyphArrangement::addFittedText (const Font& f,
  72901. const String& text,
  72902. const float x, const float y,
  72903. const float width, const float height,
  72904. const Justification& layout,
  72905. int maximumLines,
  72906. const float minimumHorizontalScale)
  72907. {
  72908. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72909. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72910. if (text.containsAnyOf ("\r\n"))
  72911. {
  72912. GlyphArrangement ga;
  72913. ga.addJustifiedText (f, text, x, y, width, layout);
  72914. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72915. float dy = y - bb.getY();
  72916. if (layout.testFlags (Justification::verticallyCentred))
  72917. dy += (height - bb.getHeight()) * 0.5f;
  72918. else if (layout.testFlags (Justification::bottom))
  72919. dy += height - bb.getHeight();
  72920. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72921. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72922. for (int i = 0; i < ga.glyphs.size(); ++i)
  72923. glyphs.add (ga.glyphs.getUnchecked (i));
  72924. ga.glyphs.clear (false);
  72925. return;
  72926. }
  72927. int startIndex = glyphs.size();
  72928. addLineOfText (f, text.trim(), x, y);
  72929. if (glyphs.size() > startIndex)
  72930. {
  72931. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72932. - glyphs.getUnchecked (startIndex)->getLeft();
  72933. if (lineWidth <= 0)
  72934. return;
  72935. if (lineWidth * minimumHorizontalScale < width)
  72936. {
  72937. if (lineWidth > width)
  72938. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72939. width / lineWidth);
  72940. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72941. x, y, width, height, layout);
  72942. }
  72943. else if (maximumLines <= 1)
  72944. {
  72945. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72946. x, y, width, height, f, layout, minimumHorizontalScale);
  72947. }
  72948. else
  72949. {
  72950. Font font (f);
  72951. String txt (text.trim());
  72952. const int length = txt.length();
  72953. const int originalStartIndex = startIndex;
  72954. int numLines = 1;
  72955. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72956. maximumLines = 1;
  72957. maximumLines = jmin (maximumLines, length);
  72958. while (numLines < maximumLines)
  72959. {
  72960. ++numLines;
  72961. const float newFontHeight = height / (float) numLines;
  72962. if (newFontHeight < font.getHeight())
  72963. {
  72964. font.setHeight (jmax (8.0f, newFontHeight));
  72965. removeRangeOfGlyphs (startIndex, -1);
  72966. addLineOfText (font, txt, x, y);
  72967. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72968. - glyphs.getUnchecked (startIndex)->getLeft();
  72969. }
  72970. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72971. break;
  72972. }
  72973. if (numLines < 1)
  72974. numLines = 1;
  72975. float lineY = y;
  72976. float widthPerLine = lineWidth / numLines;
  72977. int lastLineStartIndex = 0;
  72978. for (int line = 0; line < numLines; ++line)
  72979. {
  72980. int i = startIndex;
  72981. lastLineStartIndex = i;
  72982. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72983. if (line == numLines - 1)
  72984. {
  72985. widthPerLine = width;
  72986. i = glyphs.size();
  72987. }
  72988. else
  72989. {
  72990. while (i < glyphs.size())
  72991. {
  72992. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72993. if (lineWidth > widthPerLine)
  72994. {
  72995. // got to a point where the line's too long, so skip forward to find a
  72996. // good place to break it..
  72997. const int searchStartIndex = i;
  72998. while (i < glyphs.size())
  72999. {
  73000. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73001. {
  73002. if (glyphs.getUnchecked (i)->isWhitespace()
  73003. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73004. {
  73005. ++i;
  73006. break;
  73007. }
  73008. }
  73009. else
  73010. {
  73011. // can't find a suitable break, so try looking backwards..
  73012. i = searchStartIndex;
  73013. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73014. {
  73015. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73016. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73017. {
  73018. i -= back - 1;
  73019. break;
  73020. }
  73021. }
  73022. break;
  73023. }
  73024. ++i;
  73025. }
  73026. break;
  73027. }
  73028. ++i;
  73029. }
  73030. int wsStart = i;
  73031. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73032. --wsStart;
  73033. int wsEnd = i;
  73034. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73035. ++wsEnd;
  73036. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73037. i = jmax (wsStart, startIndex + 1);
  73038. }
  73039. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73040. x, lineY, width, font.getHeight(), font,
  73041. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73042. minimumHorizontalScale);
  73043. startIndex = i;
  73044. lineY += font.getHeight();
  73045. if (startIndex >= glyphs.size())
  73046. break;
  73047. }
  73048. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73049. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73050. }
  73051. }
  73052. }
  73053. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73054. const float dx, const float dy)
  73055. {
  73056. jassert (startIndex >= 0);
  73057. if (dx != 0.0f || dy != 0.0f)
  73058. {
  73059. if (num < 0 || startIndex + num > glyphs.size())
  73060. num = glyphs.size() - startIndex;
  73061. while (--num >= 0)
  73062. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73063. }
  73064. }
  73065. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73066. const Justification& justification, float minimumHorizontalScale)
  73067. {
  73068. int numDeleted = 0;
  73069. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73070. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73071. if (lineWidth > w)
  73072. {
  73073. if (minimumHorizontalScale < 1.0f)
  73074. {
  73075. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73076. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73077. }
  73078. if (lineWidth > w)
  73079. {
  73080. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73081. numGlyphs -= numDeleted;
  73082. }
  73083. }
  73084. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73085. return numDeleted;
  73086. }
  73087. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73088. const float horizontalScaleFactor)
  73089. {
  73090. jassert (startIndex >= 0);
  73091. if (num < 0 || startIndex + num > glyphs.size())
  73092. num = glyphs.size() - startIndex;
  73093. if (num > 0)
  73094. {
  73095. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73096. while (--num >= 0)
  73097. {
  73098. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73099. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73100. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73101. pg->w *= horizontalScaleFactor;
  73102. }
  73103. }
  73104. }
  73105. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73106. {
  73107. jassert (startIndex >= 0);
  73108. if (num < 0 || startIndex + num > glyphs.size())
  73109. num = glyphs.size() - startIndex;
  73110. Rectangle<float> result;
  73111. while (--num >= 0)
  73112. {
  73113. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73114. if (includeWhitespace || ! pg->isWhitespace())
  73115. result = result.getUnion (pg->getBounds());
  73116. }
  73117. return result;
  73118. }
  73119. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73120. const float x, const float y, const float width, const float height,
  73121. const Justification& justification)
  73122. {
  73123. jassert (num >= 0 && startIndex >= 0);
  73124. if (glyphs.size() > 0 && num > 0)
  73125. {
  73126. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73127. | Justification::horizontallyCentred)));
  73128. float deltaX = 0.0f;
  73129. if (justification.testFlags (Justification::horizontallyJustified))
  73130. deltaX = x - bb.getX();
  73131. else if (justification.testFlags (Justification::horizontallyCentred))
  73132. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73133. else if (justification.testFlags (Justification::right))
  73134. deltaX = (x + width) - bb.getRight();
  73135. else
  73136. deltaX = x - bb.getX();
  73137. float deltaY = 0.0f;
  73138. if (justification.testFlags (Justification::top))
  73139. deltaY = y - bb.getY();
  73140. else if (justification.testFlags (Justification::bottom))
  73141. deltaY = (y + height) - bb.getBottom();
  73142. else
  73143. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73144. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73145. if (justification.testFlags (Justification::horizontallyJustified))
  73146. {
  73147. int lineStart = 0;
  73148. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73149. int i;
  73150. for (i = 0; i < num; ++i)
  73151. {
  73152. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73153. if (glyphY != baseY)
  73154. {
  73155. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73156. lineStart = i;
  73157. baseY = glyphY;
  73158. }
  73159. }
  73160. if (i > lineStart)
  73161. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73162. }
  73163. }
  73164. }
  73165. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73166. {
  73167. if (start + num < glyphs.size()
  73168. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73169. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73170. {
  73171. int numSpaces = 0;
  73172. int spacesAtEnd = 0;
  73173. for (int i = 0; i < num; ++i)
  73174. {
  73175. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73176. {
  73177. ++spacesAtEnd;
  73178. ++numSpaces;
  73179. }
  73180. else
  73181. {
  73182. spacesAtEnd = 0;
  73183. }
  73184. }
  73185. numSpaces -= spacesAtEnd;
  73186. if (numSpaces > 0)
  73187. {
  73188. const float startX = glyphs.getUnchecked (start)->getLeft();
  73189. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73190. const float extraPaddingBetweenWords
  73191. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73192. float deltaX = 0.0f;
  73193. for (int i = 0; i < num; ++i)
  73194. {
  73195. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73196. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73197. deltaX += extraPaddingBetweenWords;
  73198. }
  73199. }
  73200. }
  73201. }
  73202. void GlyphArrangement::draw (const Graphics& g) const
  73203. {
  73204. for (int i = 0; i < glyphs.size(); ++i)
  73205. {
  73206. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73207. if (pg->font.isUnderlined())
  73208. {
  73209. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73210. float nextX = pg->x + pg->w;
  73211. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73212. nextX = glyphs.getUnchecked (i + 1)->x;
  73213. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73214. nextX - pg->x, lineThickness);
  73215. }
  73216. pg->draw (g);
  73217. }
  73218. }
  73219. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73220. {
  73221. for (int i = 0; i < glyphs.size(); ++i)
  73222. {
  73223. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73224. if (pg->font.isUnderlined())
  73225. {
  73226. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73227. float nextX = pg->x + pg->w;
  73228. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73229. nextX = glyphs.getUnchecked (i + 1)->x;
  73230. Path p;
  73231. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73232. nextX, pg->y + lineThickness * 2.0f),
  73233. lineThickness);
  73234. g.fillPath (p, transform);
  73235. }
  73236. pg->draw (g, transform);
  73237. }
  73238. }
  73239. void GlyphArrangement::createPath (Path& path) const
  73240. {
  73241. for (int i = 0; i < glyphs.size(); ++i)
  73242. glyphs.getUnchecked (i)->createPath (path);
  73243. }
  73244. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73245. {
  73246. for (int i = 0; i < glyphs.size(); ++i)
  73247. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73248. return i;
  73249. return -1;
  73250. }
  73251. END_JUCE_NAMESPACE
  73252. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73253. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73254. BEGIN_JUCE_NAMESPACE
  73255. class TextLayout::Token
  73256. {
  73257. public:
  73258. Token (const String& t,
  73259. const Font& f,
  73260. const bool isWhitespace_)
  73261. : text (t),
  73262. font (f),
  73263. x(0),
  73264. y(0),
  73265. isWhitespace (isWhitespace_)
  73266. {
  73267. w = font.getStringWidth (t);
  73268. h = roundToInt (f.getHeight());
  73269. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73270. }
  73271. Token (const Token& other)
  73272. : text (other.text),
  73273. font (other.font),
  73274. x (other.x),
  73275. y (other.y),
  73276. w (other.w),
  73277. h (other.h),
  73278. line (other.line),
  73279. lineHeight (other.lineHeight),
  73280. isWhitespace (other.isWhitespace),
  73281. isNewLine (other.isNewLine)
  73282. {
  73283. }
  73284. void draw (Graphics& g,
  73285. const int xOffset,
  73286. const int yOffset)
  73287. {
  73288. if (! isWhitespace)
  73289. {
  73290. g.setFont (font);
  73291. g.drawSingleLineText (text.trimEnd(),
  73292. xOffset + x,
  73293. yOffset + y + (lineHeight - h)
  73294. + roundToInt (font.getAscent()));
  73295. }
  73296. }
  73297. String text;
  73298. Font font;
  73299. int x, y, w, h;
  73300. int line, lineHeight;
  73301. bool isWhitespace, isNewLine;
  73302. private:
  73303. JUCE_LEAK_DETECTOR (Token);
  73304. };
  73305. TextLayout::TextLayout()
  73306. : totalLines (0)
  73307. {
  73308. tokens.ensureStorageAllocated (64);
  73309. }
  73310. TextLayout::TextLayout (const String& text, const Font& font)
  73311. : totalLines (0)
  73312. {
  73313. tokens.ensureStorageAllocated (64);
  73314. appendText (text, font);
  73315. }
  73316. TextLayout::TextLayout (const TextLayout& other)
  73317. : totalLines (0)
  73318. {
  73319. *this = other;
  73320. }
  73321. TextLayout& TextLayout::operator= (const TextLayout& other)
  73322. {
  73323. if (this != &other)
  73324. {
  73325. clear();
  73326. totalLines = other.totalLines;
  73327. tokens.addCopiesOf (other.tokens);
  73328. }
  73329. return *this;
  73330. }
  73331. TextLayout::~TextLayout()
  73332. {
  73333. clear();
  73334. }
  73335. void TextLayout::clear()
  73336. {
  73337. tokens.clear();
  73338. totalLines = 0;
  73339. }
  73340. bool TextLayout::isEmpty() const
  73341. {
  73342. return tokens.size() == 0;
  73343. }
  73344. void TextLayout::appendText (const String& text, const Font& font)
  73345. {
  73346. String::CharPointerType t (text.getCharPointer());
  73347. String currentString;
  73348. int lastCharType = 0;
  73349. for (;;)
  73350. {
  73351. const juce_wchar c = t.getAndAdvance();
  73352. if (c == 0)
  73353. break;
  73354. int charType;
  73355. if (c == '\r' || c == '\n')
  73356. {
  73357. charType = 0;
  73358. }
  73359. else if (CharacterFunctions::isWhitespace (c))
  73360. {
  73361. charType = 2;
  73362. }
  73363. else
  73364. {
  73365. charType = 1;
  73366. }
  73367. if (charType == 0 || charType != lastCharType)
  73368. {
  73369. if (currentString.isNotEmpty())
  73370. {
  73371. tokens.add (new Token (currentString, font,
  73372. lastCharType == 2 || lastCharType == 0));
  73373. }
  73374. currentString = String::charToString (c);
  73375. if (c == '\r' && *t == '\n')
  73376. currentString += t.getAndAdvance();
  73377. }
  73378. else
  73379. {
  73380. currentString += c;
  73381. }
  73382. lastCharType = charType;
  73383. }
  73384. if (currentString.isNotEmpty())
  73385. tokens.add (new Token (currentString, font, lastCharType == 2));
  73386. }
  73387. void TextLayout::setText (const String& text, const Font& font)
  73388. {
  73389. clear();
  73390. appendText (text, font);
  73391. }
  73392. void TextLayout::layout (int maxWidth,
  73393. const Justification& justification,
  73394. const bool attemptToBalanceLineLengths)
  73395. {
  73396. if (attemptToBalanceLineLengths)
  73397. {
  73398. const int originalW = maxWidth;
  73399. int bestWidth = maxWidth;
  73400. float bestLineProportion = 0.0f;
  73401. while (maxWidth > originalW / 2)
  73402. {
  73403. layout (maxWidth, justification, false);
  73404. if (getNumLines() <= 1)
  73405. return;
  73406. const int lastLineW = getLineWidth (getNumLines() - 1);
  73407. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73408. const float prop = lastLineW / (float) lastButOneLineW;
  73409. if (prop > 0.9f)
  73410. return;
  73411. if (prop > bestLineProportion)
  73412. {
  73413. bestLineProportion = prop;
  73414. bestWidth = maxWidth;
  73415. }
  73416. maxWidth -= 10;
  73417. }
  73418. layout (bestWidth, justification, false);
  73419. }
  73420. else
  73421. {
  73422. int x = 0;
  73423. int y = 0;
  73424. int h = 0;
  73425. totalLines = 0;
  73426. int i;
  73427. for (i = 0; i < tokens.size(); ++i)
  73428. {
  73429. Token* const t = tokens.getUnchecked(i);
  73430. t->x = x;
  73431. t->y = y;
  73432. t->line = totalLines;
  73433. x += t->w;
  73434. h = jmax (h, t->h);
  73435. const Token* nextTok = tokens [i + 1];
  73436. if (nextTok == 0)
  73437. break;
  73438. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73439. {
  73440. // finished a line, so go back and update the heights of the things on it
  73441. for (int j = i; j >= 0; --j)
  73442. {
  73443. Token* const tok = tokens.getUnchecked(j);
  73444. if (tok->line == totalLines)
  73445. tok->lineHeight = h;
  73446. else
  73447. break;
  73448. }
  73449. x = 0;
  73450. y += h;
  73451. h = 0;
  73452. ++totalLines;
  73453. }
  73454. }
  73455. // finished a line, so go back and update the heights of the things on it
  73456. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73457. {
  73458. Token* const t = tokens.getUnchecked(j);
  73459. if (t->line == totalLines)
  73460. t->lineHeight = h;
  73461. else
  73462. break;
  73463. }
  73464. ++totalLines;
  73465. if (! justification.testFlags (Justification::left))
  73466. {
  73467. int totalW = getWidth();
  73468. for (i = totalLines; --i >= 0;)
  73469. {
  73470. const int lineW = getLineWidth (i);
  73471. int dx = 0;
  73472. if (justification.testFlags (Justification::horizontallyCentred))
  73473. dx = (totalW - lineW) / 2;
  73474. else if (justification.testFlags (Justification::right))
  73475. dx = totalW - lineW;
  73476. for (int j = tokens.size(); --j >= 0;)
  73477. {
  73478. Token* const t = tokens.getUnchecked(j);
  73479. if (t->line == i)
  73480. t->x += dx;
  73481. }
  73482. }
  73483. }
  73484. }
  73485. }
  73486. int TextLayout::getLineWidth (const int lineNumber) const
  73487. {
  73488. int maxW = 0;
  73489. for (int i = tokens.size(); --i >= 0;)
  73490. {
  73491. const Token* const t = tokens.getUnchecked(i);
  73492. if (t->line == lineNumber && ! t->isWhitespace)
  73493. maxW = jmax (maxW, t->x + t->w);
  73494. }
  73495. return maxW;
  73496. }
  73497. int TextLayout::getWidth() const
  73498. {
  73499. int maxW = 0;
  73500. for (int i = tokens.size(); --i >= 0;)
  73501. {
  73502. const Token* const t = tokens.getUnchecked(i);
  73503. if (! t->isWhitespace)
  73504. maxW = jmax (maxW, t->x + t->w);
  73505. }
  73506. return maxW;
  73507. }
  73508. int TextLayout::getHeight() const
  73509. {
  73510. int maxH = 0;
  73511. for (int i = tokens.size(); --i >= 0;)
  73512. {
  73513. const Token* const t = tokens.getUnchecked(i);
  73514. if (! t->isWhitespace)
  73515. maxH = jmax (maxH, t->y + t->h);
  73516. }
  73517. return maxH;
  73518. }
  73519. void TextLayout::draw (Graphics& g,
  73520. const int xOffset,
  73521. const int yOffset) const
  73522. {
  73523. for (int i = tokens.size(); --i >= 0;)
  73524. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73525. }
  73526. void TextLayout::drawWithin (Graphics& g,
  73527. int x, int y, int w, int h,
  73528. const Justification& justification) const
  73529. {
  73530. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73531. x, y, w, h);
  73532. draw (g, x, y);
  73533. }
  73534. END_JUCE_NAMESPACE
  73535. /*** End of inlined file: juce_TextLayout.cpp ***/
  73536. /*** Start of inlined file: juce_Typeface.cpp ***/
  73537. BEGIN_JUCE_NAMESPACE
  73538. Typeface::Typeface (const String& name_) throw()
  73539. : name (name_), isFallbackFont (false)
  73540. {
  73541. }
  73542. Typeface::~Typeface()
  73543. {
  73544. }
  73545. const Typeface::Ptr Typeface::getFallbackTypeface()
  73546. {
  73547. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73548. Typeface* t = fallbackFont.getTypeface();
  73549. t->isFallbackFont = true;
  73550. return t;
  73551. }
  73552. class CustomTypeface::GlyphInfo
  73553. {
  73554. public:
  73555. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73556. : character (character_), path (path_), width (width_)
  73557. {
  73558. }
  73559. struct KerningPair
  73560. {
  73561. juce_wchar character2;
  73562. float kerningAmount;
  73563. };
  73564. void addKerningPair (const juce_wchar subsequentCharacter,
  73565. const float extraKerningAmount) throw()
  73566. {
  73567. KerningPair kp;
  73568. kp.character2 = subsequentCharacter;
  73569. kp.kerningAmount = extraKerningAmount;
  73570. kerningPairs.add (kp);
  73571. }
  73572. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73573. {
  73574. if (subsequentCharacter != 0)
  73575. {
  73576. for (int i = kerningPairs.size(); --i >= 0;)
  73577. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73578. return width + kerningPairs.getReference(i).kerningAmount;
  73579. }
  73580. return width;
  73581. }
  73582. const juce_wchar character;
  73583. const Path path;
  73584. float width;
  73585. Array <KerningPair> kerningPairs;
  73586. private:
  73587. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73588. };
  73589. CustomTypeface::CustomTypeface()
  73590. : Typeface (String::empty)
  73591. {
  73592. clear();
  73593. }
  73594. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73595. : Typeface (String::empty)
  73596. {
  73597. clear();
  73598. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73599. BufferedInputStream in (gzin, 32768);
  73600. name = in.readString();
  73601. isBold = in.readBool();
  73602. isItalic = in.readBool();
  73603. ascent = in.readFloat();
  73604. defaultCharacter = (juce_wchar) in.readShort();
  73605. int i, numChars = in.readInt();
  73606. for (i = 0; i < numChars; ++i)
  73607. {
  73608. const juce_wchar c = (juce_wchar) in.readShort();
  73609. const float width = in.readFloat();
  73610. Path p;
  73611. p.loadPathFromStream (in);
  73612. addGlyph (c, p, width);
  73613. }
  73614. const int numKerningPairs = in.readInt();
  73615. for (i = 0; i < numKerningPairs; ++i)
  73616. {
  73617. const juce_wchar char1 = (juce_wchar) in.readShort();
  73618. const juce_wchar char2 = (juce_wchar) in.readShort();
  73619. addKerningPair (char1, char2, in.readFloat());
  73620. }
  73621. }
  73622. CustomTypeface::~CustomTypeface()
  73623. {
  73624. }
  73625. void CustomTypeface::clear()
  73626. {
  73627. defaultCharacter = 0;
  73628. ascent = 1.0f;
  73629. isBold = isItalic = false;
  73630. zeromem (lookupTable, sizeof (lookupTable));
  73631. glyphs.clear();
  73632. }
  73633. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73634. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73635. {
  73636. name = name_;
  73637. defaultCharacter = defaultCharacter_;
  73638. ascent = ascent_;
  73639. isBold = isBold_;
  73640. isItalic = isItalic_;
  73641. }
  73642. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73643. {
  73644. // Check that you're not trying to add the same character twice..
  73645. jassert (findGlyph (character, false) == 0);
  73646. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73647. lookupTable [character] = (short) glyphs.size();
  73648. glyphs.add (new GlyphInfo (character, path, width));
  73649. }
  73650. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73651. {
  73652. if (extraAmount != 0)
  73653. {
  73654. GlyphInfo* const g = findGlyph (char1, true);
  73655. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73656. if (g != 0)
  73657. g->addKerningPair (char2, extraAmount);
  73658. }
  73659. }
  73660. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73661. {
  73662. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73663. return glyphs [(int) lookupTable [(int) character]];
  73664. for (int i = 0; i < glyphs.size(); ++i)
  73665. {
  73666. GlyphInfo* const g = glyphs.getUnchecked(i);
  73667. if (g->character == character)
  73668. return g;
  73669. }
  73670. if (loadIfNeeded && loadGlyphIfPossible (character))
  73671. return findGlyph (character, false);
  73672. return 0;
  73673. }
  73674. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73675. {
  73676. GlyphInfo* glyph = findGlyph (character, true);
  73677. if (glyph == 0)
  73678. {
  73679. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73680. glyph = findGlyph (L' ', true);
  73681. if (glyph == 0)
  73682. {
  73683. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73684. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73685. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73686. {
  73687. Path path;
  73688. fallbackTypeface->getOutlineForGlyph (character, path);
  73689. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73690. }
  73691. if (glyph == 0)
  73692. glyph = findGlyph (defaultCharacter, true);
  73693. }
  73694. }
  73695. return glyph;
  73696. }
  73697. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73698. {
  73699. return false;
  73700. }
  73701. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73702. {
  73703. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73704. for (int i = 0; i < numCharacters; ++i)
  73705. {
  73706. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73707. Array <int> glyphIndexes;
  73708. Array <float> offsets;
  73709. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73710. const int glyphIndex = glyphIndexes.getFirst();
  73711. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73712. {
  73713. const float glyphWidth = offsets[1];
  73714. Path p;
  73715. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73716. addGlyph (c, p, glyphWidth);
  73717. for (int j = glyphs.size() - 1; --j >= 0;)
  73718. {
  73719. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73720. glyphIndexes.clearQuick();
  73721. offsets.clearQuick();
  73722. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73723. if (offsets.size() > 1)
  73724. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73725. }
  73726. }
  73727. }
  73728. }
  73729. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73730. {
  73731. GZIPCompressorOutputStream out (&outputStream);
  73732. out.writeString (name);
  73733. out.writeBool (isBold);
  73734. out.writeBool (isItalic);
  73735. out.writeFloat (ascent);
  73736. out.writeShort ((short) (unsigned short) defaultCharacter);
  73737. out.writeInt (glyphs.size());
  73738. int i, numKerningPairs = 0;
  73739. for (i = 0; i < glyphs.size(); ++i)
  73740. {
  73741. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73742. out.writeShort ((short) (unsigned short) g->character);
  73743. out.writeFloat (g->width);
  73744. g->path.writePathToStream (out);
  73745. numKerningPairs += g->kerningPairs.size();
  73746. }
  73747. out.writeInt (numKerningPairs);
  73748. for (i = 0; i < glyphs.size(); ++i)
  73749. {
  73750. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73751. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73752. {
  73753. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73754. out.writeShort ((short) (unsigned short) g->character);
  73755. out.writeShort ((short) (unsigned short) p.character2);
  73756. out.writeFloat (p.kerningAmount);
  73757. }
  73758. }
  73759. return true;
  73760. }
  73761. float CustomTypeface::getAscent() const
  73762. {
  73763. return ascent;
  73764. }
  73765. float CustomTypeface::getDescent() const
  73766. {
  73767. return 1.0f - ascent;
  73768. }
  73769. float CustomTypeface::getStringWidth (const String& text)
  73770. {
  73771. float x = 0;
  73772. String::CharPointerType t (text.getCharPointer());
  73773. while (! t.isEmpty())
  73774. {
  73775. const GlyphInfo* const glyph = findGlyphSubstituting (t.getAndAdvance());
  73776. if (glyph == 0 && ! isFallbackFont)
  73777. {
  73778. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73779. if (fallbackTypeface != 0)
  73780. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73781. }
  73782. if (glyph != 0)
  73783. x += glyph->getHorizontalSpacing (*t);
  73784. }
  73785. return x;
  73786. }
  73787. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73788. {
  73789. xOffsets.add (0);
  73790. float x = 0;
  73791. String::CharPointerType t (text.getCharPointer());
  73792. while (! t.isEmpty())
  73793. {
  73794. const juce_wchar c = t.getAndAdvance();
  73795. const GlyphInfo* const glyph = findGlyph (c, true);
  73796. if (glyph == 0 && ! isFallbackFont)
  73797. {
  73798. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73799. if (fallbackTypeface != 0)
  73800. {
  73801. Array <int> subGlyphs;
  73802. Array <float> subOffsets;
  73803. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73804. if (subGlyphs.size() > 0)
  73805. {
  73806. resultGlyphs.add (subGlyphs.getFirst());
  73807. x += subOffsets[1];
  73808. xOffsets.add (x);
  73809. }
  73810. }
  73811. }
  73812. if (glyph != 0)
  73813. {
  73814. x += glyph->getHorizontalSpacing (*t);
  73815. resultGlyphs.add ((int) glyph->character);
  73816. xOffsets.add (x);
  73817. }
  73818. }
  73819. }
  73820. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73821. {
  73822. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73823. if (glyph == 0 && ! isFallbackFont)
  73824. {
  73825. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73826. if (fallbackTypeface != 0)
  73827. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73828. }
  73829. if (glyph != 0)
  73830. {
  73831. path = glyph->path;
  73832. return true;
  73833. }
  73834. return false;
  73835. }
  73836. END_JUCE_NAMESPACE
  73837. /*** End of inlined file: juce_Typeface.cpp ***/
  73838. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73839. BEGIN_JUCE_NAMESPACE
  73840. AffineTransform::AffineTransform() throw()
  73841. : mat00 (1.0f), mat01 (0), mat02 (0),
  73842. mat10 (0), mat11 (1.0f), mat12 (0)
  73843. {
  73844. }
  73845. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73846. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73847. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73848. {
  73849. }
  73850. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73851. const float mat10_, const float mat11_, const float mat12_) throw()
  73852. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73853. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73854. {
  73855. }
  73856. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73857. {
  73858. mat00 = other.mat00;
  73859. mat01 = other.mat01;
  73860. mat02 = other.mat02;
  73861. mat10 = other.mat10;
  73862. mat11 = other.mat11;
  73863. mat12 = other.mat12;
  73864. return *this;
  73865. }
  73866. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73867. {
  73868. return mat00 == other.mat00
  73869. && mat01 == other.mat01
  73870. && mat02 == other.mat02
  73871. && mat10 == other.mat10
  73872. && mat11 == other.mat11
  73873. && mat12 == other.mat12;
  73874. }
  73875. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73876. {
  73877. return ! operator== (other);
  73878. }
  73879. bool AffineTransform::isIdentity() const throw()
  73880. {
  73881. return (mat01 == 0)
  73882. && (mat02 == 0)
  73883. && (mat10 == 0)
  73884. && (mat12 == 0)
  73885. && (mat00 == 1.0f)
  73886. && (mat11 == 1.0f);
  73887. }
  73888. const AffineTransform AffineTransform::identity;
  73889. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73890. {
  73891. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73892. other.mat00 * mat01 + other.mat01 * mat11,
  73893. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73894. other.mat10 * mat00 + other.mat11 * mat10,
  73895. other.mat10 * mat01 + other.mat11 * mat11,
  73896. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73897. }
  73898. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  73899. {
  73900. return AffineTransform (mat00, mat01, mat02 + dx,
  73901. mat10, mat11, mat12 + dy);
  73902. }
  73903. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  73904. {
  73905. return AffineTransform (1.0f, 0, dx,
  73906. 0, 1.0f, dy);
  73907. }
  73908. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73909. {
  73910. const float cosRad = std::cos (rad);
  73911. const float sinRad = std::sin (rad);
  73912. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  73913. cosRad * mat01 + -sinRad * mat11,
  73914. cosRad * mat02 + -sinRad * mat12,
  73915. sinRad * mat00 + cosRad * mat10,
  73916. sinRad * mat01 + cosRad * mat11,
  73917. sinRad * mat02 + cosRad * mat12);
  73918. }
  73919. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73920. {
  73921. const float cosRad = std::cos (rad);
  73922. const float sinRad = std::sin (rad);
  73923. return AffineTransform (cosRad, -sinRad, 0,
  73924. sinRad, cosRad, 0);
  73925. }
  73926. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  73927. {
  73928. const float cosRad = std::cos (rad);
  73929. const float sinRad = std::sin (rad);
  73930. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  73931. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  73932. }
  73933. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  73934. {
  73935. return followedBy (rotation (angle, pivotX, pivotY));
  73936. }
  73937. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  73938. {
  73939. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73940. factorY * mat10, factorY * mat11, factorY * mat12);
  73941. }
  73942. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  73943. {
  73944. return AffineTransform (factorX, 0, 0,
  73945. 0, factorY, 0);
  73946. }
  73947. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  73948. const float pivotX, const float pivotY) const throw()
  73949. {
  73950. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  73951. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  73952. }
  73953. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  73954. const float pivotX, const float pivotY) throw()
  73955. {
  73956. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  73957. 0, factorY, pivotY * (1.0f - factorY));
  73958. }
  73959. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  73960. {
  73961. return AffineTransform (1.0f, shearX, 0,
  73962. shearY, 1.0f, 0);
  73963. }
  73964. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  73965. {
  73966. return AffineTransform (mat00 + shearX * mat10,
  73967. mat01 + shearX * mat11,
  73968. mat02 + shearX * mat12,
  73969. shearY * mat00 + mat10,
  73970. shearY * mat01 + mat11,
  73971. shearY * mat02 + mat12);
  73972. }
  73973. const AffineTransform AffineTransform::inverted() const throw()
  73974. {
  73975. double determinant = (mat00 * mat11 - mat10 * mat01);
  73976. if (determinant != 0.0)
  73977. {
  73978. determinant = 1.0 / determinant;
  73979. const float dst00 = (float) (mat11 * determinant);
  73980. const float dst10 = (float) (-mat10 * determinant);
  73981. const float dst01 = (float) (-mat01 * determinant);
  73982. const float dst11 = (float) (mat00 * determinant);
  73983. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73984. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73985. }
  73986. else
  73987. {
  73988. // singularity..
  73989. return *this;
  73990. }
  73991. }
  73992. bool AffineTransform::isSingularity() const throw()
  73993. {
  73994. return (mat00 * mat11 - mat10 * mat01) == 0;
  73995. }
  73996. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73997. const float x10, const float y10,
  73998. const float x01, const float y01) throw()
  73999. {
  74000. return AffineTransform (x10 - x00, x01 - x00, x00,
  74001. y10 - y00, y01 - y00, y00);
  74002. }
  74003. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74004. const float sx2, const float sy2, const float tx2, const float ty2,
  74005. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74006. {
  74007. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74008. .inverted()
  74009. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74010. }
  74011. bool AffineTransform::isOnlyTranslation() const throw()
  74012. {
  74013. return (mat01 == 0)
  74014. && (mat10 == 0)
  74015. && (mat00 == 1.0f)
  74016. && (mat11 == 1.0f);
  74017. }
  74018. float AffineTransform::getScaleFactor() const throw()
  74019. {
  74020. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74021. }
  74022. END_JUCE_NAMESPACE
  74023. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74024. /*** Start of inlined file: juce_Path.cpp ***/
  74025. BEGIN_JUCE_NAMESPACE
  74026. // tests that some co-ords aren't NaNs
  74027. #define CHECK_COORDS_ARE_VALID(x, y) \
  74028. jassert (x == x && y == y);
  74029. namespace PathHelpers
  74030. {
  74031. const float ellipseAngularIncrement = 0.05f;
  74032. const String nextToken (String::CharPointerType& t)
  74033. {
  74034. t = t.findEndOfWhitespace();
  74035. String::CharPointerType start (t);
  74036. int numChars = 0;
  74037. while (! (t.isEmpty() || t.isWhitespace()))
  74038. {
  74039. ++t;
  74040. ++numChars;
  74041. }
  74042. return String (start, numChars);
  74043. }
  74044. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74045. {
  74046. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74047. }
  74048. }
  74049. const float Path::lineMarker = 100001.0f;
  74050. const float Path::moveMarker = 100002.0f;
  74051. const float Path::quadMarker = 100003.0f;
  74052. const float Path::cubicMarker = 100004.0f;
  74053. const float Path::closeSubPathMarker = 100005.0f;
  74054. Path::Path()
  74055. : numElements (0),
  74056. pathXMin (0),
  74057. pathXMax (0),
  74058. pathYMin (0),
  74059. pathYMax (0),
  74060. useNonZeroWinding (true)
  74061. {
  74062. }
  74063. Path::~Path()
  74064. {
  74065. }
  74066. Path::Path (const Path& other)
  74067. : numElements (other.numElements),
  74068. pathXMin (other.pathXMin),
  74069. pathXMax (other.pathXMax),
  74070. pathYMin (other.pathYMin),
  74071. pathYMax (other.pathYMax),
  74072. useNonZeroWinding (other.useNonZeroWinding)
  74073. {
  74074. if (numElements > 0)
  74075. {
  74076. data.setAllocatedSize ((int) numElements);
  74077. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74078. }
  74079. }
  74080. Path& Path::operator= (const Path& other)
  74081. {
  74082. if (this != &other)
  74083. {
  74084. data.ensureAllocatedSize ((int) other.numElements);
  74085. numElements = other.numElements;
  74086. pathXMin = other.pathXMin;
  74087. pathXMax = other.pathXMax;
  74088. pathYMin = other.pathYMin;
  74089. pathYMax = other.pathYMax;
  74090. useNonZeroWinding = other.useNonZeroWinding;
  74091. if (numElements > 0)
  74092. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74093. }
  74094. return *this;
  74095. }
  74096. bool Path::operator== (const Path& other) const throw()
  74097. {
  74098. return ! operator!= (other);
  74099. }
  74100. bool Path::operator!= (const Path& other) const throw()
  74101. {
  74102. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74103. return true;
  74104. for (size_t i = 0; i < numElements; ++i)
  74105. if (data.elements[i] != other.data.elements[i])
  74106. return true;
  74107. return false;
  74108. }
  74109. void Path::clear() throw()
  74110. {
  74111. numElements = 0;
  74112. pathXMin = 0;
  74113. pathYMin = 0;
  74114. pathYMax = 0;
  74115. pathXMax = 0;
  74116. }
  74117. void Path::swapWithPath (Path& other) throw()
  74118. {
  74119. data.swapWith (other.data);
  74120. swapVariables <size_t> (numElements, other.numElements);
  74121. swapVariables <float> (pathXMin, other.pathXMin);
  74122. swapVariables <float> (pathXMax, other.pathXMax);
  74123. swapVariables <float> (pathYMin, other.pathYMin);
  74124. swapVariables <float> (pathYMax, other.pathYMax);
  74125. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74126. }
  74127. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74128. {
  74129. useNonZeroWinding = isNonZero;
  74130. }
  74131. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74132. const bool preserveProportions) throw()
  74133. {
  74134. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74135. }
  74136. bool Path::isEmpty() const throw()
  74137. {
  74138. size_t i = 0;
  74139. while (i < numElements)
  74140. {
  74141. const float type = data.elements [i++];
  74142. if (type == moveMarker)
  74143. {
  74144. i += 2;
  74145. }
  74146. else if (type == lineMarker
  74147. || type == quadMarker
  74148. || type == cubicMarker)
  74149. {
  74150. return false;
  74151. }
  74152. }
  74153. return true;
  74154. }
  74155. const Rectangle<float> Path::getBounds() const throw()
  74156. {
  74157. return Rectangle<float> (pathXMin, pathYMin,
  74158. pathXMax - pathXMin,
  74159. pathYMax - pathYMin);
  74160. }
  74161. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74162. {
  74163. return getBounds().transformed (transform);
  74164. }
  74165. void Path::startNewSubPath (const float x, const float y)
  74166. {
  74167. CHECK_COORDS_ARE_VALID (x, y);
  74168. if (numElements == 0)
  74169. {
  74170. pathXMin = pathXMax = x;
  74171. pathYMin = pathYMax = y;
  74172. }
  74173. else
  74174. {
  74175. pathXMin = jmin (pathXMin, x);
  74176. pathXMax = jmax (pathXMax, x);
  74177. pathYMin = jmin (pathYMin, y);
  74178. pathYMax = jmax (pathYMax, y);
  74179. }
  74180. data.ensureAllocatedSize ((int) numElements + 3);
  74181. data.elements [numElements++] = moveMarker;
  74182. data.elements [numElements++] = x;
  74183. data.elements [numElements++] = y;
  74184. }
  74185. void Path::startNewSubPath (const Point<float>& start)
  74186. {
  74187. startNewSubPath (start.getX(), start.getY());
  74188. }
  74189. void Path::lineTo (const float x, const float y)
  74190. {
  74191. CHECK_COORDS_ARE_VALID (x, y);
  74192. if (numElements == 0)
  74193. startNewSubPath (0, 0);
  74194. data.ensureAllocatedSize ((int) numElements + 3);
  74195. data.elements [numElements++] = lineMarker;
  74196. data.elements [numElements++] = x;
  74197. data.elements [numElements++] = y;
  74198. pathXMin = jmin (pathXMin, x);
  74199. pathXMax = jmax (pathXMax, x);
  74200. pathYMin = jmin (pathYMin, y);
  74201. pathYMax = jmax (pathYMax, y);
  74202. }
  74203. void Path::lineTo (const Point<float>& end)
  74204. {
  74205. lineTo (end.getX(), end.getY());
  74206. }
  74207. void Path::quadraticTo (const float x1, const float y1,
  74208. const float x2, const float y2)
  74209. {
  74210. CHECK_COORDS_ARE_VALID (x1, y1);
  74211. CHECK_COORDS_ARE_VALID (x2, y2);
  74212. if (numElements == 0)
  74213. startNewSubPath (0, 0);
  74214. data.ensureAllocatedSize ((int) numElements + 5);
  74215. data.elements [numElements++] = quadMarker;
  74216. data.elements [numElements++] = x1;
  74217. data.elements [numElements++] = y1;
  74218. data.elements [numElements++] = x2;
  74219. data.elements [numElements++] = y2;
  74220. pathXMin = jmin (pathXMin, x1, x2);
  74221. pathXMax = jmax (pathXMax, x1, x2);
  74222. pathYMin = jmin (pathYMin, y1, y2);
  74223. pathYMax = jmax (pathYMax, y1, y2);
  74224. }
  74225. void Path::quadraticTo (const Point<float>& controlPoint,
  74226. const Point<float>& endPoint)
  74227. {
  74228. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74229. endPoint.getX(), endPoint.getY());
  74230. }
  74231. void Path::cubicTo (const float x1, const float y1,
  74232. const float x2, const float y2,
  74233. const float x3, const float y3)
  74234. {
  74235. CHECK_COORDS_ARE_VALID (x1, y1);
  74236. CHECK_COORDS_ARE_VALID (x2, y2);
  74237. CHECK_COORDS_ARE_VALID (x3, y3);
  74238. if (numElements == 0)
  74239. startNewSubPath (0, 0);
  74240. data.ensureAllocatedSize ((int) numElements + 7);
  74241. data.elements [numElements++] = cubicMarker;
  74242. data.elements [numElements++] = x1;
  74243. data.elements [numElements++] = y1;
  74244. data.elements [numElements++] = x2;
  74245. data.elements [numElements++] = y2;
  74246. data.elements [numElements++] = x3;
  74247. data.elements [numElements++] = y3;
  74248. pathXMin = jmin (pathXMin, x1, x2, x3);
  74249. pathXMax = jmax (pathXMax, x1, x2, x3);
  74250. pathYMin = jmin (pathYMin, y1, y2, y3);
  74251. pathYMax = jmax (pathYMax, y1, y2, y3);
  74252. }
  74253. void Path::cubicTo (const Point<float>& controlPoint1,
  74254. const Point<float>& controlPoint2,
  74255. const Point<float>& endPoint)
  74256. {
  74257. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74258. controlPoint2.getX(), controlPoint2.getY(),
  74259. endPoint.getX(), endPoint.getY());
  74260. }
  74261. void Path::closeSubPath()
  74262. {
  74263. if (numElements > 0
  74264. && data.elements [numElements - 1] != closeSubPathMarker)
  74265. {
  74266. data.ensureAllocatedSize ((int) numElements + 1);
  74267. data.elements [numElements++] = closeSubPathMarker;
  74268. }
  74269. }
  74270. const Point<float> Path::getCurrentPosition() const
  74271. {
  74272. int i = (int) numElements - 1;
  74273. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74274. {
  74275. while (i >= 0)
  74276. {
  74277. if (data.elements[i] == moveMarker)
  74278. {
  74279. i += 2;
  74280. break;
  74281. }
  74282. --i;
  74283. }
  74284. }
  74285. if (i > 0)
  74286. return Point<float> (data.elements [i - 1], data.elements [i]);
  74287. return Point<float>();
  74288. }
  74289. void Path::addRectangle (const float x, const float y,
  74290. const float w, const float h)
  74291. {
  74292. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74293. if (w < 0)
  74294. swapVariables (x1, x2);
  74295. if (h < 0)
  74296. swapVariables (y1, y2);
  74297. data.ensureAllocatedSize ((int) numElements + 13);
  74298. if (numElements == 0)
  74299. {
  74300. pathXMin = x1;
  74301. pathXMax = x2;
  74302. pathYMin = y1;
  74303. pathYMax = y2;
  74304. }
  74305. else
  74306. {
  74307. pathXMin = jmin (pathXMin, x1);
  74308. pathXMax = jmax (pathXMax, x2);
  74309. pathYMin = jmin (pathYMin, y1);
  74310. pathYMax = jmax (pathYMax, y2);
  74311. }
  74312. data.elements [numElements++] = moveMarker;
  74313. data.elements [numElements++] = x1;
  74314. data.elements [numElements++] = y2;
  74315. data.elements [numElements++] = lineMarker;
  74316. data.elements [numElements++] = x1;
  74317. data.elements [numElements++] = y1;
  74318. data.elements [numElements++] = lineMarker;
  74319. data.elements [numElements++] = x2;
  74320. data.elements [numElements++] = y1;
  74321. data.elements [numElements++] = lineMarker;
  74322. data.elements [numElements++] = x2;
  74323. data.elements [numElements++] = y2;
  74324. data.elements [numElements++] = closeSubPathMarker;
  74325. }
  74326. void Path::addRoundedRectangle (const float x, const float y,
  74327. const float w, const float h,
  74328. float csx,
  74329. float csy)
  74330. {
  74331. csx = jmin (csx, w * 0.5f);
  74332. csy = jmin (csy, h * 0.5f);
  74333. const float cs45x = csx * 0.45f;
  74334. const float cs45y = csy * 0.45f;
  74335. const float x2 = x + w;
  74336. const float y2 = y + h;
  74337. startNewSubPath (x + csx, y);
  74338. lineTo (x2 - csx, y);
  74339. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74340. lineTo (x2, y2 - csy);
  74341. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74342. lineTo (x + csx, y2);
  74343. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74344. lineTo (x, y + csy);
  74345. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74346. closeSubPath();
  74347. }
  74348. void Path::addRoundedRectangle (const float x, const float y,
  74349. const float w, const float h,
  74350. float cs)
  74351. {
  74352. addRoundedRectangle (x, y, w, h, cs, cs);
  74353. }
  74354. void Path::addTriangle (const float x1, const float y1,
  74355. const float x2, const float y2,
  74356. const float x3, const float y3)
  74357. {
  74358. startNewSubPath (x1, y1);
  74359. lineTo (x2, y2);
  74360. lineTo (x3, y3);
  74361. closeSubPath();
  74362. }
  74363. void Path::addQuadrilateral (const float x1, const float y1,
  74364. const float x2, const float y2,
  74365. const float x3, const float y3,
  74366. const float x4, const float y4)
  74367. {
  74368. startNewSubPath (x1, y1);
  74369. lineTo (x2, y2);
  74370. lineTo (x3, y3);
  74371. lineTo (x4, y4);
  74372. closeSubPath();
  74373. }
  74374. void Path::addEllipse (const float x, const float y,
  74375. const float w, const float h)
  74376. {
  74377. const float hw = w * 0.5f;
  74378. const float hw55 = hw * 0.55f;
  74379. const float hh = h * 0.5f;
  74380. const float hh55 = hh * 0.55f;
  74381. const float cx = x + hw;
  74382. const float cy = y + hh;
  74383. startNewSubPath (cx, cy - hh);
  74384. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74385. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74386. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74387. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74388. closeSubPath();
  74389. }
  74390. void Path::addArc (const float x, const float y,
  74391. const float w, const float h,
  74392. const float fromRadians,
  74393. const float toRadians,
  74394. const bool startAsNewSubPath)
  74395. {
  74396. const float radiusX = w / 2.0f;
  74397. const float radiusY = h / 2.0f;
  74398. addCentredArc (x + radiusX,
  74399. y + radiusY,
  74400. radiusX, radiusY,
  74401. 0.0f,
  74402. fromRadians, toRadians,
  74403. startAsNewSubPath);
  74404. }
  74405. void Path::addCentredArc (const float centreX, const float centreY,
  74406. const float radiusX, const float radiusY,
  74407. const float rotationOfEllipse,
  74408. const float fromRadians,
  74409. const float toRadians,
  74410. const bool startAsNewSubPath)
  74411. {
  74412. if (radiusX > 0.0f && radiusY > 0.0f)
  74413. {
  74414. const Point<float> centre (centreX, centreY);
  74415. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74416. float angle = fromRadians;
  74417. if (startAsNewSubPath)
  74418. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74419. if (fromRadians < toRadians)
  74420. {
  74421. if (startAsNewSubPath)
  74422. angle += PathHelpers::ellipseAngularIncrement;
  74423. while (angle < toRadians)
  74424. {
  74425. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74426. angle += PathHelpers::ellipseAngularIncrement;
  74427. }
  74428. }
  74429. else
  74430. {
  74431. if (startAsNewSubPath)
  74432. angle -= PathHelpers::ellipseAngularIncrement;
  74433. while (angle > toRadians)
  74434. {
  74435. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74436. angle -= PathHelpers::ellipseAngularIncrement;
  74437. }
  74438. }
  74439. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74440. }
  74441. }
  74442. void Path::addPieSegment (const float x, const float y,
  74443. const float width, const float height,
  74444. const float fromRadians,
  74445. const float toRadians,
  74446. const float innerCircleProportionalSize)
  74447. {
  74448. float radiusX = width * 0.5f;
  74449. float radiusY = height * 0.5f;
  74450. const Point<float> centre (x + radiusX, y + radiusY);
  74451. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74452. addArc (x, y, width, height, fromRadians, toRadians);
  74453. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74454. {
  74455. closeSubPath();
  74456. if (innerCircleProportionalSize > 0)
  74457. {
  74458. radiusX *= innerCircleProportionalSize;
  74459. radiusY *= innerCircleProportionalSize;
  74460. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74461. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74462. }
  74463. }
  74464. else
  74465. {
  74466. if (innerCircleProportionalSize > 0)
  74467. {
  74468. radiusX *= innerCircleProportionalSize;
  74469. radiusY *= innerCircleProportionalSize;
  74470. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74471. }
  74472. else
  74473. {
  74474. lineTo (centre);
  74475. }
  74476. }
  74477. closeSubPath();
  74478. }
  74479. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74480. {
  74481. const Line<float> reversed (line.reversed());
  74482. lineThickness *= 0.5f;
  74483. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74484. lineTo (line.getPointAlongLine (0, -lineThickness));
  74485. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74486. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74487. closeSubPath();
  74488. }
  74489. void Path::addArrow (const Line<float>& line, float lineThickness,
  74490. float arrowheadWidth, float arrowheadLength)
  74491. {
  74492. const Line<float> reversed (line.reversed());
  74493. lineThickness *= 0.5f;
  74494. arrowheadWidth *= 0.5f;
  74495. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74496. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74497. lineTo (line.getPointAlongLine (0, -lineThickness));
  74498. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74499. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74500. lineTo (line.getEnd());
  74501. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74502. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74503. closeSubPath();
  74504. }
  74505. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74506. const float radius, const float startAngle)
  74507. {
  74508. jassert (numberOfSides > 1); // this would be silly.
  74509. if (numberOfSides > 1)
  74510. {
  74511. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74512. for (int i = 0; i < numberOfSides; ++i)
  74513. {
  74514. const float angle = startAngle + i * angleBetweenPoints;
  74515. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74516. if (i == 0)
  74517. startNewSubPath (p);
  74518. else
  74519. lineTo (p);
  74520. }
  74521. closeSubPath();
  74522. }
  74523. }
  74524. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74525. const float innerRadius, const float outerRadius, const float startAngle)
  74526. {
  74527. jassert (numberOfPoints > 1); // this would be silly.
  74528. if (numberOfPoints > 1)
  74529. {
  74530. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74531. for (int i = 0; i < numberOfPoints; ++i)
  74532. {
  74533. const float angle = startAngle + i * angleBetweenPoints;
  74534. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74535. if (i == 0)
  74536. startNewSubPath (p);
  74537. else
  74538. lineTo (p);
  74539. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74540. }
  74541. closeSubPath();
  74542. }
  74543. }
  74544. void Path::addBubble (float x, float y,
  74545. float w, float h,
  74546. float cs,
  74547. float tipX,
  74548. float tipY,
  74549. int whichSide,
  74550. float arrowPos,
  74551. float arrowWidth)
  74552. {
  74553. if (w > 1.0f && h > 1.0f)
  74554. {
  74555. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74556. const float cs2 = 2.0f * cs;
  74557. startNewSubPath (x + cs, y);
  74558. if (whichSide == 0)
  74559. {
  74560. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74561. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74562. lineTo (arrowX1, y);
  74563. lineTo (tipX, tipY);
  74564. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74565. }
  74566. lineTo (x + w - cs, y);
  74567. if (cs > 0.0f)
  74568. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74569. if (whichSide == 3)
  74570. {
  74571. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74572. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74573. lineTo (x + w, arrowY1);
  74574. lineTo (tipX, tipY);
  74575. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74576. }
  74577. lineTo (x + w, y + h - cs);
  74578. if (cs > 0.0f)
  74579. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74580. if (whichSide == 2)
  74581. {
  74582. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74583. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74584. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74585. lineTo (tipX, tipY);
  74586. lineTo (arrowX1, y + h);
  74587. }
  74588. lineTo (x + cs, y + h);
  74589. if (cs > 0.0f)
  74590. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74591. if (whichSide == 1)
  74592. {
  74593. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74594. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74595. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74596. lineTo (tipX, tipY);
  74597. lineTo (x, arrowY1);
  74598. }
  74599. lineTo (x, y + cs);
  74600. if (cs > 0.0f)
  74601. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74602. closeSubPath();
  74603. }
  74604. }
  74605. void Path::addPath (const Path& other)
  74606. {
  74607. size_t i = 0;
  74608. while (i < other.numElements)
  74609. {
  74610. const float type = other.data.elements [i++];
  74611. if (type == moveMarker)
  74612. {
  74613. startNewSubPath (other.data.elements [i],
  74614. other.data.elements [i + 1]);
  74615. i += 2;
  74616. }
  74617. else if (type == lineMarker)
  74618. {
  74619. lineTo (other.data.elements [i],
  74620. other.data.elements [i + 1]);
  74621. i += 2;
  74622. }
  74623. else if (type == quadMarker)
  74624. {
  74625. quadraticTo (other.data.elements [i],
  74626. other.data.elements [i + 1],
  74627. other.data.elements [i + 2],
  74628. other.data.elements [i + 3]);
  74629. i += 4;
  74630. }
  74631. else if (type == cubicMarker)
  74632. {
  74633. cubicTo (other.data.elements [i],
  74634. other.data.elements [i + 1],
  74635. other.data.elements [i + 2],
  74636. other.data.elements [i + 3],
  74637. other.data.elements [i + 4],
  74638. other.data.elements [i + 5]);
  74639. i += 6;
  74640. }
  74641. else if (type == closeSubPathMarker)
  74642. {
  74643. closeSubPath();
  74644. }
  74645. else
  74646. {
  74647. // something's gone wrong with the element list!
  74648. jassertfalse;
  74649. }
  74650. }
  74651. }
  74652. void Path::addPath (const Path& other,
  74653. const AffineTransform& transformToApply)
  74654. {
  74655. size_t i = 0;
  74656. while (i < other.numElements)
  74657. {
  74658. const float type = other.data.elements [i++];
  74659. if (type == closeSubPathMarker)
  74660. {
  74661. closeSubPath();
  74662. }
  74663. else
  74664. {
  74665. float x = other.data.elements [i++];
  74666. float y = other.data.elements [i++];
  74667. transformToApply.transformPoint (x, y);
  74668. if (type == moveMarker)
  74669. {
  74670. startNewSubPath (x, y);
  74671. }
  74672. else if (type == lineMarker)
  74673. {
  74674. lineTo (x, y);
  74675. }
  74676. else if (type == quadMarker)
  74677. {
  74678. float x2 = other.data.elements [i++];
  74679. float y2 = other.data.elements [i++];
  74680. transformToApply.transformPoint (x2, y2);
  74681. quadraticTo (x, y, x2, y2);
  74682. }
  74683. else if (type == cubicMarker)
  74684. {
  74685. float x2 = other.data.elements [i++];
  74686. float y2 = other.data.elements [i++];
  74687. float x3 = other.data.elements [i++];
  74688. float y3 = other.data.elements [i++];
  74689. transformToApply.transformPoints (x2, y2, x3, y3);
  74690. cubicTo (x, y, x2, y2, x3, y3);
  74691. }
  74692. else
  74693. {
  74694. // something's gone wrong with the element list!
  74695. jassertfalse;
  74696. }
  74697. }
  74698. }
  74699. }
  74700. void Path::applyTransform (const AffineTransform& transform) throw()
  74701. {
  74702. size_t i = 0;
  74703. pathYMin = pathXMin = 0;
  74704. pathYMax = pathXMax = 0;
  74705. bool setMaxMin = false;
  74706. while (i < numElements)
  74707. {
  74708. const float type = data.elements [i++];
  74709. if (type == moveMarker)
  74710. {
  74711. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74712. if (setMaxMin)
  74713. {
  74714. pathXMin = jmin (pathXMin, data.elements [i]);
  74715. pathXMax = jmax (pathXMax, data.elements [i]);
  74716. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74717. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74718. }
  74719. else
  74720. {
  74721. pathXMin = pathXMax = data.elements [i];
  74722. pathYMin = pathYMax = data.elements [i + 1];
  74723. setMaxMin = true;
  74724. }
  74725. i += 2;
  74726. }
  74727. else if (type == lineMarker)
  74728. {
  74729. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74730. pathXMin = jmin (pathXMin, data.elements [i]);
  74731. pathXMax = jmax (pathXMax, data.elements [i]);
  74732. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74733. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74734. i += 2;
  74735. }
  74736. else if (type == quadMarker)
  74737. {
  74738. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74739. data.elements [i + 2], data.elements [i + 3]);
  74740. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74741. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74742. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74743. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74744. i += 4;
  74745. }
  74746. else if (type == cubicMarker)
  74747. {
  74748. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74749. data.elements [i + 2], data.elements [i + 3],
  74750. data.elements [i + 4], data.elements [i + 5]);
  74751. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74752. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74753. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74754. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74755. i += 6;
  74756. }
  74757. }
  74758. }
  74759. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74760. const float w, const float h,
  74761. const bool preserveProportions,
  74762. const Justification& justification) const
  74763. {
  74764. Rectangle<float> bounds (getBounds());
  74765. if (preserveProportions)
  74766. {
  74767. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74768. return AffineTransform::identity;
  74769. float newW, newH;
  74770. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74771. if (srcRatio > h / w)
  74772. {
  74773. newW = h / srcRatio;
  74774. newH = h;
  74775. }
  74776. else
  74777. {
  74778. newW = w;
  74779. newH = w * srcRatio;
  74780. }
  74781. float newXCentre = x;
  74782. float newYCentre = y;
  74783. if (justification.testFlags (Justification::left))
  74784. newXCentre += newW * 0.5f;
  74785. else if (justification.testFlags (Justification::right))
  74786. newXCentre += w - newW * 0.5f;
  74787. else
  74788. newXCentre += w * 0.5f;
  74789. if (justification.testFlags (Justification::top))
  74790. newYCentre += newH * 0.5f;
  74791. else if (justification.testFlags (Justification::bottom))
  74792. newYCentre += h - newH * 0.5f;
  74793. else
  74794. newYCentre += h * 0.5f;
  74795. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74796. bounds.getHeight() * -0.5f - bounds.getY())
  74797. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74798. .translated (newXCentre, newYCentre);
  74799. }
  74800. else
  74801. {
  74802. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74803. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74804. .translated (x, y);
  74805. }
  74806. }
  74807. bool Path::contains (const float x, const float y, const float tolerance) const
  74808. {
  74809. if (x <= pathXMin || x >= pathXMax
  74810. || y <= pathYMin || y >= pathYMax)
  74811. return false;
  74812. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74813. int positiveCrossings = 0;
  74814. int negativeCrossings = 0;
  74815. while (i.next())
  74816. {
  74817. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74818. {
  74819. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74820. if (intersectX <= x)
  74821. {
  74822. if (i.y1 < i.y2)
  74823. ++positiveCrossings;
  74824. else
  74825. ++negativeCrossings;
  74826. }
  74827. }
  74828. }
  74829. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74830. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74831. }
  74832. bool Path::contains (const Point<float>& point, const float tolerance) const
  74833. {
  74834. return contains (point.getX(), point.getY(), tolerance);
  74835. }
  74836. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  74837. {
  74838. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74839. Point<float> intersection;
  74840. while (i.next())
  74841. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74842. return true;
  74843. return false;
  74844. }
  74845. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74846. {
  74847. Line<float> result (line);
  74848. const bool startInside = contains (line.getStart());
  74849. const bool endInside = contains (line.getEnd());
  74850. if (startInside == endInside)
  74851. {
  74852. if (keepSectionOutsidePath == startInside)
  74853. result = Line<float>();
  74854. }
  74855. else
  74856. {
  74857. PathFlatteningIterator i (*this, AffineTransform::identity);
  74858. Point<float> intersection;
  74859. while (i.next())
  74860. {
  74861. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74862. {
  74863. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74864. result.setStart (intersection);
  74865. else
  74866. result.setEnd (intersection);
  74867. }
  74868. }
  74869. }
  74870. return result;
  74871. }
  74872. float Path::getLength (const AffineTransform& transform) const
  74873. {
  74874. float length = 0;
  74875. PathFlatteningIterator i (*this, transform);
  74876. while (i.next())
  74877. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74878. return length;
  74879. }
  74880. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74881. {
  74882. PathFlatteningIterator i (*this, transform);
  74883. while (i.next())
  74884. {
  74885. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74886. const float lineLength = line.getLength();
  74887. if (distanceFromStart <= lineLength)
  74888. return line.getPointAlongLine (distanceFromStart);
  74889. distanceFromStart -= lineLength;
  74890. }
  74891. return Point<float> (i.x2, i.y2);
  74892. }
  74893. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74894. const AffineTransform& transform) const
  74895. {
  74896. PathFlatteningIterator i (*this, transform);
  74897. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74898. float length = 0;
  74899. Point<float> pointOnLine;
  74900. while (i.next())
  74901. {
  74902. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74903. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74904. if (distance < bestDistance)
  74905. {
  74906. bestDistance = distance;
  74907. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74908. pointOnPath = pointOnLine;
  74909. }
  74910. length += line.getLength();
  74911. }
  74912. return bestPosition;
  74913. }
  74914. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74915. {
  74916. if (cornerRadius <= 0.01f)
  74917. return *this;
  74918. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74919. size_t n = 0;
  74920. bool lastWasLine = false, firstWasLine = false;
  74921. Path p;
  74922. while (n < numElements)
  74923. {
  74924. const float type = data.elements [n++];
  74925. if (type == moveMarker)
  74926. {
  74927. indexOfPathStart = p.numElements;
  74928. indexOfPathStartThis = n - 1;
  74929. const float x = data.elements [n++];
  74930. const float y = data.elements [n++];
  74931. p.startNewSubPath (x, y);
  74932. lastWasLine = false;
  74933. firstWasLine = (data.elements [n] == lineMarker);
  74934. }
  74935. else if (type == lineMarker || type == closeSubPathMarker)
  74936. {
  74937. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74938. if (type == lineMarker)
  74939. {
  74940. endX = data.elements [n++];
  74941. endY = data.elements [n++];
  74942. if (n > 8)
  74943. {
  74944. startX = data.elements [n - 8];
  74945. startY = data.elements [n - 7];
  74946. joinX = data.elements [n - 5];
  74947. joinY = data.elements [n - 4];
  74948. }
  74949. }
  74950. else
  74951. {
  74952. endX = data.elements [indexOfPathStartThis + 1];
  74953. endY = data.elements [indexOfPathStartThis + 2];
  74954. if (n > 6)
  74955. {
  74956. startX = data.elements [n - 6];
  74957. startY = data.elements [n - 5];
  74958. joinX = data.elements [n - 3];
  74959. joinY = data.elements [n - 2];
  74960. }
  74961. }
  74962. if (lastWasLine)
  74963. {
  74964. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74965. if (len1 > 0)
  74966. {
  74967. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74968. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74969. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74970. }
  74971. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74972. if (len2 > 0)
  74973. {
  74974. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74975. p.quadraticTo (joinX, joinY,
  74976. (float) (joinX + (endX - joinX) * propNeeded),
  74977. (float) (joinY + (endY - joinY) * propNeeded));
  74978. }
  74979. p.lineTo (endX, endY);
  74980. }
  74981. else if (type == lineMarker)
  74982. {
  74983. p.lineTo (endX, endY);
  74984. lastWasLine = true;
  74985. }
  74986. if (type == closeSubPathMarker)
  74987. {
  74988. if (firstWasLine)
  74989. {
  74990. startX = data.elements [n - 3];
  74991. startY = data.elements [n - 2];
  74992. joinX = endX;
  74993. joinY = endY;
  74994. endX = data.elements [indexOfPathStartThis + 4];
  74995. endY = data.elements [indexOfPathStartThis + 5];
  74996. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74997. if (len1 > 0)
  74998. {
  74999. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75000. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75001. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75002. }
  75003. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75004. if (len2 > 0)
  75005. {
  75006. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75007. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75008. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75009. p.quadraticTo (joinX, joinY, endX, endY);
  75010. p.data.elements [indexOfPathStart + 1] = endX;
  75011. p.data.elements [indexOfPathStart + 2] = endY;
  75012. }
  75013. }
  75014. p.closeSubPath();
  75015. }
  75016. }
  75017. else if (type == quadMarker)
  75018. {
  75019. lastWasLine = false;
  75020. const float x1 = data.elements [n++];
  75021. const float y1 = data.elements [n++];
  75022. const float x2 = data.elements [n++];
  75023. const float y2 = data.elements [n++];
  75024. p.quadraticTo (x1, y1, x2, y2);
  75025. }
  75026. else if (type == cubicMarker)
  75027. {
  75028. lastWasLine = false;
  75029. const float x1 = data.elements [n++];
  75030. const float y1 = data.elements [n++];
  75031. const float x2 = data.elements [n++];
  75032. const float y2 = data.elements [n++];
  75033. const float x3 = data.elements [n++];
  75034. const float y3 = data.elements [n++];
  75035. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75036. }
  75037. }
  75038. return p;
  75039. }
  75040. void Path::loadPathFromStream (InputStream& source)
  75041. {
  75042. while (! source.isExhausted())
  75043. {
  75044. switch (source.readByte())
  75045. {
  75046. case 'm':
  75047. {
  75048. const float x = source.readFloat();
  75049. const float y = source.readFloat();
  75050. startNewSubPath (x, y);
  75051. break;
  75052. }
  75053. case 'l':
  75054. {
  75055. const float x = source.readFloat();
  75056. const float y = source.readFloat();
  75057. lineTo (x, y);
  75058. break;
  75059. }
  75060. case 'q':
  75061. {
  75062. const float x1 = source.readFloat();
  75063. const float y1 = source.readFloat();
  75064. const float x2 = source.readFloat();
  75065. const float y2 = source.readFloat();
  75066. quadraticTo (x1, y1, x2, y2);
  75067. break;
  75068. }
  75069. case 'b':
  75070. {
  75071. const float x1 = source.readFloat();
  75072. const float y1 = source.readFloat();
  75073. const float x2 = source.readFloat();
  75074. const float y2 = source.readFloat();
  75075. const float x3 = source.readFloat();
  75076. const float y3 = source.readFloat();
  75077. cubicTo (x1, y1, x2, y2, x3, y3);
  75078. break;
  75079. }
  75080. case 'c':
  75081. closeSubPath();
  75082. break;
  75083. case 'n':
  75084. useNonZeroWinding = true;
  75085. break;
  75086. case 'z':
  75087. useNonZeroWinding = false;
  75088. break;
  75089. case 'e':
  75090. return; // end of path marker
  75091. default:
  75092. jassertfalse; // illegal char in the stream
  75093. break;
  75094. }
  75095. }
  75096. }
  75097. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75098. {
  75099. MemoryInputStream in (pathData, numberOfBytes, false);
  75100. loadPathFromStream (in);
  75101. }
  75102. void Path::writePathToStream (OutputStream& dest) const
  75103. {
  75104. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75105. size_t i = 0;
  75106. while (i < numElements)
  75107. {
  75108. const float type = data.elements [i++];
  75109. if (type == moveMarker)
  75110. {
  75111. dest.writeByte ('m');
  75112. dest.writeFloat (data.elements [i++]);
  75113. dest.writeFloat (data.elements [i++]);
  75114. }
  75115. else if (type == lineMarker)
  75116. {
  75117. dest.writeByte ('l');
  75118. dest.writeFloat (data.elements [i++]);
  75119. dest.writeFloat (data.elements [i++]);
  75120. }
  75121. else if (type == quadMarker)
  75122. {
  75123. dest.writeByte ('q');
  75124. dest.writeFloat (data.elements [i++]);
  75125. dest.writeFloat (data.elements [i++]);
  75126. dest.writeFloat (data.elements [i++]);
  75127. dest.writeFloat (data.elements [i++]);
  75128. }
  75129. else if (type == cubicMarker)
  75130. {
  75131. dest.writeByte ('b');
  75132. dest.writeFloat (data.elements [i++]);
  75133. dest.writeFloat (data.elements [i++]);
  75134. dest.writeFloat (data.elements [i++]);
  75135. dest.writeFloat (data.elements [i++]);
  75136. dest.writeFloat (data.elements [i++]);
  75137. dest.writeFloat (data.elements [i++]);
  75138. }
  75139. else if (type == closeSubPathMarker)
  75140. {
  75141. dest.writeByte ('c');
  75142. }
  75143. }
  75144. dest.writeByte ('e'); // marks the end-of-path
  75145. }
  75146. const String Path::toString() const
  75147. {
  75148. MemoryOutputStream s (2048);
  75149. if (! useNonZeroWinding)
  75150. s << 'a';
  75151. size_t i = 0;
  75152. float lastMarker = 0.0f;
  75153. while (i < numElements)
  75154. {
  75155. const float marker = data.elements [i++];
  75156. char markerChar = 0;
  75157. int numCoords = 0;
  75158. if (marker == moveMarker)
  75159. {
  75160. markerChar = 'm';
  75161. numCoords = 2;
  75162. }
  75163. else if (marker == lineMarker)
  75164. {
  75165. markerChar = 'l';
  75166. numCoords = 2;
  75167. }
  75168. else if (marker == quadMarker)
  75169. {
  75170. markerChar = 'q';
  75171. numCoords = 4;
  75172. }
  75173. else if (marker == cubicMarker)
  75174. {
  75175. markerChar = 'c';
  75176. numCoords = 6;
  75177. }
  75178. else
  75179. {
  75180. jassert (marker == closeSubPathMarker);
  75181. markerChar = 'z';
  75182. }
  75183. if (marker != lastMarker)
  75184. {
  75185. if (s.getDataSize() != 0)
  75186. s << ' ';
  75187. s << markerChar;
  75188. lastMarker = marker;
  75189. }
  75190. while (--numCoords >= 0 && i < numElements)
  75191. {
  75192. String coord (data.elements [i++], 3);
  75193. while (coord.endsWithChar ('0') && coord != "0")
  75194. coord = coord.dropLastCharacters (1);
  75195. if (coord.endsWithChar ('.'))
  75196. coord = coord.dropLastCharacters (1);
  75197. if (s.getDataSize() != 0)
  75198. s << ' ';
  75199. s << coord;
  75200. }
  75201. }
  75202. return s.toUTF8();
  75203. }
  75204. void Path::restoreFromString (const String& stringVersion)
  75205. {
  75206. clear();
  75207. setUsingNonZeroWinding (true);
  75208. String::CharPointerType t (stringVersion.getCharPointer());
  75209. juce_wchar marker = 'm';
  75210. int numValues = 2;
  75211. float values [6];
  75212. for (;;)
  75213. {
  75214. const String token (PathHelpers::nextToken (t));
  75215. const juce_wchar firstChar = token[0];
  75216. int startNum = 0;
  75217. if (firstChar == 0)
  75218. break;
  75219. if (firstChar == 'm' || firstChar == 'l')
  75220. {
  75221. marker = firstChar;
  75222. numValues = 2;
  75223. }
  75224. else if (firstChar == 'q')
  75225. {
  75226. marker = firstChar;
  75227. numValues = 4;
  75228. }
  75229. else if (firstChar == 'c')
  75230. {
  75231. marker = firstChar;
  75232. numValues = 6;
  75233. }
  75234. else if (firstChar == 'z')
  75235. {
  75236. marker = firstChar;
  75237. numValues = 0;
  75238. }
  75239. else if (firstChar == 'a')
  75240. {
  75241. setUsingNonZeroWinding (false);
  75242. continue;
  75243. }
  75244. else
  75245. {
  75246. ++startNum;
  75247. values [0] = token.getFloatValue();
  75248. }
  75249. for (int i = startNum; i < numValues; ++i)
  75250. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75251. switch (marker)
  75252. {
  75253. case 'm': startNewSubPath (values[0], values[1]); break;
  75254. case 'l': lineTo (values[0], values[1]); break;
  75255. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75256. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75257. case 'z': closeSubPath(); break;
  75258. default: jassertfalse; break; // illegal string format?
  75259. }
  75260. }
  75261. }
  75262. Path::Iterator::Iterator (const Path& path_)
  75263. : path (path_),
  75264. index (0)
  75265. {
  75266. }
  75267. Path::Iterator::~Iterator()
  75268. {
  75269. }
  75270. bool Path::Iterator::next()
  75271. {
  75272. const float* const elements = path.data.elements;
  75273. if (index < path.numElements)
  75274. {
  75275. const float type = elements [index++];
  75276. if (type == moveMarker)
  75277. {
  75278. elementType = startNewSubPath;
  75279. x1 = elements [index++];
  75280. y1 = elements [index++];
  75281. }
  75282. else if (type == lineMarker)
  75283. {
  75284. elementType = lineTo;
  75285. x1 = elements [index++];
  75286. y1 = elements [index++];
  75287. }
  75288. else if (type == quadMarker)
  75289. {
  75290. elementType = quadraticTo;
  75291. x1 = elements [index++];
  75292. y1 = elements [index++];
  75293. x2 = elements [index++];
  75294. y2 = elements [index++];
  75295. }
  75296. else if (type == cubicMarker)
  75297. {
  75298. elementType = cubicTo;
  75299. x1 = elements [index++];
  75300. y1 = elements [index++];
  75301. x2 = elements [index++];
  75302. y2 = elements [index++];
  75303. x3 = elements [index++];
  75304. y3 = elements [index++];
  75305. }
  75306. else if (type == closeSubPathMarker)
  75307. {
  75308. elementType = closePath;
  75309. }
  75310. return true;
  75311. }
  75312. return false;
  75313. }
  75314. END_JUCE_NAMESPACE
  75315. /*** End of inlined file: juce_Path.cpp ***/
  75316. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75317. BEGIN_JUCE_NAMESPACE
  75318. #if JUCE_MSVC && JUCE_DEBUG
  75319. #pragma optimize ("t", on)
  75320. #endif
  75321. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75322. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75323. const AffineTransform& transform_,
  75324. const float tolerance)
  75325. : x2 (0),
  75326. y2 (0),
  75327. closesSubPath (false),
  75328. subPathIndex (-1),
  75329. path (path_),
  75330. transform (transform_),
  75331. points (path_.data.elements),
  75332. toleranceSquared (tolerance * tolerance),
  75333. subPathCloseX (0),
  75334. subPathCloseY (0),
  75335. isIdentityTransform (transform_.isIdentity()),
  75336. stackBase (32),
  75337. index (0),
  75338. stackSize (32)
  75339. {
  75340. stackPos = stackBase;
  75341. }
  75342. PathFlatteningIterator::~PathFlatteningIterator()
  75343. {
  75344. }
  75345. bool PathFlatteningIterator::next()
  75346. {
  75347. x1 = x2;
  75348. y1 = y2;
  75349. float x3 = 0;
  75350. float y3 = 0;
  75351. float x4 = 0;
  75352. float y4 = 0;
  75353. float type;
  75354. for (;;)
  75355. {
  75356. if (stackPos == stackBase)
  75357. {
  75358. if (index >= path.numElements)
  75359. {
  75360. return false;
  75361. }
  75362. else
  75363. {
  75364. type = points [index++];
  75365. if (type != Path::closeSubPathMarker)
  75366. {
  75367. x2 = points [index++];
  75368. y2 = points [index++];
  75369. if (type == Path::quadMarker)
  75370. {
  75371. x3 = points [index++];
  75372. y3 = points [index++];
  75373. if (! isIdentityTransform)
  75374. transform.transformPoints (x2, y2, x3, y3);
  75375. }
  75376. else if (type == Path::cubicMarker)
  75377. {
  75378. x3 = points [index++];
  75379. y3 = points [index++];
  75380. x4 = points [index++];
  75381. y4 = points [index++];
  75382. if (! isIdentityTransform)
  75383. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75384. }
  75385. else
  75386. {
  75387. if (! isIdentityTransform)
  75388. transform.transformPoint (x2, y2);
  75389. }
  75390. }
  75391. }
  75392. }
  75393. else
  75394. {
  75395. type = *--stackPos;
  75396. if (type != Path::closeSubPathMarker)
  75397. {
  75398. x2 = *--stackPos;
  75399. y2 = *--stackPos;
  75400. if (type == Path::quadMarker)
  75401. {
  75402. x3 = *--stackPos;
  75403. y3 = *--stackPos;
  75404. }
  75405. else if (type == Path::cubicMarker)
  75406. {
  75407. x3 = *--stackPos;
  75408. y3 = *--stackPos;
  75409. x4 = *--stackPos;
  75410. y4 = *--stackPos;
  75411. }
  75412. }
  75413. }
  75414. if (type == Path::lineMarker)
  75415. {
  75416. ++subPathIndex;
  75417. closesSubPath = (stackPos == stackBase)
  75418. && (index < path.numElements)
  75419. && (points [index] == Path::closeSubPathMarker)
  75420. && x2 == subPathCloseX
  75421. && y2 == subPathCloseY;
  75422. return true;
  75423. }
  75424. else if (type == Path::quadMarker)
  75425. {
  75426. const size_t offset = (size_t) (stackPos - stackBase);
  75427. if (offset >= stackSize - 10)
  75428. {
  75429. stackSize <<= 1;
  75430. stackBase.realloc (stackSize);
  75431. stackPos = stackBase + offset;
  75432. }
  75433. const float m1x = (x1 + x2) * 0.5f;
  75434. const float m1y = (y1 + y2) * 0.5f;
  75435. const float m2x = (x2 + x3) * 0.5f;
  75436. const float m2y = (y2 + y3) * 0.5f;
  75437. const float m3x = (m1x + m2x) * 0.5f;
  75438. const float m3y = (m1y + m2y) * 0.5f;
  75439. const float errorX = m3x - x2;
  75440. const float errorY = m3y - y2;
  75441. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75442. {
  75443. *stackPos++ = y3;
  75444. *stackPos++ = x3;
  75445. *stackPos++ = m2y;
  75446. *stackPos++ = m2x;
  75447. *stackPos++ = Path::quadMarker;
  75448. *stackPos++ = m3y;
  75449. *stackPos++ = m3x;
  75450. *stackPos++ = m1y;
  75451. *stackPos++ = m1x;
  75452. *stackPos++ = Path::quadMarker;
  75453. }
  75454. else
  75455. {
  75456. *stackPos++ = y3;
  75457. *stackPos++ = x3;
  75458. *stackPos++ = Path::lineMarker;
  75459. *stackPos++ = m3y;
  75460. *stackPos++ = m3x;
  75461. *stackPos++ = Path::lineMarker;
  75462. }
  75463. jassert (stackPos < stackBase + stackSize);
  75464. }
  75465. else if (type == Path::cubicMarker)
  75466. {
  75467. const size_t offset = (size_t) (stackPos - stackBase);
  75468. if (offset >= stackSize - 16)
  75469. {
  75470. stackSize <<= 1;
  75471. stackBase.realloc (stackSize);
  75472. stackPos = stackBase + offset;
  75473. }
  75474. const float m1x = (x1 + x2) * 0.5f;
  75475. const float m1y = (y1 + y2) * 0.5f;
  75476. const float m2x = (x3 + x2) * 0.5f;
  75477. const float m2y = (y3 + y2) * 0.5f;
  75478. const float m3x = (x3 + x4) * 0.5f;
  75479. const float m3y = (y3 + y4) * 0.5f;
  75480. const float m4x = (m1x + m2x) * 0.5f;
  75481. const float m4y = (m1y + m2y) * 0.5f;
  75482. const float m5x = (m3x + m2x) * 0.5f;
  75483. const float m5y = (m3y + m2y) * 0.5f;
  75484. const float error1X = m4x - x2;
  75485. const float error1Y = m4y - y2;
  75486. const float error2X = m5x - x3;
  75487. const float error2Y = m5y - y3;
  75488. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75489. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75490. {
  75491. *stackPos++ = y4;
  75492. *stackPos++ = x4;
  75493. *stackPos++ = m3y;
  75494. *stackPos++ = m3x;
  75495. *stackPos++ = m5y;
  75496. *stackPos++ = m5x;
  75497. *stackPos++ = Path::cubicMarker;
  75498. *stackPos++ = (m4y + m5y) * 0.5f;
  75499. *stackPos++ = (m4x + m5x) * 0.5f;
  75500. *stackPos++ = m4y;
  75501. *stackPos++ = m4x;
  75502. *stackPos++ = m1y;
  75503. *stackPos++ = m1x;
  75504. *stackPos++ = Path::cubicMarker;
  75505. }
  75506. else
  75507. {
  75508. *stackPos++ = y4;
  75509. *stackPos++ = x4;
  75510. *stackPos++ = Path::lineMarker;
  75511. *stackPos++ = m5y;
  75512. *stackPos++ = m5x;
  75513. *stackPos++ = Path::lineMarker;
  75514. *stackPos++ = m4y;
  75515. *stackPos++ = m4x;
  75516. *stackPos++ = Path::lineMarker;
  75517. }
  75518. }
  75519. else if (type == Path::closeSubPathMarker)
  75520. {
  75521. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75522. {
  75523. x1 = x2;
  75524. y1 = y2;
  75525. x2 = subPathCloseX;
  75526. y2 = subPathCloseY;
  75527. closesSubPath = true;
  75528. return true;
  75529. }
  75530. }
  75531. else
  75532. {
  75533. jassert (type == Path::moveMarker);
  75534. subPathIndex = -1;
  75535. subPathCloseX = x1 = x2;
  75536. subPathCloseY = y1 = y2;
  75537. }
  75538. }
  75539. }
  75540. #if JUCE_MSVC && JUCE_DEBUG
  75541. #pragma optimize ("", on) // resets optimisations to the project defaults
  75542. #endif
  75543. END_JUCE_NAMESPACE
  75544. /*** End of inlined file: juce_PathIterator.cpp ***/
  75545. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75546. BEGIN_JUCE_NAMESPACE
  75547. PathStrokeType::PathStrokeType (const float strokeThickness,
  75548. const JointStyle jointStyle_,
  75549. const EndCapStyle endStyle_) throw()
  75550. : thickness (strokeThickness),
  75551. jointStyle (jointStyle_),
  75552. endStyle (endStyle_)
  75553. {
  75554. }
  75555. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75556. : thickness (other.thickness),
  75557. jointStyle (other.jointStyle),
  75558. endStyle (other.endStyle)
  75559. {
  75560. }
  75561. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75562. {
  75563. thickness = other.thickness;
  75564. jointStyle = other.jointStyle;
  75565. endStyle = other.endStyle;
  75566. return *this;
  75567. }
  75568. PathStrokeType::~PathStrokeType() throw()
  75569. {
  75570. }
  75571. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75572. {
  75573. return thickness == other.thickness
  75574. && jointStyle == other.jointStyle
  75575. && endStyle == other.endStyle;
  75576. }
  75577. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75578. {
  75579. return ! operator== (other);
  75580. }
  75581. namespace PathStrokeHelpers
  75582. {
  75583. bool lineIntersection (const float x1, const float y1,
  75584. const float x2, const float y2,
  75585. const float x3, const float y3,
  75586. const float x4, const float y4,
  75587. float& intersectionX,
  75588. float& intersectionY,
  75589. float& distanceBeyondLine1EndSquared) throw()
  75590. {
  75591. if (x2 != x3 || y2 != y3)
  75592. {
  75593. const float dx1 = x2 - x1;
  75594. const float dy1 = y2 - y1;
  75595. const float dx2 = x4 - x3;
  75596. const float dy2 = y4 - y3;
  75597. const float divisor = dx1 * dy2 - dx2 * dy1;
  75598. if (divisor == 0)
  75599. {
  75600. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75601. {
  75602. if (dy1 == 0 && dy2 != 0)
  75603. {
  75604. const float along = (y1 - y3) / dy2;
  75605. intersectionX = x3 + along * dx2;
  75606. intersectionY = y1;
  75607. distanceBeyondLine1EndSquared = intersectionX - x2;
  75608. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75609. if ((x2 > x1) == (intersectionX < x2))
  75610. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75611. return along >= 0 && along <= 1.0f;
  75612. }
  75613. else if (dy2 == 0 && dy1 != 0)
  75614. {
  75615. const float along = (y3 - y1) / dy1;
  75616. intersectionX = x1 + along * dx1;
  75617. intersectionY = y3;
  75618. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75619. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75620. if (along < 1.0f)
  75621. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75622. return along >= 0 && along <= 1.0f;
  75623. }
  75624. else if (dx1 == 0 && dx2 != 0)
  75625. {
  75626. const float along = (x1 - x3) / dx2;
  75627. intersectionX = x1;
  75628. intersectionY = y3 + along * dy2;
  75629. distanceBeyondLine1EndSquared = intersectionY - y2;
  75630. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75631. if ((y2 > y1) == (intersectionY < y2))
  75632. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75633. return along >= 0 && along <= 1.0f;
  75634. }
  75635. else if (dx2 == 0 && dx1 != 0)
  75636. {
  75637. const float along = (x3 - x1) / dx1;
  75638. intersectionX = x3;
  75639. intersectionY = y1 + along * dy1;
  75640. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75641. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75642. if (along < 1.0f)
  75643. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75644. return along >= 0 && along <= 1.0f;
  75645. }
  75646. }
  75647. intersectionX = 0.5f * (x2 + x3);
  75648. intersectionY = 0.5f * (y2 + y3);
  75649. distanceBeyondLine1EndSquared = 0.0f;
  75650. return false;
  75651. }
  75652. else
  75653. {
  75654. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75655. intersectionX = x1 + along1 * dx1;
  75656. intersectionY = y1 + along1 * dy1;
  75657. if (along1 >= 0 && along1 <= 1.0f)
  75658. {
  75659. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75660. if (along2 >= 0 && along2 <= divisor)
  75661. {
  75662. distanceBeyondLine1EndSquared = 0.0f;
  75663. return true;
  75664. }
  75665. }
  75666. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75667. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75668. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75669. if (along1 < 1.0f)
  75670. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75671. return false;
  75672. }
  75673. }
  75674. intersectionX = x2;
  75675. intersectionY = y2;
  75676. distanceBeyondLine1EndSquared = 0.0f;
  75677. return true;
  75678. }
  75679. void addEdgeAndJoint (Path& destPath,
  75680. const PathStrokeType::JointStyle style,
  75681. const float maxMiterExtensionSquared, const float width,
  75682. const float x1, const float y1,
  75683. const float x2, const float y2,
  75684. const float x3, const float y3,
  75685. const float x4, const float y4,
  75686. const float midX, const float midY)
  75687. {
  75688. if (style == PathStrokeType::beveled
  75689. || (x3 == x4 && y3 == y4)
  75690. || (x1 == x2 && y1 == y2))
  75691. {
  75692. destPath.lineTo (x2, y2);
  75693. destPath.lineTo (x3, y3);
  75694. }
  75695. else
  75696. {
  75697. float jx, jy, distanceBeyondLine1EndSquared;
  75698. // if they intersect, use this point..
  75699. if (lineIntersection (x1, y1, x2, y2,
  75700. x3, y3, x4, y4,
  75701. jx, jy, distanceBeyondLine1EndSquared))
  75702. {
  75703. destPath.lineTo (jx, jy);
  75704. }
  75705. else
  75706. {
  75707. if (style == PathStrokeType::mitered)
  75708. {
  75709. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75710. && distanceBeyondLine1EndSquared > 0.0f)
  75711. {
  75712. destPath.lineTo (jx, jy);
  75713. }
  75714. else
  75715. {
  75716. // the end sticks out too far, so just use a blunt joint
  75717. destPath.lineTo (x2, y2);
  75718. destPath.lineTo (x3, y3);
  75719. }
  75720. }
  75721. else
  75722. {
  75723. // curved joints
  75724. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75725. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75726. const float angleIncrement = 0.1f;
  75727. destPath.lineTo (x2, y2);
  75728. if (std::abs (angle1 - angle2) > angleIncrement)
  75729. {
  75730. if (angle2 > angle1 + float_Pi
  75731. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75732. {
  75733. if (angle2 > angle1)
  75734. angle2 -= float_Pi * 2.0f;
  75735. jassert (angle1 <= angle2 + float_Pi);
  75736. angle1 -= angleIncrement;
  75737. while (angle1 > angle2)
  75738. {
  75739. destPath.lineTo (midX + width * std::sin (angle1),
  75740. midY + width * std::cos (angle1));
  75741. angle1 -= angleIncrement;
  75742. }
  75743. }
  75744. else
  75745. {
  75746. if (angle1 > angle2)
  75747. angle1 -= float_Pi * 2.0f;
  75748. jassert (angle1 >= angle2 - float_Pi);
  75749. angle1 += angleIncrement;
  75750. while (angle1 < angle2)
  75751. {
  75752. destPath.lineTo (midX + width * std::sin (angle1),
  75753. midY + width * std::cos (angle1));
  75754. angle1 += angleIncrement;
  75755. }
  75756. }
  75757. }
  75758. destPath.lineTo (x3, y3);
  75759. }
  75760. }
  75761. }
  75762. }
  75763. void addLineEnd (Path& destPath,
  75764. const PathStrokeType::EndCapStyle style,
  75765. const float x1, const float y1,
  75766. const float x2, const float y2,
  75767. const float width)
  75768. {
  75769. if (style == PathStrokeType::butt)
  75770. {
  75771. destPath.lineTo (x2, y2);
  75772. }
  75773. else
  75774. {
  75775. float offx1, offy1, offx2, offy2;
  75776. float dx = x2 - x1;
  75777. float dy = y2 - y1;
  75778. const float len = juce_hypot (dx, dy);
  75779. if (len == 0)
  75780. {
  75781. offx1 = offx2 = x1;
  75782. offy1 = offy2 = y1;
  75783. }
  75784. else
  75785. {
  75786. const float offset = width / len;
  75787. dx *= offset;
  75788. dy *= offset;
  75789. offx1 = x1 + dy;
  75790. offy1 = y1 - dx;
  75791. offx2 = x2 + dy;
  75792. offy2 = y2 - dx;
  75793. }
  75794. if (style == PathStrokeType::square)
  75795. {
  75796. // sqaure ends
  75797. destPath.lineTo (offx1, offy1);
  75798. destPath.lineTo (offx2, offy2);
  75799. destPath.lineTo (x2, y2);
  75800. }
  75801. else
  75802. {
  75803. // rounded ends
  75804. const float midx = (offx1 + offx2) * 0.5f;
  75805. const float midy = (offy1 + offy2) * 0.5f;
  75806. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75807. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75808. midx, midy);
  75809. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75810. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75811. x2, y2);
  75812. }
  75813. }
  75814. }
  75815. struct Arrowhead
  75816. {
  75817. float startWidth, startLength;
  75818. float endWidth, endLength;
  75819. };
  75820. void addArrowhead (Path& destPath,
  75821. const float x1, const float y1,
  75822. const float x2, const float y2,
  75823. const float tipX, const float tipY,
  75824. const float width,
  75825. const float arrowheadWidth)
  75826. {
  75827. Line<float> line (x1, y1, x2, y2);
  75828. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75829. destPath.lineTo (tipX, tipY);
  75830. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75831. destPath.lineTo (x2, y2);
  75832. }
  75833. struct LineSection
  75834. {
  75835. float x1, y1, x2, y2; // original line
  75836. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75837. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75838. };
  75839. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75840. {
  75841. while (amountAtEnd > 0 && subPath.size() > 0)
  75842. {
  75843. LineSection& l = subPath.getReference (subPath.size() - 1);
  75844. float dx = l.rx2 - l.rx1;
  75845. float dy = l.ry2 - l.ry1;
  75846. const float len = juce_hypot (dx, dy);
  75847. if (len <= amountAtEnd && subPath.size() > 1)
  75848. {
  75849. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75850. prev.x2 = l.x2;
  75851. prev.y2 = l.y2;
  75852. subPath.removeLast();
  75853. amountAtEnd -= len;
  75854. }
  75855. else
  75856. {
  75857. const float prop = jmin (0.9999f, amountAtEnd / len);
  75858. dx *= prop;
  75859. dy *= prop;
  75860. l.rx1 += dx;
  75861. l.ry1 += dy;
  75862. l.lx2 += dx;
  75863. l.ly2 += dy;
  75864. break;
  75865. }
  75866. }
  75867. while (amountAtStart > 0 && subPath.size() > 0)
  75868. {
  75869. LineSection& l = subPath.getReference (0);
  75870. float dx = l.rx2 - l.rx1;
  75871. float dy = l.ry2 - l.ry1;
  75872. const float len = juce_hypot (dx, dy);
  75873. if (len <= amountAtStart && subPath.size() > 1)
  75874. {
  75875. LineSection& next = subPath.getReference (1);
  75876. next.x1 = l.x1;
  75877. next.y1 = l.y1;
  75878. subPath.remove (0);
  75879. amountAtStart -= len;
  75880. }
  75881. else
  75882. {
  75883. const float prop = jmin (0.9999f, amountAtStart / len);
  75884. dx *= prop;
  75885. dy *= prop;
  75886. l.rx2 -= dx;
  75887. l.ry2 -= dy;
  75888. l.lx1 -= dx;
  75889. l.ly1 -= dy;
  75890. break;
  75891. }
  75892. }
  75893. }
  75894. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75895. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75896. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75897. const Arrowhead* const arrowhead)
  75898. {
  75899. jassert (subPath.size() > 0);
  75900. if (arrowhead != 0)
  75901. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75902. const LineSection& firstLine = subPath.getReference (0);
  75903. float lastX1 = firstLine.lx1;
  75904. float lastY1 = firstLine.ly1;
  75905. float lastX2 = firstLine.lx2;
  75906. float lastY2 = firstLine.ly2;
  75907. if (isClosed)
  75908. {
  75909. destPath.startNewSubPath (lastX1, lastY1);
  75910. }
  75911. else
  75912. {
  75913. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75914. if (arrowhead != 0)
  75915. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75916. width, arrowhead->startWidth);
  75917. else
  75918. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75919. }
  75920. int i;
  75921. for (i = 1; i < subPath.size(); ++i)
  75922. {
  75923. const LineSection& l = subPath.getReference (i);
  75924. addEdgeAndJoint (destPath, jointStyle,
  75925. maxMiterExtensionSquared, width,
  75926. lastX1, lastY1, lastX2, lastY2,
  75927. l.lx1, l.ly1, l.lx2, l.ly2,
  75928. l.x1, l.y1);
  75929. lastX1 = l.lx1;
  75930. lastY1 = l.ly1;
  75931. lastX2 = l.lx2;
  75932. lastY2 = l.ly2;
  75933. }
  75934. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75935. if (isClosed)
  75936. {
  75937. const LineSection& l = subPath.getReference (0);
  75938. addEdgeAndJoint (destPath, jointStyle,
  75939. maxMiterExtensionSquared, width,
  75940. lastX1, lastY1, lastX2, lastY2,
  75941. l.lx1, l.ly1, l.lx2, l.ly2,
  75942. l.x1, l.y1);
  75943. destPath.closeSubPath();
  75944. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75945. }
  75946. else
  75947. {
  75948. destPath.lineTo (lastX2, lastY2);
  75949. if (arrowhead != 0)
  75950. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75951. width, arrowhead->endWidth);
  75952. else
  75953. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75954. }
  75955. lastX1 = lastLine.rx1;
  75956. lastY1 = lastLine.ry1;
  75957. lastX2 = lastLine.rx2;
  75958. lastY2 = lastLine.ry2;
  75959. for (i = subPath.size() - 1; --i >= 0;)
  75960. {
  75961. const LineSection& l = subPath.getReference (i);
  75962. addEdgeAndJoint (destPath, jointStyle,
  75963. maxMiterExtensionSquared, width,
  75964. lastX1, lastY1, lastX2, lastY2,
  75965. l.rx1, l.ry1, l.rx2, l.ry2,
  75966. l.x2, l.y2);
  75967. lastX1 = l.rx1;
  75968. lastY1 = l.ry1;
  75969. lastX2 = l.rx2;
  75970. lastY2 = l.ry2;
  75971. }
  75972. if (isClosed)
  75973. {
  75974. addEdgeAndJoint (destPath, jointStyle,
  75975. maxMiterExtensionSquared, width,
  75976. lastX1, lastY1, lastX2, lastY2,
  75977. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75978. lastLine.x2, lastLine.y2);
  75979. }
  75980. else
  75981. {
  75982. // do the last line
  75983. destPath.lineTo (lastX2, lastY2);
  75984. }
  75985. destPath.closeSubPath();
  75986. }
  75987. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75988. const PathStrokeType::EndCapStyle endStyle,
  75989. Path& destPath, const Path& source,
  75990. const AffineTransform& transform,
  75991. const float extraAccuracy, const Arrowhead* const arrowhead)
  75992. {
  75993. jassert (extraAccuracy > 0);
  75994. if (thickness <= 0)
  75995. {
  75996. destPath.clear();
  75997. return;
  75998. }
  75999. const Path* sourcePath = &source;
  76000. Path temp;
  76001. if (sourcePath == &destPath)
  76002. {
  76003. destPath.swapWithPath (temp);
  76004. sourcePath = &temp;
  76005. }
  76006. else
  76007. {
  76008. destPath.clear();
  76009. }
  76010. destPath.setUsingNonZeroWinding (true);
  76011. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76012. const float width = 0.5f * thickness;
  76013. // Iterate the path, creating a list of the
  76014. // left/right-hand lines along either side of it...
  76015. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76016. Array <LineSection> subPath;
  76017. subPath.ensureStorageAllocated (512);
  76018. LineSection l;
  76019. l.x1 = 0;
  76020. l.y1 = 0;
  76021. const float minSegmentLength = 0.0001f;
  76022. while (it.next())
  76023. {
  76024. if (it.subPathIndex == 0)
  76025. {
  76026. if (subPath.size() > 0)
  76027. {
  76028. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76029. subPath.clearQuick();
  76030. }
  76031. l.x1 = it.x1;
  76032. l.y1 = it.y1;
  76033. }
  76034. l.x2 = it.x2;
  76035. l.y2 = it.y2;
  76036. float dx = l.x2 - l.x1;
  76037. float dy = l.y2 - l.y1;
  76038. const float hypotSquared = dx*dx + dy*dy;
  76039. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76040. {
  76041. const float len = std::sqrt (hypotSquared);
  76042. if (len == 0)
  76043. {
  76044. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76045. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76046. }
  76047. else
  76048. {
  76049. const float offset = width / len;
  76050. dx *= offset;
  76051. dy *= offset;
  76052. l.rx2 = l.x1 - dy;
  76053. l.ry2 = l.y1 + dx;
  76054. l.lx1 = l.x1 + dy;
  76055. l.ly1 = l.y1 - dx;
  76056. l.lx2 = l.x2 + dy;
  76057. l.ly2 = l.y2 - dx;
  76058. l.rx1 = l.x2 - dy;
  76059. l.ry1 = l.y2 + dx;
  76060. }
  76061. subPath.add (l);
  76062. if (it.closesSubPath)
  76063. {
  76064. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76065. subPath.clearQuick();
  76066. }
  76067. else
  76068. {
  76069. l.x1 = it.x2;
  76070. l.y1 = it.y2;
  76071. }
  76072. }
  76073. }
  76074. if (subPath.size() > 0)
  76075. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76076. }
  76077. }
  76078. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76079. const AffineTransform& transform, const float extraAccuracy) const
  76080. {
  76081. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76082. transform, extraAccuracy, 0);
  76083. }
  76084. void PathStrokeType::createDashedStroke (Path& destPath,
  76085. const Path& sourcePath,
  76086. const float* dashLengths,
  76087. int numDashLengths,
  76088. const AffineTransform& transform,
  76089. const float extraAccuracy) const
  76090. {
  76091. jassert (extraAccuracy > 0);
  76092. if (thickness <= 0)
  76093. return;
  76094. // this should really be an even number..
  76095. jassert ((numDashLengths & 1) == 0);
  76096. Path newDestPath;
  76097. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76098. bool first = true;
  76099. int dashNum = 0;
  76100. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76101. float dx = 0.0f, dy = 0.0f;
  76102. for (;;)
  76103. {
  76104. const bool isSolid = ((dashNum & 1) == 0);
  76105. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76106. jassert (dashLen > 0); // must be a positive increment!
  76107. if (dashLen <= 0)
  76108. break;
  76109. pos += dashLen;
  76110. while (pos > lineEndPos)
  76111. {
  76112. if (! it.next())
  76113. {
  76114. if (isSolid && ! first)
  76115. newDestPath.lineTo (it.x2, it.y2);
  76116. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76117. return;
  76118. }
  76119. if (isSolid && ! first)
  76120. newDestPath.lineTo (it.x1, it.y1);
  76121. else
  76122. newDestPath.startNewSubPath (it.x1, it.y1);
  76123. dx = it.x2 - it.x1;
  76124. dy = it.y2 - it.y1;
  76125. lineLen = juce_hypot (dx, dy);
  76126. lineEndPos += lineLen;
  76127. first = it.closesSubPath;
  76128. }
  76129. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76130. if (isSolid)
  76131. newDestPath.lineTo (it.x1 + dx * alpha,
  76132. it.y1 + dy * alpha);
  76133. else
  76134. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76135. it.y1 + dy * alpha);
  76136. }
  76137. }
  76138. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76139. const Path& sourcePath,
  76140. const float arrowheadStartWidth, const float arrowheadStartLength,
  76141. const float arrowheadEndWidth, const float arrowheadEndLength,
  76142. const AffineTransform& transform,
  76143. const float extraAccuracy) const
  76144. {
  76145. PathStrokeHelpers::Arrowhead head;
  76146. head.startWidth = arrowheadStartWidth;
  76147. head.startLength = arrowheadStartLength;
  76148. head.endWidth = arrowheadEndWidth;
  76149. head.endLength = arrowheadEndLength;
  76150. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76151. destPath, sourcePath, transform, extraAccuracy, &head);
  76152. }
  76153. END_JUCE_NAMESPACE
  76154. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76155. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76156. BEGIN_JUCE_NAMESPACE
  76157. RectangleList::RectangleList() throw()
  76158. {
  76159. }
  76160. RectangleList::RectangleList (const Rectangle<int>& rect)
  76161. {
  76162. if (! rect.isEmpty())
  76163. rects.add (rect);
  76164. }
  76165. RectangleList::RectangleList (const RectangleList& other)
  76166. : rects (other.rects)
  76167. {
  76168. }
  76169. RectangleList& RectangleList::operator= (const RectangleList& other)
  76170. {
  76171. rects = other.rects;
  76172. return *this;
  76173. }
  76174. RectangleList::~RectangleList()
  76175. {
  76176. }
  76177. void RectangleList::clear()
  76178. {
  76179. rects.clearQuick();
  76180. }
  76181. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76182. {
  76183. if (isPositiveAndBelow (index, rects.size()))
  76184. return rects.getReference (index);
  76185. return Rectangle<int>();
  76186. }
  76187. bool RectangleList::isEmpty() const throw()
  76188. {
  76189. return rects.size() == 0;
  76190. }
  76191. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76192. : current (0),
  76193. owner (list),
  76194. index (list.rects.size())
  76195. {
  76196. }
  76197. RectangleList::Iterator::~Iterator()
  76198. {
  76199. }
  76200. bool RectangleList::Iterator::next() throw()
  76201. {
  76202. if (--index >= 0)
  76203. {
  76204. current = & (owner.rects.getReference (index));
  76205. return true;
  76206. }
  76207. return false;
  76208. }
  76209. void RectangleList::add (const Rectangle<int>& rect)
  76210. {
  76211. if (! rect.isEmpty())
  76212. {
  76213. if (rects.size() == 0)
  76214. {
  76215. rects.add (rect);
  76216. }
  76217. else
  76218. {
  76219. bool anyOverlaps = false;
  76220. int i;
  76221. for (i = rects.size(); --i >= 0;)
  76222. {
  76223. Rectangle<int>& ourRect = rects.getReference (i);
  76224. if (rect.intersects (ourRect))
  76225. {
  76226. if (rect.contains (ourRect))
  76227. rects.remove (i);
  76228. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76229. anyOverlaps = true;
  76230. }
  76231. }
  76232. if (anyOverlaps && rects.size() > 0)
  76233. {
  76234. RectangleList r (rect);
  76235. for (i = rects.size(); --i >= 0;)
  76236. {
  76237. const Rectangle<int>& ourRect = rects.getReference (i);
  76238. if (rect.intersects (ourRect))
  76239. {
  76240. r.subtract (ourRect);
  76241. if (r.rects.size() == 0)
  76242. return;
  76243. }
  76244. }
  76245. for (i = r.getNumRectangles(); --i >= 0;)
  76246. rects.add (r.rects.getReference (i));
  76247. }
  76248. else
  76249. {
  76250. rects.add (rect);
  76251. }
  76252. }
  76253. }
  76254. }
  76255. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76256. {
  76257. if (! rect.isEmpty())
  76258. rects.add (rect);
  76259. }
  76260. void RectangleList::add (const int x, const int y, const int w, const int h)
  76261. {
  76262. if (rects.size() == 0)
  76263. {
  76264. if (w > 0 && h > 0)
  76265. rects.add (Rectangle<int> (x, y, w, h));
  76266. }
  76267. else
  76268. {
  76269. add (Rectangle<int> (x, y, w, h));
  76270. }
  76271. }
  76272. void RectangleList::add (const RectangleList& other)
  76273. {
  76274. for (int i = 0; i < other.rects.size(); ++i)
  76275. add (other.rects.getReference (i));
  76276. }
  76277. void RectangleList::subtract (const Rectangle<int>& rect)
  76278. {
  76279. const int originalNumRects = rects.size();
  76280. if (originalNumRects > 0)
  76281. {
  76282. const int x1 = rect.x;
  76283. const int y1 = rect.y;
  76284. const int x2 = x1 + rect.w;
  76285. const int y2 = y1 + rect.h;
  76286. for (int i = getNumRectangles(); --i >= 0;)
  76287. {
  76288. Rectangle<int>& r = rects.getReference (i);
  76289. const int rx1 = r.x;
  76290. const int ry1 = r.y;
  76291. const int rx2 = rx1 + r.w;
  76292. const int ry2 = ry1 + r.h;
  76293. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76294. {
  76295. if (x1 > rx1 && x1 < rx2)
  76296. {
  76297. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76298. {
  76299. r.w = x1 - rx1;
  76300. }
  76301. else
  76302. {
  76303. r.x = x1;
  76304. r.w = rx2 - x1;
  76305. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76306. i += 2;
  76307. }
  76308. }
  76309. else if (x2 > rx1 && x2 < rx2)
  76310. {
  76311. r.x = x2;
  76312. r.w = rx2 - x2;
  76313. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76314. {
  76315. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76316. i += 2;
  76317. }
  76318. }
  76319. else if (y1 > ry1 && y1 < ry2)
  76320. {
  76321. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76322. {
  76323. r.h = y1 - ry1;
  76324. }
  76325. else
  76326. {
  76327. r.y = y1;
  76328. r.h = ry2 - y1;
  76329. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76330. i += 2;
  76331. }
  76332. }
  76333. else if (y2 > ry1 && y2 < ry2)
  76334. {
  76335. r.y = y2;
  76336. r.h = ry2 - y2;
  76337. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76338. {
  76339. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76340. i += 2;
  76341. }
  76342. }
  76343. else
  76344. {
  76345. rects.remove (i);
  76346. }
  76347. }
  76348. }
  76349. }
  76350. }
  76351. bool RectangleList::subtract (const RectangleList& otherList)
  76352. {
  76353. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76354. subtract (otherList.rects.getReference (i));
  76355. return rects.size() > 0;
  76356. }
  76357. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76358. {
  76359. bool notEmpty = false;
  76360. if (rect.isEmpty())
  76361. {
  76362. clear();
  76363. }
  76364. else
  76365. {
  76366. for (int i = rects.size(); --i >= 0;)
  76367. {
  76368. Rectangle<int>& r = rects.getReference (i);
  76369. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76370. rects.remove (i);
  76371. else
  76372. notEmpty = true;
  76373. }
  76374. }
  76375. return notEmpty;
  76376. }
  76377. bool RectangleList::clipTo (const RectangleList& other)
  76378. {
  76379. if (rects.size() == 0)
  76380. return false;
  76381. RectangleList result;
  76382. for (int j = 0; j < rects.size(); ++j)
  76383. {
  76384. const Rectangle<int>& rect = rects.getReference (j);
  76385. for (int i = other.rects.size(); --i >= 0;)
  76386. {
  76387. Rectangle<int> r (other.rects.getReference (i));
  76388. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76389. result.rects.add (r);
  76390. }
  76391. }
  76392. swapWith (result);
  76393. return ! isEmpty();
  76394. }
  76395. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76396. {
  76397. destRegion.clear();
  76398. if (! rect.isEmpty())
  76399. {
  76400. for (int i = rects.size(); --i >= 0;)
  76401. {
  76402. Rectangle<int> r (rects.getReference (i));
  76403. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76404. destRegion.rects.add (r);
  76405. }
  76406. }
  76407. return destRegion.rects.size() > 0;
  76408. }
  76409. void RectangleList::swapWith (RectangleList& otherList) throw()
  76410. {
  76411. rects.swapWithArray (otherList.rects);
  76412. }
  76413. void RectangleList::consolidate()
  76414. {
  76415. int i;
  76416. for (i = 0; i < getNumRectangles() - 1; ++i)
  76417. {
  76418. Rectangle<int>& r = rects.getReference (i);
  76419. const int rx1 = r.x;
  76420. const int ry1 = r.y;
  76421. const int rx2 = rx1 + r.w;
  76422. const int ry2 = ry1 + r.h;
  76423. for (int j = rects.size(); --j > i;)
  76424. {
  76425. Rectangle<int>& r2 = rects.getReference (j);
  76426. const int jrx1 = r2.x;
  76427. const int jry1 = r2.y;
  76428. const int jrx2 = jrx1 + r2.w;
  76429. const int jry2 = jry1 + r2.h;
  76430. // if the vertical edges of any blocks are touching and their horizontals don't
  76431. // line up, split them horizontally..
  76432. if (jrx1 == rx2 || jrx2 == rx1)
  76433. {
  76434. if (jry1 > ry1 && jry1 < ry2)
  76435. {
  76436. r.h = jry1 - ry1;
  76437. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76438. i = -1;
  76439. break;
  76440. }
  76441. if (jry2 > ry1 && jry2 < ry2)
  76442. {
  76443. r.h = jry2 - ry1;
  76444. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76445. i = -1;
  76446. break;
  76447. }
  76448. else if (ry1 > jry1 && ry1 < jry2)
  76449. {
  76450. r2.h = ry1 - jry1;
  76451. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76452. i = -1;
  76453. break;
  76454. }
  76455. else if (ry2 > jry1 && ry2 < jry2)
  76456. {
  76457. r2.h = ry2 - jry1;
  76458. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76459. i = -1;
  76460. break;
  76461. }
  76462. }
  76463. }
  76464. }
  76465. for (i = 0; i < rects.size() - 1; ++i)
  76466. {
  76467. Rectangle<int>& r = rects.getReference (i);
  76468. for (int j = rects.size(); --j > i;)
  76469. {
  76470. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76471. {
  76472. rects.remove (j);
  76473. i = -1;
  76474. break;
  76475. }
  76476. }
  76477. }
  76478. }
  76479. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76480. {
  76481. for (int i = getNumRectangles(); --i >= 0;)
  76482. if (rects.getReference (i).contains (x, y))
  76483. return true;
  76484. return false;
  76485. }
  76486. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76487. {
  76488. if (rects.size() > 1)
  76489. {
  76490. RectangleList r (rectangleToCheck);
  76491. for (int i = rects.size(); --i >= 0;)
  76492. {
  76493. r.subtract (rects.getReference (i));
  76494. if (r.rects.size() == 0)
  76495. return true;
  76496. }
  76497. }
  76498. else if (rects.size() > 0)
  76499. {
  76500. return rects.getReference (0).contains (rectangleToCheck);
  76501. }
  76502. return false;
  76503. }
  76504. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76505. {
  76506. for (int i = rects.size(); --i >= 0;)
  76507. if (rects.getReference (i).intersects (rectangleToCheck))
  76508. return true;
  76509. return false;
  76510. }
  76511. bool RectangleList::intersects (const RectangleList& other) const throw()
  76512. {
  76513. for (int i = rects.size(); --i >= 0;)
  76514. if (other.intersectsRectangle (rects.getReference (i)))
  76515. return true;
  76516. return false;
  76517. }
  76518. const Rectangle<int> RectangleList::getBounds() const throw()
  76519. {
  76520. if (rects.size() <= 1)
  76521. {
  76522. if (rects.size() == 0)
  76523. return Rectangle<int>();
  76524. else
  76525. return rects.getReference (0);
  76526. }
  76527. else
  76528. {
  76529. const Rectangle<int>& r = rects.getReference (0);
  76530. int minX = r.x;
  76531. int minY = r.y;
  76532. int maxX = minX + r.w;
  76533. int maxY = minY + r.h;
  76534. for (int i = rects.size(); --i > 0;)
  76535. {
  76536. const Rectangle<int>& r2 = rects.getReference (i);
  76537. minX = jmin (minX, r2.x);
  76538. minY = jmin (minY, r2.y);
  76539. maxX = jmax (maxX, r2.getRight());
  76540. maxY = jmax (maxY, r2.getBottom());
  76541. }
  76542. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76543. }
  76544. }
  76545. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76546. {
  76547. for (int i = rects.size(); --i >= 0;)
  76548. {
  76549. Rectangle<int>& r = rects.getReference (i);
  76550. r.x += dx;
  76551. r.y += dy;
  76552. }
  76553. }
  76554. const Path RectangleList::toPath() const
  76555. {
  76556. Path p;
  76557. for (int i = rects.size(); --i >= 0;)
  76558. {
  76559. const Rectangle<int>& r = rects.getReference (i);
  76560. p.addRectangle ((float) r.x,
  76561. (float) r.y,
  76562. (float) r.w,
  76563. (float) r.h);
  76564. }
  76565. return p;
  76566. }
  76567. END_JUCE_NAMESPACE
  76568. /*** End of inlined file: juce_RectangleList.cpp ***/
  76569. /*** Start of inlined file: juce_Image.cpp ***/
  76570. BEGIN_JUCE_NAMESPACE
  76571. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76572. : format (format_), width (width_), height (height_)
  76573. {
  76574. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76575. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76576. }
  76577. Image::SharedImage::~SharedImage()
  76578. {
  76579. }
  76580. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76581. {
  76582. return imageData + lineStride * y + pixelStride * x;
  76583. }
  76584. class SoftwareSharedImage : public Image::SharedImage
  76585. {
  76586. public:
  76587. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76588. : Image::SharedImage (format_, width_, height_)
  76589. {
  76590. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76591. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76592. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76593. imageData = imageDataAllocated;
  76594. }
  76595. Image::ImageType getType() const
  76596. {
  76597. return Image::SoftwareImage;
  76598. }
  76599. LowLevelGraphicsContext* createLowLevelContext()
  76600. {
  76601. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76602. }
  76603. Image::SharedImage* clone()
  76604. {
  76605. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76606. memcpy (s->imageData, imageData, lineStride * height);
  76607. return s;
  76608. }
  76609. private:
  76610. HeapBlock<uint8> imageDataAllocated;
  76611. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  76612. };
  76613. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76614. {
  76615. return new SoftwareSharedImage (format, width, height, clearImage);
  76616. }
  76617. class SubsectionSharedImage : public Image::SharedImage
  76618. {
  76619. public:
  76620. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76621. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76622. image (image_), area (area_)
  76623. {
  76624. pixelStride = image_->getPixelStride();
  76625. lineStride = image_->getLineStride();
  76626. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76627. }
  76628. Image::ImageType getType() const
  76629. {
  76630. return Image::SoftwareImage;
  76631. }
  76632. LowLevelGraphicsContext* createLowLevelContext()
  76633. {
  76634. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76635. g->clipToRectangle (area);
  76636. g->setOrigin (area.getX(), area.getY());
  76637. return g;
  76638. }
  76639. Image::SharedImage* clone()
  76640. {
  76641. return new SubsectionSharedImage (image->clone(), area);
  76642. }
  76643. private:
  76644. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76645. const Rectangle<int> area;
  76646. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76647. };
  76648. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76649. {
  76650. if (area.contains (getBounds()))
  76651. return *this;
  76652. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76653. if (validArea.isEmpty())
  76654. return Image::null;
  76655. return Image (new SubsectionSharedImage (image, validArea));
  76656. }
  76657. Image::Image()
  76658. {
  76659. }
  76660. Image::Image (SharedImage* const instance)
  76661. : image (instance)
  76662. {
  76663. }
  76664. Image::Image (const PixelFormat format,
  76665. const int width, const int height,
  76666. const bool clearImage, const ImageType type)
  76667. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76668. : new SoftwareSharedImage (format, width, height, clearImage))
  76669. {
  76670. }
  76671. Image::Image (const Image& other)
  76672. : image (other.image)
  76673. {
  76674. }
  76675. Image& Image::operator= (const Image& other)
  76676. {
  76677. image = other.image;
  76678. return *this;
  76679. }
  76680. Image::~Image()
  76681. {
  76682. }
  76683. const Image Image::null;
  76684. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76685. {
  76686. return image == 0 ? 0 : image->createLowLevelContext();
  76687. }
  76688. void Image::duplicateIfShared()
  76689. {
  76690. if (image != 0 && image->getReferenceCount() > 1)
  76691. image = image->clone();
  76692. }
  76693. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76694. {
  76695. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76696. return *this;
  76697. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76698. Graphics g (newImage);
  76699. g.setImageResamplingQuality (quality);
  76700. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76701. return newImage;
  76702. }
  76703. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76704. {
  76705. if (image == 0 || newFormat == image->format)
  76706. return *this;
  76707. const int w = image->width, h = image->height;
  76708. Image newImage (newFormat, w, h, false, image->getType());
  76709. if (newFormat == SingleChannel)
  76710. {
  76711. if (! hasAlphaChannel())
  76712. {
  76713. newImage.clear (getBounds(), Colours::black);
  76714. }
  76715. else
  76716. {
  76717. const BitmapData destData (newImage, 0, 0, w, h, true);
  76718. const BitmapData srcData (*this, 0, 0, w, h);
  76719. for (int y = 0; y < h; ++y)
  76720. {
  76721. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76722. uint8* dst = destData.getLinePointer (y);
  76723. for (int x = w; --x >= 0;)
  76724. {
  76725. *dst++ = src->getAlpha();
  76726. ++src;
  76727. }
  76728. }
  76729. }
  76730. }
  76731. else
  76732. {
  76733. if (hasAlphaChannel())
  76734. newImage.clear (getBounds());
  76735. Graphics g (newImage);
  76736. g.drawImageAt (*this, 0, 0);
  76737. }
  76738. return newImage;
  76739. }
  76740. NamedValueSet* Image::getProperties() const
  76741. {
  76742. return image == 0 ? 0 : &(image->userData);
  76743. }
  76744. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76745. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76746. pixelFormat (image.getFormat()),
  76747. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76748. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76749. width (w),
  76750. height (h)
  76751. {
  76752. jassert (data != 0);
  76753. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76754. }
  76755. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76756. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76757. pixelFormat (image.getFormat()),
  76758. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76759. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76760. width (w),
  76761. height (h)
  76762. {
  76763. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76764. }
  76765. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76766. : data (image.image == 0 ? 0 : image.image->imageData),
  76767. pixelFormat (image.getFormat()),
  76768. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76769. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76770. width (image.getWidth()),
  76771. height (image.getHeight())
  76772. {
  76773. }
  76774. Image::BitmapData::~BitmapData()
  76775. {
  76776. }
  76777. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76778. {
  76779. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76780. const uint8* const pixel = getPixelPointer (x, y);
  76781. switch (pixelFormat)
  76782. {
  76783. case Image::ARGB:
  76784. {
  76785. PixelARGB p (*(const PixelARGB*) pixel);
  76786. p.unpremultiply();
  76787. return Colour (p.getARGB());
  76788. }
  76789. case Image::RGB:
  76790. return Colour (((const PixelRGB*) pixel)->getARGB());
  76791. case Image::SingleChannel:
  76792. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76793. default:
  76794. jassertfalse;
  76795. break;
  76796. }
  76797. return Colour();
  76798. }
  76799. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76800. {
  76801. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76802. uint8* const pixel = getPixelPointer (x, y);
  76803. const PixelARGB col (colour.getPixelARGB());
  76804. switch (pixelFormat)
  76805. {
  76806. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76807. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76808. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76809. default: jassertfalse; break;
  76810. }
  76811. }
  76812. void Image::setPixelData (int x, int y, int w, int h,
  76813. const uint8* const sourcePixelData, const int sourceLineStride)
  76814. {
  76815. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76816. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76817. {
  76818. const BitmapData dest (*this, x, y, w, h, true);
  76819. for (int i = 0; i < h; ++i)
  76820. {
  76821. memcpy (dest.getLinePointer(i),
  76822. sourcePixelData + sourceLineStride * i,
  76823. w * dest.pixelStride);
  76824. }
  76825. }
  76826. }
  76827. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76828. {
  76829. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76830. if (! clipped.isEmpty())
  76831. {
  76832. const PixelARGB col (colourToClearTo.getPixelARGB());
  76833. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76834. uint8* dest = destData.data;
  76835. int dh = clipped.getHeight();
  76836. while (--dh >= 0)
  76837. {
  76838. uint8* line = dest;
  76839. dest += destData.lineStride;
  76840. if (isARGB())
  76841. {
  76842. for (int x = clipped.getWidth(); --x >= 0;)
  76843. {
  76844. ((PixelARGB*) line)->set (col);
  76845. line += destData.pixelStride;
  76846. }
  76847. }
  76848. else if (isRGB())
  76849. {
  76850. for (int x = clipped.getWidth(); --x >= 0;)
  76851. {
  76852. ((PixelRGB*) line)->set (col);
  76853. line += destData.pixelStride;
  76854. }
  76855. }
  76856. else
  76857. {
  76858. for (int x = clipped.getWidth(); --x >= 0;)
  76859. {
  76860. *line = col.getAlpha();
  76861. line += destData.pixelStride;
  76862. }
  76863. }
  76864. }
  76865. }
  76866. }
  76867. const Colour Image::getPixelAt (const int x, const int y) const
  76868. {
  76869. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76870. {
  76871. const BitmapData srcData (*this, x, y, 1, 1);
  76872. return srcData.getPixelColour (0, 0);
  76873. }
  76874. return Colour();
  76875. }
  76876. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76877. {
  76878. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76879. {
  76880. const BitmapData destData (*this, x, y, 1, 1, true);
  76881. destData.setPixelColour (0, 0, colour);
  76882. }
  76883. }
  76884. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76885. {
  76886. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  76887. && hasAlphaChannel())
  76888. {
  76889. const BitmapData destData (*this, x, y, 1, 1, true);
  76890. if (isARGB())
  76891. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76892. else
  76893. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76894. }
  76895. }
  76896. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76897. {
  76898. if (hasAlphaChannel())
  76899. {
  76900. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76901. if (isARGB())
  76902. {
  76903. for (int y = 0; y < destData.height; ++y)
  76904. {
  76905. uint8* p = destData.getLinePointer (y);
  76906. for (int x = 0; x < destData.width; ++x)
  76907. {
  76908. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76909. p += destData.pixelStride;
  76910. }
  76911. }
  76912. }
  76913. else
  76914. {
  76915. for (int y = 0; y < destData.height; ++y)
  76916. {
  76917. uint8* p = destData.getLinePointer (y);
  76918. for (int x = 0; x < destData.width; ++x)
  76919. {
  76920. *p = (uint8) (*p * amountToMultiplyBy);
  76921. p += destData.pixelStride;
  76922. }
  76923. }
  76924. }
  76925. }
  76926. else
  76927. {
  76928. jassertfalse; // can't do this without an alpha-channel!
  76929. }
  76930. }
  76931. void Image::desaturate()
  76932. {
  76933. if (isARGB() || isRGB())
  76934. {
  76935. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76936. if (isARGB())
  76937. {
  76938. for (int y = 0; y < destData.height; ++y)
  76939. {
  76940. uint8* p = destData.getLinePointer (y);
  76941. for (int x = 0; x < destData.width; ++x)
  76942. {
  76943. ((PixelARGB*) p)->desaturate();
  76944. p += destData.pixelStride;
  76945. }
  76946. }
  76947. }
  76948. else
  76949. {
  76950. for (int y = 0; y < destData.height; ++y)
  76951. {
  76952. uint8* p = destData.getLinePointer (y);
  76953. for (int x = 0; x < destData.width; ++x)
  76954. {
  76955. ((PixelRGB*) p)->desaturate();
  76956. p += destData.pixelStride;
  76957. }
  76958. }
  76959. }
  76960. }
  76961. }
  76962. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76963. {
  76964. if (hasAlphaChannel())
  76965. {
  76966. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76967. SparseSet<int> pixelsOnRow;
  76968. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76969. for (int y = 0; y < srcData.height; ++y)
  76970. {
  76971. pixelsOnRow.clear();
  76972. const uint8* lineData = srcData.getLinePointer (y);
  76973. if (isARGB())
  76974. {
  76975. for (int x = 0; x < srcData.width; ++x)
  76976. {
  76977. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76978. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76979. lineData += srcData.pixelStride;
  76980. }
  76981. }
  76982. else
  76983. {
  76984. for (int x = 0; x < srcData.width; ++x)
  76985. {
  76986. if (*lineData >= threshold)
  76987. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76988. lineData += srcData.pixelStride;
  76989. }
  76990. }
  76991. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76992. {
  76993. const Range<int> range (pixelsOnRow.getRange (i));
  76994. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76995. }
  76996. result.consolidate();
  76997. }
  76998. }
  76999. else
  77000. {
  77001. result.add (0, 0, getWidth(), getHeight());
  77002. }
  77003. }
  77004. void Image::moveImageSection (int dx, int dy,
  77005. int sx, int sy,
  77006. int w, int h)
  77007. {
  77008. if (dx < 0)
  77009. {
  77010. w += dx;
  77011. sx -= dx;
  77012. dx = 0;
  77013. }
  77014. if (dy < 0)
  77015. {
  77016. h += dy;
  77017. sy -= dy;
  77018. dy = 0;
  77019. }
  77020. if (sx < 0)
  77021. {
  77022. w += sx;
  77023. dx -= sx;
  77024. sx = 0;
  77025. }
  77026. if (sy < 0)
  77027. {
  77028. h += sy;
  77029. dy -= sy;
  77030. sy = 0;
  77031. }
  77032. const int minX = jmin (dx, sx);
  77033. const int minY = jmin (dy, sy);
  77034. w = jmin (w, getWidth() - jmax (sx, dx));
  77035. h = jmin (h, getHeight() - jmax (sy, dy));
  77036. if (w > 0 && h > 0)
  77037. {
  77038. const int maxX = jmax (dx, sx) + w;
  77039. const int maxY = jmax (dy, sy) + h;
  77040. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77041. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77042. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77043. const int lineSize = destData.pixelStride * w;
  77044. if (dy > sy)
  77045. {
  77046. while (--h >= 0)
  77047. {
  77048. const int offset = h * destData.lineStride;
  77049. memmove (dst + offset, src + offset, lineSize);
  77050. }
  77051. }
  77052. else if (dst != src)
  77053. {
  77054. while (--h >= 0)
  77055. {
  77056. memmove (dst, src, lineSize);
  77057. dst += destData.lineStride;
  77058. src += destData.lineStride;
  77059. }
  77060. }
  77061. }
  77062. }
  77063. END_JUCE_NAMESPACE
  77064. /*** End of inlined file: juce_Image.cpp ***/
  77065. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77066. BEGIN_JUCE_NAMESPACE
  77067. class ImageCache::Pimpl : public Timer,
  77068. public DeletedAtShutdown
  77069. {
  77070. public:
  77071. Pimpl()
  77072. : cacheTimeout (5000)
  77073. {
  77074. }
  77075. ~Pimpl()
  77076. {
  77077. clearSingletonInstance();
  77078. }
  77079. const Image getFromHashCode (const int64 hashCode)
  77080. {
  77081. const ScopedLock sl (lock);
  77082. for (int i = images.size(); --i >= 0;)
  77083. {
  77084. Item* const item = images.getUnchecked(i);
  77085. if (item->hashCode == hashCode)
  77086. return item->image;
  77087. }
  77088. return Image::null;
  77089. }
  77090. void addImageToCache (const Image& image, const int64 hashCode)
  77091. {
  77092. if (image.isValid())
  77093. {
  77094. if (! isTimerRunning())
  77095. startTimer (2000);
  77096. Item* const item = new Item();
  77097. item->hashCode = hashCode;
  77098. item->image = image;
  77099. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77100. const ScopedLock sl (lock);
  77101. images.add (item);
  77102. }
  77103. }
  77104. void timerCallback()
  77105. {
  77106. const uint32 now = Time::getApproximateMillisecondCounter();
  77107. const ScopedLock sl (lock);
  77108. for (int i = images.size(); --i >= 0;)
  77109. {
  77110. Item* const item = images.getUnchecked(i);
  77111. if (item->image.getReferenceCount() <= 1)
  77112. {
  77113. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77114. images.remove (i);
  77115. }
  77116. else
  77117. {
  77118. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77119. }
  77120. }
  77121. if (images.size() == 0)
  77122. stopTimer();
  77123. }
  77124. struct Item
  77125. {
  77126. Image image;
  77127. int64 hashCode;
  77128. uint32 lastUseTime;
  77129. };
  77130. int cacheTimeout;
  77131. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77132. private:
  77133. OwnedArray<Item> images;
  77134. CriticalSection lock;
  77135. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77136. };
  77137. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77138. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77139. {
  77140. if (Pimpl::getInstanceWithoutCreating() != 0)
  77141. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77142. return Image::null;
  77143. }
  77144. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77145. {
  77146. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77147. }
  77148. const Image ImageCache::getFromFile (const File& file)
  77149. {
  77150. const int64 hashCode = file.hashCode64();
  77151. Image image (getFromHashCode (hashCode));
  77152. if (image.isNull())
  77153. {
  77154. image = ImageFileFormat::loadFrom (file);
  77155. addImageToCache (image, hashCode);
  77156. }
  77157. return image;
  77158. }
  77159. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77160. {
  77161. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77162. Image image (getFromHashCode (hashCode));
  77163. if (image.isNull())
  77164. {
  77165. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77166. addImageToCache (image, hashCode);
  77167. }
  77168. return image;
  77169. }
  77170. void ImageCache::setCacheTimeout (const int millisecs)
  77171. {
  77172. Pimpl::getInstance()->cacheTimeout = millisecs;
  77173. }
  77174. END_JUCE_NAMESPACE
  77175. /*** End of inlined file: juce_ImageCache.cpp ***/
  77176. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77177. BEGIN_JUCE_NAMESPACE
  77178. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77179. : values (size_ * size_),
  77180. size (size_)
  77181. {
  77182. clear();
  77183. }
  77184. ImageConvolutionKernel::~ImageConvolutionKernel()
  77185. {
  77186. }
  77187. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77188. {
  77189. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77190. return values [x + y * size];
  77191. jassertfalse;
  77192. return 0;
  77193. }
  77194. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77195. {
  77196. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77197. {
  77198. values [x + y * size] = value;
  77199. }
  77200. else
  77201. {
  77202. jassertfalse;
  77203. }
  77204. }
  77205. void ImageConvolutionKernel::clear()
  77206. {
  77207. for (int i = size * size; --i >= 0;)
  77208. values[i] = 0;
  77209. }
  77210. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77211. {
  77212. double currentTotal = 0.0;
  77213. for (int i = size * size; --i >= 0;)
  77214. currentTotal += values[i];
  77215. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77216. }
  77217. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77218. {
  77219. for (int i = size * size; --i >= 0;)
  77220. values[i] *= multiplier;
  77221. }
  77222. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77223. {
  77224. const double radiusFactor = -1.0 / (radius * radius * 2);
  77225. const int centre = size >> 1;
  77226. for (int y = size; --y >= 0;)
  77227. {
  77228. for (int x = size; --x >= 0;)
  77229. {
  77230. const int cx = x - centre;
  77231. const int cy = y - centre;
  77232. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77233. }
  77234. }
  77235. setOverallSum (1.0f);
  77236. }
  77237. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77238. const Image& sourceImage,
  77239. const Rectangle<int>& destinationArea) const
  77240. {
  77241. if (sourceImage == destImage)
  77242. {
  77243. destImage.duplicateIfShared();
  77244. }
  77245. else
  77246. {
  77247. if (sourceImage.getWidth() != destImage.getWidth()
  77248. || sourceImage.getHeight() != destImage.getHeight()
  77249. || sourceImage.getFormat() != destImage.getFormat())
  77250. {
  77251. jassertfalse;
  77252. return;
  77253. }
  77254. }
  77255. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77256. if (area.isEmpty())
  77257. return;
  77258. const int right = area.getRight();
  77259. const int bottom = area.getBottom();
  77260. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77261. uint8* line = destData.data;
  77262. const Image::BitmapData srcData (sourceImage, false);
  77263. if (destData.pixelStride == 4)
  77264. {
  77265. for (int y = area.getY(); y < bottom; ++y)
  77266. {
  77267. uint8* dest = line;
  77268. line += destData.lineStride;
  77269. for (int x = area.getX(); x < right; ++x)
  77270. {
  77271. float c1 = 0;
  77272. float c2 = 0;
  77273. float c3 = 0;
  77274. float c4 = 0;
  77275. for (int yy = 0; yy < size; ++yy)
  77276. {
  77277. const int sy = y + yy - (size >> 1);
  77278. if (sy >= srcData.height)
  77279. break;
  77280. if (sy >= 0)
  77281. {
  77282. int sx = x - (size >> 1);
  77283. const uint8* src = srcData.getPixelPointer (sx, sy);
  77284. for (int xx = 0; xx < size; ++xx)
  77285. {
  77286. if (sx >= srcData.width)
  77287. break;
  77288. if (sx >= 0)
  77289. {
  77290. const float kernelMult = values [xx + yy * size];
  77291. c1 += kernelMult * *src++;
  77292. c2 += kernelMult * *src++;
  77293. c3 += kernelMult * *src++;
  77294. c4 += kernelMult * *src++;
  77295. }
  77296. else
  77297. {
  77298. src += 4;
  77299. }
  77300. ++sx;
  77301. }
  77302. }
  77303. }
  77304. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77305. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77306. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77307. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77308. }
  77309. }
  77310. }
  77311. else if (destData.pixelStride == 3)
  77312. {
  77313. for (int y = area.getY(); y < bottom; ++y)
  77314. {
  77315. uint8* dest = line;
  77316. line += destData.lineStride;
  77317. for (int x = area.getX(); x < right; ++x)
  77318. {
  77319. float c1 = 0;
  77320. float c2 = 0;
  77321. float c3 = 0;
  77322. for (int yy = 0; yy < size; ++yy)
  77323. {
  77324. const int sy = y + yy - (size >> 1);
  77325. if (sy >= srcData.height)
  77326. break;
  77327. if (sy >= 0)
  77328. {
  77329. int sx = x - (size >> 1);
  77330. const uint8* src = srcData.getPixelPointer (sx, sy);
  77331. for (int xx = 0; xx < size; ++xx)
  77332. {
  77333. if (sx >= srcData.width)
  77334. break;
  77335. if (sx >= 0)
  77336. {
  77337. const float kernelMult = values [xx + yy * size];
  77338. c1 += kernelMult * *src++;
  77339. c2 += kernelMult * *src++;
  77340. c3 += kernelMult * *src++;
  77341. }
  77342. else
  77343. {
  77344. src += 3;
  77345. }
  77346. ++sx;
  77347. }
  77348. }
  77349. }
  77350. *dest++ = (uint8) roundToInt (c1);
  77351. *dest++ = (uint8) roundToInt (c2);
  77352. *dest++ = (uint8) roundToInt (c3);
  77353. }
  77354. }
  77355. }
  77356. }
  77357. END_JUCE_NAMESPACE
  77358. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77359. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77360. BEGIN_JUCE_NAMESPACE
  77361. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77362. {
  77363. static PNGImageFormat png;
  77364. static JPEGImageFormat jpg;
  77365. static GIFImageFormat gif;
  77366. ImageFileFormat* formats[4];
  77367. int numFormats = 0;
  77368. formats [numFormats++] = &png;
  77369. formats [numFormats++] = &jpg;
  77370. formats [numFormats++] = &gif;
  77371. const int64 streamPos = input.getPosition();
  77372. for (int i = 0; i < numFormats; ++i)
  77373. {
  77374. const bool found = formats[i]->canUnderstand (input);
  77375. input.setPosition (streamPos);
  77376. if (found)
  77377. return formats[i];
  77378. }
  77379. return 0;
  77380. }
  77381. const Image ImageFileFormat::loadFrom (InputStream& input)
  77382. {
  77383. ImageFileFormat* const format = findImageFormatForStream (input);
  77384. if (format != 0)
  77385. return format->decodeImage (input);
  77386. return Image::null;
  77387. }
  77388. const Image ImageFileFormat::loadFrom (const File& file)
  77389. {
  77390. InputStream* const in = file.createInputStream();
  77391. if (in != 0)
  77392. {
  77393. BufferedInputStream b (in, 8192, true);
  77394. return loadFrom (b);
  77395. }
  77396. return Image::null;
  77397. }
  77398. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77399. {
  77400. if (rawData != 0 && numBytes > 4)
  77401. {
  77402. MemoryInputStream stream (rawData, numBytes, false);
  77403. return loadFrom (stream);
  77404. }
  77405. return Image::null;
  77406. }
  77407. END_JUCE_NAMESPACE
  77408. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77409. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77410. BEGIN_JUCE_NAMESPACE
  77411. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77412. const Image juce_loadWithCoreImage (InputStream& input);
  77413. #else
  77414. class GIFLoader
  77415. {
  77416. public:
  77417. GIFLoader (InputStream& in)
  77418. : input (in),
  77419. dataBlockIsZero (false),
  77420. fresh (false),
  77421. finished (false)
  77422. {
  77423. currentBit = lastBit = lastByteIndex = 0;
  77424. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77425. firstcode = oldcode = 0;
  77426. clearCode = end_code = 0;
  77427. int imageWidth, imageHeight;
  77428. int transparent = -1;
  77429. if (! getSizeFromHeader (imageWidth, imageHeight))
  77430. return;
  77431. if ((imageWidth <= 0) || (imageHeight <= 0))
  77432. return;
  77433. unsigned char buf [16];
  77434. if (in.read (buf, 3) != 3)
  77435. return;
  77436. int numColours = 2 << (buf[0] & 7);
  77437. if ((buf[0] & 0x80) != 0)
  77438. readPalette (numColours);
  77439. for (;;)
  77440. {
  77441. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77442. break;
  77443. if (buf[0] == '!')
  77444. {
  77445. if (input.read (buf, 1) != 1)
  77446. break;
  77447. if (processExtension (buf[0], transparent) < 0)
  77448. break;
  77449. continue;
  77450. }
  77451. if (buf[0] != ',')
  77452. continue;
  77453. if (input.read (buf, 9) != 9)
  77454. break;
  77455. imageWidth = makeWord (buf[4], buf[5]);
  77456. imageHeight = makeWord (buf[6], buf[7]);
  77457. numColours = 2 << (buf[8] & 7);
  77458. if ((buf[8] & 0x80) != 0)
  77459. if (! readPalette (numColours))
  77460. break;
  77461. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77462. imageWidth, imageHeight, (transparent >= 0));
  77463. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77464. readImage ((buf[8] & 0x40) != 0, transparent);
  77465. break;
  77466. }
  77467. }
  77468. ~GIFLoader() {}
  77469. Image image;
  77470. private:
  77471. InputStream& input;
  77472. uint8 buffer [300];
  77473. uint8 palette [256][4];
  77474. bool dataBlockIsZero, fresh, finished;
  77475. int currentBit, lastBit, lastByteIndex;
  77476. int codeSize, setCodeSize;
  77477. int maxCode, maxCodeSize;
  77478. int firstcode, oldcode;
  77479. int clearCode, end_code;
  77480. enum { maxGifCode = 1 << 12 };
  77481. int table [2] [maxGifCode];
  77482. int stack [2 * maxGifCode];
  77483. int *sp;
  77484. bool getSizeFromHeader (int& w, int& h)
  77485. {
  77486. char b[8];
  77487. if (input.read (b, 6) == 6)
  77488. {
  77489. if ((strncmp ("GIF87a", b, 6) == 0)
  77490. || (strncmp ("GIF89a", b, 6) == 0))
  77491. {
  77492. if (input.read (b, 4) == 4)
  77493. {
  77494. w = makeWord (b[0], b[1]);
  77495. h = makeWord (b[2], b[3]);
  77496. return true;
  77497. }
  77498. }
  77499. }
  77500. return false;
  77501. }
  77502. bool readPalette (const int numCols)
  77503. {
  77504. unsigned char rgb[4];
  77505. for (int i = 0; i < numCols; ++i)
  77506. {
  77507. input.read (rgb, 3);
  77508. palette [i][0] = rgb[0];
  77509. palette [i][1] = rgb[1];
  77510. palette [i][2] = rgb[2];
  77511. palette [i][3] = 0xff;
  77512. }
  77513. return true;
  77514. }
  77515. int readDataBlock (unsigned char* dest)
  77516. {
  77517. unsigned char n;
  77518. if (input.read (&n, 1) == 1)
  77519. {
  77520. dataBlockIsZero = (n == 0);
  77521. if (dataBlockIsZero || (input.read (dest, n) == n))
  77522. return n;
  77523. }
  77524. return -1;
  77525. }
  77526. int processExtension (const int type, int& transparent)
  77527. {
  77528. unsigned char b [300];
  77529. int n = 0;
  77530. if (type == 0xf9)
  77531. {
  77532. n = readDataBlock (b);
  77533. if (n < 0)
  77534. return 1;
  77535. if ((b[0] & 0x1) != 0)
  77536. transparent = b[3];
  77537. }
  77538. do
  77539. {
  77540. n = readDataBlock (b);
  77541. }
  77542. while (n > 0);
  77543. return n;
  77544. }
  77545. int readLZWByte (const bool initialise, const int inputCodeSize)
  77546. {
  77547. int code, incode, i;
  77548. if (initialise)
  77549. {
  77550. setCodeSize = inputCodeSize;
  77551. codeSize = setCodeSize + 1;
  77552. clearCode = 1 << setCodeSize;
  77553. end_code = clearCode + 1;
  77554. maxCodeSize = 2 * clearCode;
  77555. maxCode = clearCode + 2;
  77556. getCode (0, true);
  77557. fresh = true;
  77558. for (i = 0; i < clearCode; ++i)
  77559. {
  77560. table[0][i] = 0;
  77561. table[1][i] = i;
  77562. }
  77563. for (; i < maxGifCode; ++i)
  77564. {
  77565. table[0][i] = 0;
  77566. table[1][i] = 0;
  77567. }
  77568. sp = stack;
  77569. return 0;
  77570. }
  77571. else if (fresh)
  77572. {
  77573. fresh = false;
  77574. do
  77575. {
  77576. firstcode = oldcode
  77577. = getCode (codeSize, false);
  77578. }
  77579. while (firstcode == clearCode);
  77580. return firstcode;
  77581. }
  77582. if (sp > stack)
  77583. return *--sp;
  77584. while ((code = getCode (codeSize, false)) >= 0)
  77585. {
  77586. if (code == clearCode)
  77587. {
  77588. for (i = 0; i < clearCode; ++i)
  77589. {
  77590. table[0][i] = 0;
  77591. table[1][i] = i;
  77592. }
  77593. for (; i < maxGifCode; ++i)
  77594. {
  77595. table[0][i] = 0;
  77596. table[1][i] = 0;
  77597. }
  77598. codeSize = setCodeSize + 1;
  77599. maxCodeSize = 2 * clearCode;
  77600. maxCode = clearCode + 2;
  77601. sp = stack;
  77602. firstcode = oldcode = getCode (codeSize, false);
  77603. return firstcode;
  77604. }
  77605. else if (code == end_code)
  77606. {
  77607. if (dataBlockIsZero)
  77608. return -2;
  77609. unsigned char buf [260];
  77610. int n;
  77611. while ((n = readDataBlock (buf)) > 0)
  77612. {}
  77613. if (n != 0)
  77614. return -2;
  77615. }
  77616. incode = code;
  77617. if (code >= maxCode)
  77618. {
  77619. *sp++ = firstcode;
  77620. code = oldcode;
  77621. }
  77622. while (code >= clearCode)
  77623. {
  77624. *sp++ = table[1][code];
  77625. if (code == table[0][code])
  77626. return -2;
  77627. code = table[0][code];
  77628. }
  77629. *sp++ = firstcode = table[1][code];
  77630. if ((code = maxCode) < maxGifCode)
  77631. {
  77632. table[0][code] = oldcode;
  77633. table[1][code] = firstcode;
  77634. ++maxCode;
  77635. if ((maxCode >= maxCodeSize)
  77636. && (maxCodeSize < maxGifCode))
  77637. {
  77638. maxCodeSize <<= 1;
  77639. ++codeSize;
  77640. }
  77641. }
  77642. oldcode = incode;
  77643. if (sp > stack)
  77644. return *--sp;
  77645. }
  77646. return code;
  77647. }
  77648. int getCode (const int codeSize_, const bool initialise)
  77649. {
  77650. if (initialise)
  77651. {
  77652. currentBit = 0;
  77653. lastBit = 0;
  77654. finished = false;
  77655. return 0;
  77656. }
  77657. if ((currentBit + codeSize_) >= lastBit)
  77658. {
  77659. if (finished)
  77660. return -1;
  77661. buffer[0] = buffer [lastByteIndex - 2];
  77662. buffer[1] = buffer [lastByteIndex - 1];
  77663. const int n = readDataBlock (&buffer[2]);
  77664. if (n == 0)
  77665. finished = true;
  77666. lastByteIndex = 2 + n;
  77667. currentBit = (currentBit - lastBit) + 16;
  77668. lastBit = (2 + n) * 8 ;
  77669. }
  77670. int result = 0;
  77671. int i = currentBit;
  77672. for (int j = 0; j < codeSize_; ++j)
  77673. {
  77674. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77675. ++i;
  77676. }
  77677. currentBit += codeSize_;
  77678. return result;
  77679. }
  77680. bool readImage (const int interlace, const int transparent)
  77681. {
  77682. unsigned char c;
  77683. if (input.read (&c, 1) != 1
  77684. || readLZWByte (true, c) < 0)
  77685. return false;
  77686. if (transparent >= 0)
  77687. {
  77688. palette [transparent][0] = 0;
  77689. palette [transparent][1] = 0;
  77690. palette [transparent][2] = 0;
  77691. palette [transparent][3] = 0;
  77692. }
  77693. int index;
  77694. int xpos = 0, ypos = 0, pass = 0;
  77695. const Image::BitmapData destData (image, true);
  77696. uint8* p = destData.data;
  77697. const bool hasAlpha = image.hasAlphaChannel();
  77698. while ((index = readLZWByte (false, c)) >= 0)
  77699. {
  77700. const uint8* const paletteEntry = palette [index];
  77701. if (hasAlpha)
  77702. {
  77703. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77704. paletteEntry[0],
  77705. paletteEntry[1],
  77706. paletteEntry[2]);
  77707. ((PixelARGB*) p)->premultiply();
  77708. }
  77709. else
  77710. {
  77711. ((PixelRGB*) p)->setARGB (0,
  77712. paletteEntry[0],
  77713. paletteEntry[1],
  77714. paletteEntry[2]);
  77715. }
  77716. p += destData.pixelStride;
  77717. ++xpos;
  77718. if (xpos == destData.width)
  77719. {
  77720. xpos = 0;
  77721. if (interlace)
  77722. {
  77723. switch (pass)
  77724. {
  77725. case 0:
  77726. case 1: ypos += 8; break;
  77727. case 2: ypos += 4; break;
  77728. case 3: ypos += 2; break;
  77729. }
  77730. while (ypos >= destData.height)
  77731. {
  77732. ++pass;
  77733. switch (pass)
  77734. {
  77735. case 1: ypos = 4; break;
  77736. case 2: ypos = 2; break;
  77737. case 3: ypos = 1; break;
  77738. default: return true;
  77739. }
  77740. }
  77741. }
  77742. else
  77743. {
  77744. ++ypos;
  77745. }
  77746. p = destData.getPixelPointer (xpos, ypos);
  77747. }
  77748. if (ypos >= destData.height)
  77749. break;
  77750. }
  77751. return true;
  77752. }
  77753. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77754. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  77755. };
  77756. #endif
  77757. GIFImageFormat::GIFImageFormat() {}
  77758. GIFImageFormat::~GIFImageFormat() {}
  77759. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77760. bool GIFImageFormat::canUnderstand (InputStream& in)
  77761. {
  77762. char header [4];
  77763. return (in.read (header, sizeof (header)) == sizeof (header))
  77764. && header[0] == 'G'
  77765. && header[1] == 'I'
  77766. && header[2] == 'F';
  77767. }
  77768. const Image GIFImageFormat::decodeImage (InputStream& in)
  77769. {
  77770. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77771. return juce_loadWithCoreImage (in);
  77772. #else
  77773. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77774. return loader->image;
  77775. #endif
  77776. }
  77777. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77778. {
  77779. jassertfalse; // writing isn't implemented for GIFs!
  77780. return false;
  77781. }
  77782. END_JUCE_NAMESPACE
  77783. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77784. #endif
  77785. //==============================================================================
  77786. // some files include lots of library code, so leave them to the end to avoid cluttering
  77787. // up the build for the clean files.
  77788. #if JUCE_BUILD_CORE
  77789. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77790. namespace zlibNamespace
  77791. {
  77792. #if JUCE_INCLUDE_ZLIB_CODE
  77793. #undef OS_CODE
  77794. #undef fdopen
  77795. /*** Start of inlined file: zlib.h ***/
  77796. #ifndef ZLIB_H
  77797. #define ZLIB_H
  77798. /*** Start of inlined file: zconf.h ***/
  77799. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77800. #ifndef ZCONF_H
  77801. #define ZCONF_H
  77802. // *** Just a few hacks here to make it compile nicely with Juce..
  77803. #define Z_PREFIX 1
  77804. #undef __MACTYPES__
  77805. #ifdef _MSC_VER
  77806. #pragma warning (disable : 4131 4127 4244 4267)
  77807. #endif
  77808. /*
  77809. * If you *really* need a unique prefix for all types and library functions,
  77810. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77811. */
  77812. #ifdef Z_PREFIX
  77813. # define deflateInit_ z_deflateInit_
  77814. # define deflate z_deflate
  77815. # define deflateEnd z_deflateEnd
  77816. # define inflateInit_ z_inflateInit_
  77817. # define inflate z_inflate
  77818. # define inflateEnd z_inflateEnd
  77819. # define inflatePrime z_inflatePrime
  77820. # define inflateGetHeader z_inflateGetHeader
  77821. # define adler32_combine z_adler32_combine
  77822. # define crc32_combine z_crc32_combine
  77823. # define deflateInit2_ z_deflateInit2_
  77824. # define deflateSetDictionary z_deflateSetDictionary
  77825. # define deflateCopy z_deflateCopy
  77826. # define deflateReset z_deflateReset
  77827. # define deflateParams z_deflateParams
  77828. # define deflateBound z_deflateBound
  77829. # define deflatePrime z_deflatePrime
  77830. # define inflateInit2_ z_inflateInit2_
  77831. # define inflateSetDictionary z_inflateSetDictionary
  77832. # define inflateSync z_inflateSync
  77833. # define inflateSyncPoint z_inflateSyncPoint
  77834. # define inflateCopy z_inflateCopy
  77835. # define inflateReset z_inflateReset
  77836. # define inflateBack z_inflateBack
  77837. # define inflateBackEnd z_inflateBackEnd
  77838. # define compress z_compress
  77839. # define compress2 z_compress2
  77840. # define compressBound z_compressBound
  77841. # define uncompress z_uncompress
  77842. # define adler32 z_adler32
  77843. # define crc32 z_crc32
  77844. # define get_crc_table z_get_crc_table
  77845. # define zError z_zError
  77846. # define alloc_func z_alloc_func
  77847. # define free_func z_free_func
  77848. # define in_func z_in_func
  77849. # define out_func z_out_func
  77850. # define Byte z_Byte
  77851. # define uInt z_uInt
  77852. # define uLong z_uLong
  77853. # define Bytef z_Bytef
  77854. # define charf z_charf
  77855. # define intf z_intf
  77856. # define uIntf z_uIntf
  77857. # define uLongf z_uLongf
  77858. # define voidpf z_voidpf
  77859. # define voidp z_voidp
  77860. #endif
  77861. #if defined(__MSDOS__) && !defined(MSDOS)
  77862. # define MSDOS
  77863. #endif
  77864. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77865. # define OS2
  77866. #endif
  77867. #if defined(_WINDOWS) && !defined(WINDOWS)
  77868. # define WINDOWS
  77869. #endif
  77870. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77871. # ifndef WIN32
  77872. # define WIN32
  77873. # endif
  77874. #endif
  77875. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77876. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77877. # ifndef SYS16BIT
  77878. # define SYS16BIT
  77879. # endif
  77880. # endif
  77881. #endif
  77882. /*
  77883. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77884. * than 64k bytes at a time (needed on systems with 16-bit int).
  77885. */
  77886. #ifdef SYS16BIT
  77887. # define MAXSEG_64K
  77888. #endif
  77889. #ifdef MSDOS
  77890. # define UNALIGNED_OK
  77891. #endif
  77892. #ifdef __STDC_VERSION__
  77893. # ifndef STDC
  77894. # define STDC
  77895. # endif
  77896. # if __STDC_VERSION__ >= 199901L
  77897. # ifndef STDC99
  77898. # define STDC99
  77899. # endif
  77900. # endif
  77901. #endif
  77902. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77903. # define STDC
  77904. #endif
  77905. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77906. # define STDC
  77907. #endif
  77908. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77909. # define STDC
  77910. #endif
  77911. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77912. # define STDC
  77913. #endif
  77914. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77915. # define STDC
  77916. #endif
  77917. #ifndef STDC
  77918. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77919. # define const /* note: need a more gentle solution here */
  77920. # endif
  77921. #endif
  77922. /* Some Mac compilers merge all .h files incorrectly: */
  77923. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77924. # define NO_DUMMY_DECL
  77925. #endif
  77926. /* Maximum value for memLevel in deflateInit2 */
  77927. #ifndef MAX_MEM_LEVEL
  77928. # ifdef MAXSEG_64K
  77929. # define MAX_MEM_LEVEL 8
  77930. # else
  77931. # define MAX_MEM_LEVEL 9
  77932. # endif
  77933. #endif
  77934. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77935. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77936. * created by gzip. (Files created by minigzip can still be extracted by
  77937. * gzip.)
  77938. */
  77939. #ifndef MAX_WBITS
  77940. # define MAX_WBITS 15 /* 32K LZ77 window */
  77941. #endif
  77942. /* The memory requirements for deflate are (in bytes):
  77943. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77944. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77945. plus a few kilobytes for small objects. For example, if you want to reduce
  77946. the default memory requirements from 256K to 128K, compile with
  77947. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77948. Of course this will generally degrade compression (there's no free lunch).
  77949. The memory requirements for inflate are (in bytes) 1 << windowBits
  77950. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77951. for small objects.
  77952. */
  77953. /* Type declarations */
  77954. #ifndef OF /* function prototypes */
  77955. # ifdef STDC
  77956. # define OF(args) args
  77957. # else
  77958. # define OF(args) ()
  77959. # endif
  77960. #endif
  77961. /* The following definitions for FAR are needed only for MSDOS mixed
  77962. * model programming (small or medium model with some far allocations).
  77963. * This was tested only with MSC; for other MSDOS compilers you may have
  77964. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77965. * just define FAR to be empty.
  77966. */
  77967. #ifdef SYS16BIT
  77968. # if defined(M_I86SM) || defined(M_I86MM)
  77969. /* MSC small or medium model */
  77970. # define SMALL_MEDIUM
  77971. # ifdef _MSC_VER
  77972. # define FAR _far
  77973. # else
  77974. # define FAR far
  77975. # endif
  77976. # endif
  77977. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77978. /* Turbo C small or medium model */
  77979. # define SMALL_MEDIUM
  77980. # ifdef __BORLANDC__
  77981. # define FAR _far
  77982. # else
  77983. # define FAR far
  77984. # endif
  77985. # endif
  77986. #endif
  77987. #if defined(WINDOWS) || defined(WIN32)
  77988. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77989. * This is not mandatory, but it offers a little performance increase.
  77990. */
  77991. # ifdef ZLIB_DLL
  77992. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77993. # ifdef ZLIB_INTERNAL
  77994. # define ZEXTERN extern __declspec(dllexport)
  77995. # else
  77996. # define ZEXTERN extern __declspec(dllimport)
  77997. # endif
  77998. # endif
  77999. # endif /* ZLIB_DLL */
  78000. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78001. * define ZLIB_WINAPI.
  78002. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78003. */
  78004. # ifdef ZLIB_WINAPI
  78005. # ifdef FAR
  78006. # undef FAR
  78007. # endif
  78008. # include <windows.h>
  78009. /* No need for _export, use ZLIB.DEF instead. */
  78010. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78011. # define ZEXPORT WINAPI
  78012. # ifdef WIN32
  78013. # define ZEXPORTVA WINAPIV
  78014. # else
  78015. # define ZEXPORTVA FAR CDECL
  78016. # endif
  78017. # endif
  78018. #endif
  78019. #if defined (__BEOS__)
  78020. # ifdef ZLIB_DLL
  78021. # ifdef ZLIB_INTERNAL
  78022. # define ZEXPORT __declspec(dllexport)
  78023. # define ZEXPORTVA __declspec(dllexport)
  78024. # else
  78025. # define ZEXPORT __declspec(dllimport)
  78026. # define ZEXPORTVA __declspec(dllimport)
  78027. # endif
  78028. # endif
  78029. #endif
  78030. #ifndef ZEXTERN
  78031. # define ZEXTERN extern
  78032. #endif
  78033. #ifndef ZEXPORT
  78034. # define ZEXPORT
  78035. #endif
  78036. #ifndef ZEXPORTVA
  78037. # define ZEXPORTVA
  78038. #endif
  78039. #ifndef FAR
  78040. # define FAR
  78041. #endif
  78042. #if !defined(__MACTYPES__)
  78043. typedef unsigned char Byte; /* 8 bits */
  78044. #endif
  78045. typedef unsigned int uInt; /* 16 bits or more */
  78046. typedef unsigned long uLong; /* 32 bits or more */
  78047. #ifdef SMALL_MEDIUM
  78048. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78049. # define Bytef Byte FAR
  78050. #else
  78051. typedef Byte FAR Bytef;
  78052. #endif
  78053. typedef char FAR charf;
  78054. typedef int FAR intf;
  78055. typedef uInt FAR uIntf;
  78056. typedef uLong FAR uLongf;
  78057. #ifdef STDC
  78058. typedef void const *voidpc;
  78059. typedef void FAR *voidpf;
  78060. typedef void *voidp;
  78061. #else
  78062. typedef Byte const *voidpc;
  78063. typedef Byte FAR *voidpf;
  78064. typedef Byte *voidp;
  78065. #endif
  78066. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78067. # include <sys/types.h> /* for off_t */
  78068. # include <unistd.h> /* for SEEK_* and off_t */
  78069. # ifdef VMS
  78070. # include <unixio.h> /* for off_t */
  78071. # endif
  78072. # define z_off_t off_t
  78073. #endif
  78074. #ifndef SEEK_SET
  78075. # define SEEK_SET 0 /* Seek from beginning of file. */
  78076. # define SEEK_CUR 1 /* Seek from current position. */
  78077. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78078. #endif
  78079. #ifndef z_off_t
  78080. # define z_off_t long
  78081. #endif
  78082. #if defined(__OS400__)
  78083. # define NO_vsnprintf
  78084. #endif
  78085. #if defined(__MVS__)
  78086. # define NO_vsnprintf
  78087. # ifdef FAR
  78088. # undef FAR
  78089. # endif
  78090. #endif
  78091. /* MVS linker does not support external names larger than 8 bytes */
  78092. #if defined(__MVS__)
  78093. # pragma map(deflateInit_,"DEIN")
  78094. # pragma map(deflateInit2_,"DEIN2")
  78095. # pragma map(deflateEnd,"DEEND")
  78096. # pragma map(deflateBound,"DEBND")
  78097. # pragma map(inflateInit_,"ININ")
  78098. # pragma map(inflateInit2_,"ININ2")
  78099. # pragma map(inflateEnd,"INEND")
  78100. # pragma map(inflateSync,"INSY")
  78101. # pragma map(inflateSetDictionary,"INSEDI")
  78102. # pragma map(compressBound,"CMBND")
  78103. # pragma map(inflate_table,"INTABL")
  78104. # pragma map(inflate_fast,"INFA")
  78105. # pragma map(inflate_copyright,"INCOPY")
  78106. #endif
  78107. #endif /* ZCONF_H */
  78108. /*** End of inlined file: zconf.h ***/
  78109. #ifdef __cplusplus
  78110. //extern "C" {
  78111. #endif
  78112. #define ZLIB_VERSION "1.2.3"
  78113. #define ZLIB_VERNUM 0x1230
  78114. /*
  78115. The 'zlib' compression library provides in-memory compression and
  78116. decompression functions, including integrity checks of the uncompressed
  78117. data. This version of the library supports only one compression method
  78118. (deflation) but other algorithms will be added later and will have the same
  78119. stream interface.
  78120. Compression can be done in a single step if the buffers are large
  78121. enough (for example if an input file is mmap'ed), or can be done by
  78122. repeated calls of the compression function. In the latter case, the
  78123. application must provide more input and/or consume the output
  78124. (providing more output space) before each call.
  78125. The compressed data format used by default by the in-memory functions is
  78126. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78127. around a deflate stream, which is itself documented in RFC 1951.
  78128. The library also supports reading and writing files in gzip (.gz) format
  78129. with an interface similar to that of stdio using the functions that start
  78130. with "gz". The gzip format is different from the zlib format. gzip is a
  78131. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78132. This library can optionally read and write gzip streams in memory as well.
  78133. The zlib format was designed to be compact and fast for use in memory
  78134. and on communications channels. The gzip format was designed for single-
  78135. file compression on file systems, has a larger header than zlib to maintain
  78136. directory information, and uses a different, slower check method than zlib.
  78137. The library does not install any signal handler. The decoder checks
  78138. the consistency of the compressed data, so the library should never
  78139. crash even in case of corrupted input.
  78140. */
  78141. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78142. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78143. struct internal_state;
  78144. typedef struct z_stream_s {
  78145. Bytef *next_in; /* next input byte */
  78146. uInt avail_in; /* number of bytes available at next_in */
  78147. uLong total_in; /* total nb of input bytes read so far */
  78148. Bytef *next_out; /* next output byte should be put there */
  78149. uInt avail_out; /* remaining free space at next_out */
  78150. uLong total_out; /* total nb of bytes output so far */
  78151. char *msg; /* last error message, NULL if no error */
  78152. struct internal_state FAR *state; /* not visible by applications */
  78153. alloc_func zalloc; /* used to allocate the internal state */
  78154. free_func zfree; /* used to free the internal state */
  78155. voidpf opaque; /* private data object passed to zalloc and zfree */
  78156. int data_type; /* best guess about the data type: binary or text */
  78157. uLong adler; /* adler32 value of the uncompressed data */
  78158. uLong reserved; /* reserved for future use */
  78159. } z_stream;
  78160. typedef z_stream FAR *z_streamp;
  78161. /*
  78162. gzip header information passed to and from zlib routines. See RFC 1952
  78163. for more details on the meanings of these fields.
  78164. */
  78165. typedef struct gz_header_s {
  78166. int text; /* true if compressed data believed to be text */
  78167. uLong time; /* modification time */
  78168. int xflags; /* extra flags (not used when writing a gzip file) */
  78169. int os; /* operating system */
  78170. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78171. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78172. uInt extra_max; /* space at extra (only when reading header) */
  78173. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78174. uInt name_max; /* space at name (only when reading header) */
  78175. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78176. uInt comm_max; /* space at comment (only when reading header) */
  78177. int hcrc; /* true if there was or will be a header crc */
  78178. int done; /* true when done reading gzip header (not used
  78179. when writing a gzip file) */
  78180. } gz_header;
  78181. typedef gz_header FAR *gz_headerp;
  78182. /*
  78183. The application must update next_in and avail_in when avail_in has
  78184. dropped to zero. It must update next_out and avail_out when avail_out
  78185. has dropped to zero. The application must initialize zalloc, zfree and
  78186. opaque before calling the init function. All other fields are set by the
  78187. compression library and must not be updated by the application.
  78188. The opaque value provided by the application will be passed as the first
  78189. parameter for calls of zalloc and zfree. This can be useful for custom
  78190. memory management. The compression library attaches no meaning to the
  78191. opaque value.
  78192. zalloc must return Z_NULL if there is not enough memory for the object.
  78193. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78194. thread safe.
  78195. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78196. exactly 65536 bytes, but will not be required to allocate more than this
  78197. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78198. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78199. have their offset normalized to zero. The default allocation function
  78200. provided by this library ensures this (see zutil.c). To reduce memory
  78201. requirements and avoid any allocation of 64K objects, at the expense of
  78202. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78203. The fields total_in and total_out can be used for statistics or
  78204. progress reports. After compression, total_in holds the total size of
  78205. the uncompressed data and may be saved for use in the decompressor
  78206. (particularly if the decompressor wants to decompress everything in
  78207. a single step).
  78208. */
  78209. /* constants */
  78210. #define Z_NO_FLUSH 0
  78211. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78212. #define Z_SYNC_FLUSH 2
  78213. #define Z_FULL_FLUSH 3
  78214. #define Z_FINISH 4
  78215. #define Z_BLOCK 5
  78216. /* Allowed flush values; see deflate() and inflate() below for details */
  78217. #define Z_OK 0
  78218. #define Z_STREAM_END 1
  78219. #define Z_NEED_DICT 2
  78220. #define Z_ERRNO (-1)
  78221. #define Z_STREAM_ERROR (-2)
  78222. #define Z_DATA_ERROR (-3)
  78223. #define Z_MEM_ERROR (-4)
  78224. #define Z_BUF_ERROR (-5)
  78225. #define Z_VERSION_ERROR (-6)
  78226. /* Return codes for the compression/decompression functions. Negative
  78227. * values are errors, positive values are used for special but normal events.
  78228. */
  78229. #define Z_NO_COMPRESSION 0
  78230. #define Z_BEST_SPEED 1
  78231. #define Z_BEST_COMPRESSION 9
  78232. #define Z_DEFAULT_COMPRESSION (-1)
  78233. /* compression levels */
  78234. #define Z_FILTERED 1
  78235. #define Z_HUFFMAN_ONLY 2
  78236. #define Z_RLE 3
  78237. #define Z_FIXED 4
  78238. #define Z_DEFAULT_STRATEGY 0
  78239. /* compression strategy; see deflateInit2() below for details */
  78240. #define Z_BINARY 0
  78241. #define Z_TEXT 1
  78242. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78243. #define Z_UNKNOWN 2
  78244. /* Possible values of the data_type field (though see inflate()) */
  78245. #define Z_DEFLATED 8
  78246. /* The deflate compression method (the only one supported in this version) */
  78247. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78248. #define zlib_version zlibVersion()
  78249. /* for compatibility with versions < 1.0.2 */
  78250. /* basic functions */
  78251. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78252. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78253. If the first character differs, the library code actually used is
  78254. not compatible with the zlib.h header file used by the application.
  78255. This check is automatically made by deflateInit and inflateInit.
  78256. */
  78257. /*
  78258. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78259. Initializes the internal stream state for compression. The fields
  78260. zalloc, zfree and opaque must be initialized before by the caller.
  78261. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78262. use default allocation functions.
  78263. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78264. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78265. all (the input data is simply copied a block at a time).
  78266. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78267. compression (currently equivalent to level 6).
  78268. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78269. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78270. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78271. with the version assumed by the caller (ZLIB_VERSION).
  78272. msg is set to null if there is no error message. deflateInit does not
  78273. perform any compression: this will be done by deflate().
  78274. */
  78275. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78276. /*
  78277. deflate compresses as much data as possible, and stops when the input
  78278. buffer becomes empty or the output buffer becomes full. It may introduce some
  78279. output latency (reading input without producing any output) except when
  78280. forced to flush.
  78281. The detailed semantics are as follows. deflate performs one or both of the
  78282. following actions:
  78283. - Compress more input starting at next_in and update next_in and avail_in
  78284. accordingly. If not all input can be processed (because there is not
  78285. enough room in the output buffer), next_in and avail_in are updated and
  78286. processing will resume at this point for the next call of deflate().
  78287. - Provide more output starting at next_out and update next_out and avail_out
  78288. accordingly. This action is forced if the parameter flush is non zero.
  78289. Forcing flush frequently degrades the compression ratio, so this parameter
  78290. should be set only when necessary (in interactive applications).
  78291. Some output may be provided even if flush is not set.
  78292. Before the call of deflate(), the application should ensure that at least
  78293. one of the actions is possible, by providing more input and/or consuming
  78294. more output, and updating avail_in or avail_out accordingly; avail_out
  78295. should never be zero before the call. The application can consume the
  78296. compressed output when it wants, for example when the output buffer is full
  78297. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78298. and with zero avail_out, it must be called again after making room in the
  78299. output buffer because there might be more output pending.
  78300. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78301. decide how much data to accumualte before producing output, in order to
  78302. maximize compression.
  78303. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78304. flushed to the output buffer and the output is aligned on a byte boundary, so
  78305. that the decompressor can get all input data available so far. (In particular
  78306. avail_in is zero after the call if enough output space has been provided
  78307. before the call.) Flushing may degrade compression for some compression
  78308. algorithms and so it should be used only when necessary.
  78309. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78310. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78311. restart from this point if previous compressed data has been damaged or if
  78312. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78313. compression.
  78314. If deflate returns with avail_out == 0, this function must be called again
  78315. with the same value of the flush parameter and more output space (updated
  78316. avail_out), until the flush is complete (deflate returns with non-zero
  78317. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78318. avail_out is greater than six to avoid repeated flush markers due to
  78319. avail_out == 0 on return.
  78320. If the parameter flush is set to Z_FINISH, pending input is processed,
  78321. pending output is flushed and deflate returns with Z_STREAM_END if there
  78322. was enough output space; if deflate returns with Z_OK, this function must be
  78323. called again with Z_FINISH and more output space (updated avail_out) but no
  78324. more input data, until it returns with Z_STREAM_END or an error. After
  78325. deflate has returned Z_STREAM_END, the only possible operations on the
  78326. stream are deflateReset or deflateEnd.
  78327. Z_FINISH can be used immediately after deflateInit if all the compression
  78328. is to be done in a single step. In this case, avail_out must be at least
  78329. the value returned by deflateBound (see below). If deflate does not return
  78330. Z_STREAM_END, then it must be called again as described above.
  78331. deflate() sets strm->adler to the adler32 checksum of all input read
  78332. so far (that is, total_in bytes).
  78333. deflate() may update strm->data_type if it can make a good guess about
  78334. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78335. binary. This field is only for information purposes and does not affect
  78336. the compression algorithm in any manner.
  78337. deflate() returns Z_OK if some progress has been made (more input
  78338. processed or more output produced), Z_STREAM_END if all input has been
  78339. consumed and all output has been produced (only when flush is set to
  78340. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78341. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78342. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78343. fatal, and deflate() can be called again with more input and more output
  78344. space to continue compressing.
  78345. */
  78346. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78347. /*
  78348. All dynamically allocated data structures for this stream are freed.
  78349. This function discards any unprocessed input and does not flush any
  78350. pending output.
  78351. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78352. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78353. prematurely (some input or output was discarded). In the error case,
  78354. msg may be set but then points to a static string (which must not be
  78355. deallocated).
  78356. */
  78357. /*
  78358. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78359. Initializes the internal stream state for decompression. The fields
  78360. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78361. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78362. value depends on the compression method), inflateInit determines the
  78363. compression method from the zlib header and allocates all data structures
  78364. accordingly; otherwise the allocation will be deferred to the first call of
  78365. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78366. use default allocation functions.
  78367. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78368. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78369. version assumed by the caller. msg is set to null if there is no error
  78370. message. inflateInit does not perform any decompression apart from reading
  78371. the zlib header if present: this will be done by inflate(). (So next_in and
  78372. avail_in may be modified, but next_out and avail_out are unchanged.)
  78373. */
  78374. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78375. /*
  78376. inflate decompresses as much data as possible, and stops when the input
  78377. buffer becomes empty or the output buffer becomes full. It may introduce
  78378. some output latency (reading input without producing any output) except when
  78379. forced to flush.
  78380. The detailed semantics are as follows. inflate performs one or both of the
  78381. following actions:
  78382. - Decompress more input starting at next_in and update next_in and avail_in
  78383. accordingly. If not all input can be processed (because there is not
  78384. enough room in the output buffer), next_in is updated and processing
  78385. will resume at this point for the next call of inflate().
  78386. - Provide more output starting at next_out and update next_out and avail_out
  78387. accordingly. inflate() provides as much output as possible, until there
  78388. is no more input data or no more space in the output buffer (see below
  78389. about the flush parameter).
  78390. Before the call of inflate(), the application should ensure that at least
  78391. one of the actions is possible, by providing more input and/or consuming
  78392. more output, and updating the next_* and avail_* values accordingly.
  78393. The application can consume the uncompressed output when it wants, for
  78394. example when the output buffer is full (avail_out == 0), or after each
  78395. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78396. must be called again after making room in the output buffer because there
  78397. might be more output pending.
  78398. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78399. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78400. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78401. if and when it gets to the next deflate block boundary. When decoding the
  78402. zlib or gzip format, this will cause inflate() to return immediately after
  78403. the header and before the first block. When doing a raw inflate, inflate()
  78404. will go ahead and process the first block, and will return when it gets to
  78405. the end of that block, or when it runs out of data.
  78406. The Z_BLOCK option assists in appending to or combining deflate streams.
  78407. Also to assist in this, on return inflate() will set strm->data_type to the
  78408. number of unused bits in the last byte taken from strm->next_in, plus 64
  78409. if inflate() is currently decoding the last block in the deflate stream,
  78410. plus 128 if inflate() returned immediately after decoding an end-of-block
  78411. code or decoding the complete header up to just before the first byte of the
  78412. deflate stream. The end-of-block will not be indicated until all of the
  78413. uncompressed data from that block has been written to strm->next_out. The
  78414. number of unused bits may in general be greater than seven, except when
  78415. bit 7 of data_type is set, in which case the number of unused bits will be
  78416. less than eight.
  78417. inflate() should normally be called until it returns Z_STREAM_END or an
  78418. error. However if all decompression is to be performed in a single step
  78419. (a single call of inflate), the parameter flush should be set to
  78420. Z_FINISH. In this case all pending input is processed and all pending
  78421. output is flushed; avail_out must be large enough to hold all the
  78422. uncompressed data. (The size of the uncompressed data may have been saved
  78423. by the compressor for this purpose.) The next operation on this stream must
  78424. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78425. is never required, but can be used to inform inflate that a faster approach
  78426. may be used for the single inflate() call.
  78427. In this implementation, inflate() always flushes as much output as
  78428. possible to the output buffer, and always uses the faster approach on the
  78429. first call. So the only effect of the flush parameter in this implementation
  78430. is on the return value of inflate(), as noted below, or when it returns early
  78431. because Z_BLOCK is used.
  78432. If a preset dictionary is needed after this call (see inflateSetDictionary
  78433. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78434. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78435. strm->adler to the adler32 checksum of all output produced so far (that is,
  78436. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78437. below. At the end of the stream, inflate() checks that its computed adler32
  78438. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78439. only if the checksum is correct.
  78440. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78441. deflate data. The header type is detected automatically. Any information
  78442. contained in the gzip header is not retained, so applications that need that
  78443. information should instead use raw inflate, see inflateInit2() below, or
  78444. inflateBack() and perform their own processing of the gzip header and
  78445. trailer.
  78446. inflate() returns Z_OK if some progress has been made (more input processed
  78447. or more output produced), Z_STREAM_END if the end of the compressed data has
  78448. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78449. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78450. corrupted (input stream not conforming to the zlib format or incorrect check
  78451. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78452. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78453. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78454. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78455. inflate() can be called again with more input and more output space to
  78456. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78457. call inflateSync() to look for a good compression block if a partial recovery
  78458. of the data is desired.
  78459. */
  78460. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78461. /*
  78462. All dynamically allocated data structures for this stream are freed.
  78463. This function discards any unprocessed input and does not flush any
  78464. pending output.
  78465. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78466. was inconsistent. In the error case, msg may be set but then points to a
  78467. static string (which must not be deallocated).
  78468. */
  78469. /* Advanced functions */
  78470. /*
  78471. The following functions are needed only in some special applications.
  78472. */
  78473. /*
  78474. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78475. int level,
  78476. int method,
  78477. int windowBits,
  78478. int memLevel,
  78479. int strategy));
  78480. This is another version of deflateInit with more compression options. The
  78481. fields next_in, zalloc, zfree and opaque must be initialized before by
  78482. the caller.
  78483. The method parameter is the compression method. It must be Z_DEFLATED in
  78484. this version of the library.
  78485. The windowBits parameter is the base two logarithm of the window size
  78486. (the size of the history buffer). It should be in the range 8..15 for this
  78487. version of the library. Larger values of this parameter result in better
  78488. compression at the expense of memory usage. The default value is 15 if
  78489. deflateInit is used instead.
  78490. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78491. determines the window size. deflate() will then generate raw deflate data
  78492. with no zlib header or trailer, and will not compute an adler32 check value.
  78493. windowBits can also be greater than 15 for optional gzip encoding. Add
  78494. 16 to windowBits to write a simple gzip header and trailer around the
  78495. compressed data instead of a zlib wrapper. The gzip header will have no
  78496. file name, no extra data, no comment, no modification time (set to zero),
  78497. no header crc, and the operating system will be set to 255 (unknown). If a
  78498. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78499. The memLevel parameter specifies how much memory should be allocated
  78500. for the internal compression state. memLevel=1 uses minimum memory but
  78501. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78502. for optimal speed. The default value is 8. See zconf.h for total memory
  78503. usage as a function of windowBits and memLevel.
  78504. The strategy parameter is used to tune the compression algorithm. Use the
  78505. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78506. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78507. string match), or Z_RLE to limit match distances to one (run-length
  78508. encoding). Filtered data consists mostly of small values with a somewhat
  78509. random distribution. In this case, the compression algorithm is tuned to
  78510. compress them better. The effect of Z_FILTERED is to force more Huffman
  78511. coding and less string matching; it is somewhat intermediate between
  78512. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78513. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78514. parameter only affects the compression ratio but not the correctness of the
  78515. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78516. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78517. applications.
  78518. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78519. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78520. method). msg is set to null if there is no error message. deflateInit2 does
  78521. not perform any compression: this will be done by deflate().
  78522. */
  78523. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78524. const Bytef *dictionary,
  78525. uInt dictLength));
  78526. /*
  78527. Initializes the compression dictionary from the given byte sequence
  78528. without producing any compressed output. This function must be called
  78529. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78530. call of deflate. The compressor and decompressor must use exactly the same
  78531. dictionary (see inflateSetDictionary).
  78532. The dictionary should consist of strings (byte sequences) that are likely
  78533. to be encountered later in the data to be compressed, with the most commonly
  78534. used strings preferably put towards the end of the dictionary. Using a
  78535. dictionary is most useful when the data to be compressed is short and can be
  78536. predicted with good accuracy; the data can then be compressed better than
  78537. with the default empty dictionary.
  78538. Depending on the size of the compression data structures selected by
  78539. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78540. discarded, for example if the dictionary is larger than the window size in
  78541. deflate or deflate2. Thus the strings most likely to be useful should be
  78542. put at the end of the dictionary, not at the front. In addition, the
  78543. current implementation of deflate will use at most the window size minus
  78544. 262 bytes of the provided dictionary.
  78545. Upon return of this function, strm->adler is set to the adler32 value
  78546. of the dictionary; the decompressor may later use this value to determine
  78547. which dictionary has been used by the compressor. (The adler32 value
  78548. applies to the whole dictionary even if only a subset of the dictionary is
  78549. actually used by the compressor.) If a raw deflate was requested, then the
  78550. adler32 value is not computed and strm->adler is not set.
  78551. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78552. parameter is invalid (such as NULL dictionary) or the stream state is
  78553. inconsistent (for example if deflate has already been called for this stream
  78554. or if the compression method is bsort). deflateSetDictionary does not
  78555. perform any compression: this will be done by deflate().
  78556. */
  78557. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78558. z_streamp source));
  78559. /*
  78560. Sets the destination stream as a complete copy of the source stream.
  78561. This function can be useful when several compression strategies will be
  78562. tried, for example when there are several ways of pre-processing the input
  78563. data with a filter. The streams that will be discarded should then be freed
  78564. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78565. compression state which can be quite large, so this strategy is slow and
  78566. can consume lots of memory.
  78567. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78568. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78569. (such as zalloc being NULL). msg is left unchanged in both source and
  78570. destination.
  78571. */
  78572. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78573. /*
  78574. This function is equivalent to deflateEnd followed by deflateInit,
  78575. but does not free and reallocate all the internal compression state.
  78576. The stream will keep the same compression level and any other attributes
  78577. that may have been set by deflateInit2.
  78578. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78579. stream state was inconsistent (such as zalloc or state being NULL).
  78580. */
  78581. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78582. int level,
  78583. int strategy));
  78584. /*
  78585. Dynamically update the compression level and compression strategy. The
  78586. interpretation of level and strategy is as in deflateInit2. This can be
  78587. used to switch between compression and straight copy of the input data, or
  78588. to switch to a different kind of input data requiring a different
  78589. strategy. If the compression level is changed, the input available so far
  78590. is compressed with the old level (and may be flushed); the new level will
  78591. take effect only at the next call of deflate().
  78592. Before the call of deflateParams, the stream state must be set as for
  78593. a call of deflate(), since the currently available input may have to
  78594. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78595. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78596. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78597. if strm->avail_out was zero.
  78598. */
  78599. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78600. int good_length,
  78601. int max_lazy,
  78602. int nice_length,
  78603. int max_chain));
  78604. /*
  78605. Fine tune deflate's internal compression parameters. This should only be
  78606. used by someone who understands the algorithm used by zlib's deflate for
  78607. searching for the best matching string, and even then only by the most
  78608. fanatic optimizer trying to squeeze out the last compressed bit for their
  78609. specific input data. Read the deflate.c source code for the meaning of the
  78610. max_lazy, good_length, nice_length, and max_chain parameters.
  78611. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78612. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78613. */
  78614. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78615. uLong sourceLen));
  78616. /*
  78617. deflateBound() returns an upper bound on the compressed size after
  78618. deflation of sourceLen bytes. It must be called after deflateInit()
  78619. or deflateInit2(). This would be used to allocate an output buffer
  78620. for deflation in a single pass, and so would be called before deflate().
  78621. */
  78622. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78623. int bits,
  78624. int value));
  78625. /*
  78626. deflatePrime() inserts bits in the deflate output stream. The intent
  78627. is that this function is used to start off the deflate output with the
  78628. bits leftover from a previous deflate stream when appending to it. As such,
  78629. this function can only be used for raw deflate, and must be used before the
  78630. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78631. less than or equal to 16, and that many of the least significant bits of
  78632. value will be inserted in the output.
  78633. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78634. stream state was inconsistent.
  78635. */
  78636. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78637. gz_headerp head));
  78638. /*
  78639. deflateSetHeader() provides gzip header information for when a gzip
  78640. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78641. after deflateInit2() or deflateReset() and before the first call of
  78642. deflate(). The text, time, os, extra field, name, and comment information
  78643. in the provided gz_header structure are written to the gzip header (xflag is
  78644. ignored -- the extra flags are set according to the compression level). The
  78645. caller must assure that, if not Z_NULL, name and comment are terminated with
  78646. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78647. available there. If hcrc is true, a gzip header crc is included. Note that
  78648. the current versions of the command-line version of gzip (up through version
  78649. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78650. gzip file" and give up.
  78651. If deflateSetHeader is not used, the default gzip header has text false,
  78652. the time set to zero, and os set to 255, with no extra, name, or comment
  78653. fields. The gzip header is returned to the default state by deflateReset().
  78654. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78655. stream state was inconsistent.
  78656. */
  78657. /*
  78658. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78659. int windowBits));
  78660. This is another version of inflateInit with an extra parameter. The
  78661. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78662. before by the caller.
  78663. The windowBits parameter is the base two logarithm of the maximum window
  78664. size (the size of the history buffer). It should be in the range 8..15 for
  78665. this version of the library. The default value is 15 if inflateInit is used
  78666. instead. windowBits must be greater than or equal to the windowBits value
  78667. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78668. deflateInit2() was not used. If a compressed stream with a larger window
  78669. size is given as input, inflate() will return with the error code
  78670. Z_DATA_ERROR instead of trying to allocate a larger window.
  78671. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78672. determines the window size. inflate() will then process raw deflate data,
  78673. not looking for a zlib or gzip header, not generating a check value, and not
  78674. looking for any check values for comparison at the end of the stream. This
  78675. is for use with other formats that use the deflate compressed data format
  78676. such as zip. Those formats provide their own check values. If a custom
  78677. format is developed using the raw deflate format for compressed data, it is
  78678. recommended that a check value such as an adler32 or a crc32 be applied to
  78679. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78680. most applications, the zlib format should be used as is. Note that comments
  78681. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78682. windowBits can also be greater than 15 for optional gzip decoding. Add
  78683. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78684. detection, or add 16 to decode only the gzip format (the zlib format will
  78685. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78686. a crc32 instead of an adler32.
  78687. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78688. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78689. is set to null if there is no error message. inflateInit2 does not perform
  78690. any decompression apart from reading the zlib header if present: this will
  78691. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78692. and avail_out are unchanged.)
  78693. */
  78694. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78695. const Bytef *dictionary,
  78696. uInt dictLength));
  78697. /*
  78698. Initializes the decompression dictionary from the given uncompressed byte
  78699. sequence. This function must be called immediately after a call of inflate,
  78700. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78701. can be determined from the adler32 value returned by that call of inflate.
  78702. The compressor and decompressor must use exactly the same dictionary (see
  78703. deflateSetDictionary). For raw inflate, this function can be called
  78704. immediately after inflateInit2() or inflateReset() and before any call of
  78705. inflate() to set the dictionary. The application must insure that the
  78706. dictionary that was used for compression is provided.
  78707. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78708. parameter is invalid (such as NULL dictionary) or the stream state is
  78709. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78710. expected one (incorrect adler32 value). inflateSetDictionary does not
  78711. perform any decompression: this will be done by subsequent calls of
  78712. inflate().
  78713. */
  78714. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78715. /*
  78716. Skips invalid compressed data until a full flush point (see above the
  78717. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78718. available input is skipped. No output is provided.
  78719. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78720. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78721. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78722. case, the application may save the current current value of total_in which
  78723. indicates where valid compressed data was found. In the error case, the
  78724. application may repeatedly call inflateSync, providing more input each time,
  78725. until success or end of the input data.
  78726. */
  78727. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78728. z_streamp source));
  78729. /*
  78730. Sets the destination stream as a complete copy of the source stream.
  78731. This function can be useful when randomly accessing a large stream. The
  78732. first pass through the stream can periodically record the inflate state,
  78733. allowing restarting inflate at those points when randomly accessing the
  78734. stream.
  78735. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78736. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78737. (such as zalloc being NULL). msg is left unchanged in both source and
  78738. destination.
  78739. */
  78740. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78741. /*
  78742. This function is equivalent to inflateEnd followed by inflateInit,
  78743. but does not free and reallocate all the internal decompression state.
  78744. The stream will keep attributes that may have been set by inflateInit2.
  78745. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78746. stream state was inconsistent (such as zalloc or state being NULL).
  78747. */
  78748. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78749. int bits,
  78750. int value));
  78751. /*
  78752. This function inserts bits in the inflate input stream. The intent is
  78753. that this function is used to start inflating at a bit position in the
  78754. middle of a byte. The provided bits will be used before any bytes are used
  78755. from next_in. This function should only be used with raw inflate, and
  78756. should be used before the first inflate() call after inflateInit2() or
  78757. inflateReset(). bits must be less than or equal to 16, and that many of the
  78758. least significant bits of value will be inserted in the input.
  78759. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78760. stream state was inconsistent.
  78761. */
  78762. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78763. gz_headerp head));
  78764. /*
  78765. inflateGetHeader() requests that gzip header information be stored in the
  78766. provided gz_header structure. inflateGetHeader() may be called after
  78767. inflateInit2() or inflateReset(), and before the first call of inflate().
  78768. As inflate() processes the gzip stream, head->done is zero until the header
  78769. is completed, at which time head->done is set to one. If a zlib stream is
  78770. being decoded, then head->done is set to -1 to indicate that there will be
  78771. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78772. force inflate() to return immediately after header processing is complete
  78773. and before any actual data is decompressed.
  78774. The text, time, xflags, and os fields are filled in with the gzip header
  78775. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78776. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78777. contains the maximum number of bytes to write to extra. Once done is true,
  78778. extra_len contains the actual extra field length, and extra contains the
  78779. extra field, or that field truncated if extra_max is less than extra_len.
  78780. If name is not Z_NULL, then up to name_max characters are written there,
  78781. terminated with a zero unless the length is greater than name_max. If
  78782. comment is not Z_NULL, then up to comm_max characters are written there,
  78783. terminated with a zero unless the length is greater than comm_max. When
  78784. any of extra, name, or comment are not Z_NULL and the respective field is
  78785. not present in the header, then that field is set to Z_NULL to signal its
  78786. absence. This allows the use of deflateSetHeader() with the returned
  78787. structure to duplicate the header. However if those fields are set to
  78788. allocated memory, then the application will need to save those pointers
  78789. elsewhere so that they can be eventually freed.
  78790. If inflateGetHeader is not used, then the header information is simply
  78791. discarded. The header is always checked for validity, including the header
  78792. CRC if present. inflateReset() will reset the process to discard the header
  78793. information. The application would need to call inflateGetHeader() again to
  78794. retrieve the header from the next gzip stream.
  78795. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78796. stream state was inconsistent.
  78797. */
  78798. /*
  78799. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78800. unsigned char FAR *window));
  78801. Initialize the internal stream state for decompression using inflateBack()
  78802. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78803. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78804. derived memory allocation routines are used. windowBits is the base two
  78805. logarithm of the window size, in the range 8..15. window is a caller
  78806. supplied buffer of that size. Except for special applications where it is
  78807. assured that deflate was used with small window sizes, windowBits must be 15
  78808. and a 32K byte window must be supplied to be able to decompress general
  78809. deflate streams.
  78810. See inflateBack() for the usage of these routines.
  78811. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78812. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78813. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78814. match the version of the header file.
  78815. */
  78816. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78817. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78818. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78819. in_func in, void FAR *in_desc,
  78820. out_func out, void FAR *out_desc));
  78821. /*
  78822. inflateBack() does a raw inflate with a single call using a call-back
  78823. interface for input and output. This is more efficient than inflate() for
  78824. file i/o applications in that it avoids copying between the output and the
  78825. sliding window by simply making the window itself the output buffer. This
  78826. function trusts the application to not change the output buffer passed by
  78827. the output function, at least until inflateBack() returns.
  78828. inflateBackInit() must be called first to allocate the internal state
  78829. and to initialize the state with the user-provided window buffer.
  78830. inflateBack() may then be used multiple times to inflate a complete, raw
  78831. deflate stream with each call. inflateBackEnd() is then called to free
  78832. the allocated state.
  78833. A raw deflate stream is one with no zlib or gzip header or trailer.
  78834. This routine would normally be used in a utility that reads zip or gzip
  78835. files and writes out uncompressed files. The utility would decode the
  78836. header and process the trailer on its own, hence this routine expects
  78837. only the raw deflate stream to decompress. This is different from the
  78838. normal behavior of inflate(), which expects either a zlib or gzip header and
  78839. trailer around the deflate stream.
  78840. inflateBack() uses two subroutines supplied by the caller that are then
  78841. called by inflateBack() for input and output. inflateBack() calls those
  78842. routines until it reads a complete deflate stream and writes out all of the
  78843. uncompressed data, or until it encounters an error. The function's
  78844. parameters and return types are defined above in the in_func and out_func
  78845. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78846. number of bytes of provided input, and a pointer to that input in buf. If
  78847. there is no input available, in() must return zero--buf is ignored in that
  78848. case--and inflateBack() will return a buffer error. inflateBack() will call
  78849. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78850. should return zero on success, or non-zero on failure. If out() returns
  78851. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78852. are permitted to change the contents of the window provided to
  78853. inflateBackInit(), which is also the buffer that out() uses to write from.
  78854. The length written by out() will be at most the window size. Any non-zero
  78855. amount of input may be provided by in().
  78856. For convenience, inflateBack() can be provided input on the first call by
  78857. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78858. in() will be called. Therefore strm->next_in must be initialized before
  78859. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78860. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78861. must also be initialized, and then if strm->avail_in is not zero, input will
  78862. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78863. The in_desc and out_desc parameters of inflateBack() is passed as the
  78864. first parameter of in() and out() respectively when they are called. These
  78865. descriptors can be optionally used to pass any information that the caller-
  78866. supplied in() and out() functions need to do their job.
  78867. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78868. pass back any unused input that was provided by the last in() call. The
  78869. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78870. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78871. error in the deflate stream (in which case strm->msg is set to indicate the
  78872. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78873. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78874. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78875. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78876. out() returning non-zero. (in() will always be called before out(), so
  78877. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78878. that inflateBack() cannot return Z_OK.
  78879. */
  78880. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78881. /*
  78882. All memory allocated by inflateBackInit() is freed.
  78883. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78884. state was inconsistent.
  78885. */
  78886. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78887. /* Return flags indicating compile-time options.
  78888. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78889. 1.0: size of uInt
  78890. 3.2: size of uLong
  78891. 5.4: size of voidpf (pointer)
  78892. 7.6: size of z_off_t
  78893. Compiler, assembler, and debug options:
  78894. 8: DEBUG
  78895. 9: ASMV or ASMINF -- use ASM code
  78896. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78897. 11: 0 (reserved)
  78898. One-time table building (smaller code, but not thread-safe if true):
  78899. 12: BUILDFIXED -- build static block decoding tables when needed
  78900. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78901. 14,15: 0 (reserved)
  78902. Library content (indicates missing functionality):
  78903. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78904. deflate code when not needed)
  78905. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78906. and decode gzip streams (to avoid linking crc code)
  78907. 18-19: 0 (reserved)
  78908. Operation variations (changes in library functionality):
  78909. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78910. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78911. 22,23: 0 (reserved)
  78912. The sprintf variant used by gzprintf (zero is best):
  78913. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78914. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78915. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78916. Remainder:
  78917. 27-31: 0 (reserved)
  78918. */
  78919. /* utility functions */
  78920. /*
  78921. The following utility functions are implemented on top of the
  78922. basic stream-oriented functions. To simplify the interface, some
  78923. default options are assumed (compression level and memory usage,
  78924. standard memory allocation functions). The source code of these
  78925. utility functions can easily be modified if you need special options.
  78926. */
  78927. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78928. const Bytef *source, uLong sourceLen));
  78929. /*
  78930. Compresses the source buffer into the destination buffer. sourceLen is
  78931. the byte length of the source buffer. Upon entry, destLen is the total
  78932. size of the destination buffer, which must be at least the value returned
  78933. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78934. compressed buffer.
  78935. This function can be used to compress a whole file at once if the
  78936. input file is mmap'ed.
  78937. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78938. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78939. buffer.
  78940. */
  78941. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78942. const Bytef *source, uLong sourceLen,
  78943. int level));
  78944. /*
  78945. Compresses the source buffer into the destination buffer. The level
  78946. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78947. length of the source buffer. Upon entry, destLen is the total size of the
  78948. destination buffer, which must be at least the value returned by
  78949. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78950. compressed buffer.
  78951. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78952. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78953. Z_STREAM_ERROR if the level parameter is invalid.
  78954. */
  78955. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78956. /*
  78957. compressBound() returns an upper bound on the compressed size after
  78958. compress() or compress2() on sourceLen bytes. It would be used before
  78959. a compress() or compress2() call to allocate the destination buffer.
  78960. */
  78961. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78962. const Bytef *source, uLong sourceLen));
  78963. /*
  78964. Decompresses the source buffer into the destination buffer. sourceLen is
  78965. the byte length of the source buffer. Upon entry, destLen is the total
  78966. size of the destination buffer, which must be large enough to hold the
  78967. entire uncompressed data. (The size of the uncompressed data must have
  78968. been saved previously by the compressor and transmitted to the decompressor
  78969. by some mechanism outside the scope of this compression library.)
  78970. Upon exit, destLen is the actual size of the compressed buffer.
  78971. This function can be used to decompress a whole file at once if the
  78972. input file is mmap'ed.
  78973. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78974. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78975. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78976. */
  78977. typedef voidp gzFile;
  78978. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78979. /*
  78980. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78981. is as in fopen ("rb" or "wb") but can also include a compression level
  78982. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78983. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78984. as in "wb1R". (See the description of deflateInit2 for more information
  78985. about the strategy parameter.)
  78986. gzopen can be used to read a file which is not in gzip format; in this
  78987. case gzread will directly read from the file without decompression.
  78988. gzopen returns NULL if the file could not be opened or if there was
  78989. insufficient memory to allocate the (de)compression state; errno
  78990. can be checked to distinguish the two cases (if errno is zero, the
  78991. zlib error is Z_MEM_ERROR). */
  78992. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78993. /*
  78994. gzdopen() associates a gzFile with the file descriptor fd. File
  78995. descriptors are obtained from calls like open, dup, creat, pipe or
  78996. fileno (in the file has been previously opened with fopen).
  78997. The mode parameter is as in gzopen.
  78998. The next call of gzclose on the returned gzFile will also close the
  78999. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79000. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79001. gzdopen returns NULL if there was insufficient memory to allocate
  79002. the (de)compression state.
  79003. */
  79004. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79005. /*
  79006. Dynamically update the compression level or strategy. See the description
  79007. of deflateInit2 for the meaning of these parameters.
  79008. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79009. opened for writing.
  79010. */
  79011. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79012. /*
  79013. Reads the given number of uncompressed bytes from the compressed file.
  79014. If the input file was not in gzip format, gzread copies the given number
  79015. of bytes into the buffer.
  79016. gzread returns the number of uncompressed bytes actually read (0 for
  79017. end of file, -1 for error). */
  79018. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79019. voidpc buf, unsigned len));
  79020. /*
  79021. Writes the given number of uncompressed bytes into the compressed file.
  79022. gzwrite returns the number of uncompressed bytes actually written
  79023. (0 in case of error).
  79024. */
  79025. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79026. /*
  79027. Converts, formats, and writes the args to the compressed file under
  79028. control of the format string, as in fprintf. gzprintf returns the number of
  79029. uncompressed bytes actually written (0 in case of error). The number of
  79030. uncompressed bytes written is limited to 4095. The caller should assure that
  79031. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79032. return an error (0) with nothing written. In this case, there may also be a
  79033. buffer overflow with unpredictable consequences, which is possible only if
  79034. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79035. because the secure snprintf() or vsnprintf() functions were not available.
  79036. */
  79037. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79038. /*
  79039. Writes the given null-terminated string to the compressed file, excluding
  79040. the terminating null character.
  79041. gzputs returns the number of characters written, or -1 in case of error.
  79042. */
  79043. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79044. /*
  79045. Reads bytes from the compressed file until len-1 characters are read, or
  79046. a newline character is read and transferred to buf, or an end-of-file
  79047. condition is encountered. The string is then terminated with a null
  79048. character.
  79049. gzgets returns buf, or Z_NULL in case of error.
  79050. */
  79051. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79052. /*
  79053. Writes c, converted to an unsigned char, into the compressed file.
  79054. gzputc returns the value that was written, or -1 in case of error.
  79055. */
  79056. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79057. /*
  79058. Reads one byte from the compressed file. gzgetc returns this byte
  79059. or -1 in case of end of file or error.
  79060. */
  79061. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79062. /*
  79063. Push one character back onto the stream to be read again later.
  79064. Only one character of push-back is allowed. gzungetc() returns the
  79065. character pushed, or -1 on failure. gzungetc() will fail if a
  79066. character has been pushed but not read yet, or if c is -1. The pushed
  79067. character will be discarded if the stream is repositioned with gzseek()
  79068. or gzrewind().
  79069. */
  79070. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79071. /*
  79072. Flushes all pending output into the compressed file. The parameter
  79073. flush is as in the deflate() function. The return value is the zlib
  79074. error number (see function gzerror below). gzflush returns Z_OK if
  79075. the flush parameter is Z_FINISH and all output could be flushed.
  79076. gzflush should be called only when strictly necessary because it can
  79077. degrade compression.
  79078. */
  79079. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79080. z_off_t offset, int whence));
  79081. /*
  79082. Sets the starting position for the next gzread or gzwrite on the
  79083. given compressed file. The offset represents a number of bytes in the
  79084. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79085. the value SEEK_END is not supported.
  79086. If the file is opened for reading, this function is emulated but can be
  79087. extremely slow. If the file is opened for writing, only forward seeks are
  79088. supported; gzseek then compresses a sequence of zeroes up to the new
  79089. starting position.
  79090. gzseek returns the resulting offset location as measured in bytes from
  79091. the beginning of the uncompressed stream, or -1 in case of error, in
  79092. particular if the file is opened for writing and the new starting position
  79093. would be before the current position.
  79094. */
  79095. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79096. /*
  79097. Rewinds the given file. This function is supported only for reading.
  79098. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79099. */
  79100. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79101. /*
  79102. Returns the starting position for the next gzread or gzwrite on the
  79103. given compressed file. This position represents a number of bytes in the
  79104. uncompressed data stream.
  79105. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79106. */
  79107. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79108. /*
  79109. Returns 1 when EOF has previously been detected reading the given
  79110. input stream, otherwise zero.
  79111. */
  79112. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79113. /*
  79114. Returns 1 if file is being read directly without decompression, otherwise
  79115. zero.
  79116. */
  79117. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79118. /*
  79119. Flushes all pending output if necessary, closes the compressed file
  79120. and deallocates all the (de)compression state. The return value is the zlib
  79121. error number (see function gzerror below).
  79122. */
  79123. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79124. /*
  79125. Returns the error message for the last error which occurred on the
  79126. given compressed file. errnum is set to zlib error number. If an
  79127. error occurred in the file system and not in the compression library,
  79128. errnum is set to Z_ERRNO and the application may consult errno
  79129. to get the exact error code.
  79130. */
  79131. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79132. /*
  79133. Clears the error and end-of-file flags for file. This is analogous to the
  79134. clearerr() function in stdio. This is useful for continuing to read a gzip
  79135. file that is being written concurrently.
  79136. */
  79137. /* checksum functions */
  79138. /*
  79139. These functions are not related to compression but are exported
  79140. anyway because they might be useful in applications using the
  79141. compression library.
  79142. */
  79143. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79144. /*
  79145. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79146. return the updated checksum. If buf is NULL, this function returns
  79147. the required initial value for the checksum.
  79148. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79149. much faster. Usage example:
  79150. uLong adler = adler32(0L, Z_NULL, 0);
  79151. while (read_buffer(buffer, length) != EOF) {
  79152. adler = adler32(adler, buffer, length);
  79153. }
  79154. if (adler != original_adler) error();
  79155. */
  79156. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79157. z_off_t len2));
  79158. /*
  79159. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79160. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79161. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79162. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79163. */
  79164. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79165. /*
  79166. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79167. updated CRC-32. If buf is NULL, this function returns the required initial
  79168. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79169. performed within this function so it shouldn't be done by the application.
  79170. Usage example:
  79171. uLong crc = crc32(0L, Z_NULL, 0);
  79172. while (read_buffer(buffer, length) != EOF) {
  79173. crc = crc32(crc, buffer, length);
  79174. }
  79175. if (crc != original_crc) error();
  79176. */
  79177. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79178. /*
  79179. Combine two CRC-32 check values into one. For two sequences of bytes,
  79180. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79181. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79182. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79183. len2.
  79184. */
  79185. /* various hacks, don't look :) */
  79186. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79187. * and the compiler's view of z_stream:
  79188. */
  79189. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79190. const char *version, int stream_size));
  79191. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79192. const char *version, int stream_size));
  79193. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79194. int windowBits, int memLevel,
  79195. int strategy, const char *version,
  79196. int stream_size));
  79197. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79198. const char *version, int stream_size));
  79199. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79200. unsigned char FAR *window,
  79201. const char *version,
  79202. int stream_size));
  79203. #define deflateInit(strm, level) \
  79204. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79205. #define inflateInit(strm) \
  79206. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79207. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79208. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79209. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79210. #define inflateInit2(strm, windowBits) \
  79211. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79212. #define inflateBackInit(strm, windowBits, window) \
  79213. inflateBackInit_((strm), (windowBits), (window), \
  79214. ZLIB_VERSION, sizeof(z_stream))
  79215. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79216. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79217. #endif
  79218. ZEXTERN const char * ZEXPORT zError OF((int));
  79219. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79220. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79221. #ifdef __cplusplus
  79222. //}
  79223. #endif
  79224. #endif /* ZLIB_H */
  79225. /*** End of inlined file: zlib.h ***/
  79226. #undef OS_CODE
  79227. #else
  79228. #include <zlib.h>
  79229. #endif
  79230. }
  79231. BEGIN_JUCE_NAMESPACE
  79232. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79233. {
  79234. public:
  79235. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79236. : data (0),
  79237. dataSize (0),
  79238. compLevel (compressionLevel),
  79239. strategy (0),
  79240. setParams (true),
  79241. streamIsValid (false),
  79242. finished (false),
  79243. shouldFinish (false)
  79244. {
  79245. using namespace zlibNamespace;
  79246. zerostruct (stream);
  79247. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79248. windowBits != 0 ? windowBits : MAX_WBITS,
  79249. 8, strategy) == Z_OK);
  79250. }
  79251. ~GZIPCompressorHelper()
  79252. {
  79253. using namespace zlibNamespace;
  79254. if (streamIsValid)
  79255. deflateEnd (&stream);
  79256. }
  79257. bool needsInput() const throw()
  79258. {
  79259. return dataSize <= 0;
  79260. }
  79261. void setInput (const uint8* const newData, const int size) throw()
  79262. {
  79263. data = newData;
  79264. dataSize = size;
  79265. }
  79266. int doNextBlock (uint8* const dest, const int destSize) throw()
  79267. {
  79268. using namespace zlibNamespace;
  79269. if (streamIsValid)
  79270. {
  79271. stream.next_in = const_cast <uint8*> (data);
  79272. stream.next_out = dest;
  79273. stream.avail_in = dataSize;
  79274. stream.avail_out = destSize;
  79275. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79276. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79277. setParams = false;
  79278. switch (result)
  79279. {
  79280. case Z_STREAM_END:
  79281. finished = true;
  79282. // Deliberate fall-through..
  79283. case Z_OK:
  79284. data += dataSize - stream.avail_in;
  79285. dataSize = stream.avail_in;
  79286. return destSize - stream.avail_out;
  79287. default:
  79288. break;
  79289. }
  79290. }
  79291. return 0;
  79292. }
  79293. enum { gzipCompBufferSize = 32768 };
  79294. private:
  79295. zlibNamespace::z_stream stream;
  79296. const uint8* data;
  79297. int dataSize, compLevel, strategy;
  79298. bool setParams, streamIsValid;
  79299. public:
  79300. bool finished, shouldFinish;
  79301. };
  79302. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79303. int compressionLevel,
  79304. const bool deleteDestStream,
  79305. const int windowBits)
  79306. : destStream (destStream_),
  79307. streamToDelete (deleteDestStream ? destStream_ : 0),
  79308. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79309. {
  79310. if (compressionLevel < 1 || compressionLevel > 9)
  79311. compressionLevel = -1;
  79312. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79313. }
  79314. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79315. {
  79316. flush();
  79317. }
  79318. void GZIPCompressorOutputStream::flush()
  79319. {
  79320. if (! helper->finished)
  79321. {
  79322. helper->shouldFinish = true;
  79323. while (! helper->finished)
  79324. doNextBlock();
  79325. }
  79326. destStream->flush();
  79327. }
  79328. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79329. {
  79330. if (! helper->finished)
  79331. {
  79332. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79333. while (! helper->needsInput())
  79334. {
  79335. if (! doNextBlock())
  79336. return false;
  79337. }
  79338. }
  79339. return true;
  79340. }
  79341. bool GZIPCompressorOutputStream::doNextBlock()
  79342. {
  79343. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79344. return len <= 0 || destStream->write (buffer, len);
  79345. }
  79346. int64 GZIPCompressorOutputStream::getPosition()
  79347. {
  79348. return destStream->getPosition();
  79349. }
  79350. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79351. {
  79352. jassertfalse; // can't do it!
  79353. return false;
  79354. }
  79355. END_JUCE_NAMESPACE
  79356. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79357. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79358. #if JUCE_MSVC
  79359. #pragma warning (push)
  79360. #pragma warning (disable: 4309 4305)
  79361. #endif
  79362. namespace zlibNamespace
  79363. {
  79364. #if JUCE_INCLUDE_ZLIB_CODE
  79365. #undef OS_CODE
  79366. #undef fdopen
  79367. #define ZLIB_INTERNAL
  79368. #define NO_DUMMY_DECL
  79369. /*** Start of inlined file: adler32.c ***/
  79370. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79371. #define ZLIB_INTERNAL
  79372. #define BASE 65521UL /* largest prime smaller than 65536 */
  79373. #define NMAX 5552
  79374. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79375. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79376. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79377. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79378. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79379. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79380. /* use NO_DIVIDE if your processor does not do division in hardware */
  79381. #ifdef NO_DIVIDE
  79382. # define MOD(a) \
  79383. do { \
  79384. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79385. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79386. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79387. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79388. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79389. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79390. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79391. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79392. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79393. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79394. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79395. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79396. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79397. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79398. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79399. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79400. if (a >= BASE) a -= BASE; \
  79401. } while (0)
  79402. # define MOD4(a) \
  79403. do { \
  79404. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79405. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79406. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79407. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79408. if (a >= BASE) a -= BASE; \
  79409. } while (0)
  79410. #else
  79411. # define MOD(a) a %= BASE
  79412. # define MOD4(a) a %= BASE
  79413. #endif
  79414. /* ========================================================================= */
  79415. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79416. {
  79417. unsigned long sum2;
  79418. unsigned n;
  79419. /* split Adler-32 into component sums */
  79420. sum2 = (adler >> 16) & 0xffff;
  79421. adler &= 0xffff;
  79422. /* in case user likes doing a byte at a time, keep it fast */
  79423. if (len == 1) {
  79424. adler += buf[0];
  79425. if (adler >= BASE)
  79426. adler -= BASE;
  79427. sum2 += adler;
  79428. if (sum2 >= BASE)
  79429. sum2 -= BASE;
  79430. return adler | (sum2 << 16);
  79431. }
  79432. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79433. if (buf == Z_NULL)
  79434. return 1L;
  79435. /* in case short lengths are provided, keep it somewhat fast */
  79436. if (len < 16) {
  79437. while (len--) {
  79438. adler += *buf++;
  79439. sum2 += adler;
  79440. }
  79441. if (adler >= BASE)
  79442. adler -= BASE;
  79443. MOD4(sum2); /* only added so many BASE's */
  79444. return adler | (sum2 << 16);
  79445. }
  79446. /* do length NMAX blocks -- requires just one modulo operation */
  79447. while (len >= NMAX) {
  79448. len -= NMAX;
  79449. n = NMAX / 16; /* NMAX is divisible by 16 */
  79450. do {
  79451. DO16(buf); /* 16 sums unrolled */
  79452. buf += 16;
  79453. } while (--n);
  79454. MOD(adler);
  79455. MOD(sum2);
  79456. }
  79457. /* do remaining bytes (less than NMAX, still just one modulo) */
  79458. if (len) { /* avoid modulos if none remaining */
  79459. while (len >= 16) {
  79460. len -= 16;
  79461. DO16(buf);
  79462. buf += 16;
  79463. }
  79464. while (len--) {
  79465. adler += *buf++;
  79466. sum2 += adler;
  79467. }
  79468. MOD(adler);
  79469. MOD(sum2);
  79470. }
  79471. /* return recombined sums */
  79472. return adler | (sum2 << 16);
  79473. }
  79474. /* ========================================================================= */
  79475. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79476. {
  79477. unsigned long sum1;
  79478. unsigned long sum2;
  79479. unsigned rem;
  79480. /* the derivation of this formula is left as an exercise for the reader */
  79481. rem = (unsigned)(len2 % BASE);
  79482. sum1 = adler1 & 0xffff;
  79483. sum2 = rem * sum1;
  79484. MOD(sum2);
  79485. sum1 += (adler2 & 0xffff) + BASE - 1;
  79486. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79487. if (sum1 > BASE) sum1 -= BASE;
  79488. if (sum1 > BASE) sum1 -= BASE;
  79489. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79490. if (sum2 > BASE) sum2 -= BASE;
  79491. return sum1 | (sum2 << 16);
  79492. }
  79493. /*** End of inlined file: adler32.c ***/
  79494. /*** Start of inlined file: compress.c ***/
  79495. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79496. #define ZLIB_INTERNAL
  79497. /* ===========================================================================
  79498. Compresses the source buffer into the destination buffer. The level
  79499. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79500. length of the source buffer. Upon entry, destLen is the total size of the
  79501. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79502. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79503. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79504. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79505. Z_STREAM_ERROR if the level parameter is invalid.
  79506. */
  79507. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79508. uLong sourceLen, int level)
  79509. {
  79510. z_stream stream;
  79511. int err;
  79512. stream.next_in = (Bytef*)source;
  79513. stream.avail_in = (uInt)sourceLen;
  79514. #ifdef MAXSEG_64K
  79515. /* Check for source > 64K on 16-bit machine: */
  79516. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79517. #endif
  79518. stream.next_out = dest;
  79519. stream.avail_out = (uInt)*destLen;
  79520. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79521. stream.zalloc = (alloc_func)0;
  79522. stream.zfree = (free_func)0;
  79523. stream.opaque = (voidpf)0;
  79524. err = deflateInit(&stream, level);
  79525. if (err != Z_OK) return err;
  79526. err = deflate(&stream, Z_FINISH);
  79527. if (err != Z_STREAM_END) {
  79528. deflateEnd(&stream);
  79529. return err == Z_OK ? Z_BUF_ERROR : err;
  79530. }
  79531. *destLen = stream.total_out;
  79532. err = deflateEnd(&stream);
  79533. return err;
  79534. }
  79535. /* ===========================================================================
  79536. */
  79537. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79538. {
  79539. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79540. }
  79541. /* ===========================================================================
  79542. If the default memLevel or windowBits for deflateInit() is changed, then
  79543. this function needs to be updated.
  79544. */
  79545. uLong ZEXPORT compressBound (uLong sourceLen)
  79546. {
  79547. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79548. }
  79549. /*** End of inlined file: compress.c ***/
  79550. #undef DO1
  79551. #undef DO8
  79552. /*** Start of inlined file: crc32.c ***/
  79553. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79554. /*
  79555. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79556. protection on the static variables used to control the first-use generation
  79557. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79558. first call get_crc_table() to initialize the tables before allowing more than
  79559. one thread to use crc32().
  79560. */
  79561. #ifdef MAKECRCH
  79562. # include <stdio.h>
  79563. # ifndef DYNAMIC_CRC_TABLE
  79564. # define DYNAMIC_CRC_TABLE
  79565. # endif /* !DYNAMIC_CRC_TABLE */
  79566. #endif /* MAKECRCH */
  79567. /*** Start of inlined file: zutil.h ***/
  79568. /* WARNING: this file should *not* be used by applications. It is
  79569. part of the implementation of the compression library and is
  79570. subject to change. Applications should only use zlib.h.
  79571. */
  79572. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79573. #ifndef ZUTIL_H
  79574. #define ZUTIL_H
  79575. #define ZLIB_INTERNAL
  79576. #ifdef STDC
  79577. # ifndef _WIN32_WCE
  79578. # include <stddef.h>
  79579. # endif
  79580. # include <string.h>
  79581. # include <stdlib.h>
  79582. #endif
  79583. #ifdef NO_ERRNO_H
  79584. # ifdef _WIN32_WCE
  79585. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79586. * errno. We define it as a global variable to simplify porting.
  79587. * Its value is always 0 and should not be used. We rename it to
  79588. * avoid conflict with other libraries that use the same workaround.
  79589. */
  79590. # define errno z_errno
  79591. # endif
  79592. extern int errno;
  79593. #else
  79594. # ifndef _WIN32_WCE
  79595. # include <errno.h>
  79596. # endif
  79597. #endif
  79598. #ifndef local
  79599. # define local static
  79600. #endif
  79601. /* compile with -Dlocal if your debugger can't find static symbols */
  79602. typedef unsigned char uch;
  79603. typedef uch FAR uchf;
  79604. typedef unsigned short ush;
  79605. typedef ush FAR ushf;
  79606. typedef unsigned long ulg;
  79607. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79608. /* (size given to avoid silly warnings with Visual C++) */
  79609. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79610. #define ERR_RETURN(strm,err) \
  79611. return (strm->msg = (char*)ERR_MSG(err), (err))
  79612. /* To be used only when the state is known to be valid */
  79613. /* common constants */
  79614. #ifndef DEF_WBITS
  79615. # define DEF_WBITS MAX_WBITS
  79616. #endif
  79617. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79618. #if MAX_MEM_LEVEL >= 8
  79619. # define DEF_MEM_LEVEL 8
  79620. #else
  79621. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79622. #endif
  79623. /* default memLevel */
  79624. #define STORED_BLOCK 0
  79625. #define STATIC_TREES 1
  79626. #define DYN_TREES 2
  79627. /* The three kinds of block type */
  79628. #define MIN_MATCH 3
  79629. #define MAX_MATCH 258
  79630. /* The minimum and maximum match lengths */
  79631. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79632. /* target dependencies */
  79633. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79634. # define OS_CODE 0x00
  79635. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79636. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79637. /* Allow compilation with ANSI keywords only enabled */
  79638. void _Cdecl farfree( void *block );
  79639. void *_Cdecl farmalloc( unsigned long nbytes );
  79640. # else
  79641. # include <alloc.h>
  79642. # endif
  79643. # else /* MSC or DJGPP */
  79644. # include <malloc.h>
  79645. # endif
  79646. #endif
  79647. #ifdef AMIGA
  79648. # define OS_CODE 0x01
  79649. #endif
  79650. #if defined(VAXC) || defined(VMS)
  79651. # define OS_CODE 0x02
  79652. # define F_OPEN(name, mode) \
  79653. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79654. #endif
  79655. #if defined(ATARI) || defined(atarist)
  79656. # define OS_CODE 0x05
  79657. #endif
  79658. #ifdef OS2
  79659. # define OS_CODE 0x06
  79660. # ifdef M_I86
  79661. #include <malloc.h>
  79662. # endif
  79663. #endif
  79664. #if defined(MACOS) || TARGET_OS_MAC
  79665. # define OS_CODE 0x07
  79666. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79667. # include <unix.h> /* for fdopen */
  79668. # else
  79669. # ifndef fdopen
  79670. # define fdopen(fd,mode) NULL /* No fdopen() */
  79671. # endif
  79672. # endif
  79673. #endif
  79674. #ifdef TOPS20
  79675. # define OS_CODE 0x0a
  79676. #endif
  79677. #ifdef WIN32
  79678. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79679. # define OS_CODE 0x0b
  79680. # endif
  79681. #endif
  79682. #ifdef __50SERIES /* Prime/PRIMOS */
  79683. # define OS_CODE 0x0f
  79684. #endif
  79685. #if defined(_BEOS_) || defined(RISCOS)
  79686. # define fdopen(fd,mode) NULL /* No fdopen() */
  79687. #endif
  79688. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79689. # if defined(_WIN32_WCE)
  79690. # define fdopen(fd,mode) NULL /* No fdopen() */
  79691. # ifndef _PTRDIFF_T_DEFINED
  79692. typedef int ptrdiff_t;
  79693. # define _PTRDIFF_T_DEFINED
  79694. # endif
  79695. # else
  79696. # define fdopen(fd,type) _fdopen(fd,type)
  79697. # endif
  79698. #endif
  79699. /* common defaults */
  79700. #ifndef OS_CODE
  79701. # define OS_CODE 0x03 /* assume Unix */
  79702. #endif
  79703. #ifndef F_OPEN
  79704. # define F_OPEN(name, mode) fopen((name), (mode))
  79705. #endif
  79706. /* functions */
  79707. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79708. # ifndef HAVE_VSNPRINTF
  79709. # define HAVE_VSNPRINTF
  79710. # endif
  79711. #endif
  79712. #if defined(__CYGWIN__)
  79713. # ifndef HAVE_VSNPRINTF
  79714. # define HAVE_VSNPRINTF
  79715. # endif
  79716. #endif
  79717. #ifndef HAVE_VSNPRINTF
  79718. # ifdef MSDOS
  79719. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79720. but for now we just assume it doesn't. */
  79721. # define NO_vsnprintf
  79722. # endif
  79723. # ifdef __TURBOC__
  79724. # define NO_vsnprintf
  79725. # endif
  79726. # ifdef WIN32
  79727. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79728. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79729. # define vsnprintf _vsnprintf
  79730. # endif
  79731. # endif
  79732. # ifdef __SASC
  79733. # define NO_vsnprintf
  79734. # endif
  79735. #endif
  79736. #ifdef VMS
  79737. # define NO_vsnprintf
  79738. #endif
  79739. #if defined(pyr)
  79740. # define NO_MEMCPY
  79741. #endif
  79742. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79743. /* Use our own functions for small and medium model with MSC <= 5.0.
  79744. * You may have to use the same strategy for Borland C (untested).
  79745. * The __SC__ check is for Symantec.
  79746. */
  79747. # define NO_MEMCPY
  79748. #endif
  79749. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79750. # define HAVE_MEMCPY
  79751. #endif
  79752. #ifdef HAVE_MEMCPY
  79753. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79754. # define zmemcpy _fmemcpy
  79755. # define zmemcmp _fmemcmp
  79756. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79757. # else
  79758. # define zmemcpy memcpy
  79759. # define zmemcmp memcmp
  79760. # define zmemzero(dest, len) memset(dest, 0, len)
  79761. # endif
  79762. #else
  79763. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79764. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79765. extern void zmemzero OF((Bytef* dest, uInt len));
  79766. #endif
  79767. /* Diagnostic functions */
  79768. #ifdef DEBUG
  79769. # include <stdio.h>
  79770. extern int z_verbose;
  79771. extern void z_error OF((const char *m));
  79772. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79773. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79774. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79775. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79776. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79777. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79778. #else
  79779. # define Assert(cond,msg)
  79780. # define Trace(x)
  79781. # define Tracev(x)
  79782. # define Tracevv(x)
  79783. # define Tracec(c,x)
  79784. # define Tracecv(c,x)
  79785. #endif
  79786. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79787. void zcfree OF((voidpf opaque, voidpf ptr));
  79788. #define ZALLOC(strm, items, size) \
  79789. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79790. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79791. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79792. #endif /* ZUTIL_H */
  79793. /*** End of inlined file: zutil.h ***/
  79794. /* for STDC and FAR definitions */
  79795. #define local static
  79796. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79797. #ifndef NOBYFOUR
  79798. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79799. # include <limits.h>
  79800. # define BYFOUR
  79801. # if (UINT_MAX == 0xffffffffUL)
  79802. typedef unsigned int u4;
  79803. # else
  79804. # if (ULONG_MAX == 0xffffffffUL)
  79805. typedef unsigned long u4;
  79806. # else
  79807. # if (USHRT_MAX == 0xffffffffUL)
  79808. typedef unsigned short u4;
  79809. # else
  79810. # undef BYFOUR /* can't find a four-byte integer type! */
  79811. # endif
  79812. # endif
  79813. # endif
  79814. # endif /* STDC */
  79815. #endif /* !NOBYFOUR */
  79816. /* Definitions for doing the crc four data bytes at a time. */
  79817. #ifdef BYFOUR
  79818. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79819. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79820. local unsigned long crc32_little OF((unsigned long,
  79821. const unsigned char FAR *, unsigned));
  79822. local unsigned long crc32_big OF((unsigned long,
  79823. const unsigned char FAR *, unsigned));
  79824. # define TBLS 8
  79825. #else
  79826. # define TBLS 1
  79827. #endif /* BYFOUR */
  79828. /* Local functions for crc concatenation */
  79829. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79830. unsigned long vec));
  79831. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79832. #ifdef DYNAMIC_CRC_TABLE
  79833. local volatile int crc_table_empty = 1;
  79834. local unsigned long FAR crc_table[TBLS][256];
  79835. local void make_crc_table OF((void));
  79836. #ifdef MAKECRCH
  79837. local void write_table OF((FILE *, const unsigned long FAR *));
  79838. #endif /* MAKECRCH */
  79839. /*
  79840. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79841. 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.
  79842. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79843. with the lowest powers in the most significant bit. Then adding polynomials
  79844. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79845. one. If we call the above polynomial p, and represent a byte as the
  79846. polynomial q, also with the lowest power in the most significant bit (so the
  79847. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79848. where a mod b means the remainder after dividing a by b.
  79849. This calculation is done using the shift-register method of multiplying and
  79850. taking the remainder. The register is initialized to zero, and for each
  79851. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79852. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79853. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79854. out is a one). We start with the highest power (least significant bit) of
  79855. q and repeat for all eight bits of q.
  79856. The first table is simply the CRC of all possible eight bit values. This is
  79857. all the information needed to generate CRCs on data a byte at a time for all
  79858. combinations of CRC register values and incoming bytes. The remaining tables
  79859. allow for word-at-a-time CRC calculation for both big-endian and little-
  79860. endian machines, where a word is four bytes.
  79861. */
  79862. local void make_crc_table()
  79863. {
  79864. unsigned long c;
  79865. int n, k;
  79866. unsigned long poly; /* polynomial exclusive-or pattern */
  79867. /* terms of polynomial defining this crc (except x^32): */
  79868. static volatile int first = 1; /* flag to limit concurrent making */
  79869. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79870. /* See if another task is already doing this (not thread-safe, but better
  79871. than nothing -- significantly reduces duration of vulnerability in
  79872. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79873. if (first) {
  79874. first = 0;
  79875. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79876. poly = 0UL;
  79877. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79878. poly |= 1UL << (31 - p[n]);
  79879. /* generate a crc for every 8-bit value */
  79880. for (n = 0; n < 256; n++) {
  79881. c = (unsigned long)n;
  79882. for (k = 0; k < 8; k++)
  79883. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79884. crc_table[0][n] = c;
  79885. }
  79886. #ifdef BYFOUR
  79887. /* generate crc for each value followed by one, two, and three zeros,
  79888. and then the byte reversal of those as well as the first table */
  79889. for (n = 0; n < 256; n++) {
  79890. c = crc_table[0][n];
  79891. crc_table[4][n] = REV(c);
  79892. for (k = 1; k < 4; k++) {
  79893. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79894. crc_table[k][n] = c;
  79895. crc_table[k + 4][n] = REV(c);
  79896. }
  79897. }
  79898. #endif /* BYFOUR */
  79899. crc_table_empty = 0;
  79900. }
  79901. else { /* not first */
  79902. /* wait for the other guy to finish (not efficient, but rare) */
  79903. while (crc_table_empty)
  79904. ;
  79905. }
  79906. #ifdef MAKECRCH
  79907. /* write out CRC tables to crc32.h */
  79908. {
  79909. FILE *out;
  79910. out = fopen("crc32.h", "w");
  79911. if (out == NULL) return;
  79912. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79913. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79914. fprintf(out, "local const unsigned long FAR ");
  79915. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79916. write_table(out, crc_table[0]);
  79917. # ifdef BYFOUR
  79918. fprintf(out, "#ifdef BYFOUR\n");
  79919. for (k = 1; k < 8; k++) {
  79920. fprintf(out, " },\n {\n");
  79921. write_table(out, crc_table[k]);
  79922. }
  79923. fprintf(out, "#endif\n");
  79924. # endif /* BYFOUR */
  79925. fprintf(out, " }\n};\n");
  79926. fclose(out);
  79927. }
  79928. #endif /* MAKECRCH */
  79929. }
  79930. #ifdef MAKECRCH
  79931. local void write_table(out, table)
  79932. FILE *out;
  79933. const unsigned long FAR *table;
  79934. {
  79935. int n;
  79936. for (n = 0; n < 256; n++)
  79937. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79938. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79939. }
  79940. #endif /* MAKECRCH */
  79941. #else /* !DYNAMIC_CRC_TABLE */
  79942. /* ========================================================================
  79943. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79944. */
  79945. /*** Start of inlined file: crc32.h ***/
  79946. local const unsigned long FAR crc_table[TBLS][256] =
  79947. {
  79948. {
  79949. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79950. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79951. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79952. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79953. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79954. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79955. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79956. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79957. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79958. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79959. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79960. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79961. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79962. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79963. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79964. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79965. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79966. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79967. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79968. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79969. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79970. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79971. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79972. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79973. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79974. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79975. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79976. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79977. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79978. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79979. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79980. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79981. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79982. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79983. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79984. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79985. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79986. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79987. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79988. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79989. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79990. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79991. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79992. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79993. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79994. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79995. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79996. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79997. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79998. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79999. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80000. 0x2d02ef8dUL
  80001. #ifdef BYFOUR
  80002. },
  80003. {
  80004. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80005. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80006. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80007. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80008. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80009. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80010. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80011. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80012. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80013. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80014. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80015. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80016. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80017. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80018. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80019. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80020. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80021. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80022. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80023. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80024. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80025. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80026. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80027. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80028. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80029. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80030. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80031. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80032. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80033. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80034. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80035. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80036. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80037. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80038. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80039. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80040. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80041. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80042. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80043. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80044. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80045. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80046. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80047. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80048. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80049. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80050. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80051. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80052. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80053. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80054. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80055. 0x9324fd72UL
  80056. },
  80057. {
  80058. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80059. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80060. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80061. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80062. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80063. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80064. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80065. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80066. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80067. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80068. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80069. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80070. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80071. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80072. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80073. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80074. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80075. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80076. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80077. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80078. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80079. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80080. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80081. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80082. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80083. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80084. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80085. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80086. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80087. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80088. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80089. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80090. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80091. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80092. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80093. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80094. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80095. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80096. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80097. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80098. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80099. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80100. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80101. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80102. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80103. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80104. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80105. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80106. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80107. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80108. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80109. 0xbe9834edUL
  80110. },
  80111. {
  80112. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80113. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80114. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80115. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80116. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80117. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80118. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80119. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80120. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80121. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80122. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80123. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80124. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80125. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80126. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80127. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80128. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80129. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80130. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80131. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80132. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80133. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80134. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80135. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80136. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80137. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80138. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80139. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80140. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80141. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80142. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80143. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80144. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80145. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80146. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80147. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80148. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80149. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80150. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80151. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80152. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80153. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80154. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80155. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80156. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80157. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80158. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80159. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80160. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80161. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80162. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80163. 0xde0506f1UL
  80164. },
  80165. {
  80166. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80167. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80168. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80169. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80170. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80171. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80172. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80173. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80174. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80175. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80176. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80177. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80178. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80179. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80180. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80181. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80182. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80183. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80184. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80185. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80186. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80187. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80188. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80189. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80190. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80191. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80192. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80193. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80194. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80195. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80196. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80197. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80198. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80199. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80200. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80201. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80202. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80203. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80204. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80205. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80206. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80207. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80208. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80209. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80210. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80211. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80212. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80213. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80214. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80215. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80216. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80217. 0x8def022dUL
  80218. },
  80219. {
  80220. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80221. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80222. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80223. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80224. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80225. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80226. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80227. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80228. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80229. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80230. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80231. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80232. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80233. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80234. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80235. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80236. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80237. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80238. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80239. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80240. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80241. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80242. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80243. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80244. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80245. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80246. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80247. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80248. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80249. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80250. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80251. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80252. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80253. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80254. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80255. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80256. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80257. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80258. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80259. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80260. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80261. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80262. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80263. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80264. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80265. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80266. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80267. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80268. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80269. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80270. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80271. 0x72fd2493UL
  80272. },
  80273. {
  80274. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80275. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80276. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80277. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80278. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80279. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80280. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80281. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80282. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80283. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80284. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80285. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80286. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80287. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80288. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80289. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80290. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80291. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80292. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80293. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80294. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80295. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80296. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80297. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80298. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80299. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80300. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80301. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80302. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80303. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80304. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80305. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80306. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80307. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80308. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80309. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80310. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80311. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80312. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80313. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80314. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80315. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80316. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80317. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80318. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80319. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80320. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80321. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80322. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80323. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80324. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80325. 0xed3498beUL
  80326. },
  80327. {
  80328. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80329. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80330. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80331. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80332. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80333. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80334. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80335. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80336. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80337. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80338. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80339. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80340. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80341. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80342. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80343. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80344. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80345. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80346. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80347. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80348. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80349. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80350. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80351. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80352. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80353. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80354. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80355. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80356. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80357. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80358. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80359. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80360. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80361. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80362. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80363. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80364. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80365. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80366. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80367. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80368. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80369. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80370. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80371. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80372. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80373. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80374. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80375. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80376. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80377. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80378. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80379. 0xf10605deUL
  80380. #endif
  80381. }
  80382. };
  80383. /*** End of inlined file: crc32.h ***/
  80384. #endif /* DYNAMIC_CRC_TABLE */
  80385. /* =========================================================================
  80386. * This function can be used by asm versions of crc32()
  80387. */
  80388. const unsigned long FAR * ZEXPORT get_crc_table()
  80389. {
  80390. #ifdef DYNAMIC_CRC_TABLE
  80391. if (crc_table_empty)
  80392. make_crc_table();
  80393. #endif /* DYNAMIC_CRC_TABLE */
  80394. return (const unsigned long FAR *)crc_table;
  80395. }
  80396. /* ========================================================================= */
  80397. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80398. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80399. /* ========================================================================= */
  80400. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80401. {
  80402. if (buf == Z_NULL) return 0UL;
  80403. #ifdef DYNAMIC_CRC_TABLE
  80404. if (crc_table_empty)
  80405. make_crc_table();
  80406. #endif /* DYNAMIC_CRC_TABLE */
  80407. #ifdef BYFOUR
  80408. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80409. u4 endian;
  80410. endian = 1;
  80411. if (*((unsigned char *)(&endian)))
  80412. return crc32_little(crc, buf, len);
  80413. else
  80414. return crc32_big(crc, buf, len);
  80415. }
  80416. #endif /* BYFOUR */
  80417. crc = crc ^ 0xffffffffUL;
  80418. while (len >= 8) {
  80419. DO8;
  80420. len -= 8;
  80421. }
  80422. if (len) do {
  80423. DO1;
  80424. } while (--len);
  80425. return crc ^ 0xffffffffUL;
  80426. }
  80427. #ifdef BYFOUR
  80428. /* ========================================================================= */
  80429. #define DOLIT4 c ^= *buf4++; \
  80430. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80431. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80432. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80433. /* ========================================================================= */
  80434. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80435. {
  80436. register u4 c;
  80437. register const u4 FAR *buf4;
  80438. c = (u4)crc;
  80439. c = ~c;
  80440. while (len && ((ptrdiff_t)buf & 3)) {
  80441. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80442. len--;
  80443. }
  80444. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80445. while (len >= 32) {
  80446. DOLIT32;
  80447. len -= 32;
  80448. }
  80449. while (len >= 4) {
  80450. DOLIT4;
  80451. len -= 4;
  80452. }
  80453. buf = (const unsigned char FAR *)buf4;
  80454. if (len) do {
  80455. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80456. } while (--len);
  80457. c = ~c;
  80458. return (unsigned long)c;
  80459. }
  80460. /* ========================================================================= */
  80461. #define DOBIG4 c ^= *++buf4; \
  80462. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80463. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80464. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80465. /* ========================================================================= */
  80466. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80467. {
  80468. register u4 c;
  80469. register const u4 FAR *buf4;
  80470. c = REV((u4)crc);
  80471. c = ~c;
  80472. while (len && ((ptrdiff_t)buf & 3)) {
  80473. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80474. len--;
  80475. }
  80476. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80477. buf4--;
  80478. while (len >= 32) {
  80479. DOBIG32;
  80480. len -= 32;
  80481. }
  80482. while (len >= 4) {
  80483. DOBIG4;
  80484. len -= 4;
  80485. }
  80486. buf4++;
  80487. buf = (const unsigned char FAR *)buf4;
  80488. if (len) do {
  80489. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80490. } while (--len);
  80491. c = ~c;
  80492. return (unsigned long)(REV(c));
  80493. }
  80494. #endif /* BYFOUR */
  80495. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80496. /* ========================================================================= */
  80497. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80498. {
  80499. unsigned long sum;
  80500. sum = 0;
  80501. while (vec) {
  80502. if (vec & 1)
  80503. sum ^= *mat;
  80504. vec >>= 1;
  80505. mat++;
  80506. }
  80507. return sum;
  80508. }
  80509. /* ========================================================================= */
  80510. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80511. {
  80512. int n;
  80513. for (n = 0; n < GF2_DIM; n++)
  80514. square[n] = gf2_matrix_times(mat, mat[n]);
  80515. }
  80516. /* ========================================================================= */
  80517. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80518. {
  80519. int n;
  80520. unsigned long row;
  80521. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80522. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80523. /* degenerate case */
  80524. if (len2 == 0)
  80525. return crc1;
  80526. /* put operator for one zero bit in odd */
  80527. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80528. row = 1;
  80529. for (n = 1; n < GF2_DIM; n++) {
  80530. odd[n] = row;
  80531. row <<= 1;
  80532. }
  80533. /* put operator for two zero bits in even */
  80534. gf2_matrix_square(even, odd);
  80535. /* put operator for four zero bits in odd */
  80536. gf2_matrix_square(odd, even);
  80537. /* apply len2 zeros to crc1 (first square will put the operator for one
  80538. zero byte, eight zero bits, in even) */
  80539. do {
  80540. /* apply zeros operator for this bit of len2 */
  80541. gf2_matrix_square(even, odd);
  80542. if (len2 & 1)
  80543. crc1 = gf2_matrix_times(even, crc1);
  80544. len2 >>= 1;
  80545. /* if no more bits set, then done */
  80546. if (len2 == 0)
  80547. break;
  80548. /* another iteration of the loop with odd and even swapped */
  80549. gf2_matrix_square(odd, even);
  80550. if (len2 & 1)
  80551. crc1 = gf2_matrix_times(odd, crc1);
  80552. len2 >>= 1;
  80553. /* if no more bits set, then done */
  80554. } while (len2 != 0);
  80555. /* return combined crc */
  80556. crc1 ^= crc2;
  80557. return crc1;
  80558. }
  80559. /*** End of inlined file: crc32.c ***/
  80560. /*** Start of inlined file: deflate.c ***/
  80561. /*
  80562. * ALGORITHM
  80563. *
  80564. * The "deflation" process depends on being able to identify portions
  80565. * of the input text which are identical to earlier input (within a
  80566. * sliding window trailing behind the input currently being processed).
  80567. *
  80568. * The most straightforward technique turns out to be the fastest for
  80569. * most input files: try all possible matches and select the longest.
  80570. * The key feature of this algorithm is that insertions into the string
  80571. * dictionary are very simple and thus fast, and deletions are avoided
  80572. * completely. Insertions are performed at each input character, whereas
  80573. * string matches are performed only when the previous match ends. So it
  80574. * is preferable to spend more time in matches to allow very fast string
  80575. * insertions and avoid deletions. The matching algorithm for small
  80576. * strings is inspired from that of Rabin & Karp. A brute force approach
  80577. * is used to find longer strings when a small match has been found.
  80578. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80579. * (by Leonid Broukhis).
  80580. * A previous version of this file used a more sophisticated algorithm
  80581. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80582. * time, but has a larger average cost, uses more memory and is patented.
  80583. * However the F&G algorithm may be faster for some highly redundant
  80584. * files if the parameter max_chain_length (described below) is too large.
  80585. *
  80586. * ACKNOWLEDGEMENTS
  80587. *
  80588. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80589. * I found it in 'freeze' written by Leonid Broukhis.
  80590. * Thanks to many people for bug reports and testing.
  80591. *
  80592. * REFERENCES
  80593. *
  80594. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80595. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80596. *
  80597. * A description of the Rabin and Karp algorithm is given in the book
  80598. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80599. *
  80600. * Fiala,E.R., and Greene,D.H.
  80601. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80602. *
  80603. */
  80604. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80605. /*** Start of inlined file: deflate.h ***/
  80606. /* WARNING: this file should *not* be used by applications. It is
  80607. part of the implementation of the compression library and is
  80608. subject to change. Applications should only use zlib.h.
  80609. */
  80610. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80611. #ifndef DEFLATE_H
  80612. #define DEFLATE_H
  80613. /* define NO_GZIP when compiling if you want to disable gzip header and
  80614. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80615. the crc code when it is not needed. For shared libraries, gzip encoding
  80616. should be left enabled. */
  80617. #ifndef NO_GZIP
  80618. # define GZIP
  80619. #endif
  80620. #define NO_DUMMY_DECL
  80621. /* ===========================================================================
  80622. * Internal compression state.
  80623. */
  80624. #define LENGTH_CODES 29
  80625. /* number of length codes, not counting the special END_BLOCK code */
  80626. #define LITERALS 256
  80627. /* number of literal bytes 0..255 */
  80628. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80629. /* number of Literal or Length codes, including the END_BLOCK code */
  80630. #define D_CODES 30
  80631. /* number of distance codes */
  80632. #define BL_CODES 19
  80633. /* number of codes used to transfer the bit lengths */
  80634. #define HEAP_SIZE (2*L_CODES+1)
  80635. /* maximum heap size */
  80636. #define MAX_BITS 15
  80637. /* All codes must not exceed MAX_BITS bits */
  80638. #define INIT_STATE 42
  80639. #define EXTRA_STATE 69
  80640. #define NAME_STATE 73
  80641. #define COMMENT_STATE 91
  80642. #define HCRC_STATE 103
  80643. #define BUSY_STATE 113
  80644. #define FINISH_STATE 666
  80645. /* Stream status */
  80646. /* Data structure describing a single value and its code string. */
  80647. typedef struct ct_data_s {
  80648. union {
  80649. ush freq; /* frequency count */
  80650. ush code; /* bit string */
  80651. } fc;
  80652. union {
  80653. ush dad; /* father node in Huffman tree */
  80654. ush len; /* length of bit string */
  80655. } dl;
  80656. } FAR ct_data;
  80657. #define Freq fc.freq
  80658. #define Code fc.code
  80659. #define Dad dl.dad
  80660. #define Len dl.len
  80661. typedef struct static_tree_desc_s static_tree_desc;
  80662. typedef struct tree_desc_s {
  80663. ct_data *dyn_tree; /* the dynamic tree */
  80664. int max_code; /* largest code with non zero frequency */
  80665. static_tree_desc *stat_desc; /* the corresponding static tree */
  80666. } FAR tree_desc;
  80667. typedef ush Pos;
  80668. typedef Pos FAR Posf;
  80669. typedef unsigned IPos;
  80670. /* A Pos is an index in the character window. We use short instead of int to
  80671. * save space in the various tables. IPos is used only for parameter passing.
  80672. */
  80673. typedef struct internal_state {
  80674. z_streamp strm; /* pointer back to this zlib stream */
  80675. int status; /* as the name implies */
  80676. Bytef *pending_buf; /* output still pending */
  80677. ulg pending_buf_size; /* size of pending_buf */
  80678. Bytef *pending_out; /* next pending byte to output to the stream */
  80679. uInt pending; /* nb of bytes in the pending buffer */
  80680. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80681. gz_headerp gzhead; /* gzip header information to write */
  80682. uInt gzindex; /* where in extra, name, or comment */
  80683. Byte method; /* STORED (for zip only) or DEFLATED */
  80684. int last_flush; /* value of flush param for previous deflate call */
  80685. /* used by deflate.c: */
  80686. uInt w_size; /* LZ77 window size (32K by default) */
  80687. uInt w_bits; /* log2(w_size) (8..16) */
  80688. uInt w_mask; /* w_size - 1 */
  80689. Bytef *window;
  80690. /* Sliding window. Input bytes are read into the second half of the window,
  80691. * and move to the first half later to keep a dictionary of at least wSize
  80692. * bytes. With this organization, matches are limited to a distance of
  80693. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80694. * performed with a length multiple of the block size. Also, it limits
  80695. * the window size to 64K, which is quite useful on MSDOS.
  80696. * To do: use the user input buffer as sliding window.
  80697. */
  80698. ulg window_size;
  80699. /* Actual size of window: 2*wSize, except when the user input buffer
  80700. * is directly used as sliding window.
  80701. */
  80702. Posf *prev;
  80703. /* Link to older string with same hash index. To limit the size of this
  80704. * array to 64K, this link is maintained only for the last 32K strings.
  80705. * An index in this array is thus a window index modulo 32K.
  80706. */
  80707. Posf *head; /* Heads of the hash chains or NIL. */
  80708. uInt ins_h; /* hash index of string to be inserted */
  80709. uInt hash_size; /* number of elements in hash table */
  80710. uInt hash_bits; /* log2(hash_size) */
  80711. uInt hash_mask; /* hash_size-1 */
  80712. uInt hash_shift;
  80713. /* Number of bits by which ins_h must be shifted at each input
  80714. * step. It must be such that after MIN_MATCH steps, the oldest
  80715. * byte no longer takes part in the hash key, that is:
  80716. * hash_shift * MIN_MATCH >= hash_bits
  80717. */
  80718. long block_start;
  80719. /* Window position at the beginning of the current output block. Gets
  80720. * negative when the window is moved backwards.
  80721. */
  80722. uInt match_length; /* length of best match */
  80723. IPos prev_match; /* previous match */
  80724. int match_available; /* set if previous match exists */
  80725. uInt strstart; /* start of string to insert */
  80726. uInt match_start; /* start of matching string */
  80727. uInt lookahead; /* number of valid bytes ahead in window */
  80728. uInt prev_length;
  80729. /* Length of the best match at previous step. Matches not greater than this
  80730. * are discarded. This is used in the lazy match evaluation.
  80731. */
  80732. uInt max_chain_length;
  80733. /* To speed up deflation, hash chains are never searched beyond this
  80734. * length. A higher limit improves compression ratio but degrades the
  80735. * speed.
  80736. */
  80737. uInt max_lazy_match;
  80738. /* Attempt to find a better match only when the current match is strictly
  80739. * smaller than this value. This mechanism is used only for compression
  80740. * levels >= 4.
  80741. */
  80742. # define max_insert_length max_lazy_match
  80743. /* Insert new strings in the hash table only if the match length is not
  80744. * greater than this length. This saves time but degrades compression.
  80745. * max_insert_length is used only for compression levels <= 3.
  80746. */
  80747. int level; /* compression level (1..9) */
  80748. int strategy; /* favor or force Huffman coding*/
  80749. uInt good_match;
  80750. /* Use a faster search when the previous match is longer than this */
  80751. int nice_match; /* Stop searching when current match exceeds this */
  80752. /* used by trees.c: */
  80753. /* Didn't use ct_data typedef below to supress compiler warning */
  80754. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80755. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80756. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80757. struct tree_desc_s l_desc; /* desc. for literal tree */
  80758. struct tree_desc_s d_desc; /* desc. for distance tree */
  80759. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80760. ush bl_count[MAX_BITS+1];
  80761. /* number of codes at each bit length for an optimal tree */
  80762. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80763. int heap_len; /* number of elements in the heap */
  80764. int heap_max; /* element of largest frequency */
  80765. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80766. * The same heap array is used to build all trees.
  80767. */
  80768. uch depth[2*L_CODES+1];
  80769. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80770. */
  80771. uchf *l_buf; /* buffer for literals or lengths */
  80772. uInt lit_bufsize;
  80773. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80774. * limiting lit_bufsize to 64K:
  80775. * - frequencies can be kept in 16 bit counters
  80776. * - if compression is not successful for the first block, all input
  80777. * data is still in the window so we can still emit a stored block even
  80778. * when input comes from standard input. (This can also be done for
  80779. * all blocks if lit_bufsize is not greater than 32K.)
  80780. * - if compression is not successful for a file smaller than 64K, we can
  80781. * even emit a stored file instead of a stored block (saving 5 bytes).
  80782. * This is applicable only for zip (not gzip or zlib).
  80783. * - creating new Huffman trees less frequently may not provide fast
  80784. * adaptation to changes in the input data statistics. (Take for
  80785. * example a binary file with poorly compressible code followed by
  80786. * a highly compressible string table.) Smaller buffer sizes give
  80787. * fast adaptation but have of course the overhead of transmitting
  80788. * trees more frequently.
  80789. * - I can't count above 4
  80790. */
  80791. uInt last_lit; /* running index in l_buf */
  80792. ushf *d_buf;
  80793. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80794. * the same number of elements. To use different lengths, an extra flag
  80795. * array would be necessary.
  80796. */
  80797. ulg opt_len; /* bit length of current block with optimal trees */
  80798. ulg static_len; /* bit length of current block with static trees */
  80799. uInt matches; /* number of string matches in current block */
  80800. int last_eob_len; /* bit length of EOB code for last block */
  80801. #ifdef DEBUG
  80802. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80803. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80804. #endif
  80805. ush bi_buf;
  80806. /* Output buffer. bits are inserted starting at the bottom (least
  80807. * significant bits).
  80808. */
  80809. int bi_valid;
  80810. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80811. * are always zero.
  80812. */
  80813. } FAR deflate_state;
  80814. /* Output a byte on the stream.
  80815. * IN assertion: there is enough room in pending_buf.
  80816. */
  80817. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80818. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80819. /* Minimum amount of lookahead, except at the end of the input file.
  80820. * See deflate.c for comments about the MIN_MATCH+1.
  80821. */
  80822. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80823. /* In order to simplify the code, particularly on 16 bit machines, match
  80824. * distances are limited to MAX_DIST instead of WSIZE.
  80825. */
  80826. /* in trees.c */
  80827. void _tr_init OF((deflate_state *s));
  80828. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80829. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80830. int eof));
  80831. void _tr_align OF((deflate_state *s));
  80832. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80833. int eof));
  80834. #define d_code(dist) \
  80835. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80836. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80837. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80838. * used.
  80839. */
  80840. #ifndef DEBUG
  80841. /* Inline versions of _tr_tally for speed: */
  80842. #if defined(GEN_TREES_H) || !defined(STDC)
  80843. extern uch _length_code[];
  80844. extern uch _dist_code[];
  80845. #else
  80846. extern const uch _length_code[];
  80847. extern const uch _dist_code[];
  80848. #endif
  80849. # define _tr_tally_lit(s, c, flush) \
  80850. { uch cc = (c); \
  80851. s->d_buf[s->last_lit] = 0; \
  80852. s->l_buf[s->last_lit++] = cc; \
  80853. s->dyn_ltree[cc].Freq++; \
  80854. flush = (s->last_lit == s->lit_bufsize-1); \
  80855. }
  80856. # define _tr_tally_dist(s, distance, length, flush) \
  80857. { uch len = (length); \
  80858. ush dist = (distance); \
  80859. s->d_buf[s->last_lit] = dist; \
  80860. s->l_buf[s->last_lit++] = len; \
  80861. dist--; \
  80862. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80863. s->dyn_dtree[d_code(dist)].Freq++; \
  80864. flush = (s->last_lit == s->lit_bufsize-1); \
  80865. }
  80866. #else
  80867. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80868. # define _tr_tally_dist(s, distance, length, flush) \
  80869. flush = _tr_tally(s, distance, length)
  80870. #endif
  80871. #endif /* DEFLATE_H */
  80872. /*** End of inlined file: deflate.h ***/
  80873. const char deflate_copyright[] =
  80874. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80875. /*
  80876. If you use the zlib library in a product, an acknowledgment is welcome
  80877. in the documentation of your product. If for some reason you cannot
  80878. include such an acknowledgment, I would appreciate that you keep this
  80879. copyright string in the executable of your product.
  80880. */
  80881. /* ===========================================================================
  80882. * Function prototypes.
  80883. */
  80884. typedef enum {
  80885. need_more, /* block not completed, need more input or more output */
  80886. block_done, /* block flush performed */
  80887. finish_started, /* finish started, need only more output at next deflate */
  80888. finish_done /* finish done, accept no more input or output */
  80889. } block_state;
  80890. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80891. /* Compression function. Returns the block state after the call. */
  80892. local void fill_window OF((deflate_state *s));
  80893. local block_state deflate_stored OF((deflate_state *s, int flush));
  80894. local block_state deflate_fast OF((deflate_state *s, int flush));
  80895. #ifndef FASTEST
  80896. local block_state deflate_slow OF((deflate_state *s, int flush));
  80897. #endif
  80898. local void lm_init OF((deflate_state *s));
  80899. local void putShortMSB OF((deflate_state *s, uInt b));
  80900. local void flush_pending OF((z_streamp strm));
  80901. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80902. #ifndef FASTEST
  80903. #ifdef ASMV
  80904. void match_init OF((void)); /* asm code initialization */
  80905. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80906. #else
  80907. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80908. #endif
  80909. #endif
  80910. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80911. #ifdef DEBUG
  80912. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80913. int length));
  80914. #endif
  80915. /* ===========================================================================
  80916. * Local data
  80917. */
  80918. #define NIL 0
  80919. /* Tail of hash chains */
  80920. #ifndef TOO_FAR
  80921. # define TOO_FAR 4096
  80922. #endif
  80923. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80924. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80925. /* Minimum amount of lookahead, except at the end of the input file.
  80926. * See deflate.c for comments about the MIN_MATCH+1.
  80927. */
  80928. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80929. * the desired pack level (0..9). The values given below have been tuned to
  80930. * exclude worst case performance for pathological files. Better values may be
  80931. * found for specific files.
  80932. */
  80933. typedef struct config_s {
  80934. ush good_length; /* reduce lazy search above this match length */
  80935. ush max_lazy; /* do not perform lazy search above this match length */
  80936. ush nice_length; /* quit search above this match length */
  80937. ush max_chain;
  80938. compress_func func;
  80939. } config;
  80940. #ifdef FASTEST
  80941. local const config configuration_table[2] = {
  80942. /* good lazy nice chain */
  80943. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80944. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80945. #else
  80946. local const config configuration_table[10] = {
  80947. /* good lazy nice chain */
  80948. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80949. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80950. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80951. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80952. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80953. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80954. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80955. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80956. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80957. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80958. #endif
  80959. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80960. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80961. * meaning.
  80962. */
  80963. #define EQUAL 0
  80964. /* result of memcmp for equal strings */
  80965. #ifndef NO_DUMMY_DECL
  80966. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80967. #endif
  80968. /* ===========================================================================
  80969. * Update a hash value with the given input byte
  80970. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80971. * input characters, so that a running hash key can be computed from the
  80972. * previous key instead of complete recalculation each time.
  80973. */
  80974. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80975. /* ===========================================================================
  80976. * Insert string str in the dictionary and set match_head to the previous head
  80977. * of the hash chain (the most recent string with same hash key). Return
  80978. * the previous length of the hash chain.
  80979. * If this file is compiled with -DFASTEST, the compression level is forced
  80980. * to 1, and no hash chains are maintained.
  80981. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80982. * input characters and the first MIN_MATCH bytes of str are valid
  80983. * (except for the last MIN_MATCH-1 bytes of the input file).
  80984. */
  80985. #ifdef FASTEST
  80986. #define INSERT_STRING(s, str, match_head) \
  80987. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80988. match_head = s->head[s->ins_h], \
  80989. s->head[s->ins_h] = (Pos)(str))
  80990. #else
  80991. #define INSERT_STRING(s, str, match_head) \
  80992. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80993. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80994. s->head[s->ins_h] = (Pos)(str))
  80995. #endif
  80996. /* ===========================================================================
  80997. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80998. * prev[] will be initialized on the fly.
  80999. */
  81000. #define CLEAR_HASH(s) \
  81001. s->head[s->hash_size-1] = NIL; \
  81002. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81003. /* ========================================================================= */
  81004. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81005. {
  81006. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81007. Z_DEFAULT_STRATEGY, version, stream_size);
  81008. /* To do: ignore strm->next_in if we use it as window */
  81009. }
  81010. /* ========================================================================= */
  81011. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81012. {
  81013. deflate_state *s;
  81014. int wrap = 1;
  81015. static const char my_version[] = ZLIB_VERSION;
  81016. ushf *overlay;
  81017. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81018. * output size for (length,distance) codes is <= 24 bits.
  81019. */
  81020. if (version == Z_NULL || version[0] != my_version[0] ||
  81021. stream_size != sizeof(z_stream)) {
  81022. return Z_VERSION_ERROR;
  81023. }
  81024. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81025. strm->msg = Z_NULL;
  81026. if (strm->zalloc == (alloc_func)0) {
  81027. strm->zalloc = zcalloc;
  81028. strm->opaque = (voidpf)0;
  81029. }
  81030. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81031. #ifdef FASTEST
  81032. if (level != 0) level = 1;
  81033. #else
  81034. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81035. #endif
  81036. if (windowBits < 0) { /* suppress zlib wrapper */
  81037. wrap = 0;
  81038. windowBits = -windowBits;
  81039. }
  81040. #ifdef GZIP
  81041. else if (windowBits > 15) {
  81042. wrap = 2; /* write gzip wrapper instead */
  81043. windowBits -= 16;
  81044. }
  81045. #endif
  81046. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81047. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81048. strategy < 0 || strategy > Z_FIXED) {
  81049. return Z_STREAM_ERROR;
  81050. }
  81051. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81052. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81053. if (s == Z_NULL) return Z_MEM_ERROR;
  81054. strm->state = (struct internal_state FAR *)s;
  81055. s->strm = strm;
  81056. s->wrap = wrap;
  81057. s->gzhead = Z_NULL;
  81058. s->w_bits = windowBits;
  81059. s->w_size = 1 << s->w_bits;
  81060. s->w_mask = s->w_size - 1;
  81061. s->hash_bits = memLevel + 7;
  81062. s->hash_size = 1 << s->hash_bits;
  81063. s->hash_mask = s->hash_size - 1;
  81064. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81065. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81066. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81067. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81068. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81069. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81070. s->pending_buf = (uchf *) overlay;
  81071. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81072. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81073. s->pending_buf == Z_NULL) {
  81074. s->status = FINISH_STATE;
  81075. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81076. deflateEnd (strm);
  81077. return Z_MEM_ERROR;
  81078. }
  81079. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81080. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81081. s->level = level;
  81082. s->strategy = strategy;
  81083. s->method = (Byte)method;
  81084. return deflateReset(strm);
  81085. }
  81086. /* ========================================================================= */
  81087. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81088. {
  81089. deflate_state *s;
  81090. uInt length = dictLength;
  81091. uInt n;
  81092. IPos hash_head = 0;
  81093. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81094. strm->state->wrap == 2 ||
  81095. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81096. return Z_STREAM_ERROR;
  81097. s = strm->state;
  81098. if (s->wrap)
  81099. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81100. if (length < MIN_MATCH) return Z_OK;
  81101. if (length > MAX_DIST(s)) {
  81102. length = MAX_DIST(s);
  81103. dictionary += dictLength - length; /* use the tail of the dictionary */
  81104. }
  81105. zmemcpy(s->window, dictionary, length);
  81106. s->strstart = length;
  81107. s->block_start = (long)length;
  81108. /* Insert all strings in the hash table (except for the last two bytes).
  81109. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81110. * call of fill_window.
  81111. */
  81112. s->ins_h = s->window[0];
  81113. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81114. for (n = 0; n <= length - MIN_MATCH; n++) {
  81115. INSERT_STRING(s, n, hash_head);
  81116. }
  81117. if (hash_head) hash_head = 0; /* to make compiler happy */
  81118. return Z_OK;
  81119. }
  81120. /* ========================================================================= */
  81121. int ZEXPORT deflateReset (z_streamp strm)
  81122. {
  81123. deflate_state *s;
  81124. if (strm == Z_NULL || strm->state == Z_NULL ||
  81125. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81126. return Z_STREAM_ERROR;
  81127. }
  81128. strm->total_in = strm->total_out = 0;
  81129. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81130. strm->data_type = Z_UNKNOWN;
  81131. s = (deflate_state *)strm->state;
  81132. s->pending = 0;
  81133. s->pending_out = s->pending_buf;
  81134. if (s->wrap < 0) {
  81135. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81136. }
  81137. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81138. strm->adler =
  81139. #ifdef GZIP
  81140. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81141. #endif
  81142. adler32(0L, Z_NULL, 0);
  81143. s->last_flush = Z_NO_FLUSH;
  81144. _tr_init(s);
  81145. lm_init(s);
  81146. return Z_OK;
  81147. }
  81148. /* ========================================================================= */
  81149. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81150. {
  81151. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81152. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81153. strm->state->gzhead = head;
  81154. return Z_OK;
  81155. }
  81156. /* ========================================================================= */
  81157. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81158. {
  81159. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81160. strm->state->bi_valid = bits;
  81161. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81162. return Z_OK;
  81163. }
  81164. /* ========================================================================= */
  81165. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81166. {
  81167. deflate_state *s;
  81168. compress_func func;
  81169. int err = Z_OK;
  81170. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81171. s = strm->state;
  81172. #ifdef FASTEST
  81173. if (level != 0) level = 1;
  81174. #else
  81175. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81176. #endif
  81177. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81178. return Z_STREAM_ERROR;
  81179. }
  81180. func = configuration_table[s->level].func;
  81181. if (func != configuration_table[level].func && strm->total_in != 0) {
  81182. /* Flush the last buffer: */
  81183. err = deflate(strm, Z_PARTIAL_FLUSH);
  81184. }
  81185. if (s->level != level) {
  81186. s->level = level;
  81187. s->max_lazy_match = configuration_table[level].max_lazy;
  81188. s->good_match = configuration_table[level].good_length;
  81189. s->nice_match = configuration_table[level].nice_length;
  81190. s->max_chain_length = configuration_table[level].max_chain;
  81191. }
  81192. s->strategy = strategy;
  81193. return err;
  81194. }
  81195. /* ========================================================================= */
  81196. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81197. {
  81198. deflate_state *s;
  81199. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81200. s = strm->state;
  81201. s->good_match = good_length;
  81202. s->max_lazy_match = max_lazy;
  81203. s->nice_match = nice_length;
  81204. s->max_chain_length = max_chain;
  81205. return Z_OK;
  81206. }
  81207. /* =========================================================================
  81208. * For the default windowBits of 15 and memLevel of 8, this function returns
  81209. * a close to exact, as well as small, upper bound on the compressed size.
  81210. * They are coded as constants here for a reason--if the #define's are
  81211. * changed, then this function needs to be changed as well. The return
  81212. * value for 15 and 8 only works for those exact settings.
  81213. *
  81214. * For any setting other than those defaults for windowBits and memLevel,
  81215. * the value returned is a conservative worst case for the maximum expansion
  81216. * resulting from using fixed blocks instead of stored blocks, which deflate
  81217. * can emit on compressed data for some combinations of the parameters.
  81218. *
  81219. * This function could be more sophisticated to provide closer upper bounds
  81220. * for every combination of windowBits and memLevel, as well as wrap.
  81221. * But even the conservative upper bound of about 14% expansion does not
  81222. * seem onerous for output buffer allocation.
  81223. */
  81224. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81225. {
  81226. deflate_state *s;
  81227. uLong destLen;
  81228. /* conservative upper bound */
  81229. destLen = sourceLen +
  81230. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81231. /* if can't get parameters, return conservative bound */
  81232. if (strm == Z_NULL || strm->state == Z_NULL)
  81233. return destLen;
  81234. /* if not default parameters, return conservative bound */
  81235. s = strm->state;
  81236. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81237. return destLen;
  81238. /* default settings: return tight bound for that case */
  81239. return compressBound(sourceLen);
  81240. }
  81241. /* =========================================================================
  81242. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81243. * IN assertion: the stream state is correct and there is enough room in
  81244. * pending_buf.
  81245. */
  81246. local void putShortMSB (deflate_state *s, uInt b)
  81247. {
  81248. put_byte(s, (Byte)(b >> 8));
  81249. put_byte(s, (Byte)(b & 0xff));
  81250. }
  81251. /* =========================================================================
  81252. * Flush as much pending output as possible. All deflate() output goes
  81253. * through this function so some applications may wish to modify it
  81254. * to avoid allocating a large strm->next_out buffer and copying into it.
  81255. * (See also read_buf()).
  81256. */
  81257. local void flush_pending (z_streamp strm)
  81258. {
  81259. unsigned len = strm->state->pending;
  81260. if (len > strm->avail_out) len = strm->avail_out;
  81261. if (len == 0) return;
  81262. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81263. strm->next_out += len;
  81264. strm->state->pending_out += len;
  81265. strm->total_out += len;
  81266. strm->avail_out -= len;
  81267. strm->state->pending -= len;
  81268. if (strm->state->pending == 0) {
  81269. strm->state->pending_out = strm->state->pending_buf;
  81270. }
  81271. }
  81272. /* ========================================================================= */
  81273. int ZEXPORT deflate (z_streamp strm, int flush)
  81274. {
  81275. int old_flush; /* value of flush param for previous deflate call */
  81276. deflate_state *s;
  81277. if (strm == Z_NULL || strm->state == Z_NULL ||
  81278. flush > Z_FINISH || flush < 0) {
  81279. return Z_STREAM_ERROR;
  81280. }
  81281. s = strm->state;
  81282. if (strm->next_out == Z_NULL ||
  81283. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81284. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81285. ERR_RETURN(strm, Z_STREAM_ERROR);
  81286. }
  81287. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81288. s->strm = strm; /* just in case */
  81289. old_flush = s->last_flush;
  81290. s->last_flush = flush;
  81291. /* Write the header */
  81292. if (s->status == INIT_STATE) {
  81293. #ifdef GZIP
  81294. if (s->wrap == 2) {
  81295. strm->adler = crc32(0L, Z_NULL, 0);
  81296. put_byte(s, 31);
  81297. put_byte(s, 139);
  81298. put_byte(s, 8);
  81299. if (s->gzhead == NULL) {
  81300. put_byte(s, 0);
  81301. put_byte(s, 0);
  81302. put_byte(s, 0);
  81303. put_byte(s, 0);
  81304. put_byte(s, 0);
  81305. put_byte(s, s->level == 9 ? 2 :
  81306. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81307. 4 : 0));
  81308. put_byte(s, OS_CODE);
  81309. s->status = BUSY_STATE;
  81310. }
  81311. else {
  81312. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81313. (s->gzhead->hcrc ? 2 : 0) +
  81314. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81315. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81316. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81317. );
  81318. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81319. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81320. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81321. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81322. put_byte(s, s->level == 9 ? 2 :
  81323. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81324. 4 : 0));
  81325. put_byte(s, s->gzhead->os & 0xff);
  81326. if (s->gzhead->extra != NULL) {
  81327. put_byte(s, s->gzhead->extra_len & 0xff);
  81328. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81329. }
  81330. if (s->gzhead->hcrc)
  81331. strm->adler = crc32(strm->adler, s->pending_buf,
  81332. s->pending);
  81333. s->gzindex = 0;
  81334. s->status = EXTRA_STATE;
  81335. }
  81336. }
  81337. else
  81338. #endif
  81339. {
  81340. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81341. uInt level_flags;
  81342. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81343. level_flags = 0;
  81344. else if (s->level < 6)
  81345. level_flags = 1;
  81346. else if (s->level == 6)
  81347. level_flags = 2;
  81348. else
  81349. level_flags = 3;
  81350. header |= (level_flags << 6);
  81351. if (s->strstart != 0) header |= PRESET_DICT;
  81352. header += 31 - (header % 31);
  81353. s->status = BUSY_STATE;
  81354. putShortMSB(s, header);
  81355. /* Save the adler32 of the preset dictionary: */
  81356. if (s->strstart != 0) {
  81357. putShortMSB(s, (uInt)(strm->adler >> 16));
  81358. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81359. }
  81360. strm->adler = adler32(0L, Z_NULL, 0);
  81361. }
  81362. }
  81363. #ifdef GZIP
  81364. if (s->status == EXTRA_STATE) {
  81365. if (s->gzhead->extra != NULL) {
  81366. uInt beg = s->pending; /* start of bytes to update crc */
  81367. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81368. if (s->pending == s->pending_buf_size) {
  81369. if (s->gzhead->hcrc && s->pending > beg)
  81370. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81371. s->pending - beg);
  81372. flush_pending(strm);
  81373. beg = s->pending;
  81374. if (s->pending == s->pending_buf_size)
  81375. break;
  81376. }
  81377. put_byte(s, s->gzhead->extra[s->gzindex]);
  81378. s->gzindex++;
  81379. }
  81380. if (s->gzhead->hcrc && s->pending > beg)
  81381. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81382. s->pending - beg);
  81383. if (s->gzindex == s->gzhead->extra_len) {
  81384. s->gzindex = 0;
  81385. s->status = NAME_STATE;
  81386. }
  81387. }
  81388. else
  81389. s->status = NAME_STATE;
  81390. }
  81391. if (s->status == NAME_STATE) {
  81392. if (s->gzhead->name != NULL) {
  81393. uInt beg = s->pending; /* start of bytes to update crc */
  81394. int val;
  81395. do {
  81396. if (s->pending == s->pending_buf_size) {
  81397. if (s->gzhead->hcrc && s->pending > beg)
  81398. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81399. s->pending - beg);
  81400. flush_pending(strm);
  81401. beg = s->pending;
  81402. if (s->pending == s->pending_buf_size) {
  81403. val = 1;
  81404. break;
  81405. }
  81406. }
  81407. val = s->gzhead->name[s->gzindex++];
  81408. put_byte(s, val);
  81409. } while (val != 0);
  81410. if (s->gzhead->hcrc && s->pending > beg)
  81411. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81412. s->pending - beg);
  81413. if (val == 0) {
  81414. s->gzindex = 0;
  81415. s->status = COMMENT_STATE;
  81416. }
  81417. }
  81418. else
  81419. s->status = COMMENT_STATE;
  81420. }
  81421. if (s->status == COMMENT_STATE) {
  81422. if (s->gzhead->comment != NULL) {
  81423. uInt beg = s->pending; /* start of bytes to update crc */
  81424. int val;
  81425. do {
  81426. if (s->pending == s->pending_buf_size) {
  81427. if (s->gzhead->hcrc && s->pending > beg)
  81428. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81429. s->pending - beg);
  81430. flush_pending(strm);
  81431. beg = s->pending;
  81432. if (s->pending == s->pending_buf_size) {
  81433. val = 1;
  81434. break;
  81435. }
  81436. }
  81437. val = s->gzhead->comment[s->gzindex++];
  81438. put_byte(s, val);
  81439. } while (val != 0);
  81440. if (s->gzhead->hcrc && s->pending > beg)
  81441. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81442. s->pending - beg);
  81443. if (val == 0)
  81444. s->status = HCRC_STATE;
  81445. }
  81446. else
  81447. s->status = HCRC_STATE;
  81448. }
  81449. if (s->status == HCRC_STATE) {
  81450. if (s->gzhead->hcrc) {
  81451. if (s->pending + 2 > s->pending_buf_size)
  81452. flush_pending(strm);
  81453. if (s->pending + 2 <= s->pending_buf_size) {
  81454. put_byte(s, (Byte)(strm->adler & 0xff));
  81455. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81456. strm->adler = crc32(0L, Z_NULL, 0);
  81457. s->status = BUSY_STATE;
  81458. }
  81459. }
  81460. else
  81461. s->status = BUSY_STATE;
  81462. }
  81463. #endif
  81464. /* Flush as much pending output as possible */
  81465. if (s->pending != 0) {
  81466. flush_pending(strm);
  81467. if (strm->avail_out == 0) {
  81468. /* Since avail_out is 0, deflate will be called again with
  81469. * more output space, but possibly with both pending and
  81470. * avail_in equal to zero. There won't be anything to do,
  81471. * but this is not an error situation so make sure we
  81472. * return OK instead of BUF_ERROR at next call of deflate:
  81473. */
  81474. s->last_flush = -1;
  81475. return Z_OK;
  81476. }
  81477. /* Make sure there is something to do and avoid duplicate consecutive
  81478. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81479. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81480. */
  81481. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81482. flush != Z_FINISH) {
  81483. ERR_RETURN(strm, Z_BUF_ERROR);
  81484. }
  81485. /* User must not provide more input after the first FINISH: */
  81486. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81487. ERR_RETURN(strm, Z_BUF_ERROR);
  81488. }
  81489. /* Start a new block or continue the current one.
  81490. */
  81491. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81492. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81493. block_state bstate;
  81494. bstate = (*(configuration_table[s->level].func))(s, flush);
  81495. if (bstate == finish_started || bstate == finish_done) {
  81496. s->status = FINISH_STATE;
  81497. }
  81498. if (bstate == need_more || bstate == finish_started) {
  81499. if (strm->avail_out == 0) {
  81500. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81501. }
  81502. return Z_OK;
  81503. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81504. * of deflate should use the same flush parameter to make sure
  81505. * that the flush is complete. So we don't have to output an
  81506. * empty block here, this will be done at next call. This also
  81507. * ensures that for a very small output buffer, we emit at most
  81508. * one empty block.
  81509. */
  81510. }
  81511. if (bstate == block_done) {
  81512. if (flush == Z_PARTIAL_FLUSH) {
  81513. _tr_align(s);
  81514. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81515. _tr_stored_block(s, (char*)0, 0L, 0);
  81516. /* For a full flush, this empty block will be recognized
  81517. * as a special marker by inflate_sync().
  81518. */
  81519. if (flush == Z_FULL_FLUSH) {
  81520. CLEAR_HASH(s); /* forget history */
  81521. }
  81522. }
  81523. flush_pending(strm);
  81524. if (strm->avail_out == 0) {
  81525. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81526. return Z_OK;
  81527. }
  81528. }
  81529. }
  81530. Assert(strm->avail_out > 0, "bug2");
  81531. if (flush != Z_FINISH) return Z_OK;
  81532. if (s->wrap <= 0) return Z_STREAM_END;
  81533. /* Write the trailer */
  81534. #ifdef GZIP
  81535. if (s->wrap == 2) {
  81536. put_byte(s, (Byte)(strm->adler & 0xff));
  81537. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81538. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81539. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81540. put_byte(s, (Byte)(strm->total_in & 0xff));
  81541. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81542. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81543. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81544. }
  81545. else
  81546. #endif
  81547. {
  81548. putShortMSB(s, (uInt)(strm->adler >> 16));
  81549. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81550. }
  81551. flush_pending(strm);
  81552. /* If avail_out is zero, the application will call deflate again
  81553. * to flush the rest.
  81554. */
  81555. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81556. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81557. }
  81558. /* ========================================================================= */
  81559. int ZEXPORT deflateEnd (z_streamp strm)
  81560. {
  81561. int status;
  81562. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81563. status = strm->state->status;
  81564. if (status != INIT_STATE &&
  81565. status != EXTRA_STATE &&
  81566. status != NAME_STATE &&
  81567. status != COMMENT_STATE &&
  81568. status != HCRC_STATE &&
  81569. status != BUSY_STATE &&
  81570. status != FINISH_STATE) {
  81571. return Z_STREAM_ERROR;
  81572. }
  81573. /* Deallocate in reverse order of allocations: */
  81574. TRY_FREE(strm, strm->state->pending_buf);
  81575. TRY_FREE(strm, strm->state->head);
  81576. TRY_FREE(strm, strm->state->prev);
  81577. TRY_FREE(strm, strm->state->window);
  81578. ZFREE(strm, strm->state);
  81579. strm->state = Z_NULL;
  81580. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81581. }
  81582. /* =========================================================================
  81583. * Copy the source state to the destination state.
  81584. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81585. * doesn't have enough memory anyway to duplicate compression states).
  81586. */
  81587. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81588. {
  81589. #ifdef MAXSEG_64K
  81590. return Z_STREAM_ERROR;
  81591. #else
  81592. deflate_state *ds;
  81593. deflate_state *ss;
  81594. ushf *overlay;
  81595. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81596. return Z_STREAM_ERROR;
  81597. }
  81598. ss = source->state;
  81599. zmemcpy(dest, source, sizeof(z_stream));
  81600. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81601. if (ds == Z_NULL) return Z_MEM_ERROR;
  81602. dest->state = (struct internal_state FAR *) ds;
  81603. zmemcpy(ds, ss, sizeof(deflate_state));
  81604. ds->strm = dest;
  81605. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81606. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81607. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81608. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81609. ds->pending_buf = (uchf *) overlay;
  81610. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81611. ds->pending_buf == Z_NULL) {
  81612. deflateEnd (dest);
  81613. return Z_MEM_ERROR;
  81614. }
  81615. /* following zmemcpy do not work for 16-bit MSDOS */
  81616. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81617. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81618. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81619. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81620. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81621. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81622. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81623. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81624. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81625. ds->bl_desc.dyn_tree = ds->bl_tree;
  81626. return Z_OK;
  81627. #endif /* MAXSEG_64K */
  81628. }
  81629. /* ===========================================================================
  81630. * Read a new buffer from the current input stream, update the adler32
  81631. * and total number of bytes read. All deflate() input goes through
  81632. * this function so some applications may wish to modify it to avoid
  81633. * allocating a large strm->next_in buffer and copying from it.
  81634. * (See also flush_pending()).
  81635. */
  81636. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81637. {
  81638. unsigned len = strm->avail_in;
  81639. if (len > size) len = size;
  81640. if (len == 0) return 0;
  81641. strm->avail_in -= len;
  81642. if (strm->state->wrap == 1) {
  81643. strm->adler = adler32(strm->adler, strm->next_in, len);
  81644. }
  81645. #ifdef GZIP
  81646. else if (strm->state->wrap == 2) {
  81647. strm->adler = crc32(strm->adler, strm->next_in, len);
  81648. }
  81649. #endif
  81650. zmemcpy(buf, strm->next_in, len);
  81651. strm->next_in += len;
  81652. strm->total_in += len;
  81653. return (int)len;
  81654. }
  81655. /* ===========================================================================
  81656. * Initialize the "longest match" routines for a new zlib stream
  81657. */
  81658. local void lm_init (deflate_state *s)
  81659. {
  81660. s->window_size = (ulg)2L*s->w_size;
  81661. CLEAR_HASH(s);
  81662. /* Set the default configuration parameters:
  81663. */
  81664. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81665. s->good_match = configuration_table[s->level].good_length;
  81666. s->nice_match = configuration_table[s->level].nice_length;
  81667. s->max_chain_length = configuration_table[s->level].max_chain;
  81668. s->strstart = 0;
  81669. s->block_start = 0L;
  81670. s->lookahead = 0;
  81671. s->match_length = s->prev_length = MIN_MATCH-1;
  81672. s->match_available = 0;
  81673. s->ins_h = 0;
  81674. #ifndef FASTEST
  81675. #ifdef ASMV
  81676. match_init(); /* initialize the asm code */
  81677. #endif
  81678. #endif
  81679. }
  81680. #ifndef FASTEST
  81681. /* ===========================================================================
  81682. * Set match_start to the longest match starting at the given string and
  81683. * return its length. Matches shorter or equal to prev_length are discarded,
  81684. * in which case the result is equal to prev_length and match_start is
  81685. * garbage.
  81686. * IN assertions: cur_match is the head of the hash chain for the current
  81687. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81688. * OUT assertion: the match length is not greater than s->lookahead.
  81689. */
  81690. #ifndef ASMV
  81691. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81692. * match.S. The code will be functionally equivalent.
  81693. */
  81694. local uInt longest_match(deflate_state *s, IPos cur_match)
  81695. {
  81696. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81697. register Bytef *scan = s->window + s->strstart; /* current string */
  81698. register Bytef *match; /* matched string */
  81699. register int len; /* length of current match */
  81700. int best_len = s->prev_length; /* best match length so far */
  81701. int nice_match = s->nice_match; /* stop if match long enough */
  81702. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81703. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81704. /* Stop when cur_match becomes <= limit. To simplify the code,
  81705. * we prevent matches with the string of window index 0.
  81706. */
  81707. Posf *prev = s->prev;
  81708. uInt wmask = s->w_mask;
  81709. #ifdef UNALIGNED_OK
  81710. /* Compare two bytes at a time. Note: this is not always beneficial.
  81711. * Try with and without -DUNALIGNED_OK to check.
  81712. */
  81713. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81714. register ush scan_start = *(ushf*)scan;
  81715. register ush scan_end = *(ushf*)(scan+best_len-1);
  81716. #else
  81717. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81718. register Byte scan_end1 = scan[best_len-1];
  81719. register Byte scan_end = scan[best_len];
  81720. #endif
  81721. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81722. * It is easy to get rid of this optimization if necessary.
  81723. */
  81724. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81725. /* Do not waste too much time if we already have a good match: */
  81726. if (s->prev_length >= s->good_match) {
  81727. chain_length >>= 2;
  81728. }
  81729. /* Do not look for matches beyond the end of the input. This is necessary
  81730. * to make deflate deterministic.
  81731. */
  81732. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81733. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81734. do {
  81735. Assert(cur_match < s->strstart, "no future");
  81736. match = s->window + cur_match;
  81737. /* Skip to next match if the match length cannot increase
  81738. * or if the match length is less than 2. Note that the checks below
  81739. * for insufficient lookahead only occur occasionally for performance
  81740. * reasons. Therefore uninitialized memory will be accessed, and
  81741. * conditional jumps will be made that depend on those values.
  81742. * However the length of the match is limited to the lookahead, so
  81743. * the output of deflate is not affected by the uninitialized values.
  81744. */
  81745. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81746. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81747. * UNALIGNED_OK if your compiler uses a different size.
  81748. */
  81749. if (*(ushf*)(match+best_len-1) != scan_end ||
  81750. *(ushf*)match != scan_start) continue;
  81751. /* It is not necessary to compare scan[2] and match[2] since they are
  81752. * always equal when the other bytes match, given that the hash keys
  81753. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81754. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81755. * lookahead only every 4th comparison; the 128th check will be made
  81756. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81757. * necessary to put more guard bytes at the end of the window, or
  81758. * to check more often for insufficient lookahead.
  81759. */
  81760. Assert(scan[2] == match[2], "scan[2]?");
  81761. scan++, match++;
  81762. do {
  81763. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81764. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81765. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81766. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81767. scan < strend);
  81768. /* The funny "do {}" generates better code on most compilers */
  81769. /* Here, scan <= window+strstart+257 */
  81770. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81771. if (*scan == *match) scan++;
  81772. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81773. scan = strend - (MAX_MATCH-1);
  81774. #else /* UNALIGNED_OK */
  81775. if (match[best_len] != scan_end ||
  81776. match[best_len-1] != scan_end1 ||
  81777. *match != *scan ||
  81778. *++match != scan[1]) continue;
  81779. /* The check at best_len-1 can be removed because it will be made
  81780. * again later. (This heuristic is not always a win.)
  81781. * It is not necessary to compare scan[2] and match[2] since they
  81782. * are always equal when the other bytes match, given that
  81783. * the hash keys are equal and that HASH_BITS >= 8.
  81784. */
  81785. scan += 2, match++;
  81786. Assert(*scan == *match, "match[2]?");
  81787. /* We check for insufficient lookahead only every 8th comparison;
  81788. * the 256th check will be made at strstart+258.
  81789. */
  81790. do {
  81791. } while (*++scan == *++match && *++scan == *++match &&
  81792. *++scan == *++match && *++scan == *++match &&
  81793. *++scan == *++match && *++scan == *++match &&
  81794. *++scan == *++match && *++scan == *++match &&
  81795. scan < strend);
  81796. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81797. len = MAX_MATCH - (int)(strend - scan);
  81798. scan = strend - MAX_MATCH;
  81799. #endif /* UNALIGNED_OK */
  81800. if (len > best_len) {
  81801. s->match_start = cur_match;
  81802. best_len = len;
  81803. if (len >= nice_match) break;
  81804. #ifdef UNALIGNED_OK
  81805. scan_end = *(ushf*)(scan+best_len-1);
  81806. #else
  81807. scan_end1 = scan[best_len-1];
  81808. scan_end = scan[best_len];
  81809. #endif
  81810. }
  81811. } while ((cur_match = prev[cur_match & wmask]) > limit
  81812. && --chain_length != 0);
  81813. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81814. return s->lookahead;
  81815. }
  81816. #endif /* ASMV */
  81817. #endif /* FASTEST */
  81818. /* ---------------------------------------------------------------------------
  81819. * Optimized version for level == 1 or strategy == Z_RLE only
  81820. */
  81821. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81822. {
  81823. register Bytef *scan = s->window + s->strstart; /* current string */
  81824. register Bytef *match; /* matched string */
  81825. register int len; /* length of current match */
  81826. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81827. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81828. * It is easy to get rid of this optimization if necessary.
  81829. */
  81830. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81831. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81832. Assert(cur_match < s->strstart, "no future");
  81833. match = s->window + cur_match;
  81834. /* Return failure if the match length is less than 2:
  81835. */
  81836. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81837. /* The check at best_len-1 can be removed because it will be made
  81838. * again later. (This heuristic is not always a win.)
  81839. * It is not necessary to compare scan[2] and match[2] since they
  81840. * are always equal when the other bytes match, given that
  81841. * the hash keys are equal and that HASH_BITS >= 8.
  81842. */
  81843. scan += 2, match += 2;
  81844. Assert(*scan == *match, "match[2]?");
  81845. /* We check for insufficient lookahead only every 8th comparison;
  81846. * the 256th check will be made at strstart+258.
  81847. */
  81848. do {
  81849. } while (*++scan == *++match && *++scan == *++match &&
  81850. *++scan == *++match && *++scan == *++match &&
  81851. *++scan == *++match && *++scan == *++match &&
  81852. *++scan == *++match && *++scan == *++match &&
  81853. scan < strend);
  81854. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81855. len = MAX_MATCH - (int)(strend - scan);
  81856. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81857. s->match_start = cur_match;
  81858. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81859. }
  81860. #ifdef DEBUG
  81861. /* ===========================================================================
  81862. * Check that the match at match_start is indeed a match.
  81863. */
  81864. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81865. {
  81866. /* check that the match is indeed a match */
  81867. if (zmemcmp(s->window + match,
  81868. s->window + start, length) != EQUAL) {
  81869. fprintf(stderr, " start %u, match %u, length %d\n",
  81870. start, match, length);
  81871. do {
  81872. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81873. } while (--length != 0);
  81874. z_error("invalid match");
  81875. }
  81876. if (z_verbose > 1) {
  81877. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81878. do { putc(s->window[start++], stderr); } while (--length != 0);
  81879. }
  81880. }
  81881. #else
  81882. # define check_match(s, start, match, length)
  81883. #endif /* DEBUG */
  81884. /* ===========================================================================
  81885. * Fill the window when the lookahead becomes insufficient.
  81886. * Updates strstart and lookahead.
  81887. *
  81888. * IN assertion: lookahead < MIN_LOOKAHEAD
  81889. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81890. * At least one byte has been read, or avail_in == 0; reads are
  81891. * performed for at least two bytes (required for the zip translate_eol
  81892. * option -- not supported here).
  81893. */
  81894. local void fill_window (deflate_state *s)
  81895. {
  81896. register unsigned n, m;
  81897. register Posf *p;
  81898. unsigned more; /* Amount of free space at the end of the window. */
  81899. uInt wsize = s->w_size;
  81900. do {
  81901. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81902. /* Deal with !@#$% 64K limit: */
  81903. if (sizeof(int) <= 2) {
  81904. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81905. more = wsize;
  81906. } else if (more == (unsigned)(-1)) {
  81907. /* Very unlikely, but possible on 16 bit machine if
  81908. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81909. */
  81910. more--;
  81911. }
  81912. }
  81913. /* If the window is almost full and there is insufficient lookahead,
  81914. * move the upper half to the lower one to make room in the upper half.
  81915. */
  81916. if (s->strstart >= wsize+MAX_DIST(s)) {
  81917. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81918. s->match_start -= wsize;
  81919. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81920. s->block_start -= (long) wsize;
  81921. /* Slide the hash table (could be avoided with 32 bit values
  81922. at the expense of memory usage). We slide even when level == 0
  81923. to keep the hash table consistent if we switch back to level > 0
  81924. later. (Using level 0 permanently is not an optimal usage of
  81925. zlib, so we don't care about this pathological case.)
  81926. */
  81927. /* %%% avoid this when Z_RLE */
  81928. n = s->hash_size;
  81929. p = &s->head[n];
  81930. do {
  81931. m = *--p;
  81932. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81933. } while (--n);
  81934. n = wsize;
  81935. #ifndef FASTEST
  81936. p = &s->prev[n];
  81937. do {
  81938. m = *--p;
  81939. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81940. /* If n is not on any hash chain, prev[n] is garbage but
  81941. * its value will never be used.
  81942. */
  81943. } while (--n);
  81944. #endif
  81945. more += wsize;
  81946. }
  81947. if (s->strm->avail_in == 0) return;
  81948. /* If there was no sliding:
  81949. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81950. * more == window_size - lookahead - strstart
  81951. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81952. * => more >= window_size - 2*WSIZE + 2
  81953. * In the BIG_MEM or MMAP case (not yet supported),
  81954. * window_size == input_size + MIN_LOOKAHEAD &&
  81955. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81956. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81957. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81958. */
  81959. Assert(more >= 2, "more < 2");
  81960. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81961. s->lookahead += n;
  81962. /* Initialize the hash value now that we have some input: */
  81963. if (s->lookahead >= MIN_MATCH) {
  81964. s->ins_h = s->window[s->strstart];
  81965. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81966. #if MIN_MATCH != 3
  81967. Call UPDATE_HASH() MIN_MATCH-3 more times
  81968. #endif
  81969. }
  81970. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81971. * but this is not important since only literal bytes will be emitted.
  81972. */
  81973. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81974. }
  81975. /* ===========================================================================
  81976. * Flush the current block, with given end-of-file flag.
  81977. * IN assertion: strstart is set to the end of the current match.
  81978. */
  81979. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81980. _tr_flush_block(s, (s->block_start >= 0L ? \
  81981. (charf *)&s->window[(unsigned)s->block_start] : \
  81982. (charf *)Z_NULL), \
  81983. (ulg)((long)s->strstart - s->block_start), \
  81984. (eof)); \
  81985. s->block_start = s->strstart; \
  81986. flush_pending(s->strm); \
  81987. Tracev((stderr,"[FLUSH]")); \
  81988. }
  81989. /* Same but force premature exit if necessary. */
  81990. #define FLUSH_BLOCK(s, eof) { \
  81991. FLUSH_BLOCK_ONLY(s, eof); \
  81992. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81993. }
  81994. /* ===========================================================================
  81995. * Copy without compression as much as possible from the input stream, return
  81996. * the current block state.
  81997. * This function does not insert new strings in the dictionary since
  81998. * uncompressible data is probably not useful. This function is used
  81999. * only for the level=0 compression option.
  82000. * NOTE: this function should be optimized to avoid extra copying from
  82001. * window to pending_buf.
  82002. */
  82003. local block_state deflate_stored(deflate_state *s, int flush)
  82004. {
  82005. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82006. * to pending_buf_size, and each stored block has a 5 byte header:
  82007. */
  82008. ulg max_block_size = 0xffff;
  82009. ulg max_start;
  82010. if (max_block_size > s->pending_buf_size - 5) {
  82011. max_block_size = s->pending_buf_size - 5;
  82012. }
  82013. /* Copy as much as possible from input to output: */
  82014. for (;;) {
  82015. /* Fill the window as much as possible: */
  82016. if (s->lookahead <= 1) {
  82017. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82018. s->block_start >= (long)s->w_size, "slide too late");
  82019. fill_window(s);
  82020. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82021. if (s->lookahead == 0) break; /* flush the current block */
  82022. }
  82023. Assert(s->block_start >= 0L, "block gone");
  82024. s->strstart += s->lookahead;
  82025. s->lookahead = 0;
  82026. /* Emit a stored block if pending_buf will be full: */
  82027. max_start = s->block_start + max_block_size;
  82028. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82029. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82030. s->lookahead = (uInt)(s->strstart - max_start);
  82031. s->strstart = (uInt)max_start;
  82032. FLUSH_BLOCK(s, 0);
  82033. }
  82034. /* Flush if we may have to slide, otherwise block_start may become
  82035. * negative and the data will be gone:
  82036. */
  82037. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82038. FLUSH_BLOCK(s, 0);
  82039. }
  82040. }
  82041. FLUSH_BLOCK(s, flush == Z_FINISH);
  82042. return flush == Z_FINISH ? finish_done : block_done;
  82043. }
  82044. /* ===========================================================================
  82045. * Compress as much as possible from the input stream, return the current
  82046. * block state.
  82047. * This function does not perform lazy evaluation of matches and inserts
  82048. * new strings in the dictionary only for unmatched strings or for short
  82049. * matches. It is used only for the fast compression options.
  82050. */
  82051. local block_state deflate_fast(deflate_state *s, int flush)
  82052. {
  82053. IPos hash_head = NIL; /* head of the hash chain */
  82054. int bflush; /* set if current block must be flushed */
  82055. for (;;) {
  82056. /* Make sure that we always have enough lookahead, except
  82057. * at the end of the input file. We need MAX_MATCH bytes
  82058. * for the next match, plus MIN_MATCH bytes to insert the
  82059. * string following the next match.
  82060. */
  82061. if (s->lookahead < MIN_LOOKAHEAD) {
  82062. fill_window(s);
  82063. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82064. return need_more;
  82065. }
  82066. if (s->lookahead == 0) break; /* flush the current block */
  82067. }
  82068. /* Insert the string window[strstart .. strstart+2] in the
  82069. * dictionary, and set hash_head to the head of the hash chain:
  82070. */
  82071. if (s->lookahead >= MIN_MATCH) {
  82072. INSERT_STRING(s, s->strstart, hash_head);
  82073. }
  82074. /* Find the longest match, discarding those <= prev_length.
  82075. * At this point we have always match_length < MIN_MATCH
  82076. */
  82077. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82078. /* To simplify the code, we prevent matches with the string
  82079. * of window index 0 (in particular we have to avoid a match
  82080. * of the string with itself at the start of the input file).
  82081. */
  82082. #ifdef FASTEST
  82083. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82084. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82085. s->match_length = longest_match_fast (s, hash_head);
  82086. }
  82087. #else
  82088. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82089. s->match_length = longest_match (s, hash_head);
  82090. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82091. s->match_length = longest_match_fast (s, hash_head);
  82092. }
  82093. #endif
  82094. /* longest_match() or longest_match_fast() sets match_start */
  82095. }
  82096. if (s->match_length >= MIN_MATCH) {
  82097. check_match(s, s->strstart, s->match_start, s->match_length);
  82098. _tr_tally_dist(s, s->strstart - s->match_start,
  82099. s->match_length - MIN_MATCH, bflush);
  82100. s->lookahead -= s->match_length;
  82101. /* Insert new strings in the hash table only if the match length
  82102. * is not too large. This saves time but degrades compression.
  82103. */
  82104. #ifndef FASTEST
  82105. if (s->match_length <= s->max_insert_length &&
  82106. s->lookahead >= MIN_MATCH) {
  82107. s->match_length--; /* string at strstart already in table */
  82108. do {
  82109. s->strstart++;
  82110. INSERT_STRING(s, s->strstart, hash_head);
  82111. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82112. * always MIN_MATCH bytes ahead.
  82113. */
  82114. } while (--s->match_length != 0);
  82115. s->strstart++;
  82116. } else
  82117. #endif
  82118. {
  82119. s->strstart += s->match_length;
  82120. s->match_length = 0;
  82121. s->ins_h = s->window[s->strstart];
  82122. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82123. #if MIN_MATCH != 3
  82124. Call UPDATE_HASH() MIN_MATCH-3 more times
  82125. #endif
  82126. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82127. * matter since it will be recomputed at next deflate call.
  82128. */
  82129. }
  82130. } else {
  82131. /* No match, output a literal byte */
  82132. Tracevv((stderr,"%c", s->window[s->strstart]));
  82133. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82134. s->lookahead--;
  82135. s->strstart++;
  82136. }
  82137. if (bflush) FLUSH_BLOCK(s, 0);
  82138. }
  82139. FLUSH_BLOCK(s, flush == Z_FINISH);
  82140. return flush == Z_FINISH ? finish_done : block_done;
  82141. }
  82142. #ifndef FASTEST
  82143. /* ===========================================================================
  82144. * Same as above, but achieves better compression. We use a lazy
  82145. * evaluation for matches: a match is finally adopted only if there is
  82146. * no better match at the next window position.
  82147. */
  82148. local block_state deflate_slow(deflate_state *s, int flush)
  82149. {
  82150. IPos hash_head = NIL; /* head of hash chain */
  82151. int bflush; /* set if current block must be flushed */
  82152. /* Process the input block. */
  82153. for (;;) {
  82154. /* Make sure that we always have enough lookahead, except
  82155. * at the end of the input file. We need MAX_MATCH bytes
  82156. * for the next match, plus MIN_MATCH bytes to insert the
  82157. * string following the next match.
  82158. */
  82159. if (s->lookahead < MIN_LOOKAHEAD) {
  82160. fill_window(s);
  82161. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82162. return need_more;
  82163. }
  82164. if (s->lookahead == 0) break; /* flush the current block */
  82165. }
  82166. /* Insert the string window[strstart .. strstart+2] in the
  82167. * dictionary, and set hash_head to the head of the hash chain:
  82168. */
  82169. if (s->lookahead >= MIN_MATCH) {
  82170. INSERT_STRING(s, s->strstart, hash_head);
  82171. }
  82172. /* Find the longest match, discarding those <= prev_length.
  82173. */
  82174. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82175. s->match_length = MIN_MATCH-1;
  82176. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82177. s->strstart - hash_head <= MAX_DIST(s)) {
  82178. /* To simplify the code, we prevent matches with the string
  82179. * of window index 0 (in particular we have to avoid a match
  82180. * of the string with itself at the start of the input file).
  82181. */
  82182. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82183. s->match_length = longest_match (s, hash_head);
  82184. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82185. s->match_length = longest_match_fast (s, hash_head);
  82186. }
  82187. /* longest_match() or longest_match_fast() sets match_start */
  82188. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82189. #if TOO_FAR <= 32767
  82190. || (s->match_length == MIN_MATCH &&
  82191. s->strstart - s->match_start > TOO_FAR)
  82192. #endif
  82193. )) {
  82194. /* If prev_match is also MIN_MATCH, match_start is garbage
  82195. * but we will ignore the current match anyway.
  82196. */
  82197. s->match_length = MIN_MATCH-1;
  82198. }
  82199. }
  82200. /* If there was a match at the previous step and the current
  82201. * match is not better, output the previous match:
  82202. */
  82203. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82204. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82205. /* Do not insert strings in hash table beyond this. */
  82206. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82207. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82208. s->prev_length - MIN_MATCH, bflush);
  82209. /* Insert in hash table all strings up to the end of the match.
  82210. * strstart-1 and strstart are already inserted. If there is not
  82211. * enough lookahead, the last two strings are not inserted in
  82212. * the hash table.
  82213. */
  82214. s->lookahead -= s->prev_length-1;
  82215. s->prev_length -= 2;
  82216. do {
  82217. if (++s->strstart <= max_insert) {
  82218. INSERT_STRING(s, s->strstart, hash_head);
  82219. }
  82220. } while (--s->prev_length != 0);
  82221. s->match_available = 0;
  82222. s->match_length = MIN_MATCH-1;
  82223. s->strstart++;
  82224. if (bflush) FLUSH_BLOCK(s, 0);
  82225. } else if (s->match_available) {
  82226. /* If there was no match at the previous position, output a
  82227. * single literal. If there was a match but the current match
  82228. * is longer, truncate the previous match to a single literal.
  82229. */
  82230. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82231. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82232. if (bflush) {
  82233. FLUSH_BLOCK_ONLY(s, 0);
  82234. }
  82235. s->strstart++;
  82236. s->lookahead--;
  82237. if (s->strm->avail_out == 0) return need_more;
  82238. } else {
  82239. /* There is no previous match to compare with, wait for
  82240. * the next step to decide.
  82241. */
  82242. s->match_available = 1;
  82243. s->strstart++;
  82244. s->lookahead--;
  82245. }
  82246. }
  82247. Assert (flush != Z_NO_FLUSH, "no flush?");
  82248. if (s->match_available) {
  82249. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82250. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82251. s->match_available = 0;
  82252. }
  82253. FLUSH_BLOCK(s, flush == Z_FINISH);
  82254. return flush == Z_FINISH ? finish_done : block_done;
  82255. }
  82256. #endif /* FASTEST */
  82257. #if 0
  82258. /* ===========================================================================
  82259. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82260. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82261. * deflate switches away from Z_RLE.)
  82262. */
  82263. local block_state deflate_rle(s, flush)
  82264. deflate_state *s;
  82265. int flush;
  82266. {
  82267. int bflush; /* set if current block must be flushed */
  82268. uInt run; /* length of run */
  82269. uInt max; /* maximum length of run */
  82270. uInt prev; /* byte at distance one to match */
  82271. Bytef *scan; /* scan for end of run */
  82272. for (;;) {
  82273. /* Make sure that we always have enough lookahead, except
  82274. * at the end of the input file. We need MAX_MATCH bytes
  82275. * for the longest encodable run.
  82276. */
  82277. if (s->lookahead < MAX_MATCH) {
  82278. fill_window(s);
  82279. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82280. return need_more;
  82281. }
  82282. if (s->lookahead == 0) break; /* flush the current block */
  82283. }
  82284. /* See how many times the previous byte repeats */
  82285. run = 0;
  82286. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82287. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82288. scan = s->window + s->strstart - 1;
  82289. prev = *scan++;
  82290. do {
  82291. if (*scan++ != prev)
  82292. break;
  82293. } while (++run < max);
  82294. }
  82295. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82296. if (run >= MIN_MATCH) {
  82297. check_match(s, s->strstart, s->strstart - 1, run);
  82298. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82299. s->lookahead -= run;
  82300. s->strstart += run;
  82301. } else {
  82302. /* No match, output a literal byte */
  82303. Tracevv((stderr,"%c", s->window[s->strstart]));
  82304. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82305. s->lookahead--;
  82306. s->strstart++;
  82307. }
  82308. if (bflush) FLUSH_BLOCK(s, 0);
  82309. }
  82310. FLUSH_BLOCK(s, flush == Z_FINISH);
  82311. return flush == Z_FINISH ? finish_done : block_done;
  82312. }
  82313. #endif
  82314. /*** End of inlined file: deflate.c ***/
  82315. /*** Start of inlined file: inffast.c ***/
  82316. /*** Start of inlined file: inftrees.h ***/
  82317. /* WARNING: this file should *not* be used by applications. It is
  82318. part of the implementation of the compression library and is
  82319. subject to change. Applications should only use zlib.h.
  82320. */
  82321. #ifndef _INFTREES_H_
  82322. #define _INFTREES_H_
  82323. /* Structure for decoding tables. Each entry provides either the
  82324. information needed to do the operation requested by the code that
  82325. indexed that table entry, or it provides a pointer to another
  82326. table that indexes more bits of the code. op indicates whether
  82327. the entry is a pointer to another table, a literal, a length or
  82328. distance, an end-of-block, or an invalid code. For a table
  82329. pointer, the low four bits of op is the number of index bits of
  82330. that table. For a length or distance, the low four bits of op
  82331. is the number of extra bits to get after the code. bits is
  82332. the number of bits in this code or part of the code to drop off
  82333. of the bit buffer. val is the actual byte to output in the case
  82334. of a literal, the base length or distance, or the offset from
  82335. the current table to the next table. Each entry is four bytes. */
  82336. typedef struct {
  82337. unsigned char op; /* operation, extra bits, table bits */
  82338. unsigned char bits; /* bits in this part of the code */
  82339. unsigned short val; /* offset in table or code value */
  82340. } code;
  82341. /* op values as set by inflate_table():
  82342. 00000000 - literal
  82343. 0000tttt - table link, tttt != 0 is the number of table index bits
  82344. 0001eeee - length or distance, eeee is the number of extra bits
  82345. 01100000 - end of block
  82346. 01000000 - invalid code
  82347. */
  82348. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82349. exhaustive search was 1444 code structures (852 for length/literals
  82350. and 592 for distances, the latter actually the result of an
  82351. exhaustive search). The true maximum is not known, but the value
  82352. below is more than safe. */
  82353. #define ENOUGH 2048
  82354. #define MAXD 592
  82355. /* Type of code to build for inftable() */
  82356. typedef enum {
  82357. CODES,
  82358. LENS,
  82359. DISTS
  82360. } codetype;
  82361. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82362. unsigned codes, code FAR * FAR *table,
  82363. unsigned FAR *bits, unsigned short FAR *work));
  82364. #endif
  82365. /*** End of inlined file: inftrees.h ***/
  82366. /*** Start of inlined file: inflate.h ***/
  82367. /* WARNING: this file should *not* be used by applications. It is
  82368. part of the implementation of the compression library and is
  82369. subject to change. Applications should only use zlib.h.
  82370. */
  82371. #ifndef _INFLATE_H_
  82372. #define _INFLATE_H_
  82373. /* define NO_GZIP when compiling if you want to disable gzip header and
  82374. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82375. the crc code when it is not needed. For shared libraries, gzip decoding
  82376. should be left enabled. */
  82377. #ifndef NO_GZIP
  82378. # define GUNZIP
  82379. #endif
  82380. /* Possible inflate modes between inflate() calls */
  82381. typedef enum {
  82382. HEAD, /* i: waiting for magic header */
  82383. FLAGS, /* i: waiting for method and flags (gzip) */
  82384. TIME, /* i: waiting for modification time (gzip) */
  82385. OS, /* i: waiting for extra flags and operating system (gzip) */
  82386. EXLEN, /* i: waiting for extra length (gzip) */
  82387. EXTRA, /* i: waiting for extra bytes (gzip) */
  82388. NAME, /* i: waiting for end of file name (gzip) */
  82389. COMMENT, /* i: waiting for end of comment (gzip) */
  82390. HCRC, /* i: waiting for header crc (gzip) */
  82391. DICTID, /* i: waiting for dictionary check value */
  82392. DICT, /* waiting for inflateSetDictionary() call */
  82393. TYPE, /* i: waiting for type bits, including last-flag bit */
  82394. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82395. STORED, /* i: waiting for stored size (length and complement) */
  82396. COPY, /* i/o: waiting for input or output to copy stored block */
  82397. TABLE, /* i: waiting for dynamic block table lengths */
  82398. LENLENS, /* i: waiting for code length code lengths */
  82399. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82400. LEN, /* i: waiting for length/lit code */
  82401. LENEXT, /* i: waiting for length extra bits */
  82402. DIST, /* i: waiting for distance code */
  82403. DISTEXT, /* i: waiting for distance extra bits */
  82404. MATCH, /* o: waiting for output space to copy string */
  82405. LIT, /* o: waiting for output space to write literal */
  82406. CHECK, /* i: waiting for 32-bit check value */
  82407. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82408. DONE, /* finished check, done -- remain here until reset */
  82409. BAD, /* got a data error -- remain here until reset */
  82410. MEM, /* got an inflate() memory error -- remain here until reset */
  82411. SYNC /* looking for synchronization bytes to restart inflate() */
  82412. } inflate_mode;
  82413. /*
  82414. State transitions between above modes -
  82415. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82416. Process header:
  82417. HEAD -> (gzip) or (zlib)
  82418. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82419. NAME -> COMMENT -> HCRC -> TYPE
  82420. (zlib) -> DICTID or TYPE
  82421. DICTID -> DICT -> TYPE
  82422. Read deflate blocks:
  82423. TYPE -> STORED or TABLE or LEN or CHECK
  82424. STORED -> COPY -> TYPE
  82425. TABLE -> LENLENS -> CODELENS -> LEN
  82426. Read deflate codes:
  82427. LEN -> LENEXT or LIT or TYPE
  82428. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82429. LIT -> LEN
  82430. Process trailer:
  82431. CHECK -> LENGTH -> DONE
  82432. */
  82433. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82434. struct inflate_state {
  82435. inflate_mode mode; /* current inflate mode */
  82436. int last; /* true if processing last block */
  82437. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82438. int havedict; /* true if dictionary provided */
  82439. int flags; /* gzip header method and flags (0 if zlib) */
  82440. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82441. unsigned long check; /* protected copy of check value */
  82442. unsigned long total; /* protected copy of output count */
  82443. gz_headerp head; /* where to save gzip header information */
  82444. /* sliding window */
  82445. unsigned wbits; /* log base 2 of requested window size */
  82446. unsigned wsize; /* window size or zero if not using window */
  82447. unsigned whave; /* valid bytes in the window */
  82448. unsigned write; /* window write index */
  82449. unsigned char FAR *window; /* allocated sliding window, if needed */
  82450. /* bit accumulator */
  82451. unsigned long hold; /* input bit accumulator */
  82452. unsigned bits; /* number of bits in "in" */
  82453. /* for string and stored block copying */
  82454. unsigned length; /* literal or length of data to copy */
  82455. unsigned offset; /* distance back to copy string from */
  82456. /* for table and code decoding */
  82457. unsigned extra; /* extra bits needed */
  82458. /* fixed and dynamic code tables */
  82459. code const FAR *lencode; /* starting table for length/literal codes */
  82460. code const FAR *distcode; /* starting table for distance codes */
  82461. unsigned lenbits; /* index bits for lencode */
  82462. unsigned distbits; /* index bits for distcode */
  82463. /* dynamic table building */
  82464. unsigned ncode; /* number of code length code lengths */
  82465. unsigned nlen; /* number of length code lengths */
  82466. unsigned ndist; /* number of distance code lengths */
  82467. unsigned have; /* number of code lengths in lens[] */
  82468. code FAR *next; /* next available space in codes[] */
  82469. unsigned short lens[320]; /* temporary storage for code lengths */
  82470. unsigned short work[288]; /* work area for code table building */
  82471. code codes[ENOUGH]; /* space for code tables */
  82472. };
  82473. #endif
  82474. /*** End of inlined file: inflate.h ***/
  82475. /*** Start of inlined file: inffast.h ***/
  82476. /* WARNING: this file should *not* be used by applications. It is
  82477. part of the implementation of the compression library and is
  82478. subject to change. Applications should only use zlib.h.
  82479. */
  82480. void inflate_fast OF((z_streamp strm, unsigned start));
  82481. /*** End of inlined file: inffast.h ***/
  82482. #ifndef ASMINF
  82483. /* Allow machine dependent optimization for post-increment or pre-increment.
  82484. Based on testing to date,
  82485. Pre-increment preferred for:
  82486. - PowerPC G3 (Adler)
  82487. - MIPS R5000 (Randers-Pehrson)
  82488. Post-increment preferred for:
  82489. - none
  82490. No measurable difference:
  82491. - Pentium III (Anderson)
  82492. - M68060 (Nikl)
  82493. */
  82494. #ifdef POSTINC
  82495. # define OFF 0
  82496. # define PUP(a) *(a)++
  82497. #else
  82498. # define OFF 1
  82499. # define PUP(a) *++(a)
  82500. #endif
  82501. /*
  82502. Decode literal, length, and distance codes and write out the resulting
  82503. literal and match bytes until either not enough input or output is
  82504. available, an end-of-block is encountered, or a data error is encountered.
  82505. When large enough input and output buffers are supplied to inflate(), for
  82506. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82507. inflate execution time is spent in this routine.
  82508. Entry assumptions:
  82509. state->mode == LEN
  82510. strm->avail_in >= 6
  82511. strm->avail_out >= 258
  82512. start >= strm->avail_out
  82513. state->bits < 8
  82514. On return, state->mode is one of:
  82515. LEN -- ran out of enough output space or enough available input
  82516. TYPE -- reached end of block code, inflate() to interpret next block
  82517. BAD -- error in block data
  82518. Notes:
  82519. - The maximum input bits used by a length/distance pair is 15 bits for the
  82520. length code, 5 bits for the length extra, 15 bits for the distance code,
  82521. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82522. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82523. checking for available input while decoding.
  82524. - The maximum bytes that a single length/distance pair can output is 258
  82525. bytes, which is the maximum length that can be coded. inflate_fast()
  82526. requires strm->avail_out >= 258 for each loop to avoid checking for
  82527. output space.
  82528. */
  82529. void inflate_fast (z_streamp strm, unsigned start)
  82530. {
  82531. struct inflate_state FAR *state;
  82532. unsigned char FAR *in; /* local strm->next_in */
  82533. unsigned char FAR *last; /* while in < last, enough input available */
  82534. unsigned char FAR *out; /* local strm->next_out */
  82535. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82536. unsigned char FAR *end; /* while out < end, enough space available */
  82537. #ifdef INFLATE_STRICT
  82538. unsigned dmax; /* maximum distance from zlib header */
  82539. #endif
  82540. unsigned wsize; /* window size or zero if not using window */
  82541. unsigned whave; /* valid bytes in the window */
  82542. unsigned write; /* window write index */
  82543. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82544. unsigned long hold; /* local strm->hold */
  82545. unsigned bits; /* local strm->bits */
  82546. code const FAR *lcode; /* local strm->lencode */
  82547. code const FAR *dcode; /* local strm->distcode */
  82548. unsigned lmask; /* mask for first level of length codes */
  82549. unsigned dmask; /* mask for first level of distance codes */
  82550. code thisx; /* retrieved table entry */
  82551. unsigned op; /* code bits, operation, extra bits, or */
  82552. /* window position, window bytes to copy */
  82553. unsigned len; /* match length, unused bytes */
  82554. unsigned dist; /* match distance */
  82555. unsigned char FAR *from; /* where to copy match from */
  82556. /* copy state to local variables */
  82557. state = (struct inflate_state FAR *)strm->state;
  82558. in = strm->next_in - OFF;
  82559. last = in + (strm->avail_in - 5);
  82560. out = strm->next_out - OFF;
  82561. beg = out - (start - strm->avail_out);
  82562. end = out + (strm->avail_out - 257);
  82563. #ifdef INFLATE_STRICT
  82564. dmax = state->dmax;
  82565. #endif
  82566. wsize = state->wsize;
  82567. whave = state->whave;
  82568. write = state->write;
  82569. window = state->window;
  82570. hold = state->hold;
  82571. bits = state->bits;
  82572. lcode = state->lencode;
  82573. dcode = state->distcode;
  82574. lmask = (1U << state->lenbits) - 1;
  82575. dmask = (1U << state->distbits) - 1;
  82576. /* decode literals and length/distances until end-of-block or not enough
  82577. input data or output space */
  82578. do {
  82579. if (bits < 15) {
  82580. hold += (unsigned long)(PUP(in)) << bits;
  82581. bits += 8;
  82582. hold += (unsigned long)(PUP(in)) << bits;
  82583. bits += 8;
  82584. }
  82585. thisx = lcode[hold & lmask];
  82586. dolen:
  82587. op = (unsigned)(thisx.bits);
  82588. hold >>= op;
  82589. bits -= op;
  82590. op = (unsigned)(thisx.op);
  82591. if (op == 0) { /* literal */
  82592. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82593. "inflate: literal '%c'\n" :
  82594. "inflate: literal 0x%02x\n", thisx.val));
  82595. PUP(out) = (unsigned char)(thisx.val);
  82596. }
  82597. else if (op & 16) { /* length base */
  82598. len = (unsigned)(thisx.val);
  82599. op &= 15; /* number of extra bits */
  82600. if (op) {
  82601. if (bits < op) {
  82602. hold += (unsigned long)(PUP(in)) << bits;
  82603. bits += 8;
  82604. }
  82605. len += (unsigned)hold & ((1U << op) - 1);
  82606. hold >>= op;
  82607. bits -= op;
  82608. }
  82609. Tracevv((stderr, "inflate: length %u\n", len));
  82610. if (bits < 15) {
  82611. hold += (unsigned long)(PUP(in)) << bits;
  82612. bits += 8;
  82613. hold += (unsigned long)(PUP(in)) << bits;
  82614. bits += 8;
  82615. }
  82616. thisx = dcode[hold & dmask];
  82617. dodist:
  82618. op = (unsigned)(thisx.bits);
  82619. hold >>= op;
  82620. bits -= op;
  82621. op = (unsigned)(thisx.op);
  82622. if (op & 16) { /* distance base */
  82623. dist = (unsigned)(thisx.val);
  82624. op &= 15; /* number of extra bits */
  82625. if (bits < op) {
  82626. hold += (unsigned long)(PUP(in)) << bits;
  82627. bits += 8;
  82628. if (bits < op) {
  82629. hold += (unsigned long)(PUP(in)) << bits;
  82630. bits += 8;
  82631. }
  82632. }
  82633. dist += (unsigned)hold & ((1U << op) - 1);
  82634. #ifdef INFLATE_STRICT
  82635. if (dist > dmax) {
  82636. strm->msg = (char *)"invalid distance too far back";
  82637. state->mode = BAD;
  82638. break;
  82639. }
  82640. #endif
  82641. hold >>= op;
  82642. bits -= op;
  82643. Tracevv((stderr, "inflate: distance %u\n", dist));
  82644. op = (unsigned)(out - beg); /* max distance in output */
  82645. if (dist > op) { /* see if copy from window */
  82646. op = dist - op; /* distance back in window */
  82647. if (op > whave) {
  82648. strm->msg = (char *)"invalid distance too far back";
  82649. state->mode = BAD;
  82650. break;
  82651. }
  82652. from = window - OFF;
  82653. if (write == 0) { /* very common case */
  82654. from += wsize - op;
  82655. if (op < len) { /* some from window */
  82656. len -= op;
  82657. do {
  82658. PUP(out) = PUP(from);
  82659. } while (--op);
  82660. from = out - dist; /* rest from output */
  82661. }
  82662. }
  82663. else if (write < op) { /* wrap around window */
  82664. from += wsize + write - op;
  82665. op -= write;
  82666. if (op < len) { /* some from end of window */
  82667. len -= op;
  82668. do {
  82669. PUP(out) = PUP(from);
  82670. } while (--op);
  82671. from = window - OFF;
  82672. if (write < len) { /* some from start of window */
  82673. op = write;
  82674. len -= op;
  82675. do {
  82676. PUP(out) = PUP(from);
  82677. } while (--op);
  82678. from = out - dist; /* rest from output */
  82679. }
  82680. }
  82681. }
  82682. else { /* contiguous in window */
  82683. from += write - op;
  82684. if (op < len) { /* some from window */
  82685. len -= op;
  82686. do {
  82687. PUP(out) = PUP(from);
  82688. } while (--op);
  82689. from = out - dist; /* rest from output */
  82690. }
  82691. }
  82692. while (len > 2) {
  82693. PUP(out) = PUP(from);
  82694. PUP(out) = PUP(from);
  82695. PUP(out) = PUP(from);
  82696. len -= 3;
  82697. }
  82698. if (len) {
  82699. PUP(out) = PUP(from);
  82700. if (len > 1)
  82701. PUP(out) = PUP(from);
  82702. }
  82703. }
  82704. else {
  82705. from = out - dist; /* copy direct from output */
  82706. do { /* minimum length is three */
  82707. PUP(out) = PUP(from);
  82708. PUP(out) = PUP(from);
  82709. PUP(out) = PUP(from);
  82710. len -= 3;
  82711. } while (len > 2);
  82712. if (len) {
  82713. PUP(out) = PUP(from);
  82714. if (len > 1)
  82715. PUP(out) = PUP(from);
  82716. }
  82717. }
  82718. }
  82719. else if ((op & 64) == 0) { /* 2nd level distance code */
  82720. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82721. goto dodist;
  82722. }
  82723. else {
  82724. strm->msg = (char *)"invalid distance code";
  82725. state->mode = BAD;
  82726. break;
  82727. }
  82728. }
  82729. else if ((op & 64) == 0) { /* 2nd level length code */
  82730. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82731. goto dolen;
  82732. }
  82733. else if (op & 32) { /* end-of-block */
  82734. Tracevv((stderr, "inflate: end of block\n"));
  82735. state->mode = TYPE;
  82736. break;
  82737. }
  82738. else {
  82739. strm->msg = (char *)"invalid literal/length code";
  82740. state->mode = BAD;
  82741. break;
  82742. }
  82743. } while (in < last && out < end);
  82744. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82745. len = bits >> 3;
  82746. in -= len;
  82747. bits -= len << 3;
  82748. hold &= (1U << bits) - 1;
  82749. /* update state and return */
  82750. strm->next_in = in + OFF;
  82751. strm->next_out = out + OFF;
  82752. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82753. strm->avail_out = (unsigned)(out < end ?
  82754. 257 + (end - out) : 257 - (out - end));
  82755. state->hold = hold;
  82756. state->bits = bits;
  82757. return;
  82758. }
  82759. /*
  82760. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82761. - Using bit fields for code structure
  82762. - Different op definition to avoid & for extra bits (do & for table bits)
  82763. - Three separate decoding do-loops for direct, window, and write == 0
  82764. - Special case for distance > 1 copies to do overlapped load and store copy
  82765. - Explicit branch predictions (based on measured branch probabilities)
  82766. - Deferring match copy and interspersed it with decoding subsequent codes
  82767. - Swapping literal/length else
  82768. - Swapping window/direct else
  82769. - Larger unrolled copy loops (three is about right)
  82770. - Moving len -= 3 statement into middle of loop
  82771. */
  82772. #endif /* !ASMINF */
  82773. /*** End of inlined file: inffast.c ***/
  82774. #undef PULLBYTE
  82775. #undef LOAD
  82776. #undef RESTORE
  82777. #undef INITBITS
  82778. #undef NEEDBITS
  82779. #undef DROPBITS
  82780. #undef BYTEBITS
  82781. /*** Start of inlined file: inflate.c ***/
  82782. /*
  82783. * Change history:
  82784. *
  82785. * 1.2.beta0 24 Nov 2002
  82786. * - First version -- complete rewrite of inflate to simplify code, avoid
  82787. * creation of window when not needed, minimize use of window when it is
  82788. * needed, make inffast.c even faster, implement gzip decoding, and to
  82789. * improve code readability and style over the previous zlib inflate code
  82790. *
  82791. * 1.2.beta1 25 Nov 2002
  82792. * - Use pointers for available input and output checking in inffast.c
  82793. * - Remove input and output counters in inffast.c
  82794. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82795. * - Remove unnecessary second byte pull from length extra in inffast.c
  82796. * - Unroll direct copy to three copies per loop in inffast.c
  82797. *
  82798. * 1.2.beta2 4 Dec 2002
  82799. * - Change external routine names to reduce potential conflicts
  82800. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82801. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82802. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82803. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82804. *
  82805. * 1.2.beta3 22 Dec 2002
  82806. * - Add comments on state->bits assertion in inffast.c
  82807. * - Add comments on op field in inftrees.h
  82808. * - Fix bug in reuse of allocated window after inflateReset()
  82809. * - Remove bit fields--back to byte structure for speed
  82810. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82811. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82812. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82813. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82814. * - Use local copies of stream next and avail values, as well as local bit
  82815. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82816. *
  82817. * 1.2.beta4 1 Jan 2003
  82818. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82819. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82820. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82821. * - Rearrange window copies in inflate_fast() for speed and simplification
  82822. * - Unroll last copy for window match in inflate_fast()
  82823. * - Use local copies of window variables in inflate_fast() for speed
  82824. * - Pull out common write == 0 case for speed in inflate_fast()
  82825. * - Make op and len in inflate_fast() unsigned for consistency
  82826. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82827. * - Simplified bad distance check in inflate_fast()
  82828. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82829. * source file infback.c to provide a call-back interface to inflate for
  82830. * programs like gzip and unzip -- uses window as output buffer to avoid
  82831. * window copying
  82832. *
  82833. * 1.2.beta5 1 Jan 2003
  82834. * - Improved inflateBack() interface to allow the caller to provide initial
  82835. * input in strm.
  82836. * - Fixed stored blocks bug in inflateBack()
  82837. *
  82838. * 1.2.beta6 4 Jan 2003
  82839. * - Added comments in inffast.c on effectiveness of POSTINC
  82840. * - Typecasting all around to reduce compiler warnings
  82841. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82842. * make compilers happy
  82843. * - Changed type of window in inflateBackInit() to unsigned char *
  82844. *
  82845. * 1.2.beta7 27 Jan 2003
  82846. * - Changed many types to unsigned or unsigned short to avoid warnings
  82847. * - Added inflateCopy() function
  82848. *
  82849. * 1.2.0 9 Mar 2003
  82850. * - Changed inflateBack() interface to provide separate opaque descriptors
  82851. * for the in() and out() functions
  82852. * - Changed inflateBack() argument and in_func typedef to swap the length
  82853. * and buffer address return values for the input function
  82854. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82855. *
  82856. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82857. */
  82858. /*** Start of inlined file: inffast.h ***/
  82859. /* WARNING: this file should *not* be used by applications. It is
  82860. part of the implementation of the compression library and is
  82861. subject to change. Applications should only use zlib.h.
  82862. */
  82863. void inflate_fast OF((z_streamp strm, unsigned start));
  82864. /*** End of inlined file: inffast.h ***/
  82865. #ifdef MAKEFIXED
  82866. # ifndef BUILDFIXED
  82867. # define BUILDFIXED
  82868. # endif
  82869. #endif
  82870. /* function prototypes */
  82871. local void fixedtables OF((struct inflate_state FAR *state));
  82872. local int updatewindow OF((z_streamp strm, unsigned out));
  82873. #ifdef BUILDFIXED
  82874. void makefixed OF((void));
  82875. #endif
  82876. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82877. unsigned len));
  82878. int ZEXPORT inflateReset (z_streamp strm)
  82879. {
  82880. struct inflate_state FAR *state;
  82881. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82882. state = (struct inflate_state FAR *)strm->state;
  82883. strm->total_in = strm->total_out = state->total = 0;
  82884. strm->msg = Z_NULL;
  82885. strm->adler = 1; /* to support ill-conceived Java test suite */
  82886. state->mode = HEAD;
  82887. state->last = 0;
  82888. state->havedict = 0;
  82889. state->dmax = 32768U;
  82890. state->head = Z_NULL;
  82891. state->wsize = 0;
  82892. state->whave = 0;
  82893. state->write = 0;
  82894. state->hold = 0;
  82895. state->bits = 0;
  82896. state->lencode = state->distcode = state->next = state->codes;
  82897. Tracev((stderr, "inflate: reset\n"));
  82898. return Z_OK;
  82899. }
  82900. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82901. {
  82902. struct inflate_state FAR *state;
  82903. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82904. state = (struct inflate_state FAR *)strm->state;
  82905. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82906. value &= (1L << bits) - 1;
  82907. state->hold += value << state->bits;
  82908. state->bits += bits;
  82909. return Z_OK;
  82910. }
  82911. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82912. {
  82913. struct inflate_state FAR *state;
  82914. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82915. stream_size != (int)(sizeof(z_stream)))
  82916. return Z_VERSION_ERROR;
  82917. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82918. strm->msg = Z_NULL; /* in case we return an error */
  82919. if (strm->zalloc == (alloc_func)0) {
  82920. strm->zalloc = zcalloc;
  82921. strm->opaque = (voidpf)0;
  82922. }
  82923. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82924. state = (struct inflate_state FAR *)
  82925. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82926. if (state == Z_NULL) return Z_MEM_ERROR;
  82927. Tracev((stderr, "inflate: allocated\n"));
  82928. strm->state = (struct internal_state FAR *)state;
  82929. if (windowBits < 0) {
  82930. state->wrap = 0;
  82931. windowBits = -windowBits;
  82932. }
  82933. else {
  82934. state->wrap = (windowBits >> 4) + 1;
  82935. #ifdef GUNZIP
  82936. if (windowBits < 48) windowBits &= 15;
  82937. #endif
  82938. }
  82939. if (windowBits < 8 || windowBits > 15) {
  82940. ZFREE(strm, state);
  82941. strm->state = Z_NULL;
  82942. return Z_STREAM_ERROR;
  82943. }
  82944. state->wbits = (unsigned)windowBits;
  82945. state->window = Z_NULL;
  82946. return inflateReset(strm);
  82947. }
  82948. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82949. {
  82950. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82951. }
  82952. /*
  82953. Return state with length and distance decoding tables and index sizes set to
  82954. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82955. If BUILDFIXED is defined, then instead this routine builds the tables the
  82956. first time it's called, and returns those tables the first time and
  82957. thereafter. This reduces the size of the code by about 2K bytes, in
  82958. exchange for a little execution time. However, BUILDFIXED should not be
  82959. used for threaded applications, since the rewriting of the tables and virgin
  82960. may not be thread-safe.
  82961. */
  82962. local void fixedtables (struct inflate_state FAR *state)
  82963. {
  82964. #ifdef BUILDFIXED
  82965. static int virgin = 1;
  82966. static code *lenfix, *distfix;
  82967. static code fixed[544];
  82968. /* build fixed huffman tables if first call (may not be thread safe) */
  82969. if (virgin) {
  82970. unsigned sym, bits;
  82971. static code *next;
  82972. /* literal/length table */
  82973. sym = 0;
  82974. while (sym < 144) state->lens[sym++] = 8;
  82975. while (sym < 256) state->lens[sym++] = 9;
  82976. while (sym < 280) state->lens[sym++] = 7;
  82977. while (sym < 288) state->lens[sym++] = 8;
  82978. next = fixed;
  82979. lenfix = next;
  82980. bits = 9;
  82981. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82982. /* distance table */
  82983. sym = 0;
  82984. while (sym < 32) state->lens[sym++] = 5;
  82985. distfix = next;
  82986. bits = 5;
  82987. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82988. /* do this just once */
  82989. virgin = 0;
  82990. }
  82991. #else /* !BUILDFIXED */
  82992. /*** Start of inlined file: inffixed.h ***/
  82993. /* WARNING: this file should *not* be used by applications. It
  82994. is part of the implementation of the compression library and
  82995. is subject to change. Applications should only use zlib.h.
  82996. */
  82997. static const code lenfix[512] = {
  82998. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82999. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83000. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83001. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83002. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83003. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83004. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83005. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83006. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83007. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83008. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83009. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83010. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83011. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83012. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83013. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83014. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83015. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83016. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83017. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83018. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83019. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83020. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83021. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83022. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83023. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83024. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83025. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83026. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83027. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83028. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83029. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83030. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83031. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83032. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83033. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83034. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83035. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83036. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83037. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83038. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83039. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83040. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83041. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83042. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83043. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83044. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83045. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83046. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83047. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83048. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83049. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83050. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83051. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83052. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83053. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83054. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83055. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83056. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83057. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83058. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83059. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83060. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83061. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83062. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83063. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83064. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83065. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83066. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83067. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83068. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83069. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83070. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83071. {0,9,255}
  83072. };
  83073. static const code distfix[32] = {
  83074. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83075. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83076. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83077. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83078. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83079. {22,5,193},{64,5,0}
  83080. };
  83081. /*** End of inlined file: inffixed.h ***/
  83082. #endif /* BUILDFIXED */
  83083. state->lencode = lenfix;
  83084. state->lenbits = 9;
  83085. state->distcode = distfix;
  83086. state->distbits = 5;
  83087. }
  83088. #ifdef MAKEFIXED
  83089. #include <stdio.h>
  83090. /*
  83091. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83092. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83093. those tables to stdout, which would be piped to inffixed.h. A small program
  83094. can simply call makefixed to do this:
  83095. void makefixed(void);
  83096. int main(void)
  83097. {
  83098. makefixed();
  83099. return 0;
  83100. }
  83101. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83102. a.out > inffixed.h
  83103. */
  83104. void makefixed()
  83105. {
  83106. unsigned low, size;
  83107. struct inflate_state state;
  83108. fixedtables(&state);
  83109. puts(" /* inffixed.h -- table for decoding fixed codes");
  83110. puts(" * Generated automatically by makefixed().");
  83111. puts(" */");
  83112. puts("");
  83113. puts(" /* WARNING: this file should *not* be used by applications.");
  83114. puts(" It is part of the implementation of this library and is");
  83115. puts(" subject to change. Applications should only use zlib.h.");
  83116. puts(" */");
  83117. puts("");
  83118. size = 1U << 9;
  83119. printf(" static const code lenfix[%u] = {", size);
  83120. low = 0;
  83121. for (;;) {
  83122. if ((low % 7) == 0) printf("\n ");
  83123. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83124. state.lencode[low].val);
  83125. if (++low == size) break;
  83126. putchar(',');
  83127. }
  83128. puts("\n };");
  83129. size = 1U << 5;
  83130. printf("\n static const code distfix[%u] = {", size);
  83131. low = 0;
  83132. for (;;) {
  83133. if ((low % 6) == 0) printf("\n ");
  83134. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83135. state.distcode[low].val);
  83136. if (++low == size) break;
  83137. putchar(',');
  83138. }
  83139. puts("\n };");
  83140. }
  83141. #endif /* MAKEFIXED */
  83142. /*
  83143. Update the window with the last wsize (normally 32K) bytes written before
  83144. returning. If window does not exist yet, create it. This is only called
  83145. when a window is already in use, or when output has been written during this
  83146. inflate call, but the end of the deflate stream has not been reached yet.
  83147. It is also called to create a window for dictionary data when a dictionary
  83148. is loaded.
  83149. Providing output buffers larger than 32K to inflate() should provide a speed
  83150. advantage, since only the last 32K of output is copied to the sliding window
  83151. upon return from inflate(), and since all distances after the first 32K of
  83152. output will fall in the output data, making match copies simpler and faster.
  83153. The advantage may be dependent on the size of the processor's data caches.
  83154. */
  83155. local int updatewindow (z_streamp strm, unsigned out)
  83156. {
  83157. struct inflate_state FAR *state;
  83158. unsigned copy, dist;
  83159. state = (struct inflate_state FAR *)strm->state;
  83160. /* if it hasn't been done already, allocate space for the window */
  83161. if (state->window == Z_NULL) {
  83162. state->window = (unsigned char FAR *)
  83163. ZALLOC(strm, 1U << state->wbits,
  83164. sizeof(unsigned char));
  83165. if (state->window == Z_NULL) return 1;
  83166. }
  83167. /* if window not in use yet, initialize */
  83168. if (state->wsize == 0) {
  83169. state->wsize = 1U << state->wbits;
  83170. state->write = 0;
  83171. state->whave = 0;
  83172. }
  83173. /* copy state->wsize or less output bytes into the circular window */
  83174. copy = out - strm->avail_out;
  83175. if (copy >= state->wsize) {
  83176. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83177. state->write = 0;
  83178. state->whave = state->wsize;
  83179. }
  83180. else {
  83181. dist = state->wsize - state->write;
  83182. if (dist > copy) dist = copy;
  83183. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83184. copy -= dist;
  83185. if (copy) {
  83186. zmemcpy(state->window, strm->next_out - copy, copy);
  83187. state->write = copy;
  83188. state->whave = state->wsize;
  83189. }
  83190. else {
  83191. state->write += dist;
  83192. if (state->write == state->wsize) state->write = 0;
  83193. if (state->whave < state->wsize) state->whave += dist;
  83194. }
  83195. }
  83196. return 0;
  83197. }
  83198. /* Macros for inflate(): */
  83199. /* check function to use adler32() for zlib or crc32() for gzip */
  83200. #ifdef GUNZIP
  83201. # define UPDATE(check, buf, len) \
  83202. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83203. #else
  83204. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83205. #endif
  83206. /* check macros for header crc */
  83207. #ifdef GUNZIP
  83208. # define CRC2(check, word) \
  83209. do { \
  83210. hbuf[0] = (unsigned char)(word); \
  83211. hbuf[1] = (unsigned char)((word) >> 8); \
  83212. check = crc32(check, hbuf, 2); \
  83213. } while (0)
  83214. # define CRC4(check, word) \
  83215. do { \
  83216. hbuf[0] = (unsigned char)(word); \
  83217. hbuf[1] = (unsigned char)((word) >> 8); \
  83218. hbuf[2] = (unsigned char)((word) >> 16); \
  83219. hbuf[3] = (unsigned char)((word) >> 24); \
  83220. check = crc32(check, hbuf, 4); \
  83221. } while (0)
  83222. #endif
  83223. /* Load registers with state in inflate() for speed */
  83224. #define LOAD() \
  83225. do { \
  83226. put = strm->next_out; \
  83227. left = strm->avail_out; \
  83228. next = strm->next_in; \
  83229. have = strm->avail_in; \
  83230. hold = state->hold; \
  83231. bits = state->bits; \
  83232. } while (0)
  83233. /* Restore state from registers in inflate() */
  83234. #define RESTORE() \
  83235. do { \
  83236. strm->next_out = put; \
  83237. strm->avail_out = left; \
  83238. strm->next_in = next; \
  83239. strm->avail_in = have; \
  83240. state->hold = hold; \
  83241. state->bits = bits; \
  83242. } while (0)
  83243. /* Clear the input bit accumulator */
  83244. #define INITBITS() \
  83245. do { \
  83246. hold = 0; \
  83247. bits = 0; \
  83248. } while (0)
  83249. /* Get a byte of input into the bit accumulator, or return from inflate()
  83250. if there is no input available. */
  83251. #define PULLBYTE() \
  83252. do { \
  83253. if (have == 0) goto inf_leave; \
  83254. have--; \
  83255. hold += (unsigned long)(*next++) << bits; \
  83256. bits += 8; \
  83257. } while (0)
  83258. /* Assure that there are at least n bits in the bit accumulator. If there is
  83259. not enough available input to do that, then return from inflate(). */
  83260. #define NEEDBITS(n) \
  83261. do { \
  83262. while (bits < (unsigned)(n)) \
  83263. PULLBYTE(); \
  83264. } while (0)
  83265. /* Return the low n bits of the bit accumulator (n < 16) */
  83266. #define BITS(n) \
  83267. ((unsigned)hold & ((1U << (n)) - 1))
  83268. /* Remove n bits from the bit accumulator */
  83269. #define DROPBITS(n) \
  83270. do { \
  83271. hold >>= (n); \
  83272. bits -= (unsigned)(n); \
  83273. } while (0)
  83274. /* Remove zero to seven bits as needed to go to a byte boundary */
  83275. #define BYTEBITS() \
  83276. do { \
  83277. hold >>= bits & 7; \
  83278. bits -= bits & 7; \
  83279. } while (0)
  83280. /* Reverse the bytes in a 32-bit value */
  83281. #define REVERSE(q) \
  83282. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83283. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83284. /*
  83285. inflate() uses a state machine to process as much input data and generate as
  83286. much output data as possible before returning. The state machine is
  83287. structured roughly as follows:
  83288. for (;;) switch (state) {
  83289. ...
  83290. case STATEn:
  83291. if (not enough input data or output space to make progress)
  83292. return;
  83293. ... make progress ...
  83294. state = STATEm;
  83295. break;
  83296. ...
  83297. }
  83298. so when inflate() is called again, the same case is attempted again, and
  83299. if the appropriate resources are provided, the machine proceeds to the
  83300. next state. The NEEDBITS() macro is usually the way the state evaluates
  83301. whether it can proceed or should return. NEEDBITS() does the return if
  83302. the requested bits are not available. The typical use of the BITS macros
  83303. is:
  83304. NEEDBITS(n);
  83305. ... do something with BITS(n) ...
  83306. DROPBITS(n);
  83307. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83308. input left to load n bits into the accumulator, or it continues. BITS(n)
  83309. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83310. the low n bits off the accumulator. INITBITS() clears the accumulator
  83311. and sets the number of available bits to zero. BYTEBITS() discards just
  83312. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83313. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83314. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83315. if there is no input available. The decoding of variable length codes uses
  83316. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83317. code, and no more.
  83318. Some states loop until they get enough input, making sure that enough
  83319. state information is maintained to continue the loop where it left off
  83320. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83321. would all have to actually be part of the saved state in case NEEDBITS()
  83322. returns:
  83323. case STATEw:
  83324. while (want < need) {
  83325. NEEDBITS(n);
  83326. keep[want++] = BITS(n);
  83327. DROPBITS(n);
  83328. }
  83329. state = STATEx;
  83330. case STATEx:
  83331. As shown above, if the next state is also the next case, then the break
  83332. is omitted.
  83333. A state may also return if there is not enough output space available to
  83334. complete that state. Those states are copying stored data, writing a
  83335. literal byte, and copying a matching string.
  83336. When returning, a "goto inf_leave" is used to update the total counters,
  83337. update the check value, and determine whether any progress has been made
  83338. during that inflate() call in order to return the proper return code.
  83339. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83340. When there is a window, goto inf_leave will update the window with the last
  83341. output written. If a goto inf_leave occurs in the middle of decompression
  83342. and there is no window currently, goto inf_leave will create one and copy
  83343. output to the window for the next call of inflate().
  83344. In this implementation, the flush parameter of inflate() only affects the
  83345. return code (per zlib.h). inflate() always writes as much as possible to
  83346. strm->next_out, given the space available and the provided input--the effect
  83347. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83348. the allocation of and copying into a sliding window until necessary, which
  83349. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83350. stream available. So the only thing the flush parameter actually does is:
  83351. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83352. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83353. */
  83354. int ZEXPORT inflate (z_streamp strm, int flush)
  83355. {
  83356. struct inflate_state FAR *state;
  83357. unsigned char FAR *next; /* next input */
  83358. unsigned char FAR *put; /* next output */
  83359. unsigned have, left; /* available input and output */
  83360. unsigned long hold; /* bit buffer */
  83361. unsigned bits; /* bits in bit buffer */
  83362. unsigned in, out; /* save starting available input and output */
  83363. unsigned copy; /* number of stored or match bytes to copy */
  83364. unsigned char FAR *from; /* where to copy match bytes from */
  83365. code thisx; /* current decoding table entry */
  83366. code last; /* parent table entry */
  83367. unsigned len; /* length to copy for repeats, bits to drop */
  83368. int ret; /* return code */
  83369. #ifdef GUNZIP
  83370. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83371. #endif
  83372. static const unsigned short order[19] = /* permutation of code lengths */
  83373. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83374. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83375. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83376. return Z_STREAM_ERROR;
  83377. state = (struct inflate_state FAR *)strm->state;
  83378. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83379. LOAD();
  83380. in = have;
  83381. out = left;
  83382. ret = Z_OK;
  83383. for (;;)
  83384. switch (state->mode) {
  83385. case HEAD:
  83386. if (state->wrap == 0) {
  83387. state->mode = TYPEDO;
  83388. break;
  83389. }
  83390. NEEDBITS(16);
  83391. #ifdef GUNZIP
  83392. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83393. state->check = crc32(0L, Z_NULL, 0);
  83394. CRC2(state->check, hold);
  83395. INITBITS();
  83396. state->mode = FLAGS;
  83397. break;
  83398. }
  83399. state->flags = 0; /* expect zlib header */
  83400. if (state->head != Z_NULL)
  83401. state->head->done = -1;
  83402. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83403. #else
  83404. if (
  83405. #endif
  83406. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83407. strm->msg = (char *)"incorrect header check";
  83408. state->mode = BAD;
  83409. break;
  83410. }
  83411. if (BITS(4) != Z_DEFLATED) {
  83412. strm->msg = (char *)"unknown compression method";
  83413. state->mode = BAD;
  83414. break;
  83415. }
  83416. DROPBITS(4);
  83417. len = BITS(4) + 8;
  83418. if (len > state->wbits) {
  83419. strm->msg = (char *)"invalid window size";
  83420. state->mode = BAD;
  83421. break;
  83422. }
  83423. state->dmax = 1U << len;
  83424. Tracev((stderr, "inflate: zlib header ok\n"));
  83425. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83426. state->mode = hold & 0x200 ? DICTID : TYPE;
  83427. INITBITS();
  83428. break;
  83429. #ifdef GUNZIP
  83430. case FLAGS:
  83431. NEEDBITS(16);
  83432. state->flags = (int)(hold);
  83433. if ((state->flags & 0xff) != Z_DEFLATED) {
  83434. strm->msg = (char *)"unknown compression method";
  83435. state->mode = BAD;
  83436. break;
  83437. }
  83438. if (state->flags & 0xe000) {
  83439. strm->msg = (char *)"unknown header flags set";
  83440. state->mode = BAD;
  83441. break;
  83442. }
  83443. if (state->head != Z_NULL)
  83444. state->head->text = (int)((hold >> 8) & 1);
  83445. if (state->flags & 0x0200) CRC2(state->check, hold);
  83446. INITBITS();
  83447. state->mode = TIME;
  83448. case TIME:
  83449. NEEDBITS(32);
  83450. if (state->head != Z_NULL)
  83451. state->head->time = hold;
  83452. if (state->flags & 0x0200) CRC4(state->check, hold);
  83453. INITBITS();
  83454. state->mode = OS;
  83455. case OS:
  83456. NEEDBITS(16);
  83457. if (state->head != Z_NULL) {
  83458. state->head->xflags = (int)(hold & 0xff);
  83459. state->head->os = (int)(hold >> 8);
  83460. }
  83461. if (state->flags & 0x0200) CRC2(state->check, hold);
  83462. INITBITS();
  83463. state->mode = EXLEN;
  83464. case EXLEN:
  83465. if (state->flags & 0x0400) {
  83466. NEEDBITS(16);
  83467. state->length = (unsigned)(hold);
  83468. if (state->head != Z_NULL)
  83469. state->head->extra_len = (unsigned)hold;
  83470. if (state->flags & 0x0200) CRC2(state->check, hold);
  83471. INITBITS();
  83472. }
  83473. else if (state->head != Z_NULL)
  83474. state->head->extra = Z_NULL;
  83475. state->mode = EXTRA;
  83476. case EXTRA:
  83477. if (state->flags & 0x0400) {
  83478. copy = state->length;
  83479. if (copy > have) copy = have;
  83480. if (copy) {
  83481. if (state->head != Z_NULL &&
  83482. state->head->extra != Z_NULL) {
  83483. len = state->head->extra_len - state->length;
  83484. zmemcpy(state->head->extra + len, next,
  83485. len + copy > state->head->extra_max ?
  83486. state->head->extra_max - len : copy);
  83487. }
  83488. if (state->flags & 0x0200)
  83489. state->check = crc32(state->check, next, copy);
  83490. have -= copy;
  83491. next += copy;
  83492. state->length -= copy;
  83493. }
  83494. if (state->length) goto inf_leave;
  83495. }
  83496. state->length = 0;
  83497. state->mode = NAME;
  83498. case NAME:
  83499. if (state->flags & 0x0800) {
  83500. if (have == 0) goto inf_leave;
  83501. copy = 0;
  83502. do {
  83503. len = (unsigned)(next[copy++]);
  83504. if (state->head != Z_NULL &&
  83505. state->head->name != Z_NULL &&
  83506. state->length < state->head->name_max)
  83507. state->head->name[state->length++] = len;
  83508. } while (len && copy < have);
  83509. if (state->flags & 0x0200)
  83510. state->check = crc32(state->check, next, copy);
  83511. have -= copy;
  83512. next += copy;
  83513. if (len) goto inf_leave;
  83514. }
  83515. else if (state->head != Z_NULL)
  83516. state->head->name = Z_NULL;
  83517. state->length = 0;
  83518. state->mode = COMMENT;
  83519. case COMMENT:
  83520. if (state->flags & 0x1000) {
  83521. if (have == 0) goto inf_leave;
  83522. copy = 0;
  83523. do {
  83524. len = (unsigned)(next[copy++]);
  83525. if (state->head != Z_NULL &&
  83526. state->head->comment != Z_NULL &&
  83527. state->length < state->head->comm_max)
  83528. state->head->comment[state->length++] = len;
  83529. } while (len && copy < have);
  83530. if (state->flags & 0x0200)
  83531. state->check = crc32(state->check, next, copy);
  83532. have -= copy;
  83533. next += copy;
  83534. if (len) goto inf_leave;
  83535. }
  83536. else if (state->head != Z_NULL)
  83537. state->head->comment = Z_NULL;
  83538. state->mode = HCRC;
  83539. case HCRC:
  83540. if (state->flags & 0x0200) {
  83541. NEEDBITS(16);
  83542. if (hold != (state->check & 0xffff)) {
  83543. strm->msg = (char *)"header crc mismatch";
  83544. state->mode = BAD;
  83545. break;
  83546. }
  83547. INITBITS();
  83548. }
  83549. if (state->head != Z_NULL) {
  83550. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83551. state->head->done = 1;
  83552. }
  83553. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83554. state->mode = TYPE;
  83555. break;
  83556. #endif
  83557. case DICTID:
  83558. NEEDBITS(32);
  83559. strm->adler = state->check = REVERSE(hold);
  83560. INITBITS();
  83561. state->mode = DICT;
  83562. case DICT:
  83563. if (state->havedict == 0) {
  83564. RESTORE();
  83565. return Z_NEED_DICT;
  83566. }
  83567. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83568. state->mode = TYPE;
  83569. case TYPE:
  83570. if (flush == Z_BLOCK) goto inf_leave;
  83571. case TYPEDO:
  83572. if (state->last) {
  83573. BYTEBITS();
  83574. state->mode = CHECK;
  83575. break;
  83576. }
  83577. NEEDBITS(3);
  83578. state->last = BITS(1);
  83579. DROPBITS(1);
  83580. switch (BITS(2)) {
  83581. case 0: /* stored block */
  83582. Tracev((stderr, "inflate: stored block%s\n",
  83583. state->last ? " (last)" : ""));
  83584. state->mode = STORED;
  83585. break;
  83586. case 1: /* fixed block */
  83587. fixedtables(state);
  83588. Tracev((stderr, "inflate: fixed codes block%s\n",
  83589. state->last ? " (last)" : ""));
  83590. state->mode = LEN; /* decode codes */
  83591. break;
  83592. case 2: /* dynamic block */
  83593. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83594. state->last ? " (last)" : ""));
  83595. state->mode = TABLE;
  83596. break;
  83597. case 3:
  83598. strm->msg = (char *)"invalid block type";
  83599. state->mode = BAD;
  83600. }
  83601. DROPBITS(2);
  83602. break;
  83603. case STORED:
  83604. BYTEBITS(); /* go to byte boundary */
  83605. NEEDBITS(32);
  83606. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83607. strm->msg = (char *)"invalid stored block lengths";
  83608. state->mode = BAD;
  83609. break;
  83610. }
  83611. state->length = (unsigned)hold & 0xffff;
  83612. Tracev((stderr, "inflate: stored length %u\n",
  83613. state->length));
  83614. INITBITS();
  83615. state->mode = COPY;
  83616. case COPY:
  83617. copy = state->length;
  83618. if (copy) {
  83619. if (copy > have) copy = have;
  83620. if (copy > left) copy = left;
  83621. if (copy == 0) goto inf_leave;
  83622. zmemcpy(put, next, copy);
  83623. have -= copy;
  83624. next += copy;
  83625. left -= copy;
  83626. put += copy;
  83627. state->length -= copy;
  83628. break;
  83629. }
  83630. Tracev((stderr, "inflate: stored end\n"));
  83631. state->mode = TYPE;
  83632. break;
  83633. case TABLE:
  83634. NEEDBITS(14);
  83635. state->nlen = BITS(5) + 257;
  83636. DROPBITS(5);
  83637. state->ndist = BITS(5) + 1;
  83638. DROPBITS(5);
  83639. state->ncode = BITS(4) + 4;
  83640. DROPBITS(4);
  83641. #ifndef PKZIP_BUG_WORKAROUND
  83642. if (state->nlen > 286 || state->ndist > 30) {
  83643. strm->msg = (char *)"too many length or distance symbols";
  83644. state->mode = BAD;
  83645. break;
  83646. }
  83647. #endif
  83648. Tracev((stderr, "inflate: table sizes ok\n"));
  83649. state->have = 0;
  83650. state->mode = LENLENS;
  83651. case LENLENS:
  83652. while (state->have < state->ncode) {
  83653. NEEDBITS(3);
  83654. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83655. DROPBITS(3);
  83656. }
  83657. while (state->have < 19)
  83658. state->lens[order[state->have++]] = 0;
  83659. state->next = state->codes;
  83660. state->lencode = (code const FAR *)(state->next);
  83661. state->lenbits = 7;
  83662. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83663. &(state->lenbits), state->work);
  83664. if (ret) {
  83665. strm->msg = (char *)"invalid code lengths set";
  83666. state->mode = BAD;
  83667. break;
  83668. }
  83669. Tracev((stderr, "inflate: code lengths ok\n"));
  83670. state->have = 0;
  83671. state->mode = CODELENS;
  83672. case CODELENS:
  83673. while (state->have < state->nlen + state->ndist) {
  83674. for (;;) {
  83675. thisx = state->lencode[BITS(state->lenbits)];
  83676. if ((unsigned)(thisx.bits) <= bits) break;
  83677. PULLBYTE();
  83678. }
  83679. if (thisx.val < 16) {
  83680. NEEDBITS(thisx.bits);
  83681. DROPBITS(thisx.bits);
  83682. state->lens[state->have++] = thisx.val;
  83683. }
  83684. else {
  83685. if (thisx.val == 16) {
  83686. NEEDBITS(thisx.bits + 2);
  83687. DROPBITS(thisx.bits);
  83688. if (state->have == 0) {
  83689. strm->msg = (char *)"invalid bit length repeat";
  83690. state->mode = BAD;
  83691. break;
  83692. }
  83693. len = state->lens[state->have - 1];
  83694. copy = 3 + BITS(2);
  83695. DROPBITS(2);
  83696. }
  83697. else if (thisx.val == 17) {
  83698. NEEDBITS(thisx.bits + 3);
  83699. DROPBITS(thisx.bits);
  83700. len = 0;
  83701. copy = 3 + BITS(3);
  83702. DROPBITS(3);
  83703. }
  83704. else {
  83705. NEEDBITS(thisx.bits + 7);
  83706. DROPBITS(thisx.bits);
  83707. len = 0;
  83708. copy = 11 + BITS(7);
  83709. DROPBITS(7);
  83710. }
  83711. if (state->have + copy > state->nlen + state->ndist) {
  83712. strm->msg = (char *)"invalid bit length repeat";
  83713. state->mode = BAD;
  83714. break;
  83715. }
  83716. while (copy--)
  83717. state->lens[state->have++] = (unsigned short)len;
  83718. }
  83719. }
  83720. /* handle error breaks in while */
  83721. if (state->mode == BAD) break;
  83722. /* build code tables */
  83723. state->next = state->codes;
  83724. state->lencode = (code const FAR *)(state->next);
  83725. state->lenbits = 9;
  83726. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83727. &(state->lenbits), state->work);
  83728. if (ret) {
  83729. strm->msg = (char *)"invalid literal/lengths set";
  83730. state->mode = BAD;
  83731. break;
  83732. }
  83733. state->distcode = (code const FAR *)(state->next);
  83734. state->distbits = 6;
  83735. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83736. &(state->next), &(state->distbits), state->work);
  83737. if (ret) {
  83738. strm->msg = (char *)"invalid distances set";
  83739. state->mode = BAD;
  83740. break;
  83741. }
  83742. Tracev((stderr, "inflate: codes ok\n"));
  83743. state->mode = LEN;
  83744. case LEN:
  83745. if (have >= 6 && left >= 258) {
  83746. RESTORE();
  83747. inflate_fast(strm, out);
  83748. LOAD();
  83749. break;
  83750. }
  83751. for (;;) {
  83752. thisx = state->lencode[BITS(state->lenbits)];
  83753. if ((unsigned)(thisx.bits) <= bits) break;
  83754. PULLBYTE();
  83755. }
  83756. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83757. last = thisx;
  83758. for (;;) {
  83759. thisx = state->lencode[last.val +
  83760. (BITS(last.bits + last.op) >> last.bits)];
  83761. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83762. PULLBYTE();
  83763. }
  83764. DROPBITS(last.bits);
  83765. }
  83766. DROPBITS(thisx.bits);
  83767. state->length = (unsigned)thisx.val;
  83768. if ((int)(thisx.op) == 0) {
  83769. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83770. "inflate: literal '%c'\n" :
  83771. "inflate: literal 0x%02x\n", thisx.val));
  83772. state->mode = LIT;
  83773. break;
  83774. }
  83775. if (thisx.op & 32) {
  83776. Tracevv((stderr, "inflate: end of block\n"));
  83777. state->mode = TYPE;
  83778. break;
  83779. }
  83780. if (thisx.op & 64) {
  83781. strm->msg = (char *)"invalid literal/length code";
  83782. state->mode = BAD;
  83783. break;
  83784. }
  83785. state->extra = (unsigned)(thisx.op) & 15;
  83786. state->mode = LENEXT;
  83787. case LENEXT:
  83788. if (state->extra) {
  83789. NEEDBITS(state->extra);
  83790. state->length += BITS(state->extra);
  83791. DROPBITS(state->extra);
  83792. }
  83793. Tracevv((stderr, "inflate: length %u\n", state->length));
  83794. state->mode = DIST;
  83795. case DIST:
  83796. for (;;) {
  83797. thisx = state->distcode[BITS(state->distbits)];
  83798. if ((unsigned)(thisx.bits) <= bits) break;
  83799. PULLBYTE();
  83800. }
  83801. if ((thisx.op & 0xf0) == 0) {
  83802. last = thisx;
  83803. for (;;) {
  83804. thisx = state->distcode[last.val +
  83805. (BITS(last.bits + last.op) >> last.bits)];
  83806. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83807. PULLBYTE();
  83808. }
  83809. DROPBITS(last.bits);
  83810. }
  83811. DROPBITS(thisx.bits);
  83812. if (thisx.op & 64) {
  83813. strm->msg = (char *)"invalid distance code";
  83814. state->mode = BAD;
  83815. break;
  83816. }
  83817. state->offset = (unsigned)thisx.val;
  83818. state->extra = (unsigned)(thisx.op) & 15;
  83819. state->mode = DISTEXT;
  83820. case DISTEXT:
  83821. if (state->extra) {
  83822. NEEDBITS(state->extra);
  83823. state->offset += BITS(state->extra);
  83824. DROPBITS(state->extra);
  83825. }
  83826. #ifdef INFLATE_STRICT
  83827. if (state->offset > state->dmax) {
  83828. strm->msg = (char *)"invalid distance too far back";
  83829. state->mode = BAD;
  83830. break;
  83831. }
  83832. #endif
  83833. if (state->offset > state->whave + out - left) {
  83834. strm->msg = (char *)"invalid distance too far back";
  83835. state->mode = BAD;
  83836. break;
  83837. }
  83838. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83839. state->mode = MATCH;
  83840. case MATCH:
  83841. if (left == 0) goto inf_leave;
  83842. copy = out - left;
  83843. if (state->offset > copy) { /* copy from window */
  83844. copy = state->offset - copy;
  83845. if (copy > state->write) {
  83846. copy -= state->write;
  83847. from = state->window + (state->wsize - copy);
  83848. }
  83849. else
  83850. from = state->window + (state->write - copy);
  83851. if (copy > state->length) copy = state->length;
  83852. }
  83853. else { /* copy from output */
  83854. from = put - state->offset;
  83855. copy = state->length;
  83856. }
  83857. if (copy > left) copy = left;
  83858. left -= copy;
  83859. state->length -= copy;
  83860. do {
  83861. *put++ = *from++;
  83862. } while (--copy);
  83863. if (state->length == 0) state->mode = LEN;
  83864. break;
  83865. case LIT:
  83866. if (left == 0) goto inf_leave;
  83867. *put++ = (unsigned char)(state->length);
  83868. left--;
  83869. state->mode = LEN;
  83870. break;
  83871. case CHECK:
  83872. if (state->wrap) {
  83873. NEEDBITS(32);
  83874. out -= left;
  83875. strm->total_out += out;
  83876. state->total += out;
  83877. if (out)
  83878. strm->adler = state->check =
  83879. UPDATE(state->check, put - out, out);
  83880. out = left;
  83881. if ((
  83882. #ifdef GUNZIP
  83883. state->flags ? hold :
  83884. #endif
  83885. REVERSE(hold)) != state->check) {
  83886. strm->msg = (char *)"incorrect data check";
  83887. state->mode = BAD;
  83888. break;
  83889. }
  83890. INITBITS();
  83891. Tracev((stderr, "inflate: check matches trailer\n"));
  83892. }
  83893. #ifdef GUNZIP
  83894. state->mode = LENGTH;
  83895. case LENGTH:
  83896. if (state->wrap && state->flags) {
  83897. NEEDBITS(32);
  83898. if (hold != (state->total & 0xffffffffUL)) {
  83899. strm->msg = (char *)"incorrect length check";
  83900. state->mode = BAD;
  83901. break;
  83902. }
  83903. INITBITS();
  83904. Tracev((stderr, "inflate: length matches trailer\n"));
  83905. }
  83906. #endif
  83907. state->mode = DONE;
  83908. case DONE:
  83909. ret = Z_STREAM_END;
  83910. goto inf_leave;
  83911. case BAD:
  83912. ret = Z_DATA_ERROR;
  83913. goto inf_leave;
  83914. case MEM:
  83915. return Z_MEM_ERROR;
  83916. case SYNC:
  83917. default:
  83918. return Z_STREAM_ERROR;
  83919. }
  83920. /*
  83921. Return from inflate(), updating the total counts and the check value.
  83922. If there was no progress during the inflate() call, return a buffer
  83923. error. Call updatewindow() to create and/or update the window state.
  83924. Note: a memory error from inflate() is non-recoverable.
  83925. */
  83926. inf_leave:
  83927. RESTORE();
  83928. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83929. if (updatewindow(strm, out)) {
  83930. state->mode = MEM;
  83931. return Z_MEM_ERROR;
  83932. }
  83933. in -= strm->avail_in;
  83934. out -= strm->avail_out;
  83935. strm->total_in += in;
  83936. strm->total_out += out;
  83937. state->total += out;
  83938. if (state->wrap && out)
  83939. strm->adler = state->check =
  83940. UPDATE(state->check, strm->next_out - out, out);
  83941. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83942. (state->mode == TYPE ? 128 : 0);
  83943. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83944. ret = Z_BUF_ERROR;
  83945. return ret;
  83946. }
  83947. int ZEXPORT inflateEnd (z_streamp strm)
  83948. {
  83949. struct inflate_state FAR *state;
  83950. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83951. return Z_STREAM_ERROR;
  83952. state = (struct inflate_state FAR *)strm->state;
  83953. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83954. ZFREE(strm, strm->state);
  83955. strm->state = Z_NULL;
  83956. Tracev((stderr, "inflate: end\n"));
  83957. return Z_OK;
  83958. }
  83959. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83960. {
  83961. struct inflate_state FAR *state;
  83962. unsigned long id_;
  83963. /* check state */
  83964. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83965. state = (struct inflate_state FAR *)strm->state;
  83966. if (state->wrap != 0 && state->mode != DICT)
  83967. return Z_STREAM_ERROR;
  83968. /* check for correct dictionary id */
  83969. if (state->mode == DICT) {
  83970. id_ = adler32(0L, Z_NULL, 0);
  83971. id_ = adler32(id_, dictionary, dictLength);
  83972. if (id_ != state->check)
  83973. return Z_DATA_ERROR;
  83974. }
  83975. /* copy dictionary to window */
  83976. if (updatewindow(strm, strm->avail_out)) {
  83977. state->mode = MEM;
  83978. return Z_MEM_ERROR;
  83979. }
  83980. if (dictLength > state->wsize) {
  83981. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83982. state->wsize);
  83983. state->whave = state->wsize;
  83984. }
  83985. else {
  83986. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83987. dictLength);
  83988. state->whave = dictLength;
  83989. }
  83990. state->havedict = 1;
  83991. Tracev((stderr, "inflate: dictionary set\n"));
  83992. return Z_OK;
  83993. }
  83994. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83995. {
  83996. struct inflate_state FAR *state;
  83997. /* check state */
  83998. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83999. state = (struct inflate_state FAR *)strm->state;
  84000. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84001. /* save header structure */
  84002. state->head = head;
  84003. head->done = 0;
  84004. return Z_OK;
  84005. }
  84006. /*
  84007. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84008. or when out of input. When called, *have is the number of pattern bytes
  84009. found in order so far, in 0..3. On return *have is updated to the new
  84010. state. If on return *have equals four, then the pattern was found and the
  84011. return value is how many bytes were read including the last byte of the
  84012. pattern. If *have is less than four, then the pattern has not been found
  84013. yet and the return value is len. In the latter case, syncsearch() can be
  84014. called again with more data and the *have state. *have is initialized to
  84015. zero for the first call.
  84016. */
  84017. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84018. {
  84019. unsigned got;
  84020. unsigned next;
  84021. got = *have;
  84022. next = 0;
  84023. while (next < len && got < 4) {
  84024. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84025. got++;
  84026. else if (buf[next])
  84027. got = 0;
  84028. else
  84029. got = 4 - got;
  84030. next++;
  84031. }
  84032. *have = got;
  84033. return next;
  84034. }
  84035. int ZEXPORT inflateSync (z_streamp strm)
  84036. {
  84037. unsigned len; /* number of bytes to look at or looked at */
  84038. unsigned long in, out; /* temporary to save total_in and total_out */
  84039. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84040. struct inflate_state FAR *state;
  84041. /* check parameters */
  84042. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84043. state = (struct inflate_state FAR *)strm->state;
  84044. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84045. /* if first time, start search in bit buffer */
  84046. if (state->mode != SYNC) {
  84047. state->mode = SYNC;
  84048. state->hold <<= state->bits & 7;
  84049. state->bits -= state->bits & 7;
  84050. len = 0;
  84051. while (state->bits >= 8) {
  84052. buf[len++] = (unsigned char)(state->hold);
  84053. state->hold >>= 8;
  84054. state->bits -= 8;
  84055. }
  84056. state->have = 0;
  84057. syncsearch(&(state->have), buf, len);
  84058. }
  84059. /* search available input */
  84060. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84061. strm->avail_in -= len;
  84062. strm->next_in += len;
  84063. strm->total_in += len;
  84064. /* return no joy or set up to restart inflate() on a new block */
  84065. if (state->have != 4) return Z_DATA_ERROR;
  84066. in = strm->total_in; out = strm->total_out;
  84067. inflateReset(strm);
  84068. strm->total_in = in; strm->total_out = out;
  84069. state->mode = TYPE;
  84070. return Z_OK;
  84071. }
  84072. /*
  84073. Returns true if inflate is currently at the end of a block generated by
  84074. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84075. implementation to provide an additional safety check. PPP uses
  84076. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84077. block. When decompressing, PPP checks that at the end of input packet,
  84078. inflate is waiting for these length bytes.
  84079. */
  84080. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84081. {
  84082. struct inflate_state FAR *state;
  84083. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84084. state = (struct inflate_state FAR *)strm->state;
  84085. return state->mode == STORED && state->bits == 0;
  84086. }
  84087. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84088. {
  84089. struct inflate_state FAR *state;
  84090. struct inflate_state FAR *copy;
  84091. unsigned char FAR *window;
  84092. unsigned wsize;
  84093. /* check input */
  84094. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84095. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84096. return Z_STREAM_ERROR;
  84097. state = (struct inflate_state FAR *)source->state;
  84098. /* allocate space */
  84099. copy = (struct inflate_state FAR *)
  84100. ZALLOC(source, 1, sizeof(struct inflate_state));
  84101. if (copy == Z_NULL) return Z_MEM_ERROR;
  84102. window = Z_NULL;
  84103. if (state->window != Z_NULL) {
  84104. window = (unsigned char FAR *)
  84105. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84106. if (window == Z_NULL) {
  84107. ZFREE(source, copy);
  84108. return Z_MEM_ERROR;
  84109. }
  84110. }
  84111. /* copy state */
  84112. zmemcpy(dest, source, sizeof(z_stream));
  84113. zmemcpy(copy, state, sizeof(struct inflate_state));
  84114. if (state->lencode >= state->codes &&
  84115. state->lencode <= state->codes + ENOUGH - 1) {
  84116. copy->lencode = copy->codes + (state->lencode - state->codes);
  84117. copy->distcode = copy->codes + (state->distcode - state->codes);
  84118. }
  84119. copy->next = copy->codes + (state->next - state->codes);
  84120. if (window != Z_NULL) {
  84121. wsize = 1U << state->wbits;
  84122. zmemcpy(window, state->window, wsize);
  84123. }
  84124. copy->window = window;
  84125. dest->state = (struct internal_state FAR *)copy;
  84126. return Z_OK;
  84127. }
  84128. /*** End of inlined file: inflate.c ***/
  84129. /*** Start of inlined file: inftrees.c ***/
  84130. #define MAXBITS 15
  84131. const char inflate_copyright[] =
  84132. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84133. /*
  84134. If you use the zlib library in a product, an acknowledgment is welcome
  84135. in the documentation of your product. If for some reason you cannot
  84136. include such an acknowledgment, I would appreciate that you keep this
  84137. copyright string in the executable of your product.
  84138. */
  84139. /*
  84140. Build a set of tables to decode the provided canonical Huffman code.
  84141. The code lengths are lens[0..codes-1]. The result starts at *table,
  84142. whose indices are 0..2^bits-1. work is a writable array of at least
  84143. lens shorts, which is used as a work area. type is the type of code
  84144. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84145. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84146. on return points to the next available entry's address. bits is the
  84147. requested root table index bits, and on return it is the actual root
  84148. table index bits. It will differ if the request is greater than the
  84149. longest code or if it is less than the shortest code.
  84150. */
  84151. int inflate_table (codetype type,
  84152. unsigned short FAR *lens,
  84153. unsigned codes,
  84154. code FAR * FAR *table,
  84155. unsigned FAR *bits,
  84156. unsigned short FAR *work)
  84157. {
  84158. unsigned len; /* a code's length in bits */
  84159. unsigned sym; /* index of code symbols */
  84160. unsigned min, max; /* minimum and maximum code lengths */
  84161. unsigned root; /* number of index bits for root table */
  84162. unsigned curr; /* number of index bits for current table */
  84163. unsigned drop; /* code bits to drop for sub-table */
  84164. int left; /* number of prefix codes available */
  84165. unsigned used; /* code entries in table used */
  84166. unsigned huff; /* Huffman code */
  84167. unsigned incr; /* for incrementing code, index */
  84168. unsigned fill; /* index for replicating entries */
  84169. unsigned low; /* low bits for current root entry */
  84170. unsigned mask; /* mask for low root bits */
  84171. code thisx; /* table entry for duplication */
  84172. code FAR *next; /* next available space in table */
  84173. const unsigned short FAR *base; /* base value table to use */
  84174. const unsigned short FAR *extra; /* extra bits table to use */
  84175. int end; /* use base and extra for symbol > end */
  84176. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84177. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84178. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84179. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84180. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84181. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84182. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84183. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84184. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84185. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84186. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84187. 8193, 12289, 16385, 24577, 0, 0};
  84188. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84189. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84190. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84191. 28, 28, 29, 29, 64, 64};
  84192. /*
  84193. Process a set of code lengths to create a canonical Huffman code. The
  84194. code lengths are lens[0..codes-1]. Each length corresponds to the
  84195. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84196. symbols by length from short to long, and retaining the symbol order
  84197. for codes with equal lengths. Then the code starts with all zero bits
  84198. for the first code of the shortest length, and the codes are integer
  84199. increments for the same length, and zeros are appended as the length
  84200. increases. For the deflate format, these bits are stored backwards
  84201. from their more natural integer increment ordering, and so when the
  84202. decoding tables are built in the large loop below, the integer codes
  84203. are incremented backwards.
  84204. This routine assumes, but does not check, that all of the entries in
  84205. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84206. 1..MAXBITS is interpreted as that code length. zero means that that
  84207. symbol does not occur in this code.
  84208. The codes are sorted by computing a count of codes for each length,
  84209. creating from that a table of starting indices for each length in the
  84210. sorted table, and then entering the symbols in order in the sorted
  84211. table. The sorted table is work[], with that space being provided by
  84212. the caller.
  84213. The length counts are used for other purposes as well, i.e. finding
  84214. the minimum and maximum length codes, determining if there are any
  84215. codes at all, checking for a valid set of lengths, and looking ahead
  84216. at length counts to determine sub-table sizes when building the
  84217. decoding tables.
  84218. */
  84219. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84220. for (len = 0; len <= MAXBITS; len++)
  84221. count[len] = 0;
  84222. for (sym = 0; sym < codes; sym++)
  84223. count[lens[sym]]++;
  84224. /* bound code lengths, force root to be within code lengths */
  84225. root = *bits;
  84226. for (max = MAXBITS; max >= 1; max--)
  84227. if (count[max] != 0) break;
  84228. if (root > max) root = max;
  84229. if (max == 0) { /* no symbols to code at all */
  84230. thisx.op = (unsigned char)64; /* invalid code marker */
  84231. thisx.bits = (unsigned char)1;
  84232. thisx.val = (unsigned short)0;
  84233. *(*table)++ = thisx; /* make a table to force an error */
  84234. *(*table)++ = thisx;
  84235. *bits = 1;
  84236. return 0; /* no symbols, but wait for decoding to report error */
  84237. }
  84238. for (min = 1; min <= MAXBITS; min++)
  84239. if (count[min] != 0) break;
  84240. if (root < min) root = min;
  84241. /* check for an over-subscribed or incomplete set of lengths */
  84242. left = 1;
  84243. for (len = 1; len <= MAXBITS; len++) {
  84244. left <<= 1;
  84245. left -= count[len];
  84246. if (left < 0) return -1; /* over-subscribed */
  84247. }
  84248. if (left > 0 && (type == CODES || max != 1))
  84249. return -1; /* incomplete set */
  84250. /* generate offsets into symbol table for each length for sorting */
  84251. offs[1] = 0;
  84252. for (len = 1; len < MAXBITS; len++)
  84253. offs[len + 1] = offs[len] + count[len];
  84254. /* sort symbols by length, by symbol order within each length */
  84255. for (sym = 0; sym < codes; sym++)
  84256. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84257. /*
  84258. Create and fill in decoding tables. In this loop, the table being
  84259. filled is at next and has curr index bits. The code being used is huff
  84260. with length len. That code is converted to an index by dropping drop
  84261. bits off of the bottom. For codes where len is less than drop + curr,
  84262. those top drop + curr - len bits are incremented through all values to
  84263. fill the table with replicated entries.
  84264. root is the number of index bits for the root table. When len exceeds
  84265. root, sub-tables are created pointed to by the root entry with an index
  84266. of the low root bits of huff. This is saved in low to check for when a
  84267. new sub-table should be started. drop is zero when the root table is
  84268. being filled, and drop is root when sub-tables are being filled.
  84269. When a new sub-table is needed, it is necessary to look ahead in the
  84270. code lengths to determine what size sub-table is needed. The length
  84271. counts are used for this, and so count[] is decremented as codes are
  84272. entered in the tables.
  84273. used keeps track of how many table entries have been allocated from the
  84274. provided *table space. It is checked when a LENS table is being made
  84275. against the space in *table, ENOUGH, minus the maximum space needed by
  84276. the worst case distance code, MAXD. This should never happen, but the
  84277. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84278. This assumes that when type == LENS, bits == 9.
  84279. sym increments through all symbols, and the loop terminates when
  84280. all codes of length max, i.e. all codes, have been processed. This
  84281. routine permits incomplete codes, so another loop after this one fills
  84282. in the rest of the decoding tables with invalid code markers.
  84283. */
  84284. /* set up for code type */
  84285. switch (type) {
  84286. case CODES:
  84287. base = extra = work; /* dummy value--not used */
  84288. end = 19;
  84289. break;
  84290. case LENS:
  84291. base = lbase;
  84292. base -= 257;
  84293. extra = lext;
  84294. extra -= 257;
  84295. end = 256;
  84296. break;
  84297. default: /* DISTS */
  84298. base = dbase;
  84299. extra = dext;
  84300. end = -1;
  84301. }
  84302. /* initialize state for loop */
  84303. huff = 0; /* starting code */
  84304. sym = 0; /* starting code symbol */
  84305. len = min; /* starting code length */
  84306. next = *table; /* current table to fill in */
  84307. curr = root; /* current table index bits */
  84308. drop = 0; /* current bits to drop from code for index */
  84309. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84310. used = 1U << root; /* use root table entries */
  84311. mask = used - 1; /* mask for comparing low */
  84312. /* check available table space */
  84313. if (type == LENS && used >= ENOUGH - MAXD)
  84314. return 1;
  84315. /* process all codes and make table entries */
  84316. for (;;) {
  84317. /* create table entry */
  84318. thisx.bits = (unsigned char)(len - drop);
  84319. if ((int)(work[sym]) < end) {
  84320. thisx.op = (unsigned char)0;
  84321. thisx.val = work[sym];
  84322. }
  84323. else if ((int)(work[sym]) > end) {
  84324. thisx.op = (unsigned char)(extra[work[sym]]);
  84325. thisx.val = base[work[sym]];
  84326. }
  84327. else {
  84328. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84329. thisx.val = 0;
  84330. }
  84331. /* replicate for those indices with low len bits equal to huff */
  84332. incr = 1U << (len - drop);
  84333. fill = 1U << curr;
  84334. min = fill; /* save offset to next table */
  84335. do {
  84336. fill -= incr;
  84337. next[(huff >> drop) + fill] = thisx;
  84338. } while (fill != 0);
  84339. /* backwards increment the len-bit code huff */
  84340. incr = 1U << (len - 1);
  84341. while (huff & incr)
  84342. incr >>= 1;
  84343. if (incr != 0) {
  84344. huff &= incr - 1;
  84345. huff += incr;
  84346. }
  84347. else
  84348. huff = 0;
  84349. /* go to next symbol, update count, len */
  84350. sym++;
  84351. if (--(count[len]) == 0) {
  84352. if (len == max) break;
  84353. len = lens[work[sym]];
  84354. }
  84355. /* create new sub-table if needed */
  84356. if (len > root && (huff & mask) != low) {
  84357. /* if first time, transition to sub-tables */
  84358. if (drop == 0)
  84359. drop = root;
  84360. /* increment past last table */
  84361. next += min; /* here min is 1 << curr */
  84362. /* determine length of next table */
  84363. curr = len - drop;
  84364. left = (int)(1 << curr);
  84365. while (curr + drop < max) {
  84366. left -= count[curr + drop];
  84367. if (left <= 0) break;
  84368. curr++;
  84369. left <<= 1;
  84370. }
  84371. /* check for enough space */
  84372. used += 1U << curr;
  84373. if (type == LENS && used >= ENOUGH - MAXD)
  84374. return 1;
  84375. /* point entry in root table to sub-table */
  84376. low = huff & mask;
  84377. (*table)[low].op = (unsigned char)curr;
  84378. (*table)[low].bits = (unsigned char)root;
  84379. (*table)[low].val = (unsigned short)(next - *table);
  84380. }
  84381. }
  84382. /*
  84383. Fill in rest of table for incomplete codes. This loop is similar to the
  84384. loop above in incrementing huff for table indices. It is assumed that
  84385. len is equal to curr + drop, so there is no loop needed to increment
  84386. through high index bits. When the current sub-table is filled, the loop
  84387. drops back to the root table to fill in any remaining entries there.
  84388. */
  84389. thisx.op = (unsigned char)64; /* invalid code marker */
  84390. thisx.bits = (unsigned char)(len - drop);
  84391. thisx.val = (unsigned short)0;
  84392. while (huff != 0) {
  84393. /* when done with sub-table, drop back to root table */
  84394. if (drop != 0 && (huff & mask) != low) {
  84395. drop = 0;
  84396. len = root;
  84397. next = *table;
  84398. thisx.bits = (unsigned char)len;
  84399. }
  84400. /* put invalid code marker in table */
  84401. next[huff >> drop] = thisx;
  84402. /* backwards increment the len-bit code huff */
  84403. incr = 1U << (len - 1);
  84404. while (huff & incr)
  84405. incr >>= 1;
  84406. if (incr != 0) {
  84407. huff &= incr - 1;
  84408. huff += incr;
  84409. }
  84410. else
  84411. huff = 0;
  84412. }
  84413. /* set return parameters */
  84414. *table += used;
  84415. *bits = root;
  84416. return 0;
  84417. }
  84418. /*** End of inlined file: inftrees.c ***/
  84419. /*** Start of inlined file: trees.c ***/
  84420. /*
  84421. * ALGORITHM
  84422. *
  84423. * The "deflation" process uses several Huffman trees. The more
  84424. * common source values are represented by shorter bit sequences.
  84425. *
  84426. * Each code tree is stored in a compressed form which is itself
  84427. * a Huffman encoding of the lengths of all the code strings (in
  84428. * ascending order by source values). The actual code strings are
  84429. * reconstructed from the lengths in the inflate process, as described
  84430. * in the deflate specification.
  84431. *
  84432. * REFERENCES
  84433. *
  84434. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84435. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84436. *
  84437. * Storer, James A.
  84438. * Data Compression: Methods and Theory, pp. 49-50.
  84439. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84440. *
  84441. * Sedgewick, R.
  84442. * Algorithms, p290.
  84443. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84444. */
  84445. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84446. /* #define GEN_TREES_H */
  84447. #ifdef DEBUG
  84448. # include <ctype.h>
  84449. #endif
  84450. /* ===========================================================================
  84451. * Constants
  84452. */
  84453. #define MAX_BL_BITS 7
  84454. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84455. #define END_BLOCK 256
  84456. /* end of block literal code */
  84457. #define REP_3_6 16
  84458. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84459. #define REPZ_3_10 17
  84460. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84461. #define REPZ_11_138 18
  84462. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84463. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84464. = {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};
  84465. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84466. = {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};
  84467. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84468. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84469. local const uch bl_order[BL_CODES]
  84470. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84471. /* The lengths of the bit length codes are sent in order of decreasing
  84472. * probability, to avoid transmitting the lengths for unused bit length codes.
  84473. */
  84474. #define Buf_size (8 * 2*sizeof(char))
  84475. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84476. * more than 16 bits on some systems.)
  84477. */
  84478. /* ===========================================================================
  84479. * Local data. These are initialized only once.
  84480. */
  84481. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84482. #if defined(GEN_TREES_H) || !defined(STDC)
  84483. /* non ANSI compilers may not accept trees.h */
  84484. local ct_data static_ltree[L_CODES+2];
  84485. /* The static literal tree. Since the bit lengths are imposed, there is no
  84486. * need for the L_CODES extra codes used during heap construction. However
  84487. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84488. * below).
  84489. */
  84490. local ct_data static_dtree[D_CODES];
  84491. /* The static distance tree. (Actually a trivial tree since all codes use
  84492. * 5 bits.)
  84493. */
  84494. uch _dist_code[DIST_CODE_LEN];
  84495. /* Distance codes. The first 256 values correspond to the distances
  84496. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84497. * the 15 bit distances.
  84498. */
  84499. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84500. /* length code for each normalized match length (0 == MIN_MATCH) */
  84501. local int base_length[LENGTH_CODES];
  84502. /* First normalized length for each code (0 = MIN_MATCH) */
  84503. local int base_dist[D_CODES];
  84504. /* First normalized distance for each code (0 = distance of 1) */
  84505. #else
  84506. /*** Start of inlined file: trees.h ***/
  84507. local const ct_data static_ltree[L_CODES+2] = {
  84508. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84509. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84510. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84511. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84512. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84513. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84514. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84515. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84516. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84517. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84518. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84519. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84520. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84521. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84522. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84523. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84524. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84525. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84526. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84527. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84528. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84529. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84530. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84531. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84532. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84533. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84534. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84535. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84536. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84537. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84538. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84539. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84540. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84541. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84542. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84543. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84544. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84545. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84546. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84547. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84548. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84549. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84550. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84551. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84552. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84553. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84554. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84555. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84556. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84557. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84558. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84559. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84560. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84561. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84562. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84563. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84564. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84565. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84566. };
  84567. local const ct_data static_dtree[D_CODES] = {
  84568. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84569. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84570. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84571. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84572. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84573. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84574. };
  84575. const uch _dist_code[DIST_CODE_LEN] = {
  84576. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84577. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84578. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84579. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84580. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84581. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84582. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84583. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84584. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84585. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84586. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84587. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84588. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84589. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84590. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84591. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84592. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84593. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84594. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84595. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84596. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84597. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84598. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84599. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84600. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84601. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84602. };
  84603. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84604. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84605. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84606. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84607. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84608. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84609. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84610. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84611. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84612. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84613. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84614. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84615. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84616. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84617. };
  84618. local const int base_length[LENGTH_CODES] = {
  84619. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84620. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84621. };
  84622. local const int base_dist[D_CODES] = {
  84623. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84624. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84625. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84626. };
  84627. /*** End of inlined file: trees.h ***/
  84628. #endif /* GEN_TREES_H */
  84629. struct static_tree_desc_s {
  84630. const ct_data *static_tree; /* static tree or NULL */
  84631. const intf *extra_bits; /* extra bits for each code or NULL */
  84632. int extra_base; /* base index for extra_bits */
  84633. int elems; /* max number of elements in the tree */
  84634. int max_length; /* max bit length for the codes */
  84635. };
  84636. local static_tree_desc static_l_desc =
  84637. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84638. local static_tree_desc static_d_desc =
  84639. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84640. local static_tree_desc static_bl_desc =
  84641. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84642. /* ===========================================================================
  84643. * Local (static) routines in this file.
  84644. */
  84645. local void tr_static_init OF((void));
  84646. local void init_block OF((deflate_state *s));
  84647. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84648. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84649. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84650. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84651. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84652. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84653. local int build_bl_tree OF((deflate_state *s));
  84654. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84655. int blcodes));
  84656. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84657. ct_data *dtree));
  84658. local void set_data_type OF((deflate_state *s));
  84659. local unsigned bi_reverse OF((unsigned value, int length));
  84660. local void bi_windup OF((deflate_state *s));
  84661. local void bi_flush OF((deflate_state *s));
  84662. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84663. int header));
  84664. #ifdef GEN_TREES_H
  84665. local void gen_trees_header OF((void));
  84666. #endif
  84667. #ifndef DEBUG
  84668. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84669. /* Send a code of the given tree. c and tree must not have side effects */
  84670. #else /* DEBUG */
  84671. # define send_code(s, c, tree) \
  84672. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84673. send_bits(s, tree[c].Code, tree[c].Len); }
  84674. #endif
  84675. /* ===========================================================================
  84676. * Output a short LSB first on the stream.
  84677. * IN assertion: there is enough room in pendingBuf.
  84678. */
  84679. #define put_short(s, w) { \
  84680. put_byte(s, (uch)((w) & 0xff)); \
  84681. put_byte(s, (uch)((ush)(w) >> 8)); \
  84682. }
  84683. /* ===========================================================================
  84684. * Send a value on a given number of bits.
  84685. * IN assertion: length <= 16 and value fits in length bits.
  84686. */
  84687. #ifdef DEBUG
  84688. local void send_bits OF((deflate_state *s, int value, int length));
  84689. local void send_bits (deflate_state *s, int value, int length)
  84690. {
  84691. Tracevv((stderr," l %2d v %4x ", length, value));
  84692. Assert(length > 0 && length <= 15, "invalid length");
  84693. s->bits_sent += (ulg)length;
  84694. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84695. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84696. * unused bits in value.
  84697. */
  84698. if (s->bi_valid > (int)Buf_size - length) {
  84699. s->bi_buf |= (value << s->bi_valid);
  84700. put_short(s, s->bi_buf);
  84701. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84702. s->bi_valid += length - Buf_size;
  84703. } else {
  84704. s->bi_buf |= value << s->bi_valid;
  84705. s->bi_valid += length;
  84706. }
  84707. }
  84708. #else /* !DEBUG */
  84709. #define send_bits(s, value, length) \
  84710. { int len = length;\
  84711. if (s->bi_valid > (int)Buf_size - len) {\
  84712. int val = value;\
  84713. s->bi_buf |= (val << s->bi_valid);\
  84714. put_short(s, s->bi_buf);\
  84715. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84716. s->bi_valid += len - Buf_size;\
  84717. } else {\
  84718. s->bi_buf |= (value) << s->bi_valid;\
  84719. s->bi_valid += len;\
  84720. }\
  84721. }
  84722. #endif /* DEBUG */
  84723. /* the arguments must not have side effects */
  84724. /* ===========================================================================
  84725. * Initialize the various 'constant' tables.
  84726. */
  84727. local void tr_static_init()
  84728. {
  84729. #if defined(GEN_TREES_H) || !defined(STDC)
  84730. static int static_init_done = 0;
  84731. int n; /* iterates over tree elements */
  84732. int bits; /* bit counter */
  84733. int length; /* length value */
  84734. int code; /* code value */
  84735. int dist; /* distance index */
  84736. ush bl_count[MAX_BITS+1];
  84737. /* number of codes at each bit length for an optimal tree */
  84738. if (static_init_done) return;
  84739. /* For some embedded targets, global variables are not initialized: */
  84740. static_l_desc.static_tree = static_ltree;
  84741. static_l_desc.extra_bits = extra_lbits;
  84742. static_d_desc.static_tree = static_dtree;
  84743. static_d_desc.extra_bits = extra_dbits;
  84744. static_bl_desc.extra_bits = extra_blbits;
  84745. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84746. length = 0;
  84747. for (code = 0; code < LENGTH_CODES-1; code++) {
  84748. base_length[code] = length;
  84749. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84750. _length_code[length++] = (uch)code;
  84751. }
  84752. }
  84753. Assert (length == 256, "tr_static_init: length != 256");
  84754. /* Note that the length 255 (match length 258) can be represented
  84755. * in two different ways: code 284 + 5 bits or code 285, so we
  84756. * overwrite length_code[255] to use the best encoding:
  84757. */
  84758. _length_code[length-1] = (uch)code;
  84759. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84760. dist = 0;
  84761. for (code = 0 ; code < 16; code++) {
  84762. base_dist[code] = dist;
  84763. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84764. _dist_code[dist++] = (uch)code;
  84765. }
  84766. }
  84767. Assert (dist == 256, "tr_static_init: dist != 256");
  84768. dist >>= 7; /* from now on, all distances are divided by 128 */
  84769. for ( ; code < D_CODES; code++) {
  84770. base_dist[code] = dist << 7;
  84771. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84772. _dist_code[256 + dist++] = (uch)code;
  84773. }
  84774. }
  84775. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84776. /* Construct the codes of the static literal tree */
  84777. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84778. n = 0;
  84779. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84780. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84781. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84782. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84783. /* Codes 286 and 287 do not exist, but we must include them in the
  84784. * tree construction to get a canonical Huffman tree (longest code
  84785. * all ones)
  84786. */
  84787. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84788. /* The static distance tree is trivial: */
  84789. for (n = 0; n < D_CODES; n++) {
  84790. static_dtree[n].Len = 5;
  84791. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84792. }
  84793. static_init_done = 1;
  84794. # ifdef GEN_TREES_H
  84795. gen_trees_header();
  84796. # endif
  84797. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84798. }
  84799. /* ===========================================================================
  84800. * Genererate the file trees.h describing the static trees.
  84801. */
  84802. #ifdef GEN_TREES_H
  84803. # ifndef DEBUG
  84804. # include <stdio.h>
  84805. # endif
  84806. # define SEPARATOR(i, last, width) \
  84807. ((i) == (last)? "\n};\n\n" : \
  84808. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84809. void gen_trees_header()
  84810. {
  84811. FILE *header = fopen("trees.h", "w");
  84812. int i;
  84813. Assert (header != NULL, "Can't open trees.h");
  84814. fprintf(header,
  84815. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84816. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84817. for (i = 0; i < L_CODES+2; i++) {
  84818. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84819. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84820. }
  84821. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84822. for (i = 0; i < D_CODES; i++) {
  84823. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84824. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84825. }
  84826. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84827. for (i = 0; i < DIST_CODE_LEN; i++) {
  84828. fprintf(header, "%2u%s", _dist_code[i],
  84829. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84830. }
  84831. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84832. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84833. fprintf(header, "%2u%s", _length_code[i],
  84834. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84835. }
  84836. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84837. for (i = 0; i < LENGTH_CODES; i++) {
  84838. fprintf(header, "%1u%s", base_length[i],
  84839. SEPARATOR(i, LENGTH_CODES-1, 20));
  84840. }
  84841. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84842. for (i = 0; i < D_CODES; i++) {
  84843. fprintf(header, "%5u%s", base_dist[i],
  84844. SEPARATOR(i, D_CODES-1, 10));
  84845. }
  84846. fclose(header);
  84847. }
  84848. #endif /* GEN_TREES_H */
  84849. /* ===========================================================================
  84850. * Initialize the tree data structures for a new zlib stream.
  84851. */
  84852. void _tr_init(deflate_state *s)
  84853. {
  84854. tr_static_init();
  84855. s->l_desc.dyn_tree = s->dyn_ltree;
  84856. s->l_desc.stat_desc = &static_l_desc;
  84857. s->d_desc.dyn_tree = s->dyn_dtree;
  84858. s->d_desc.stat_desc = &static_d_desc;
  84859. s->bl_desc.dyn_tree = s->bl_tree;
  84860. s->bl_desc.stat_desc = &static_bl_desc;
  84861. s->bi_buf = 0;
  84862. s->bi_valid = 0;
  84863. s->last_eob_len = 8; /* enough lookahead for inflate */
  84864. #ifdef DEBUG
  84865. s->compressed_len = 0L;
  84866. s->bits_sent = 0L;
  84867. #endif
  84868. /* Initialize the first block of the first file: */
  84869. init_block(s);
  84870. }
  84871. /* ===========================================================================
  84872. * Initialize a new block.
  84873. */
  84874. local void init_block (deflate_state *s)
  84875. {
  84876. int n; /* iterates over tree elements */
  84877. /* Initialize the trees. */
  84878. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84879. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84880. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84881. s->dyn_ltree[END_BLOCK].Freq = 1;
  84882. s->opt_len = s->static_len = 0L;
  84883. s->last_lit = s->matches = 0;
  84884. }
  84885. #define SMALLEST 1
  84886. /* Index within the heap array of least frequent node in the Huffman tree */
  84887. /* ===========================================================================
  84888. * Remove the smallest element from the heap and recreate the heap with
  84889. * one less element. Updates heap and heap_len.
  84890. */
  84891. #define pqremove(s, tree, top) \
  84892. {\
  84893. top = s->heap[SMALLEST]; \
  84894. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84895. pqdownheap(s, tree, SMALLEST); \
  84896. }
  84897. /* ===========================================================================
  84898. * Compares to subtrees, using the tree depth as tie breaker when
  84899. * the subtrees have equal frequency. This minimizes the worst case length.
  84900. */
  84901. #define smaller(tree, n, m, depth) \
  84902. (tree[n].Freq < tree[m].Freq || \
  84903. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84904. /* ===========================================================================
  84905. * Restore the heap property by moving down the tree starting at node k,
  84906. * exchanging a node with the smallest of its two sons if necessary, stopping
  84907. * when the heap property is re-established (each father smaller than its
  84908. * two sons).
  84909. */
  84910. local void pqdownheap (deflate_state *s,
  84911. ct_data *tree, /* the tree to restore */
  84912. int k) /* node to move down */
  84913. {
  84914. int v = s->heap[k];
  84915. int j = k << 1; /* left son of k */
  84916. while (j <= s->heap_len) {
  84917. /* Set j to the smallest of the two sons: */
  84918. if (j < s->heap_len &&
  84919. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84920. j++;
  84921. }
  84922. /* Exit if v is smaller than both sons */
  84923. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84924. /* Exchange v with the smallest son */
  84925. s->heap[k] = s->heap[j]; k = j;
  84926. /* And continue down the tree, setting j to the left son of k */
  84927. j <<= 1;
  84928. }
  84929. s->heap[k] = v;
  84930. }
  84931. /* ===========================================================================
  84932. * Compute the optimal bit lengths for a tree and update the total bit length
  84933. * for the current block.
  84934. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84935. * above are the tree nodes sorted by increasing frequency.
  84936. * OUT assertions: the field len is set to the optimal bit length, the
  84937. * array bl_count contains the frequencies for each bit length.
  84938. * The length opt_len is updated; static_len is also updated if stree is
  84939. * not null.
  84940. */
  84941. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84942. {
  84943. ct_data *tree = desc->dyn_tree;
  84944. int max_code = desc->max_code;
  84945. const ct_data *stree = desc->stat_desc->static_tree;
  84946. const intf *extra = desc->stat_desc->extra_bits;
  84947. int base = desc->stat_desc->extra_base;
  84948. int max_length = desc->stat_desc->max_length;
  84949. int h; /* heap index */
  84950. int n, m; /* iterate over the tree elements */
  84951. int bits; /* bit length */
  84952. int xbits; /* extra bits */
  84953. ush f; /* frequency */
  84954. int overflow = 0; /* number of elements with bit length too large */
  84955. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84956. /* In a first pass, compute the optimal bit lengths (which may
  84957. * overflow in the case of the bit length tree).
  84958. */
  84959. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84960. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84961. n = s->heap[h];
  84962. bits = tree[tree[n].Dad].Len + 1;
  84963. if (bits > max_length) bits = max_length, overflow++;
  84964. tree[n].Len = (ush)bits;
  84965. /* We overwrite tree[n].Dad which is no longer needed */
  84966. if (n > max_code) continue; /* not a leaf node */
  84967. s->bl_count[bits]++;
  84968. xbits = 0;
  84969. if (n >= base) xbits = extra[n-base];
  84970. f = tree[n].Freq;
  84971. s->opt_len += (ulg)f * (bits + xbits);
  84972. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84973. }
  84974. if (overflow == 0) return;
  84975. Trace((stderr,"\nbit length overflow\n"));
  84976. /* This happens for example on obj2 and pic of the Calgary corpus */
  84977. /* Find the first bit length which could increase: */
  84978. do {
  84979. bits = max_length-1;
  84980. while (s->bl_count[bits] == 0) bits--;
  84981. s->bl_count[bits]--; /* move one leaf down the tree */
  84982. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84983. s->bl_count[max_length]--;
  84984. /* The brother of the overflow item also moves one step up,
  84985. * but this does not affect bl_count[max_length]
  84986. */
  84987. overflow -= 2;
  84988. } while (overflow > 0);
  84989. /* Now recompute all bit lengths, scanning in increasing frequency.
  84990. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84991. * lengths instead of fixing only the wrong ones. This idea is taken
  84992. * from 'ar' written by Haruhiko Okumura.)
  84993. */
  84994. for (bits = max_length; bits != 0; bits--) {
  84995. n = s->bl_count[bits];
  84996. while (n != 0) {
  84997. m = s->heap[--h];
  84998. if (m > max_code) continue;
  84999. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85000. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85001. s->opt_len += ((long)bits - (long)tree[m].Len)
  85002. *(long)tree[m].Freq;
  85003. tree[m].Len = (ush)bits;
  85004. }
  85005. n--;
  85006. }
  85007. }
  85008. }
  85009. /* ===========================================================================
  85010. * Generate the codes for a given tree and bit counts (which need not be
  85011. * optimal).
  85012. * IN assertion: the array bl_count contains the bit length statistics for
  85013. * the given tree and the field len is set for all tree elements.
  85014. * OUT assertion: the field code is set for all tree elements of non
  85015. * zero code length.
  85016. */
  85017. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85018. int max_code, /* largest code with non zero frequency */
  85019. ushf *bl_count) /* number of codes at each bit length */
  85020. {
  85021. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85022. ush code = 0; /* running code value */
  85023. int bits; /* bit index */
  85024. int n; /* code index */
  85025. /* The distribution counts are first used to generate the code values
  85026. * without bit reversal.
  85027. */
  85028. for (bits = 1; bits <= MAX_BITS; bits++) {
  85029. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85030. }
  85031. /* Check that the bit counts in bl_count are consistent. The last code
  85032. * must be all ones.
  85033. */
  85034. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85035. "inconsistent bit counts");
  85036. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85037. for (n = 0; n <= max_code; n++) {
  85038. int len = tree[n].Len;
  85039. if (len == 0) continue;
  85040. /* Now reverse the bits */
  85041. tree[n].Code = bi_reverse(next_code[len]++, len);
  85042. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85043. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85044. }
  85045. }
  85046. /* ===========================================================================
  85047. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85048. * Update the total bit length for the current block.
  85049. * IN assertion: the field freq is set for all tree elements.
  85050. * OUT assertions: the fields len and code are set to the optimal bit length
  85051. * and corresponding code. The length opt_len is updated; static_len is
  85052. * also updated if stree is not null. The field max_code is set.
  85053. */
  85054. local void build_tree (deflate_state *s,
  85055. tree_desc *desc) /* the tree descriptor */
  85056. {
  85057. ct_data *tree = desc->dyn_tree;
  85058. const ct_data *stree = desc->stat_desc->static_tree;
  85059. int elems = desc->stat_desc->elems;
  85060. int n, m; /* iterate over heap elements */
  85061. int max_code = -1; /* largest code with non zero frequency */
  85062. int node; /* new node being created */
  85063. /* Construct the initial heap, with least frequent element in
  85064. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85065. * heap[0] is not used.
  85066. */
  85067. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85068. for (n = 0; n < elems; n++) {
  85069. if (tree[n].Freq != 0) {
  85070. s->heap[++(s->heap_len)] = max_code = n;
  85071. s->depth[n] = 0;
  85072. } else {
  85073. tree[n].Len = 0;
  85074. }
  85075. }
  85076. /* The pkzip format requires that at least one distance code exists,
  85077. * and that at least one bit should be sent even if there is only one
  85078. * possible code. So to avoid special checks later on we force at least
  85079. * two codes of non zero frequency.
  85080. */
  85081. while (s->heap_len < 2) {
  85082. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85083. tree[node].Freq = 1;
  85084. s->depth[node] = 0;
  85085. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85086. /* node is 0 or 1 so it does not have extra bits */
  85087. }
  85088. desc->max_code = max_code;
  85089. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85090. * establish sub-heaps of increasing lengths:
  85091. */
  85092. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85093. /* Construct the Huffman tree by repeatedly combining the least two
  85094. * frequent nodes.
  85095. */
  85096. node = elems; /* next internal node of the tree */
  85097. do {
  85098. pqremove(s, tree, n); /* n = node of least frequency */
  85099. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85100. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85101. s->heap[--(s->heap_max)] = m;
  85102. /* Create a new node father of n and m */
  85103. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85104. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85105. s->depth[n] : s->depth[m]) + 1);
  85106. tree[n].Dad = tree[m].Dad = (ush)node;
  85107. #ifdef DUMP_BL_TREE
  85108. if (tree == s->bl_tree) {
  85109. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85110. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85111. }
  85112. #endif
  85113. /* and insert the new node in the heap */
  85114. s->heap[SMALLEST] = node++;
  85115. pqdownheap(s, tree, SMALLEST);
  85116. } while (s->heap_len >= 2);
  85117. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85118. /* At this point, the fields freq and dad are set. We can now
  85119. * generate the bit lengths.
  85120. */
  85121. gen_bitlen(s, (tree_desc *)desc);
  85122. /* The field len is now set, we can generate the bit codes */
  85123. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85124. }
  85125. /* ===========================================================================
  85126. * Scan a literal or distance tree to determine the frequencies of the codes
  85127. * in the bit length tree.
  85128. */
  85129. local void scan_tree (deflate_state *s,
  85130. ct_data *tree, /* the tree to be scanned */
  85131. int max_code) /* and its largest code of non zero frequency */
  85132. {
  85133. int n; /* iterates over all tree elements */
  85134. int prevlen = -1; /* last emitted length */
  85135. int curlen; /* length of current code */
  85136. int nextlen = tree[0].Len; /* length of next code */
  85137. int count = 0; /* repeat count of the current code */
  85138. int max_count = 7; /* max repeat count */
  85139. int min_count = 4; /* min repeat count */
  85140. if (nextlen == 0) max_count = 138, min_count = 3;
  85141. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85142. for (n = 0; n <= max_code; n++) {
  85143. curlen = nextlen; nextlen = tree[n+1].Len;
  85144. if (++count < max_count && curlen == nextlen) {
  85145. continue;
  85146. } else if (count < min_count) {
  85147. s->bl_tree[curlen].Freq += count;
  85148. } else if (curlen != 0) {
  85149. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85150. s->bl_tree[REP_3_6].Freq++;
  85151. } else if (count <= 10) {
  85152. s->bl_tree[REPZ_3_10].Freq++;
  85153. } else {
  85154. s->bl_tree[REPZ_11_138].Freq++;
  85155. }
  85156. count = 0; prevlen = curlen;
  85157. if (nextlen == 0) {
  85158. max_count = 138, min_count = 3;
  85159. } else if (curlen == nextlen) {
  85160. max_count = 6, min_count = 3;
  85161. } else {
  85162. max_count = 7, min_count = 4;
  85163. }
  85164. }
  85165. }
  85166. /* ===========================================================================
  85167. * Send a literal or distance tree in compressed form, using the codes in
  85168. * bl_tree.
  85169. */
  85170. local void send_tree (deflate_state *s,
  85171. ct_data *tree, /* the tree to be scanned */
  85172. int max_code) /* and its largest code of non zero frequency */
  85173. {
  85174. int n; /* iterates over all tree elements */
  85175. int prevlen = -1; /* last emitted length */
  85176. int curlen; /* length of current code */
  85177. int nextlen = tree[0].Len; /* length of next code */
  85178. int count = 0; /* repeat count of the current code */
  85179. int max_count = 7; /* max repeat count */
  85180. int min_count = 4; /* min repeat count */
  85181. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85182. if (nextlen == 0) max_count = 138, min_count = 3;
  85183. for (n = 0; n <= max_code; n++) {
  85184. curlen = nextlen; nextlen = tree[n+1].Len;
  85185. if (++count < max_count && curlen == nextlen) {
  85186. continue;
  85187. } else if (count < min_count) {
  85188. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85189. } else if (curlen != 0) {
  85190. if (curlen != prevlen) {
  85191. send_code(s, curlen, s->bl_tree); count--;
  85192. }
  85193. Assert(count >= 3 && count <= 6, " 3_6?");
  85194. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85195. } else if (count <= 10) {
  85196. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85197. } else {
  85198. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85199. }
  85200. count = 0; prevlen = curlen;
  85201. if (nextlen == 0) {
  85202. max_count = 138, min_count = 3;
  85203. } else if (curlen == nextlen) {
  85204. max_count = 6, min_count = 3;
  85205. } else {
  85206. max_count = 7, min_count = 4;
  85207. }
  85208. }
  85209. }
  85210. /* ===========================================================================
  85211. * Construct the Huffman tree for the bit lengths and return the index in
  85212. * bl_order of the last bit length code to send.
  85213. */
  85214. local int build_bl_tree (deflate_state *s)
  85215. {
  85216. int max_blindex; /* index of last bit length code of non zero freq */
  85217. /* Determine the bit length frequencies for literal and distance trees */
  85218. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85219. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85220. /* Build the bit length tree: */
  85221. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85222. /* opt_len now includes the length of the tree representations, except
  85223. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85224. */
  85225. /* Determine the number of bit length codes to send. The pkzip format
  85226. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85227. * 3 but the actual value used is 4.)
  85228. */
  85229. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85230. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85231. }
  85232. /* Update opt_len to include the bit length tree and counts */
  85233. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85234. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85235. s->opt_len, s->static_len));
  85236. return max_blindex;
  85237. }
  85238. /* ===========================================================================
  85239. * Send the header for a block using dynamic Huffman trees: the counts, the
  85240. * lengths of the bit length codes, the literal tree and the distance tree.
  85241. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85242. */
  85243. local void send_all_trees (deflate_state *s,
  85244. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85245. {
  85246. int rank; /* index in bl_order */
  85247. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85248. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85249. "too many codes");
  85250. Tracev((stderr, "\nbl counts: "));
  85251. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85252. send_bits(s, dcodes-1, 5);
  85253. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85254. for (rank = 0; rank < blcodes; rank++) {
  85255. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85256. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85257. }
  85258. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85259. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85260. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85261. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85262. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85263. }
  85264. /* ===========================================================================
  85265. * Send a stored block
  85266. */
  85267. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85268. {
  85269. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85270. #ifdef DEBUG
  85271. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85272. s->compressed_len += (stored_len + 4) << 3;
  85273. #endif
  85274. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85275. }
  85276. /* ===========================================================================
  85277. * Send one empty static block to give enough lookahead for inflate.
  85278. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85279. * The current inflate code requires 9 bits of lookahead. If the
  85280. * last two codes for the previous block (real code plus EOB) were coded
  85281. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85282. * the last real code. In this case we send two empty static blocks instead
  85283. * of one. (There are no problems if the previous block is stored or fixed.)
  85284. * To simplify the code, we assume the worst case of last real code encoded
  85285. * on one bit only.
  85286. */
  85287. void _tr_align (deflate_state *s)
  85288. {
  85289. send_bits(s, STATIC_TREES<<1, 3);
  85290. send_code(s, END_BLOCK, static_ltree);
  85291. #ifdef DEBUG
  85292. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85293. #endif
  85294. bi_flush(s);
  85295. /* Of the 10 bits for the empty block, we have already sent
  85296. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85297. * the EOB of the previous block) was thus at least one plus the length
  85298. * of the EOB plus what we have just sent of the empty static block.
  85299. */
  85300. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85301. send_bits(s, STATIC_TREES<<1, 3);
  85302. send_code(s, END_BLOCK, static_ltree);
  85303. #ifdef DEBUG
  85304. s->compressed_len += 10L;
  85305. #endif
  85306. bi_flush(s);
  85307. }
  85308. s->last_eob_len = 7;
  85309. }
  85310. /* ===========================================================================
  85311. * Determine the best encoding for the current block: dynamic trees, static
  85312. * trees or store, and output the encoded block to the zip file.
  85313. */
  85314. void _tr_flush_block (deflate_state *s,
  85315. charf *buf, /* input block, or NULL if too old */
  85316. ulg stored_len, /* length of input block */
  85317. int eof) /* true if this is the last block for a file */
  85318. {
  85319. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85320. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85321. /* Build the Huffman trees unless a stored block is forced */
  85322. if (s->level > 0) {
  85323. /* Check if the file is binary or text */
  85324. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85325. set_data_type(s);
  85326. /* Construct the literal and distance trees */
  85327. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85328. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85329. s->static_len));
  85330. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85331. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85332. s->static_len));
  85333. /* At this point, opt_len and static_len are the total bit lengths of
  85334. * the compressed block data, excluding the tree representations.
  85335. */
  85336. /* Build the bit length tree for the above two trees, and get the index
  85337. * in bl_order of the last bit length code to send.
  85338. */
  85339. max_blindex = build_bl_tree(s);
  85340. /* Determine the best encoding. Compute the block lengths in bytes. */
  85341. opt_lenb = (s->opt_len+3+7)>>3;
  85342. static_lenb = (s->static_len+3+7)>>3;
  85343. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85344. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85345. s->last_lit));
  85346. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85347. } else {
  85348. Assert(buf != (char*)0, "lost buf");
  85349. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85350. }
  85351. #ifdef FORCE_STORED
  85352. if (buf != (char*)0) { /* force stored block */
  85353. #else
  85354. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85355. /* 4: two words for the lengths */
  85356. #endif
  85357. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85358. * Otherwise we can't have processed more than WSIZE input bytes since
  85359. * the last block flush, because compression would have been
  85360. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85361. * transform a block into a stored block.
  85362. */
  85363. _tr_stored_block(s, buf, stored_len, eof);
  85364. #ifdef FORCE_STATIC
  85365. } else if (static_lenb >= 0) { /* force static trees */
  85366. #else
  85367. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85368. #endif
  85369. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85370. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85371. #ifdef DEBUG
  85372. s->compressed_len += 3 + s->static_len;
  85373. #endif
  85374. } else {
  85375. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85376. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85377. max_blindex+1);
  85378. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85379. #ifdef DEBUG
  85380. s->compressed_len += 3 + s->opt_len;
  85381. #endif
  85382. }
  85383. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85384. /* The above check is made mod 2^32, for files larger than 512 MB
  85385. * and uLong implemented on 32 bits.
  85386. */
  85387. init_block(s);
  85388. if (eof) {
  85389. bi_windup(s);
  85390. #ifdef DEBUG
  85391. s->compressed_len += 7; /* align on byte boundary */
  85392. #endif
  85393. }
  85394. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85395. s->compressed_len-7*eof));
  85396. }
  85397. /* ===========================================================================
  85398. * Save the match info and tally the frequency counts. Return true if
  85399. * the current block must be flushed.
  85400. */
  85401. int _tr_tally (deflate_state *s,
  85402. unsigned dist, /* distance of matched string */
  85403. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85404. {
  85405. s->d_buf[s->last_lit] = (ush)dist;
  85406. s->l_buf[s->last_lit++] = (uch)lc;
  85407. if (dist == 0) {
  85408. /* lc is the unmatched char */
  85409. s->dyn_ltree[lc].Freq++;
  85410. } else {
  85411. s->matches++;
  85412. /* Here, lc is the match length - MIN_MATCH */
  85413. dist--; /* dist = match distance - 1 */
  85414. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85415. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85416. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85417. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85418. s->dyn_dtree[d_code(dist)].Freq++;
  85419. }
  85420. #ifdef TRUNCATE_BLOCK
  85421. /* Try to guess if it is profitable to stop the current block here */
  85422. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85423. /* Compute an upper bound for the compressed length */
  85424. ulg out_length = (ulg)s->last_lit*8L;
  85425. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85426. int dcode;
  85427. for (dcode = 0; dcode < D_CODES; dcode++) {
  85428. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85429. (5L+extra_dbits[dcode]);
  85430. }
  85431. out_length >>= 3;
  85432. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85433. s->last_lit, in_length, out_length,
  85434. 100L - out_length*100L/in_length));
  85435. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85436. }
  85437. #endif
  85438. return (s->last_lit == s->lit_bufsize-1);
  85439. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85440. * on 16 bit machines and because stored blocks are restricted to
  85441. * 64K-1 bytes.
  85442. */
  85443. }
  85444. /* ===========================================================================
  85445. * Send the block data compressed using the given Huffman trees
  85446. */
  85447. local void compress_block (deflate_state *s,
  85448. ct_data *ltree, /* literal tree */
  85449. ct_data *dtree) /* distance tree */
  85450. {
  85451. unsigned dist; /* distance of matched string */
  85452. int lc; /* match length or unmatched char (if dist == 0) */
  85453. unsigned lx = 0; /* running index in l_buf */
  85454. unsigned code; /* the code to send */
  85455. int extra; /* number of extra bits to send */
  85456. if (s->last_lit != 0) do {
  85457. dist = s->d_buf[lx];
  85458. lc = s->l_buf[lx++];
  85459. if (dist == 0) {
  85460. send_code(s, lc, ltree); /* send a literal byte */
  85461. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85462. } else {
  85463. /* Here, lc is the match length - MIN_MATCH */
  85464. code = _length_code[lc];
  85465. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85466. extra = extra_lbits[code];
  85467. if (extra != 0) {
  85468. lc -= base_length[code];
  85469. send_bits(s, lc, extra); /* send the extra length bits */
  85470. }
  85471. dist--; /* dist is now the match distance - 1 */
  85472. code = d_code(dist);
  85473. Assert (code < D_CODES, "bad d_code");
  85474. send_code(s, code, dtree); /* send the distance code */
  85475. extra = extra_dbits[code];
  85476. if (extra != 0) {
  85477. dist -= base_dist[code];
  85478. send_bits(s, dist, extra); /* send the extra distance bits */
  85479. }
  85480. } /* literal or match pair ? */
  85481. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85482. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85483. "pendingBuf overflow");
  85484. } while (lx < s->last_lit);
  85485. send_code(s, END_BLOCK, ltree);
  85486. s->last_eob_len = ltree[END_BLOCK].Len;
  85487. }
  85488. /* ===========================================================================
  85489. * Set the data type to BINARY or TEXT, using a crude approximation:
  85490. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85491. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85492. * IN assertion: the fields Freq of dyn_ltree are set.
  85493. */
  85494. local void set_data_type (deflate_state *s)
  85495. {
  85496. int n;
  85497. for (n = 0; n < 9; n++)
  85498. if (s->dyn_ltree[n].Freq != 0)
  85499. break;
  85500. if (n == 9)
  85501. for (n = 14; n < 32; n++)
  85502. if (s->dyn_ltree[n].Freq != 0)
  85503. break;
  85504. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85505. }
  85506. /* ===========================================================================
  85507. * Reverse the first len bits of a code, using straightforward code (a faster
  85508. * method would use a table)
  85509. * IN assertion: 1 <= len <= 15
  85510. */
  85511. local unsigned bi_reverse (unsigned code, int len)
  85512. {
  85513. register unsigned res = 0;
  85514. do {
  85515. res |= code & 1;
  85516. code >>= 1, res <<= 1;
  85517. } while (--len > 0);
  85518. return res >> 1;
  85519. }
  85520. /* ===========================================================================
  85521. * Flush the bit buffer, keeping at most 7 bits in it.
  85522. */
  85523. local void bi_flush (deflate_state *s)
  85524. {
  85525. if (s->bi_valid == 16) {
  85526. put_short(s, s->bi_buf);
  85527. s->bi_buf = 0;
  85528. s->bi_valid = 0;
  85529. } else if (s->bi_valid >= 8) {
  85530. put_byte(s, (Byte)s->bi_buf);
  85531. s->bi_buf >>= 8;
  85532. s->bi_valid -= 8;
  85533. }
  85534. }
  85535. /* ===========================================================================
  85536. * Flush the bit buffer and align the output on a byte boundary
  85537. */
  85538. local void bi_windup (deflate_state *s)
  85539. {
  85540. if (s->bi_valid > 8) {
  85541. put_short(s, s->bi_buf);
  85542. } else if (s->bi_valid > 0) {
  85543. put_byte(s, (Byte)s->bi_buf);
  85544. }
  85545. s->bi_buf = 0;
  85546. s->bi_valid = 0;
  85547. #ifdef DEBUG
  85548. s->bits_sent = (s->bits_sent+7) & ~7;
  85549. #endif
  85550. }
  85551. /* ===========================================================================
  85552. * Copy a stored block, storing first the length and its
  85553. * one's complement if requested.
  85554. */
  85555. local void copy_block(deflate_state *s,
  85556. charf *buf, /* the input data */
  85557. unsigned len, /* its length */
  85558. int header) /* true if block header must be written */
  85559. {
  85560. bi_windup(s); /* align on byte boundary */
  85561. s->last_eob_len = 8; /* enough lookahead for inflate */
  85562. if (header) {
  85563. put_short(s, (ush)len);
  85564. put_short(s, (ush)~len);
  85565. #ifdef DEBUG
  85566. s->bits_sent += 2*16;
  85567. #endif
  85568. }
  85569. #ifdef DEBUG
  85570. s->bits_sent += (ulg)len<<3;
  85571. #endif
  85572. while (len--) {
  85573. put_byte(s, *buf++);
  85574. }
  85575. }
  85576. /*** End of inlined file: trees.c ***/
  85577. /*** Start of inlined file: zutil.c ***/
  85578. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85579. #ifndef NO_DUMMY_DECL
  85580. struct internal_state {int dummy;}; /* for buggy compilers */
  85581. #endif
  85582. const char * const z_errmsg[10] = {
  85583. "need dictionary", /* Z_NEED_DICT 2 */
  85584. "stream end", /* Z_STREAM_END 1 */
  85585. "", /* Z_OK 0 */
  85586. "file error", /* Z_ERRNO (-1) */
  85587. "stream error", /* Z_STREAM_ERROR (-2) */
  85588. "data error", /* Z_DATA_ERROR (-3) */
  85589. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85590. "buffer error", /* Z_BUF_ERROR (-5) */
  85591. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85592. ""};
  85593. /*const char * ZEXPORT zlibVersion()
  85594. {
  85595. return ZLIB_VERSION;
  85596. }
  85597. uLong ZEXPORT zlibCompileFlags()
  85598. {
  85599. uLong flags;
  85600. flags = 0;
  85601. switch (sizeof(uInt)) {
  85602. case 2: break;
  85603. case 4: flags += 1; break;
  85604. case 8: flags += 2; break;
  85605. default: flags += 3;
  85606. }
  85607. switch (sizeof(uLong)) {
  85608. case 2: break;
  85609. case 4: flags += 1 << 2; break;
  85610. case 8: flags += 2 << 2; break;
  85611. default: flags += 3 << 2;
  85612. }
  85613. switch (sizeof(voidpf)) {
  85614. case 2: break;
  85615. case 4: flags += 1 << 4; break;
  85616. case 8: flags += 2 << 4; break;
  85617. default: flags += 3 << 4;
  85618. }
  85619. switch (sizeof(z_off_t)) {
  85620. case 2: break;
  85621. case 4: flags += 1 << 6; break;
  85622. case 8: flags += 2 << 6; break;
  85623. default: flags += 3 << 6;
  85624. }
  85625. #ifdef DEBUG
  85626. flags += 1 << 8;
  85627. #endif
  85628. #if defined(ASMV) || defined(ASMINF)
  85629. flags += 1 << 9;
  85630. #endif
  85631. #ifdef ZLIB_WINAPI
  85632. flags += 1 << 10;
  85633. #endif
  85634. #ifdef BUILDFIXED
  85635. flags += 1 << 12;
  85636. #endif
  85637. #ifdef DYNAMIC_CRC_TABLE
  85638. flags += 1 << 13;
  85639. #endif
  85640. #ifdef NO_GZCOMPRESS
  85641. flags += 1L << 16;
  85642. #endif
  85643. #ifdef NO_GZIP
  85644. flags += 1L << 17;
  85645. #endif
  85646. #ifdef PKZIP_BUG_WORKAROUND
  85647. flags += 1L << 20;
  85648. #endif
  85649. #ifdef FASTEST
  85650. flags += 1L << 21;
  85651. #endif
  85652. #ifdef STDC
  85653. # ifdef NO_vsnprintf
  85654. flags += 1L << 25;
  85655. # ifdef HAS_vsprintf_void
  85656. flags += 1L << 26;
  85657. # endif
  85658. # else
  85659. # ifdef HAS_vsnprintf_void
  85660. flags += 1L << 26;
  85661. # endif
  85662. # endif
  85663. #else
  85664. flags += 1L << 24;
  85665. # ifdef NO_snprintf
  85666. flags += 1L << 25;
  85667. # ifdef HAS_sprintf_void
  85668. flags += 1L << 26;
  85669. # endif
  85670. # else
  85671. # ifdef HAS_snprintf_void
  85672. flags += 1L << 26;
  85673. # endif
  85674. # endif
  85675. #endif
  85676. return flags;
  85677. }*/
  85678. #ifdef DEBUG
  85679. # ifndef verbose
  85680. # define verbose 0
  85681. # endif
  85682. int z_verbose = verbose;
  85683. void z_error (const char *m)
  85684. {
  85685. fprintf(stderr, "%s\n", m);
  85686. exit(1);
  85687. }
  85688. #endif
  85689. /* exported to allow conversion of error code to string for compress() and
  85690. * uncompress()
  85691. */
  85692. const char * ZEXPORT zError(int err)
  85693. {
  85694. return ERR_MSG(err);
  85695. }
  85696. #if defined(_WIN32_WCE)
  85697. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85698. * errno. We define it as a global variable to simplify porting.
  85699. * Its value is always 0 and should not be used.
  85700. */
  85701. int errno = 0;
  85702. #endif
  85703. #ifndef HAVE_MEMCPY
  85704. void zmemcpy(dest, source, len)
  85705. Bytef* dest;
  85706. const Bytef* source;
  85707. uInt len;
  85708. {
  85709. if (len == 0) return;
  85710. do {
  85711. *dest++ = *source++; /* ??? to be unrolled */
  85712. } while (--len != 0);
  85713. }
  85714. int zmemcmp(s1, s2, len)
  85715. const Bytef* s1;
  85716. const Bytef* s2;
  85717. uInt len;
  85718. {
  85719. uInt j;
  85720. for (j = 0; j < len; j++) {
  85721. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85722. }
  85723. return 0;
  85724. }
  85725. void zmemzero(dest, len)
  85726. Bytef* dest;
  85727. uInt len;
  85728. {
  85729. if (len == 0) return;
  85730. do {
  85731. *dest++ = 0; /* ??? to be unrolled */
  85732. } while (--len != 0);
  85733. }
  85734. #endif
  85735. #ifdef SYS16BIT
  85736. #ifdef __TURBOC__
  85737. /* Turbo C in 16-bit mode */
  85738. # define MY_ZCALLOC
  85739. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85740. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85741. * must fix the pointer. Warning: the pointer must be put back to its
  85742. * original form in order to free it, use zcfree().
  85743. */
  85744. #define MAX_PTR 10
  85745. /* 10*64K = 640K */
  85746. local int next_ptr = 0;
  85747. typedef struct ptr_table_s {
  85748. voidpf org_ptr;
  85749. voidpf new_ptr;
  85750. } ptr_table;
  85751. local ptr_table table[MAX_PTR];
  85752. /* This table is used to remember the original form of pointers
  85753. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85754. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85755. * protected from concurrent access. This hack doesn't work anyway on
  85756. * a protected system like OS/2. Use Microsoft C instead.
  85757. */
  85758. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85759. {
  85760. voidpf buf = opaque; /* just to make some compilers happy */
  85761. ulg bsize = (ulg)items*size;
  85762. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85763. * will return a usable pointer which doesn't have to be normalized.
  85764. */
  85765. if (bsize < 65520L) {
  85766. buf = farmalloc(bsize);
  85767. if (*(ush*)&buf != 0) return buf;
  85768. } else {
  85769. buf = farmalloc(bsize + 16L);
  85770. }
  85771. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85772. table[next_ptr].org_ptr = buf;
  85773. /* Normalize the pointer to seg:0 */
  85774. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85775. *(ush*)&buf = 0;
  85776. table[next_ptr++].new_ptr = buf;
  85777. return buf;
  85778. }
  85779. void zcfree (voidpf opaque, voidpf ptr)
  85780. {
  85781. int n;
  85782. if (*(ush*)&ptr != 0) { /* object < 64K */
  85783. farfree(ptr);
  85784. return;
  85785. }
  85786. /* Find the original pointer */
  85787. for (n = 0; n < next_ptr; n++) {
  85788. if (ptr != table[n].new_ptr) continue;
  85789. farfree(table[n].org_ptr);
  85790. while (++n < next_ptr) {
  85791. table[n-1] = table[n];
  85792. }
  85793. next_ptr--;
  85794. return;
  85795. }
  85796. ptr = opaque; /* just to make some compilers happy */
  85797. Assert(0, "zcfree: ptr not found");
  85798. }
  85799. #endif /* __TURBOC__ */
  85800. #ifdef M_I86
  85801. /* Microsoft C in 16-bit mode */
  85802. # define MY_ZCALLOC
  85803. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85804. # define _halloc halloc
  85805. # define _hfree hfree
  85806. #endif
  85807. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85808. {
  85809. if (opaque) opaque = 0; /* to make compiler happy */
  85810. return _halloc((long)items, size);
  85811. }
  85812. void zcfree (voidpf opaque, voidpf ptr)
  85813. {
  85814. if (opaque) opaque = 0; /* to make compiler happy */
  85815. _hfree(ptr);
  85816. }
  85817. #endif /* M_I86 */
  85818. #endif /* SYS16BIT */
  85819. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85820. #ifndef STDC
  85821. extern voidp malloc OF((uInt size));
  85822. extern voidp calloc OF((uInt items, uInt size));
  85823. extern void free OF((voidpf ptr));
  85824. #endif
  85825. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85826. {
  85827. if (opaque) items += size - size; /* make compiler happy */
  85828. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85829. (voidpf)calloc(items, size);
  85830. }
  85831. void zcfree (voidpf opaque, voidpf ptr)
  85832. {
  85833. free(ptr);
  85834. if (opaque) return; /* make compiler happy */
  85835. }
  85836. #endif /* MY_ZCALLOC */
  85837. /*** End of inlined file: zutil.c ***/
  85838. #undef Byte
  85839. #else
  85840. #include <zlib.h>
  85841. #endif
  85842. }
  85843. #if JUCE_MSVC
  85844. #pragma warning (pop)
  85845. #endif
  85846. BEGIN_JUCE_NAMESPACE
  85847. // internal helper object that holds the zlib structures so they don't have to be
  85848. // included publicly.
  85849. class GZIPDecompressorInputStream::GZIPDecompressHelper
  85850. {
  85851. public:
  85852. GZIPDecompressHelper (const bool noWrap)
  85853. : finished (true),
  85854. needsDictionary (false),
  85855. error (true),
  85856. streamIsValid (false),
  85857. data (0),
  85858. dataSize (0)
  85859. {
  85860. using namespace zlibNamespace;
  85861. zerostruct (stream);
  85862. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85863. finished = error = ! streamIsValid;
  85864. }
  85865. ~GZIPDecompressHelper()
  85866. {
  85867. using namespace zlibNamespace;
  85868. if (streamIsValid)
  85869. inflateEnd (&stream);
  85870. }
  85871. bool needsInput() const throw() { return dataSize <= 0; }
  85872. void setInput (uint8* const data_, const int size) throw()
  85873. {
  85874. data = data_;
  85875. dataSize = size;
  85876. }
  85877. int doNextBlock (uint8* const dest, const int destSize)
  85878. {
  85879. using namespace zlibNamespace;
  85880. if (streamIsValid && data != 0 && ! finished)
  85881. {
  85882. stream.next_in = data;
  85883. stream.next_out = dest;
  85884. stream.avail_in = dataSize;
  85885. stream.avail_out = destSize;
  85886. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85887. {
  85888. case Z_STREAM_END:
  85889. finished = true;
  85890. // deliberate fall-through
  85891. case Z_OK:
  85892. data += dataSize - stream.avail_in;
  85893. dataSize = stream.avail_in;
  85894. return destSize - stream.avail_out;
  85895. case Z_NEED_DICT:
  85896. needsDictionary = true;
  85897. data += dataSize - stream.avail_in;
  85898. dataSize = stream.avail_in;
  85899. break;
  85900. case Z_DATA_ERROR:
  85901. case Z_MEM_ERROR:
  85902. error = true;
  85903. default:
  85904. break;
  85905. }
  85906. }
  85907. return 0;
  85908. }
  85909. bool finished, needsDictionary, error, streamIsValid;
  85910. enum { gzipDecompBufferSize = 32768 };
  85911. private:
  85912. zlibNamespace::z_stream stream;
  85913. uint8* data;
  85914. int dataSize;
  85915. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  85916. };
  85917. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85918. const bool deleteSourceWhenDestroyed,
  85919. const bool noWrap_,
  85920. const int64 uncompressedStreamLength_)
  85921. : sourceStream (sourceStream_),
  85922. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85923. uncompressedStreamLength (uncompressedStreamLength_),
  85924. noWrap (noWrap_),
  85925. isEof (false),
  85926. activeBufferSize (0),
  85927. originalSourcePos (sourceStream_->getPosition()),
  85928. currentPos (0),
  85929. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85930. helper (new GZIPDecompressHelper (noWrap_))
  85931. {
  85932. }
  85933. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  85934. : sourceStream (&sourceStream_),
  85935. uncompressedStreamLength (-1),
  85936. noWrap (false),
  85937. isEof (false),
  85938. activeBufferSize (0),
  85939. originalSourcePos (sourceStream_.getPosition()),
  85940. currentPos (0),
  85941. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85942. helper (new GZIPDecompressHelper (false))
  85943. {
  85944. }
  85945. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85946. {
  85947. }
  85948. int64 GZIPDecompressorInputStream::getTotalLength()
  85949. {
  85950. return uncompressedStreamLength;
  85951. }
  85952. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85953. {
  85954. if ((howMany > 0) && ! isEof)
  85955. {
  85956. jassert (destBuffer != 0);
  85957. if (destBuffer != 0)
  85958. {
  85959. int numRead = 0;
  85960. uint8* d = static_cast <uint8*> (destBuffer);
  85961. while (! helper->error)
  85962. {
  85963. const int n = helper->doNextBlock (d, howMany);
  85964. currentPos += n;
  85965. if (n == 0)
  85966. {
  85967. if (helper->finished || helper->needsDictionary)
  85968. {
  85969. isEof = true;
  85970. return numRead;
  85971. }
  85972. if (helper->needsInput())
  85973. {
  85974. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  85975. if (activeBufferSize > 0)
  85976. {
  85977. helper->setInput (buffer, activeBufferSize);
  85978. }
  85979. else
  85980. {
  85981. isEof = true;
  85982. return numRead;
  85983. }
  85984. }
  85985. }
  85986. else
  85987. {
  85988. numRead += n;
  85989. howMany -= n;
  85990. d += n;
  85991. if (howMany <= 0)
  85992. return numRead;
  85993. }
  85994. }
  85995. }
  85996. }
  85997. return 0;
  85998. }
  85999. bool GZIPDecompressorInputStream::isExhausted()
  86000. {
  86001. return helper->error || isEof;
  86002. }
  86003. int64 GZIPDecompressorInputStream::getPosition()
  86004. {
  86005. return currentPos;
  86006. }
  86007. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86008. {
  86009. if (newPos < currentPos)
  86010. {
  86011. // to go backwards, reset the stream and start again..
  86012. isEof = false;
  86013. activeBufferSize = 0;
  86014. currentPos = 0;
  86015. helper = new GZIPDecompressHelper (noWrap);
  86016. sourceStream->setPosition (originalSourcePos);
  86017. }
  86018. skipNextBytes (newPos - currentPos);
  86019. return true;
  86020. }
  86021. END_JUCE_NAMESPACE
  86022. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86023. #endif
  86024. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86025. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86026. #if JUCE_USE_FLAC
  86027. #if JUCE_WINDOWS
  86028. #include <windows.h>
  86029. #endif
  86030. namespace FlacNamespace
  86031. {
  86032. #if JUCE_INCLUDE_FLAC_CODE
  86033. #if JUCE_MSVC
  86034. #pragma warning (disable: 4505 181 111)
  86035. #endif
  86036. #define FLAC__NO_DLL 1
  86037. #if ! defined (SIZE_MAX)
  86038. #define SIZE_MAX 0xffffffff
  86039. #endif
  86040. #define __STDC_LIMIT_MACROS 1
  86041. /*** Start of inlined file: all.h ***/
  86042. #ifndef FLAC__ALL_H
  86043. #define FLAC__ALL_H
  86044. /*** Start of inlined file: export.h ***/
  86045. #ifndef FLAC__EXPORT_H
  86046. #define FLAC__EXPORT_H
  86047. /** \file include/FLAC/export.h
  86048. *
  86049. * \brief
  86050. * This module contains #defines and symbols for exporting function
  86051. * calls, and providing version information and compiled-in features.
  86052. *
  86053. * See the \link flac_export export \endlink module.
  86054. */
  86055. /** \defgroup flac_export FLAC/export.h: export symbols
  86056. * \ingroup flac
  86057. *
  86058. * \brief
  86059. * This module contains #defines and symbols for exporting function
  86060. * calls, and providing version information and compiled-in features.
  86061. *
  86062. * If you are compiling with MSVC and will link to the static library
  86063. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86064. * make sure the symbols are exported properly.
  86065. *
  86066. * \{
  86067. */
  86068. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86069. #define FLAC_API
  86070. #else
  86071. #ifdef FLAC_API_EXPORTS
  86072. #define FLAC_API _declspec(dllexport)
  86073. #else
  86074. #define FLAC_API _declspec(dllimport)
  86075. #endif
  86076. #endif
  86077. /** These #defines will mirror the libtool-based library version number, see
  86078. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86079. */
  86080. #define FLAC_API_VERSION_CURRENT 10
  86081. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86082. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86083. #ifdef __cplusplus
  86084. extern "C" {
  86085. #endif
  86086. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86087. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86088. #ifdef __cplusplus
  86089. }
  86090. #endif
  86091. /* \} */
  86092. #endif
  86093. /*** End of inlined file: export.h ***/
  86094. /*** Start of inlined file: assert.h ***/
  86095. #ifndef FLAC__ASSERT_H
  86096. #define FLAC__ASSERT_H
  86097. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86098. #ifdef DEBUG
  86099. #include <assert.h>
  86100. #define FLAC__ASSERT(x) assert(x)
  86101. #define FLAC__ASSERT_DECLARATION(x) x
  86102. #else
  86103. #define FLAC__ASSERT(x)
  86104. #define FLAC__ASSERT_DECLARATION(x)
  86105. #endif
  86106. #endif
  86107. /*** End of inlined file: assert.h ***/
  86108. /*** Start of inlined file: callback.h ***/
  86109. #ifndef FLAC__CALLBACK_H
  86110. #define FLAC__CALLBACK_H
  86111. /*** Start of inlined file: ordinals.h ***/
  86112. #ifndef FLAC__ORDINALS_H
  86113. #define FLAC__ORDINALS_H
  86114. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86115. #include <inttypes.h>
  86116. #endif
  86117. typedef signed char FLAC__int8;
  86118. typedef unsigned char FLAC__uint8;
  86119. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86120. typedef __int16 FLAC__int16;
  86121. typedef __int32 FLAC__int32;
  86122. typedef __int64 FLAC__int64;
  86123. typedef unsigned __int16 FLAC__uint16;
  86124. typedef unsigned __int32 FLAC__uint32;
  86125. typedef unsigned __int64 FLAC__uint64;
  86126. #elif defined(__EMX__)
  86127. typedef short FLAC__int16;
  86128. typedef long FLAC__int32;
  86129. typedef long long FLAC__int64;
  86130. typedef unsigned short FLAC__uint16;
  86131. typedef unsigned long FLAC__uint32;
  86132. typedef unsigned long long FLAC__uint64;
  86133. #else
  86134. typedef int16_t FLAC__int16;
  86135. typedef int32_t FLAC__int32;
  86136. typedef int64_t FLAC__int64;
  86137. typedef uint16_t FLAC__uint16;
  86138. typedef uint32_t FLAC__uint32;
  86139. typedef uint64_t FLAC__uint64;
  86140. #endif
  86141. typedef int FLAC__bool;
  86142. typedef FLAC__uint8 FLAC__byte;
  86143. #ifdef true
  86144. #undef true
  86145. #endif
  86146. #ifdef false
  86147. #undef false
  86148. #endif
  86149. #ifndef __cplusplus
  86150. #define true 1
  86151. #define false 0
  86152. #endif
  86153. #endif
  86154. /*** End of inlined file: ordinals.h ***/
  86155. #include <stdlib.h> /* for size_t */
  86156. /** \file include/FLAC/callback.h
  86157. *
  86158. * \brief
  86159. * This module defines the structures for describing I/O callbacks
  86160. * to the other FLAC interfaces.
  86161. *
  86162. * See the detailed documentation for callbacks in the
  86163. * \link flac_callbacks callbacks \endlink module.
  86164. */
  86165. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86166. * \ingroup flac
  86167. *
  86168. * \brief
  86169. * This module defines the structures for describing I/O callbacks
  86170. * to the other FLAC interfaces.
  86171. *
  86172. * The purpose of the I/O callback functions is to create a common way
  86173. * for the metadata interfaces to handle I/O.
  86174. *
  86175. * Originally the metadata interfaces required filenames as the way of
  86176. * specifying FLAC files to operate on. This is problematic in some
  86177. * environments so there is an additional option to specify a set of
  86178. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86179. *
  86180. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86181. * opaque structure for a data source.
  86182. *
  86183. * The callback function prototypes are similar (but not identical) to the
  86184. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86185. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86186. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86187. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86188. * is required. \warning You generally CANNOT directly use fseek or ftell
  86189. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86190. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86191. * large files. You will have to find an equivalent function (e.g. ftello),
  86192. * or write a wrapper. The same is true for feof() since this is usually
  86193. * implemented as a macro, not as a function whose address can be taken.
  86194. *
  86195. * \{
  86196. */
  86197. #ifdef __cplusplus
  86198. extern "C" {
  86199. #endif
  86200. /** This is the opaque handle type used by the callbacks. Typically
  86201. * this is a \c FILE* or address of a file descriptor.
  86202. */
  86203. typedef void* FLAC__IOHandle;
  86204. /** Signature for the read callback.
  86205. * The signature and semantics match POSIX fread() implementations
  86206. * and can generally be used interchangeably.
  86207. *
  86208. * \param ptr The address of the read buffer.
  86209. * \param size The size of the records to be read.
  86210. * \param nmemb The number of records to be read.
  86211. * \param handle The handle to the data source.
  86212. * \retval size_t
  86213. * The number of records read.
  86214. */
  86215. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86216. /** Signature for the write callback.
  86217. * The signature and semantics match POSIX fwrite() implementations
  86218. * and can generally be used interchangeably.
  86219. *
  86220. * \param ptr The address of the write buffer.
  86221. * \param size The size of the records to be written.
  86222. * \param nmemb The number of records to be written.
  86223. * \param handle The handle to the data source.
  86224. * \retval size_t
  86225. * The number of records written.
  86226. */
  86227. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86228. /** Signature for the seek callback.
  86229. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86230. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86231. * and 32-bits wide.
  86232. *
  86233. * \param handle The handle to the data source.
  86234. * \param offset The new position, relative to \a whence
  86235. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86236. * \retval int
  86237. * \c 0 on success, \c -1 on error.
  86238. */
  86239. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86240. /** Signature for the tell callback.
  86241. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86242. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86243. * and 32-bits wide.
  86244. *
  86245. * \param handle The handle to the data source.
  86246. * \retval FLAC__int64
  86247. * The current position on success, \c -1 on error.
  86248. */
  86249. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86250. /** Signature for the EOF callback.
  86251. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86252. * on many systems, feof() is a macro, so in this case a wrapper function
  86253. * must be provided instead.
  86254. *
  86255. * \param handle The handle to the data source.
  86256. * \retval int
  86257. * \c 0 if not at end of file, nonzero if at end of file.
  86258. */
  86259. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86260. /** Signature for the close callback.
  86261. * The signature and semantics match POSIX fclose() implementations
  86262. * and can generally be used interchangeably.
  86263. *
  86264. * \param handle The handle to the data source.
  86265. * \retval int
  86266. * \c 0 on success, \c EOF on error.
  86267. */
  86268. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86269. /** A structure for holding a set of callbacks.
  86270. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86271. * describe which of the callbacks are required. The ones that are not
  86272. * required may be set to NULL.
  86273. *
  86274. * If the seek requirement for an interface is optional, you can signify that
  86275. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86276. */
  86277. typedef struct {
  86278. FLAC__IOCallback_Read read;
  86279. FLAC__IOCallback_Write write;
  86280. FLAC__IOCallback_Seek seek;
  86281. FLAC__IOCallback_Tell tell;
  86282. FLAC__IOCallback_Eof eof;
  86283. FLAC__IOCallback_Close close;
  86284. } FLAC__IOCallbacks;
  86285. /* \} */
  86286. #ifdef __cplusplus
  86287. }
  86288. #endif
  86289. #endif
  86290. /*** End of inlined file: callback.h ***/
  86291. /*** Start of inlined file: format.h ***/
  86292. #ifndef FLAC__FORMAT_H
  86293. #define FLAC__FORMAT_H
  86294. #ifdef __cplusplus
  86295. extern "C" {
  86296. #endif
  86297. /** \file include/FLAC/format.h
  86298. *
  86299. * \brief
  86300. * This module contains structure definitions for the representation
  86301. * of FLAC format components in memory. These are the basic
  86302. * structures used by the rest of the interfaces.
  86303. *
  86304. * See the detailed documentation in the
  86305. * \link flac_format format \endlink module.
  86306. */
  86307. /** \defgroup flac_format FLAC/format.h: format components
  86308. * \ingroup flac
  86309. *
  86310. * \brief
  86311. * This module contains structure definitions for the representation
  86312. * of FLAC format components in memory. These are the basic
  86313. * structures used by the rest of the interfaces.
  86314. *
  86315. * First, you should be familiar with the
  86316. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86317. * follow directly from the specification. As a user of libFLAC, the
  86318. * interesting parts really are the structures that describe the frame
  86319. * header and metadata blocks.
  86320. *
  86321. * The format structures here are very primitive, designed to store
  86322. * information in an efficient way. Reading information from the
  86323. * structures is easy but creating or modifying them directly is
  86324. * more complex. For the most part, as a user of a library, editing
  86325. * is not necessary; however, for metadata blocks it is, so there are
  86326. * convenience functions provided in the \link flac_metadata metadata
  86327. * module \endlink to simplify the manipulation of metadata blocks.
  86328. *
  86329. * \note
  86330. * It's not the best convention, but symbols ending in _LEN are in bits
  86331. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86332. * global variables because they are usually used when declaring byte
  86333. * arrays and some compilers require compile-time knowledge of array
  86334. * sizes when declared on the stack.
  86335. *
  86336. * \{
  86337. */
  86338. /*
  86339. Most of the values described in this file are defined by the FLAC
  86340. format specification. There is nothing to tune here.
  86341. */
  86342. /** The largest legal metadata type code. */
  86343. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86344. /** The minimum block size, in samples, permitted by the format. */
  86345. #define FLAC__MIN_BLOCK_SIZE (16u)
  86346. /** The maximum block size, in samples, permitted by the format. */
  86347. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86348. /** The maximum block size, in samples, permitted by the FLAC subset for
  86349. * sample rates up to 48kHz. */
  86350. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86351. /** The maximum number of channels permitted by the format. */
  86352. #define FLAC__MAX_CHANNELS (8u)
  86353. /** The minimum sample resolution permitted by the format. */
  86354. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86355. /** The maximum sample resolution permitted by the format. */
  86356. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86357. /** The maximum sample resolution permitted by libFLAC.
  86358. *
  86359. * \warning
  86360. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86361. * the reference encoder/decoder is currently limited to 24 bits because
  86362. * of prevalent 32-bit math, so make sure and use this value when
  86363. * appropriate.
  86364. */
  86365. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86366. /** The maximum sample rate permitted by the format. The value is
  86367. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86368. * as to why.
  86369. */
  86370. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86371. /** The maximum LPC order permitted by the format. */
  86372. #define FLAC__MAX_LPC_ORDER (32u)
  86373. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86374. * up to 48kHz. */
  86375. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86376. /** The minimum quantized linear predictor coefficient precision
  86377. * permitted by the format.
  86378. */
  86379. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86380. /** The maximum quantized linear predictor coefficient precision
  86381. * permitted by the format.
  86382. */
  86383. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86384. /** The maximum order of the fixed predictors permitted by the format. */
  86385. #define FLAC__MAX_FIXED_ORDER (4u)
  86386. /** The maximum Rice partition order permitted by the format. */
  86387. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86388. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86389. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86390. /** The version string of the release, stamped onto the libraries and binaries.
  86391. *
  86392. * \note
  86393. * This does not correspond to the shared library version number, which
  86394. * is used to determine binary compatibility.
  86395. */
  86396. extern FLAC_API const char *FLAC__VERSION_STRING;
  86397. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86398. * This is a NUL-terminated ASCII string; when inserted into the
  86399. * VORBIS_COMMENT the trailing null is stripped.
  86400. */
  86401. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86402. /** The byte string representation of the beginning of a FLAC stream. */
  86403. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86404. /** The 32-bit integer big-endian representation of the beginning of
  86405. * a FLAC stream.
  86406. */
  86407. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86408. /** The length of the FLAC signature in bits. */
  86409. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86410. /** The length of the FLAC signature in bytes. */
  86411. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86412. /*****************************************************************************
  86413. *
  86414. * Subframe structures
  86415. *
  86416. *****************************************************************************/
  86417. /*****************************************************************************/
  86418. /** An enumeration of the available entropy coding methods. */
  86419. typedef enum {
  86420. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86421. /**< Residual is coded by partitioning into contexts, each with it's own
  86422. * 4-bit Rice parameter. */
  86423. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86424. /**< Residual is coded by partitioning into contexts, each with it's own
  86425. * 5-bit Rice parameter. */
  86426. } FLAC__EntropyCodingMethodType;
  86427. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86428. *
  86429. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86430. * give the string equivalent. The contents should not be modified.
  86431. */
  86432. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86433. /** Contents of a Rice partitioned residual
  86434. */
  86435. typedef struct {
  86436. unsigned *parameters;
  86437. /**< The Rice parameters for each context. */
  86438. unsigned *raw_bits;
  86439. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86440. * partitions and zero for unescaped partitions.
  86441. */
  86442. unsigned capacity_by_order;
  86443. /**< The capacity of the \a parameters and \a raw_bits arrays
  86444. * specified as an order, i.e. the number of array elements
  86445. * allocated is 2 ^ \a capacity_by_order.
  86446. */
  86447. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86448. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86449. */
  86450. typedef struct {
  86451. unsigned order;
  86452. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86453. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86454. /**< The context's Rice parameters and/or raw bits. */
  86455. } FLAC__EntropyCodingMethod_PartitionedRice;
  86456. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86457. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86458. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86459. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86460. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86461. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86462. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86463. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86464. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86465. */
  86466. typedef struct {
  86467. FLAC__EntropyCodingMethodType type;
  86468. union {
  86469. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86470. } data;
  86471. } FLAC__EntropyCodingMethod;
  86472. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86473. /*****************************************************************************/
  86474. /** An enumeration of the available subframe types. */
  86475. typedef enum {
  86476. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86477. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86478. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86479. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86480. } FLAC__SubframeType;
  86481. /** Maps a FLAC__SubframeType to a C string.
  86482. *
  86483. * Using a FLAC__SubframeType as the index to this array will
  86484. * give the string equivalent. The contents should not be modified.
  86485. */
  86486. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86487. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86488. */
  86489. typedef struct {
  86490. FLAC__int32 value; /**< The constant signal value. */
  86491. } FLAC__Subframe_Constant;
  86492. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86493. */
  86494. typedef struct {
  86495. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86496. } FLAC__Subframe_Verbatim;
  86497. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86498. */
  86499. typedef struct {
  86500. FLAC__EntropyCodingMethod entropy_coding_method;
  86501. /**< The residual coding method. */
  86502. unsigned order;
  86503. /**< The polynomial order. */
  86504. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86505. /**< Warmup samples to prime the predictor, length == order. */
  86506. const FLAC__int32 *residual;
  86507. /**< The residual signal, length == (blocksize minus order) samples. */
  86508. } FLAC__Subframe_Fixed;
  86509. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86510. */
  86511. typedef struct {
  86512. FLAC__EntropyCodingMethod entropy_coding_method;
  86513. /**< The residual coding method. */
  86514. unsigned order;
  86515. /**< The FIR order. */
  86516. unsigned qlp_coeff_precision;
  86517. /**< Quantized FIR filter coefficient precision in bits. */
  86518. int quantization_level;
  86519. /**< The qlp coeff shift needed. */
  86520. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86521. /**< FIR filter coefficients. */
  86522. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86523. /**< Warmup samples to prime the predictor, length == order. */
  86524. const FLAC__int32 *residual;
  86525. /**< The residual signal, length == (blocksize minus order) samples. */
  86526. } FLAC__Subframe_LPC;
  86527. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86528. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86529. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86530. */
  86531. typedef struct {
  86532. FLAC__SubframeType type;
  86533. union {
  86534. FLAC__Subframe_Constant constant;
  86535. FLAC__Subframe_Fixed fixed;
  86536. FLAC__Subframe_LPC lpc;
  86537. FLAC__Subframe_Verbatim verbatim;
  86538. } data;
  86539. unsigned wasted_bits;
  86540. } FLAC__Subframe;
  86541. /** == 1 (bit)
  86542. *
  86543. * This used to be a zero-padding bit (hence the name
  86544. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86545. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86546. * to mean something else.
  86547. */
  86548. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86549. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86550. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86551. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86552. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86553. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86554. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86555. /*****************************************************************************/
  86556. /*****************************************************************************
  86557. *
  86558. * Frame structures
  86559. *
  86560. *****************************************************************************/
  86561. /** An enumeration of the available channel assignments. */
  86562. typedef enum {
  86563. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86564. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86565. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86566. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86567. } FLAC__ChannelAssignment;
  86568. /** Maps a FLAC__ChannelAssignment to a C string.
  86569. *
  86570. * Using a FLAC__ChannelAssignment as the index to this array will
  86571. * give the string equivalent. The contents should not be modified.
  86572. */
  86573. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86574. /** An enumeration of the possible frame numbering methods. */
  86575. typedef enum {
  86576. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86577. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86578. } FLAC__FrameNumberType;
  86579. /** Maps a FLAC__FrameNumberType to a C string.
  86580. *
  86581. * Using a FLAC__FrameNumberType as the index to this array will
  86582. * give the string equivalent. The contents should not be modified.
  86583. */
  86584. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86585. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86586. */
  86587. typedef struct {
  86588. unsigned blocksize;
  86589. /**< The number of samples per subframe. */
  86590. unsigned sample_rate;
  86591. /**< The sample rate in Hz. */
  86592. unsigned channels;
  86593. /**< The number of channels (== number of subframes). */
  86594. FLAC__ChannelAssignment channel_assignment;
  86595. /**< The channel assignment for the frame. */
  86596. unsigned bits_per_sample;
  86597. /**< The sample resolution. */
  86598. FLAC__FrameNumberType number_type;
  86599. /**< The numbering scheme used for the frame. As a convenience, the
  86600. * decoder will always convert a frame number to a sample number because
  86601. * the rules are complex. */
  86602. union {
  86603. FLAC__uint32 frame_number;
  86604. FLAC__uint64 sample_number;
  86605. } number;
  86606. /**< The frame number or sample number of first sample in frame;
  86607. * use the \a number_type value to determine which to use. */
  86608. FLAC__uint8 crc;
  86609. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86610. * of the raw frame header bytes, meaning everything before the CRC byte
  86611. * including the sync code.
  86612. */
  86613. } FLAC__FrameHeader;
  86614. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86615. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86616. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86617. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86618. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86619. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86620. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86621. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86622. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86623. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86624. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86625. */
  86626. typedef struct {
  86627. FLAC__uint16 crc;
  86628. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86629. * 0) of the bytes before the crc, back to and including the frame header
  86630. * sync code.
  86631. */
  86632. } FLAC__FrameFooter;
  86633. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86634. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86635. */
  86636. typedef struct {
  86637. FLAC__FrameHeader header;
  86638. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86639. FLAC__FrameFooter footer;
  86640. } FLAC__Frame;
  86641. /*****************************************************************************/
  86642. /*****************************************************************************
  86643. *
  86644. * Meta-data structures
  86645. *
  86646. *****************************************************************************/
  86647. /** An enumeration of the available metadata block types. */
  86648. typedef enum {
  86649. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86650. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86651. FLAC__METADATA_TYPE_PADDING = 1,
  86652. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86653. FLAC__METADATA_TYPE_APPLICATION = 2,
  86654. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86655. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86656. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86657. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86658. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86659. FLAC__METADATA_TYPE_CUESHEET = 5,
  86660. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86661. FLAC__METADATA_TYPE_PICTURE = 6,
  86662. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86663. FLAC__METADATA_TYPE_UNDEFINED = 7
  86664. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86665. } FLAC__MetadataType;
  86666. /** Maps a FLAC__MetadataType to a C string.
  86667. *
  86668. * Using a FLAC__MetadataType as the index to this array will
  86669. * give the string equivalent. The contents should not be modified.
  86670. */
  86671. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86672. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86673. */
  86674. typedef struct {
  86675. unsigned min_blocksize, max_blocksize;
  86676. unsigned min_framesize, max_framesize;
  86677. unsigned sample_rate;
  86678. unsigned channels;
  86679. unsigned bits_per_sample;
  86680. FLAC__uint64 total_samples;
  86681. FLAC__byte md5sum[16];
  86682. } FLAC__StreamMetadata_StreamInfo;
  86683. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86684. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86685. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86686. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86687. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86688. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86689. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86690. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86691. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86692. /** The total stream length of the STREAMINFO block in bytes. */
  86693. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86694. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86695. */
  86696. typedef struct {
  86697. int dummy;
  86698. /**< Conceptually this is an empty struct since we don't store the
  86699. * padding bytes. Empty structs are not allowed by some C compilers,
  86700. * hence the dummy.
  86701. */
  86702. } FLAC__StreamMetadata_Padding;
  86703. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86704. */
  86705. typedef struct {
  86706. FLAC__byte id[4];
  86707. FLAC__byte *data;
  86708. } FLAC__StreamMetadata_Application;
  86709. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86710. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86711. */
  86712. typedef struct {
  86713. FLAC__uint64 sample_number;
  86714. /**< The sample number of the target frame. */
  86715. FLAC__uint64 stream_offset;
  86716. /**< The offset, in bytes, of the target frame with respect to
  86717. * beginning of the first frame. */
  86718. unsigned frame_samples;
  86719. /**< The number of samples in the target frame. */
  86720. } FLAC__StreamMetadata_SeekPoint;
  86721. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86722. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86723. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86724. /** The total stream length of a seek point in bytes. */
  86725. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86726. /** The value used in the \a sample_number field of
  86727. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86728. * point (== 0xffffffffffffffff).
  86729. */
  86730. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86731. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86732. *
  86733. * \note From the format specification:
  86734. * - The seek points must be sorted by ascending sample number.
  86735. * - Each seek point's sample number must be the first sample of the
  86736. * target frame.
  86737. * - Each seek point's sample number must be unique within the table.
  86738. * - Existence of a SEEKTABLE block implies a correct setting of
  86739. * total_samples in the stream_info block.
  86740. * - Behavior is undefined when more than one SEEKTABLE block is
  86741. * present in a stream.
  86742. */
  86743. typedef struct {
  86744. unsigned num_points;
  86745. FLAC__StreamMetadata_SeekPoint *points;
  86746. } FLAC__StreamMetadata_SeekTable;
  86747. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86748. *
  86749. * For convenience, the APIs maintain a trailing NUL character at the end of
  86750. * \a entry which is not counted toward \a length, i.e.
  86751. * \code strlen(entry) == length \endcode
  86752. */
  86753. typedef struct {
  86754. FLAC__uint32 length;
  86755. FLAC__byte *entry;
  86756. } FLAC__StreamMetadata_VorbisComment_Entry;
  86757. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86758. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86759. */
  86760. typedef struct {
  86761. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86762. FLAC__uint32 num_comments;
  86763. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86764. } FLAC__StreamMetadata_VorbisComment;
  86765. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86766. /** FLAC CUESHEET track index structure. (See the
  86767. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86768. * the full description of each field.)
  86769. */
  86770. typedef struct {
  86771. FLAC__uint64 offset;
  86772. /**< Offset in samples, relative to the track offset, of the index
  86773. * point.
  86774. */
  86775. FLAC__byte number;
  86776. /**< The index point number. */
  86777. } FLAC__StreamMetadata_CueSheet_Index;
  86778. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86779. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86780. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86781. /** FLAC CUESHEET track structure. (See the
  86782. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86783. * the full description of each field.)
  86784. */
  86785. typedef struct {
  86786. FLAC__uint64 offset;
  86787. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86788. FLAC__byte number;
  86789. /**< The track number. */
  86790. char isrc[13];
  86791. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86792. unsigned type:1;
  86793. /**< The track type: 0 for audio, 1 for non-audio. */
  86794. unsigned pre_emphasis:1;
  86795. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86796. FLAC__byte num_indices;
  86797. /**< The number of track index points. */
  86798. FLAC__StreamMetadata_CueSheet_Index *indices;
  86799. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86800. } FLAC__StreamMetadata_CueSheet_Track;
  86801. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86802. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86803. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86804. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86805. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86806. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86807. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86808. /** FLAC CUESHEET structure. (See the
  86809. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86810. * for the full description of each field.)
  86811. */
  86812. typedef struct {
  86813. char media_catalog_number[129];
  86814. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86815. * general, the media catalog number may be 0 to 128 bytes long; any
  86816. * unused characters should be right-padded with NUL characters.
  86817. */
  86818. FLAC__uint64 lead_in;
  86819. /**< The number of lead-in samples. */
  86820. FLAC__bool is_cd;
  86821. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86822. unsigned num_tracks;
  86823. /**< The number of tracks. */
  86824. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86825. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86826. } FLAC__StreamMetadata_CueSheet;
  86827. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86828. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86829. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86830. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86831. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86832. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86833. typedef enum {
  86834. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86835. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86836. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86837. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86838. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86839. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86840. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86841. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86842. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86843. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86844. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86845. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86846. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86847. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86848. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86849. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86850. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86851. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86852. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86853. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86854. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86855. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86856. } FLAC__StreamMetadata_Picture_Type;
  86857. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86858. *
  86859. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86860. * will give the string equivalent. The contents should not be
  86861. * modified.
  86862. */
  86863. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86864. /** FLAC PICTURE structure. (See the
  86865. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86866. * for the full description of each field.)
  86867. */
  86868. typedef struct {
  86869. FLAC__StreamMetadata_Picture_Type type;
  86870. /**< The kind of picture stored. */
  86871. char *mime_type;
  86872. /**< Picture data's MIME type, in ASCII printable characters
  86873. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86874. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86875. * MIME type of '-->' is also allowed, in which case the picture
  86876. * data should be a complete URL. In file storage, the MIME type is
  86877. * stored as a 32-bit length followed by the ASCII string with no NUL
  86878. * terminator, but is converted to a plain C string in this structure
  86879. * for convenience.
  86880. */
  86881. FLAC__byte *description;
  86882. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86883. * the description is stored as a 32-bit length followed by the UTF-8
  86884. * string with no NUL terminator, but is converted to a plain C string
  86885. * in this structure for convenience.
  86886. */
  86887. FLAC__uint32 width;
  86888. /**< Picture's width in pixels. */
  86889. FLAC__uint32 height;
  86890. /**< Picture's height in pixels. */
  86891. FLAC__uint32 depth;
  86892. /**< Picture's color depth in bits-per-pixel. */
  86893. FLAC__uint32 colors;
  86894. /**< For indexed palettes (like GIF), picture's number of colors (the
  86895. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86896. */
  86897. FLAC__uint32 data_length;
  86898. /**< Length of binary picture data in bytes. */
  86899. FLAC__byte *data;
  86900. /**< Binary picture data. */
  86901. } FLAC__StreamMetadata_Picture;
  86902. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86903. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86904. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86905. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86906. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86907. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86908. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86909. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86910. /** Structure that is used when a metadata block of unknown type is loaded.
  86911. * The contents are opaque. The structure is used only internally to
  86912. * correctly handle unknown metadata.
  86913. */
  86914. typedef struct {
  86915. FLAC__byte *data;
  86916. } FLAC__StreamMetadata_Unknown;
  86917. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86918. */
  86919. typedef struct {
  86920. FLAC__MetadataType type;
  86921. /**< The type of the metadata block; used determine which member of the
  86922. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86923. * then \a data.unknown must be used. */
  86924. FLAC__bool is_last;
  86925. /**< \c true if this metadata block is the last, else \a false */
  86926. unsigned length;
  86927. /**< Length, in bytes, of the block data as it appears in the stream. */
  86928. union {
  86929. FLAC__StreamMetadata_StreamInfo stream_info;
  86930. FLAC__StreamMetadata_Padding padding;
  86931. FLAC__StreamMetadata_Application application;
  86932. FLAC__StreamMetadata_SeekTable seek_table;
  86933. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86934. FLAC__StreamMetadata_CueSheet cue_sheet;
  86935. FLAC__StreamMetadata_Picture picture;
  86936. FLAC__StreamMetadata_Unknown unknown;
  86937. } data;
  86938. /**< Polymorphic block data; use the \a type value to determine which
  86939. * to use. */
  86940. } FLAC__StreamMetadata;
  86941. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86942. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86943. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86944. /** The total stream length of a metadata block header in bytes. */
  86945. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86946. /*****************************************************************************/
  86947. /*****************************************************************************
  86948. *
  86949. * Utility functions
  86950. *
  86951. *****************************************************************************/
  86952. /** Tests that a sample rate is valid for FLAC.
  86953. *
  86954. * \param sample_rate The sample rate to test for compliance.
  86955. * \retval FLAC__bool
  86956. * \c true if the given sample rate conforms to the specification, else
  86957. * \c false.
  86958. */
  86959. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86960. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86961. * for valid sample rates are slightly more complex since the rate has to
  86962. * be expressible completely in the frame header.
  86963. *
  86964. * \param sample_rate The sample rate to test for compliance.
  86965. * \retval FLAC__bool
  86966. * \c true if the given sample rate conforms to the specification for the
  86967. * subset, else \c false.
  86968. */
  86969. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86970. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86971. * comment specification.
  86972. *
  86973. * Vorbis comment names must be composed only of characters from
  86974. * [0x20-0x3C,0x3E-0x7D].
  86975. *
  86976. * \param name A NUL-terminated string to be checked.
  86977. * \assert
  86978. * \code name != NULL \endcode
  86979. * \retval FLAC__bool
  86980. * \c false if entry name is illegal, else \c true.
  86981. */
  86982. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86983. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86984. * comment specification.
  86985. *
  86986. * Vorbis comment values must be valid UTF-8 sequences.
  86987. *
  86988. * \param value A string to be checked.
  86989. * \param length A the length of \a value in bytes. May be
  86990. * \c (unsigned)(-1) to indicate that \a value is a plain
  86991. * UTF-8 NUL-terminated string.
  86992. * \assert
  86993. * \code value != NULL \endcode
  86994. * \retval FLAC__bool
  86995. * \c false if entry name is illegal, else \c true.
  86996. */
  86997. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86998. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86999. * comment specification.
  87000. *
  87001. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87002. * 'value' must be legal according to
  87003. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87004. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87005. *
  87006. * \param entry An entry to be checked.
  87007. * \param length The length of \a entry in bytes.
  87008. * \assert
  87009. * \code value != NULL \endcode
  87010. * \retval FLAC__bool
  87011. * \c false if entry name is illegal, else \c true.
  87012. */
  87013. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87014. /** Check a seek table to see if it conforms to the FLAC specification.
  87015. * See the format specification for limits on the contents of the
  87016. * seek table.
  87017. *
  87018. * \param seek_table A pointer to a seek table to be checked.
  87019. * \assert
  87020. * \code seek_table != NULL \endcode
  87021. * \retval FLAC__bool
  87022. * \c false if seek table is illegal, else \c true.
  87023. */
  87024. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87025. /** Sort a seek table's seek points according to the format specification.
  87026. * This includes a "unique-ification" step to remove duplicates, i.e.
  87027. * seek points with identical \a sample_number values. Duplicate seek
  87028. * points are converted into placeholder points and sorted to the end of
  87029. * the table.
  87030. *
  87031. * \param seek_table A pointer to a seek table to be sorted.
  87032. * \assert
  87033. * \code seek_table != NULL \endcode
  87034. * \retval unsigned
  87035. * The number of duplicate seek points converted into placeholders.
  87036. */
  87037. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87038. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87039. * See the format specification for limits on the contents of the
  87040. * cue sheet.
  87041. *
  87042. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87043. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87044. * stringent requirements for a CD-DA (audio) disc.
  87045. * \param violation Address of a pointer to a string. If there is a
  87046. * violation, a pointer to a string explanation of the
  87047. * violation will be returned here. \a violation may be
  87048. * \c NULL if you don't need the returned string. Do not
  87049. * free the returned string; it will always point to static
  87050. * data.
  87051. * \assert
  87052. * \code cue_sheet != NULL \endcode
  87053. * \retval FLAC__bool
  87054. * \c false if cue sheet is illegal, else \c true.
  87055. */
  87056. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87057. /** Check picture data to see if it conforms to the FLAC specification.
  87058. * See the format specification for limits on the contents of the
  87059. * PICTURE block.
  87060. *
  87061. * \param picture A pointer to existing picture data to be checked.
  87062. * \param violation Address of a pointer to a string. If there is a
  87063. * violation, a pointer to a string explanation of the
  87064. * violation will be returned here. \a violation may be
  87065. * \c NULL if you don't need the returned string. Do not
  87066. * free the returned string; it will always point to static
  87067. * data.
  87068. * \assert
  87069. * \code picture != NULL \endcode
  87070. * \retval FLAC__bool
  87071. * \c false if picture data is illegal, else \c true.
  87072. */
  87073. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87074. /* \} */
  87075. #ifdef __cplusplus
  87076. }
  87077. #endif
  87078. #endif
  87079. /*** End of inlined file: format.h ***/
  87080. /*** Start of inlined file: metadata.h ***/
  87081. #ifndef FLAC__METADATA_H
  87082. #define FLAC__METADATA_H
  87083. #include <sys/types.h> /* for off_t */
  87084. /* --------------------------------------------------------------------
  87085. (For an example of how all these routines are used, see the source
  87086. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87087. metaflac in src/metaflac/)
  87088. ------------------------------------------------------------------*/
  87089. /** \file include/FLAC/metadata.h
  87090. *
  87091. * \brief
  87092. * This module provides functions for creating and manipulating FLAC
  87093. * metadata blocks in memory, and three progressively more powerful
  87094. * interfaces for traversing and editing metadata in FLAC files.
  87095. *
  87096. * See the detailed documentation for each interface in the
  87097. * \link flac_metadata metadata \endlink module.
  87098. */
  87099. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87100. * \ingroup flac
  87101. *
  87102. * \brief
  87103. * This module provides functions for creating and manipulating FLAC
  87104. * metadata blocks in memory, and three progressively more powerful
  87105. * interfaces for traversing and editing metadata in native FLAC files.
  87106. * Note that currently only the Chain interface (level 2) supports Ogg
  87107. * FLAC files, and it is read-only i.e. no writing back changed
  87108. * metadata to file.
  87109. *
  87110. * There are three metadata interfaces of increasing complexity:
  87111. *
  87112. * Level 0:
  87113. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87114. * PICTURE blocks.
  87115. *
  87116. * Level 1:
  87117. * Read-write access to all metadata blocks. This level is write-
  87118. * efficient in most cases (more on this below), and uses less memory
  87119. * than level 2.
  87120. *
  87121. * Level 2:
  87122. * Read-write access to all metadata blocks. This level is write-
  87123. * efficient in all cases, but uses more memory since all metadata for
  87124. * the whole file is read into memory and manipulated before writing
  87125. * out again.
  87126. *
  87127. * What do we mean by efficient? Since FLAC metadata appears at the
  87128. * beginning of the file, when writing metadata back to a FLAC file
  87129. * it is possible to grow or shrink the metadata such that the entire
  87130. * file must be rewritten. However, if the size remains the same during
  87131. * changes or PADDING blocks are utilized, only the metadata needs to be
  87132. * overwritten, which is much faster.
  87133. *
  87134. * Efficient means the whole file is rewritten at most one time, and only
  87135. * when necessary. Level 1 is not efficient only in the case that you
  87136. * cause more than one metadata block to grow or shrink beyond what can
  87137. * be accomodated by padding. In this case you should probably use level
  87138. * 2, which allows you to edit all the metadata for a file in memory and
  87139. * write it out all at once.
  87140. *
  87141. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87142. * front of the file.
  87143. *
  87144. * All levels access files via their filenames. In addition, level 2
  87145. * has additional alternative read and write functions that take an I/O
  87146. * handle and callbacks, for situations where access by filename is not
  87147. * possible.
  87148. *
  87149. * In addition to the three interfaces, this module defines functions for
  87150. * creating and manipulating various metadata objects in memory. As we see
  87151. * from the Format module, FLAC metadata blocks in memory are very primitive
  87152. * structures for storing information in an efficient way. Reading
  87153. * information from the structures is easy but creating or modifying them
  87154. * directly is more complex. The metadata object routines here facilitate
  87155. * this by taking care of the consistency and memory management drudgery.
  87156. *
  87157. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87158. * metadata however, you will not probably not need these.
  87159. *
  87160. * From a dependency standpoint, none of the encoders or decoders require
  87161. * the metadata module. This is so that embedded users can strip out the
  87162. * metadata module from libFLAC to reduce the size and complexity.
  87163. */
  87164. #ifdef __cplusplus
  87165. extern "C" {
  87166. #endif
  87167. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87168. * \ingroup flac_metadata
  87169. *
  87170. * \brief
  87171. * The level 0 interface consists of individual routines to read the
  87172. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87173. * only a filename.
  87174. *
  87175. * They try to skip any ID3v2 tag at the head of the file.
  87176. *
  87177. * \{
  87178. */
  87179. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87180. * will try to skip any ID3v2 tag at the head of the file.
  87181. *
  87182. * \param filename The path to the FLAC file to read.
  87183. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87184. * FLAC__StreamMetadata is a simple structure with no
  87185. * memory allocation involved, you pass the address of
  87186. * an existing structure. It need not be initialized.
  87187. * \assert
  87188. * \code filename != NULL \endcode
  87189. * \code streaminfo != NULL \endcode
  87190. * \retval FLAC__bool
  87191. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87192. * \c false if there was a memory allocation error, a file decoder error,
  87193. * or the file contained no STREAMINFO block. (A memory allocation error
  87194. * is possible because this function must set up a file decoder.)
  87195. */
  87196. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87197. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87198. * function will try to skip any ID3v2 tag at the head of the file.
  87199. *
  87200. * \param filename The path to the FLAC file to read.
  87201. * \param tags The address where the returned pointer will be
  87202. * stored. The \a tags object must be deleted by
  87203. * the caller using FLAC__metadata_object_delete().
  87204. * \assert
  87205. * \code filename != NULL \endcode
  87206. * \code tags != NULL \endcode
  87207. * \retval FLAC__bool
  87208. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87209. * and \a *tags will be set to the address of the metadata structure.
  87210. * Returns \c false if there was a memory allocation error, a file
  87211. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87212. * \a *tags will be set to \c NULL.
  87213. */
  87214. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87215. /** Read the CUESHEET metadata block of the given FLAC file. This
  87216. * function will try to skip any ID3v2 tag at the head of the file.
  87217. *
  87218. * \param filename The path to the FLAC file to read.
  87219. * \param cuesheet The address where the returned pointer will be
  87220. * stored. The \a cuesheet object must be deleted by
  87221. * the caller using FLAC__metadata_object_delete().
  87222. * \assert
  87223. * \code filename != NULL \endcode
  87224. * \code cuesheet != NULL \endcode
  87225. * \retval FLAC__bool
  87226. * \c true if a valid CUESHEET block was read from \a filename,
  87227. * and \a *cuesheet will be set to the address of the metadata
  87228. * structure. Returns \c false if there was a memory allocation
  87229. * error, a file decoder error, or the file contained no CUESHEET
  87230. * block, and \a *cuesheet will be set to \c NULL.
  87231. */
  87232. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87233. /** Read a PICTURE metadata block of the given FLAC file. This
  87234. * function will try to skip any ID3v2 tag at the head of the file.
  87235. * Since there can be more than one PICTURE block in a file, this
  87236. * function takes a number of parameters that act as constraints to
  87237. * the search. The PICTURE block with the largest area matching all
  87238. * the constraints will be returned, or \a *picture will be set to
  87239. * \c NULL if there was no such block.
  87240. *
  87241. * \param filename The path to the FLAC file to read.
  87242. * \param picture The address where the returned pointer will be
  87243. * stored. The \a picture object must be deleted by
  87244. * the caller using FLAC__metadata_object_delete().
  87245. * \param type The desired picture type. Use \c -1 to mean
  87246. * "any type".
  87247. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87248. * string will be matched exactly. Use \c NULL to
  87249. * mean "any MIME type".
  87250. * \param description The desired description. The string will be
  87251. * matched exactly. Use \c NULL to mean "any
  87252. * description".
  87253. * \param max_width The maximum width in pixels desired. Use
  87254. * \c (unsigned)(-1) to mean "any width".
  87255. * \param max_height The maximum height in pixels desired. Use
  87256. * \c (unsigned)(-1) to mean "any height".
  87257. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87258. * Use \c (unsigned)(-1) to mean "any depth".
  87259. * \param max_colors The maximum number of colors desired. Use
  87260. * \c (unsigned)(-1) to mean "any number of colors".
  87261. * \assert
  87262. * \code filename != NULL \endcode
  87263. * \code picture != NULL \endcode
  87264. * \retval FLAC__bool
  87265. * \c true if a valid PICTURE block was read from \a filename,
  87266. * and \a *picture will be set to the address of the metadata
  87267. * structure. Returns \c false if there was a memory allocation
  87268. * error, a file decoder error, or the file contained no PICTURE
  87269. * block, and \a *picture will be set to \c NULL.
  87270. */
  87271. 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);
  87272. /* \} */
  87273. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87274. * \ingroup flac_metadata
  87275. *
  87276. * \brief
  87277. * The level 1 interface provides read-write access to FLAC file metadata and
  87278. * operates directly on the FLAC file.
  87279. *
  87280. * The general usage of this interface is:
  87281. *
  87282. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87283. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87284. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87285. * see if the file is writable, or only read access is allowed.
  87286. * - Use FLAC__metadata_simple_iterator_next() and
  87287. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87288. * This is does not read the actual blocks themselves.
  87289. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87290. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87291. * forward from the front of the file.
  87292. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87293. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87294. * the current iterator position. The returned object is yours to modify
  87295. * and free.
  87296. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87297. * back. You must have write permission to the original file. Make sure to
  87298. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87299. * below.
  87300. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87301. * Use the object creation functions from
  87302. * \link flac_metadata_object here \endlink to generate new objects.
  87303. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87304. * currently referred to by the iterator, or replace it with padding.
  87305. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87306. * finished.
  87307. *
  87308. * \note
  87309. * The FLAC file remains open the whole time between
  87310. * FLAC__metadata_simple_iterator_init() and
  87311. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87312. * the file during this time.
  87313. *
  87314. * \note
  87315. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87316. * FLAC__StreamMetadata objects. These are managed automatically.
  87317. *
  87318. * \note
  87319. * If any of the modification functions
  87320. * (FLAC__metadata_simple_iterator_set_block(),
  87321. * FLAC__metadata_simple_iterator_delete_block(),
  87322. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87323. * you should delete the iterator as it may no longer be valid.
  87324. *
  87325. * \{
  87326. */
  87327. struct FLAC__Metadata_SimpleIterator;
  87328. /** The opaque structure definition for the level 1 iterator type.
  87329. * See the
  87330. * \link flac_metadata_level1 metadata level 1 module \endlink
  87331. * for a detailed description.
  87332. */
  87333. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87334. /** Status type for FLAC__Metadata_SimpleIterator.
  87335. *
  87336. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87337. */
  87338. typedef enum {
  87339. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87340. /**< The iterator is in the normal OK state */
  87341. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87342. /**< The data passed into a function violated the function's usage criteria */
  87343. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87344. /**< The iterator could not open the target file */
  87345. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87346. /**< The iterator could not find the FLAC signature at the start of the file */
  87347. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87348. /**< The iterator tried to write to a file that was not writable */
  87349. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87350. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87351. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87352. /**< The iterator encountered an error while reading the FLAC file */
  87353. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87354. /**< The iterator encountered an error while seeking in the FLAC file */
  87355. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87356. /**< The iterator encountered an error while writing the FLAC file */
  87357. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87358. /**< The iterator encountered an error renaming the FLAC file */
  87359. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87360. /**< The iterator encountered an error removing the temporary file */
  87361. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87362. /**< Memory allocation failed */
  87363. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87364. /**< The caller violated an assertion or an unexpected error occurred */
  87365. } FLAC__Metadata_SimpleIteratorStatus;
  87366. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87367. *
  87368. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87369. * will give the string equivalent. The contents should not be modified.
  87370. */
  87371. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87372. /** Create a new iterator instance.
  87373. *
  87374. * \retval FLAC__Metadata_SimpleIterator*
  87375. * \c NULL if there was an error allocating memory, else the new instance.
  87376. */
  87377. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87378. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87379. *
  87380. * \param iterator A pointer to an existing iterator.
  87381. * \assert
  87382. * \code iterator != NULL \endcode
  87383. */
  87384. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87385. /** Get the current status of the iterator. Call this after a function
  87386. * returns \c false to get the reason for the error. Also resets the status
  87387. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87388. *
  87389. * \param iterator A pointer to an existing iterator.
  87390. * \assert
  87391. * \code iterator != NULL \endcode
  87392. * \retval FLAC__Metadata_SimpleIteratorStatus
  87393. * The current status of the iterator.
  87394. */
  87395. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87396. /** Initialize the iterator to point to the first metadata block in the
  87397. * given FLAC file.
  87398. *
  87399. * \param iterator A pointer to an existing iterator.
  87400. * \param filename The path to the FLAC file.
  87401. * \param read_only If \c true, the FLAC file will be opened
  87402. * in read-only mode; if \c false, the FLAC
  87403. * file will be opened for edit even if no
  87404. * edits are performed.
  87405. * \param preserve_file_stats If \c true, the owner and modification
  87406. * time will be preserved even if the FLAC
  87407. * file is written to.
  87408. * \assert
  87409. * \code iterator != NULL \endcode
  87410. * \code filename != NULL \endcode
  87411. * \retval FLAC__bool
  87412. * \c false if a memory allocation error occurs, the file can't be
  87413. * opened, or another error occurs, else \c true.
  87414. */
  87415. 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);
  87416. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87417. * FLAC__metadata_simple_iterator_set_block() and
  87418. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87419. *
  87420. * \param iterator A pointer to an existing iterator.
  87421. * \assert
  87422. * \code iterator != NULL \endcode
  87423. * \retval FLAC__bool
  87424. * See above.
  87425. */
  87426. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87427. /** Moves the iterator forward one metadata block, returning \c false if
  87428. * already at the end.
  87429. *
  87430. * \param iterator A pointer to an existing initialized iterator.
  87431. * \assert
  87432. * \code iterator != NULL \endcode
  87433. * \a iterator has been successfully initialized with
  87434. * FLAC__metadata_simple_iterator_init()
  87435. * \retval FLAC__bool
  87436. * \c false if already at the last metadata block of the chain, else
  87437. * \c true.
  87438. */
  87439. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87440. /** Moves the iterator backward one metadata block, returning \c false if
  87441. * already at the beginning.
  87442. *
  87443. * \param iterator A pointer to an existing initialized iterator.
  87444. * \assert
  87445. * \code iterator != NULL \endcode
  87446. * \a iterator has been successfully initialized with
  87447. * FLAC__metadata_simple_iterator_init()
  87448. * \retval FLAC__bool
  87449. * \c false if already at the first metadata block of the chain, else
  87450. * \c true.
  87451. */
  87452. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87453. /** Returns a flag telling if the current metadata block is the last.
  87454. *
  87455. * \param iterator A pointer to an existing initialized iterator.
  87456. * \assert
  87457. * \code iterator != NULL \endcode
  87458. * \a iterator has been successfully initialized with
  87459. * FLAC__metadata_simple_iterator_init()
  87460. * \retval FLAC__bool
  87461. * \c true if the current metadata block is the last in the file,
  87462. * else \c false.
  87463. */
  87464. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87465. /** Get the offset of the metadata block at the current position. This
  87466. * avoids reading the actual block data which can save time for large
  87467. * blocks.
  87468. *
  87469. * \param iterator A pointer to an existing initialized iterator.
  87470. * \assert
  87471. * \code iterator != NULL \endcode
  87472. * \a iterator has been successfully initialized with
  87473. * FLAC__metadata_simple_iterator_init()
  87474. * \retval off_t
  87475. * The offset of the metadata block at the current iterator position.
  87476. * This is the byte offset relative to the beginning of the file of
  87477. * the current metadata block's header.
  87478. */
  87479. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87480. /** Get the type of the metadata block at the current position. This
  87481. * avoids reading the actual block data which can save time for large
  87482. * blocks.
  87483. *
  87484. * \param iterator A pointer to an existing initialized iterator.
  87485. * \assert
  87486. * \code iterator != NULL \endcode
  87487. * \a iterator has been successfully initialized with
  87488. * FLAC__metadata_simple_iterator_init()
  87489. * \retval FLAC__MetadataType
  87490. * The type of the metadata block at the current iterator position.
  87491. */
  87492. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87493. /** Get the length of the metadata block at the current position. This
  87494. * avoids reading the actual block data which can save time for large
  87495. * blocks.
  87496. *
  87497. * \param iterator A pointer to an existing initialized iterator.
  87498. * \assert
  87499. * \code iterator != NULL \endcode
  87500. * \a iterator has been successfully initialized with
  87501. * FLAC__metadata_simple_iterator_init()
  87502. * \retval unsigned
  87503. * The length of the metadata block at the current iterator position.
  87504. * The is same length as that in the
  87505. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87506. * i.e. the length of the metadata body that follows the header.
  87507. */
  87508. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87509. /** Get the application ID of the \c APPLICATION block at the current
  87510. * position. This avoids reading the actual block data which can save
  87511. * time for large blocks.
  87512. *
  87513. * \param iterator A pointer to an existing initialized iterator.
  87514. * \param id A pointer to a buffer of at least \c 4 bytes where
  87515. * the ID will be stored.
  87516. * \assert
  87517. * \code iterator != NULL \endcode
  87518. * \code id != NULL \endcode
  87519. * \a iterator has been successfully initialized with
  87520. * FLAC__metadata_simple_iterator_init()
  87521. * \retval FLAC__bool
  87522. * \c true if the ID was successfully read, else \c false, in which
  87523. * case you should check FLAC__metadata_simple_iterator_status() to
  87524. * find out why. If the status is
  87525. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87526. * current metadata block is not an \c APPLICATION block. Otherwise
  87527. * if the status is
  87528. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87529. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87530. * occurred and the iterator can no longer be used.
  87531. */
  87532. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87533. /** Get the metadata block at the current position. You can modify the
  87534. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87535. * write it back to the FLAC file.
  87536. *
  87537. * You must call FLAC__metadata_object_delete() on the returned object
  87538. * when you are finished with it.
  87539. *
  87540. * \param iterator A pointer to an existing initialized iterator.
  87541. * \assert
  87542. * \code iterator != NULL \endcode
  87543. * \a iterator has been successfully initialized with
  87544. * FLAC__metadata_simple_iterator_init()
  87545. * \retval FLAC__StreamMetadata*
  87546. * The current metadata block, or \c NULL if there was a memory
  87547. * allocation error.
  87548. */
  87549. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87550. /** Write a block back to the FLAC file. This function tries to be
  87551. * as efficient as possible; how the block is actually written is
  87552. * shown by the following:
  87553. *
  87554. * Existing block is a STREAMINFO block and the new block is a
  87555. * STREAMINFO block: the new block is written in place. Make sure
  87556. * you know what you're doing when changing the values of a
  87557. * STREAMINFO block.
  87558. *
  87559. * Existing block is a STREAMINFO block and the new block is a
  87560. * not a STREAMINFO block: this is an error since the first block
  87561. * must be a STREAMINFO block. Returns \c false without altering the
  87562. * file.
  87563. *
  87564. * Existing block is not a STREAMINFO block and the new block is a
  87565. * STREAMINFO block: this is an error since there may be only one
  87566. * STREAMINFO block. Returns \c false without altering the file.
  87567. *
  87568. * Existing block and new block are the same length: the existing
  87569. * block will be replaced by the new block, written in place.
  87570. *
  87571. * Existing block is longer than new block: if use_padding is \c true,
  87572. * the existing block will be overwritten in place with the new
  87573. * block followed by a PADDING block, if possible, to make the total
  87574. * size the same as the existing block. Remember that a padding
  87575. * block requires at least four bytes so if the difference in size
  87576. * between the new block and existing block is less than that, the
  87577. * entire file will have to be rewritten, using the new block's
  87578. * exact size. If use_padding is \c false, the entire file will be
  87579. * rewritten, replacing the existing block by the new block.
  87580. *
  87581. * Existing block is shorter than new block: if use_padding is \c true,
  87582. * the function will try and expand the new block into the following
  87583. * PADDING block, if it exists and doing so won't shrink the PADDING
  87584. * block to less than 4 bytes. If there is no following PADDING
  87585. * block, or it will shrink to less than 4 bytes, or use_padding is
  87586. * \c false, the entire file is rewritten, replacing the existing block
  87587. * with the new block. Note that in this case any following PADDING
  87588. * block is preserved as is.
  87589. *
  87590. * After writing the block, the iterator will remain in the same
  87591. * place, i.e. pointing to the new block.
  87592. *
  87593. * \param iterator A pointer to an existing initialized iterator.
  87594. * \param block The block to set.
  87595. * \param use_padding See above.
  87596. * \assert
  87597. * \code iterator != NULL \endcode
  87598. * \a iterator has been successfully initialized with
  87599. * FLAC__metadata_simple_iterator_init()
  87600. * \code block != NULL \endcode
  87601. * \retval FLAC__bool
  87602. * \c true if successful, else \c false.
  87603. */
  87604. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87605. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87606. * except that instead of writing over an existing block, it appends
  87607. * a block after the existing block. \a use_padding is again used to
  87608. * tell the function to try an expand into following padding in an
  87609. * attempt to avoid rewriting the entire file.
  87610. *
  87611. * This function will fail and return \c false if given a STREAMINFO
  87612. * block.
  87613. *
  87614. * After writing the block, the iterator will be pointing to the
  87615. * new block.
  87616. *
  87617. * \param iterator A pointer to an existing initialized iterator.
  87618. * \param block The block to set.
  87619. * \param use_padding See above.
  87620. * \assert
  87621. * \code iterator != NULL \endcode
  87622. * \a iterator has been successfully initialized with
  87623. * FLAC__metadata_simple_iterator_init()
  87624. * \code block != NULL \endcode
  87625. * \retval FLAC__bool
  87626. * \c true if successful, else \c false.
  87627. */
  87628. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87629. /** Deletes the block at the current position. This will cause the
  87630. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87631. * in which case the block will be replaced by an equal-sized PADDING
  87632. * block. The iterator will be left pointing to the block before the
  87633. * one just deleted.
  87634. *
  87635. * You may not delete the STREAMINFO block.
  87636. *
  87637. * \param iterator A pointer to an existing initialized iterator.
  87638. * \param use_padding See above.
  87639. * \assert
  87640. * \code iterator != NULL \endcode
  87641. * \a iterator has been successfully initialized with
  87642. * FLAC__metadata_simple_iterator_init()
  87643. * \retval FLAC__bool
  87644. * \c true if successful, else \c false.
  87645. */
  87646. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87647. /* \} */
  87648. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87649. * \ingroup flac_metadata
  87650. *
  87651. * \brief
  87652. * The level 2 interface provides read-write access to FLAC file metadata;
  87653. * all metadata is read into memory, operated on in memory, and then written
  87654. * to file, which is more efficient than level 1 when editing multiple blocks.
  87655. *
  87656. * Currently Ogg FLAC is supported for read only, via
  87657. * FLAC__metadata_chain_read_ogg() but a subsequent
  87658. * FLAC__metadata_chain_write() will fail.
  87659. *
  87660. * The general usage of this interface is:
  87661. *
  87662. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87663. * linked list of FLAC metadata blocks.
  87664. * - Read all metadata into the the chain from a FLAC file using
  87665. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87666. * check the status.
  87667. * - Optionally, consolidate the padding using
  87668. * FLAC__metadata_chain_merge_padding() or
  87669. * FLAC__metadata_chain_sort_padding().
  87670. * - Create a new iterator using FLAC__metadata_iterator_new()
  87671. * - Initialize the iterator to point to the first element in the chain
  87672. * using FLAC__metadata_iterator_init()
  87673. * - Traverse the chain using FLAC__metadata_iterator_next and
  87674. * FLAC__metadata_iterator_prev().
  87675. * - Get a block for reading or modification using
  87676. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87677. * inside the chain is returned, so the block is yours to modify.
  87678. * Changes will be reflected in the FLAC file when you write the
  87679. * chain. You can also add and delete blocks (see functions below).
  87680. * - When done, write out the chain using FLAC__metadata_chain_write().
  87681. * Make sure to read the whole comment to the function below.
  87682. * - Delete the chain using FLAC__metadata_chain_delete().
  87683. *
  87684. * \note
  87685. * Even though the FLAC file is not open while the chain is being
  87686. * manipulated, you must not alter the file externally during
  87687. * this time. The chain assumes the FLAC file will not change
  87688. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87689. * and FLAC__metadata_chain_write().
  87690. *
  87691. * \note
  87692. * Do not modify the is_last, length, or type fields of returned
  87693. * FLAC__StreamMetadata objects. These are managed automatically.
  87694. *
  87695. * \note
  87696. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87697. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87698. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87699. * become owned by the chain and they will be deleted when the chain is
  87700. * deleted.
  87701. *
  87702. * \{
  87703. */
  87704. struct FLAC__Metadata_Chain;
  87705. /** The opaque structure definition for the level 2 chain type.
  87706. */
  87707. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87708. struct FLAC__Metadata_Iterator;
  87709. /** The opaque structure definition for the level 2 iterator type.
  87710. */
  87711. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87712. typedef enum {
  87713. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87714. /**< The chain is in the normal OK state */
  87715. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87716. /**< The data passed into a function violated the function's usage criteria */
  87717. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87718. /**< The chain could not open the target file */
  87719. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87720. /**< The chain could not find the FLAC signature at the start of the file */
  87721. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87722. /**< The chain tried to write to a file that was not writable */
  87723. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87724. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87725. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87726. /**< The chain encountered an error while reading the FLAC file */
  87727. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87728. /**< The chain encountered an error while seeking in the FLAC file */
  87729. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87730. /**< The chain encountered an error while writing the FLAC file */
  87731. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87732. /**< The chain encountered an error renaming the FLAC file */
  87733. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87734. /**< The chain encountered an error removing the temporary file */
  87735. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87736. /**< Memory allocation failed */
  87737. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87738. /**< The caller violated an assertion or an unexpected error occurred */
  87739. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87740. /**< One or more of the required callbacks was NULL */
  87741. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87742. /**< FLAC__metadata_chain_write() was called on a chain read by
  87743. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87744. * or
  87745. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87746. * was called on a chain read by
  87747. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87748. * Matching read/write methods must always be used. */
  87749. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87750. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87751. * chain write requires a tempfile; use
  87752. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87753. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87754. * called when the chain write does not require a tempfile; use
  87755. * FLAC__metadata_chain_write_with_callbacks() instead.
  87756. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87757. * before writing via callbacks. */
  87758. } FLAC__Metadata_ChainStatus;
  87759. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87760. *
  87761. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87762. * will give the string equivalent. The contents should not be modified.
  87763. */
  87764. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87765. /*********** FLAC__Metadata_Chain ***********/
  87766. /** Create a new chain instance.
  87767. *
  87768. * \retval FLAC__Metadata_Chain*
  87769. * \c NULL if there was an error allocating memory, else the new instance.
  87770. */
  87771. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87772. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87773. *
  87774. * \param chain A pointer to an existing chain.
  87775. * \assert
  87776. * \code chain != NULL \endcode
  87777. */
  87778. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87779. /** Get the current status of the chain. Call this after a function
  87780. * returns \c false to get the reason for the error. Also resets the
  87781. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87782. *
  87783. * \param chain A pointer to an existing chain.
  87784. * \assert
  87785. * \code chain != NULL \endcode
  87786. * \retval FLAC__Metadata_ChainStatus
  87787. * The current status of the chain.
  87788. */
  87789. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87790. /** Read all metadata from a FLAC file into the chain.
  87791. *
  87792. * \param chain A pointer to an existing chain.
  87793. * \param filename The path to the FLAC file to read.
  87794. * \assert
  87795. * \code chain != NULL \endcode
  87796. * \code filename != NULL \endcode
  87797. * \retval FLAC__bool
  87798. * \c true if a valid list of metadata blocks was read from
  87799. * \a filename, else \c false. On failure, check the status with
  87800. * FLAC__metadata_chain_status().
  87801. */
  87802. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87803. /** Read all metadata from an Ogg FLAC file into the chain.
  87804. *
  87805. * \note Ogg FLAC metadata data writing is not supported yet and
  87806. * FLAC__metadata_chain_write() will fail.
  87807. *
  87808. * \param chain A pointer to an existing chain.
  87809. * \param filename The path to the Ogg FLAC file to read.
  87810. * \assert
  87811. * \code chain != NULL \endcode
  87812. * \code filename != NULL \endcode
  87813. * \retval FLAC__bool
  87814. * \c true if a valid list of metadata blocks was read from
  87815. * \a filename, else \c false. On failure, check the status with
  87816. * FLAC__metadata_chain_status().
  87817. */
  87818. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87819. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87820. *
  87821. * The \a handle need only be open for reading, but must be seekable.
  87822. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87823. * for Windows).
  87824. *
  87825. * \param chain A pointer to an existing chain.
  87826. * \param handle The I/O handle of the FLAC stream to read. The
  87827. * handle will NOT be closed after the metadata is read;
  87828. * that is the duty of the caller.
  87829. * \param callbacks
  87830. * A set of callbacks to use for I/O. The mandatory
  87831. * callbacks are \a read, \a seek, and \a tell.
  87832. * \assert
  87833. * \code chain != NULL \endcode
  87834. * \retval FLAC__bool
  87835. * \c true if a valid list of metadata blocks was read from
  87836. * \a handle, else \c false. On failure, check the status with
  87837. * FLAC__metadata_chain_status().
  87838. */
  87839. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87840. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87841. *
  87842. * The \a handle need only be open for reading, but must be seekable.
  87843. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87844. * for Windows).
  87845. *
  87846. * \note Ogg FLAC metadata data writing is not supported yet and
  87847. * FLAC__metadata_chain_write() will fail.
  87848. *
  87849. * \param chain A pointer to an existing chain.
  87850. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87851. * handle will NOT be closed after the metadata is read;
  87852. * that is the duty of the caller.
  87853. * \param callbacks
  87854. * A set of callbacks to use for I/O. The mandatory
  87855. * callbacks are \a read, \a seek, and \a tell.
  87856. * \assert
  87857. * \code chain != NULL \endcode
  87858. * \retval FLAC__bool
  87859. * \c true if a valid list of metadata blocks was read from
  87860. * \a handle, else \c false. On failure, check the status with
  87861. * FLAC__metadata_chain_status().
  87862. */
  87863. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87864. /** Checks if writing the given chain would require the use of a
  87865. * temporary file, or if it could be written in place.
  87866. *
  87867. * Under certain conditions, padding can be utilized so that writing
  87868. * edited metadata back to the FLAC file does not require rewriting the
  87869. * entire file. If rewriting is required, then a temporary workfile is
  87870. * required. When writing metadata using callbacks, you must check
  87871. * this function to know whether to call
  87872. * FLAC__metadata_chain_write_with_callbacks() or
  87873. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87874. * writing with FLAC__metadata_chain_write(), the temporary file is
  87875. * handled internally.
  87876. *
  87877. * \param chain A pointer to an existing chain.
  87878. * \param use_padding
  87879. * Whether or not padding will be allowed to be used
  87880. * during the write. The value of \a use_padding given
  87881. * here must match the value later passed to
  87882. * FLAC__metadata_chain_write_with_callbacks() or
  87883. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87884. * \assert
  87885. * \code chain != NULL \endcode
  87886. * \retval FLAC__bool
  87887. * \c true if writing the current chain would require a tempfile, or
  87888. * \c false if metadata can be written in place.
  87889. */
  87890. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87891. /** Write all metadata out to the FLAC file. This function tries to be as
  87892. * efficient as possible; how the metadata is actually written is shown by
  87893. * the following:
  87894. *
  87895. * If the current chain is the same size as the existing metadata, the new
  87896. * data is written in place.
  87897. *
  87898. * If the current chain is longer than the existing metadata, and
  87899. * \a use_padding is \c true, and the last block is a PADDING block of
  87900. * sufficient length, the function will truncate the final padding block
  87901. * so that the overall size of the metadata is the same as the existing
  87902. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87903. * the above conditions are met, the entire FLAC file must be rewritten.
  87904. * If you want to use padding this way it is a good idea to call
  87905. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87906. * amount of padding to work with, unless you need to preserve ordering
  87907. * of the PADDING blocks for some reason.
  87908. *
  87909. * If the current chain is shorter than the existing metadata, and
  87910. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87911. * is extended to make the overall size the same as the existing data. If
  87912. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87913. * PADDING block is added to the end of the new data to make it the same
  87914. * size as the existing data (if possible, see the note to
  87915. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87916. * and the new data is written in place. If none of the above apply or
  87917. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87918. *
  87919. * If \a preserve_file_stats is \c true, the owner and modification time will
  87920. * be preserved even if the FLAC file is written.
  87921. *
  87922. * For this write function to be used, the chain must have been read with
  87923. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87924. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87925. *
  87926. * \param chain A pointer to an existing chain.
  87927. * \param use_padding See above.
  87928. * \param preserve_file_stats See above.
  87929. * \assert
  87930. * \code chain != NULL \endcode
  87931. * \retval FLAC__bool
  87932. * \c true if the write succeeded, else \c false. On failure,
  87933. * check the status with FLAC__metadata_chain_status().
  87934. */
  87935. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87936. /** Write all metadata out to a FLAC stream via callbacks.
  87937. *
  87938. * (See FLAC__metadata_chain_write() for the details on how padding is
  87939. * used to write metadata in place if possible.)
  87940. *
  87941. * The \a handle must be open for updating and be seekable. The
  87942. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87943. * for Windows).
  87944. *
  87945. * For this write function to be used, the chain must have been read with
  87946. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87947. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87948. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87949. * \c false.
  87950. *
  87951. * \param chain A pointer to an existing chain.
  87952. * \param use_padding See FLAC__metadata_chain_write()
  87953. * \param handle The I/O handle of the FLAC stream to write. The
  87954. * handle will NOT be closed after the metadata is
  87955. * written; that is the duty of the caller.
  87956. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87957. * callbacks are \a write and \a seek.
  87958. * \assert
  87959. * \code chain != NULL \endcode
  87960. * \retval FLAC__bool
  87961. * \c true if the write succeeded, else \c false. On failure,
  87962. * check the status with FLAC__metadata_chain_status().
  87963. */
  87964. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87965. /** Write all metadata out to a FLAC stream via callbacks.
  87966. *
  87967. * (See FLAC__metadata_chain_write() for the details on how padding is
  87968. * used to write metadata in place if possible.)
  87969. *
  87970. * This version of the write-with-callbacks function must be used when
  87971. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87972. * this function, you must supply an I/O handle corresponding to the
  87973. * FLAC file to edit, and a temporary handle to which the new FLAC
  87974. * file will be written. It is the caller's job to move this temporary
  87975. * FLAC file on top of the original FLAC file to complete the metadata
  87976. * edit.
  87977. *
  87978. * The \a handle must be open for reading and be seekable. The
  87979. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87980. * for Windows).
  87981. *
  87982. * The \a temp_handle must be open for writing. The
  87983. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87984. * for Windows). It should be an empty stream, or at least positioned
  87985. * at the start-of-file (in which case it is the caller's duty to
  87986. * truncate it on return).
  87987. *
  87988. * For this write function to be used, the chain must have been read with
  87989. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87990. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87991. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87992. * \c true.
  87993. *
  87994. * \param chain A pointer to an existing chain.
  87995. * \param use_padding See FLAC__metadata_chain_write()
  87996. * \param handle The I/O handle of the original FLAC stream to read.
  87997. * The handle will NOT be closed after the metadata is
  87998. * written; that is the duty of the caller.
  87999. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88000. * The mandatory callbacks are \a read, \a seek, and
  88001. * \a eof.
  88002. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88003. * handle will NOT be closed after the metadata is
  88004. * written; that is the duty of the caller.
  88005. * \param temp_callbacks
  88006. * A set of callbacks to use for I/O on temp_handle.
  88007. * The only mandatory callback is \a write.
  88008. * \assert
  88009. * \code chain != NULL \endcode
  88010. * \retval FLAC__bool
  88011. * \c true if the write succeeded, else \c false. On failure,
  88012. * check the status with FLAC__metadata_chain_status().
  88013. */
  88014. 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);
  88015. /** Merge adjacent PADDING blocks into a single block.
  88016. *
  88017. * \note This function does not write to the FLAC file, it only
  88018. * modifies the chain.
  88019. *
  88020. * \warning Any iterator on the current chain will become invalid after this
  88021. * call. You should delete the iterator and get a new one.
  88022. *
  88023. * \param chain A pointer to an existing chain.
  88024. * \assert
  88025. * \code chain != NULL \endcode
  88026. */
  88027. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88028. /** This function will move all PADDING blocks to the end on the metadata,
  88029. * then merge them into a single block.
  88030. *
  88031. * \note This function does not write to the FLAC file, it only
  88032. * modifies the chain.
  88033. *
  88034. * \warning Any iterator on the current chain will become invalid after this
  88035. * call. You should delete the iterator and get a new one.
  88036. *
  88037. * \param chain A pointer to an existing chain.
  88038. * \assert
  88039. * \code chain != NULL \endcode
  88040. */
  88041. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88042. /*********** FLAC__Metadata_Iterator ***********/
  88043. /** Create a new iterator instance.
  88044. *
  88045. * \retval FLAC__Metadata_Iterator*
  88046. * \c NULL if there was an error allocating memory, else the new instance.
  88047. */
  88048. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88049. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88050. *
  88051. * \param iterator A pointer to an existing iterator.
  88052. * \assert
  88053. * \code iterator != NULL \endcode
  88054. */
  88055. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88056. /** Initialize the iterator to point to the first metadata block in the
  88057. * given chain.
  88058. *
  88059. * \param iterator A pointer to an existing iterator.
  88060. * \param chain A pointer to an existing and initialized (read) chain.
  88061. * \assert
  88062. * \code iterator != NULL \endcode
  88063. * \code chain != NULL \endcode
  88064. */
  88065. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88066. /** Moves the iterator forward one metadata block, returning \c false if
  88067. * already at the end.
  88068. *
  88069. * \param iterator A pointer to an existing initialized iterator.
  88070. * \assert
  88071. * \code iterator != NULL \endcode
  88072. * \a iterator has been successfully initialized with
  88073. * FLAC__metadata_iterator_init()
  88074. * \retval FLAC__bool
  88075. * \c false if already at the last metadata block of the chain, else
  88076. * \c true.
  88077. */
  88078. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88079. /** Moves the iterator backward one metadata block, returning \c false if
  88080. * already at the beginning.
  88081. *
  88082. * \param iterator A pointer to an existing initialized iterator.
  88083. * \assert
  88084. * \code iterator != NULL \endcode
  88085. * \a iterator has been successfully initialized with
  88086. * FLAC__metadata_iterator_init()
  88087. * \retval FLAC__bool
  88088. * \c false if already at the first metadata block of the chain, else
  88089. * \c true.
  88090. */
  88091. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88092. /** Get the type of the metadata block at the current position.
  88093. *
  88094. * \param iterator A pointer to an existing initialized iterator.
  88095. * \assert
  88096. * \code iterator != NULL \endcode
  88097. * \a iterator has been successfully initialized with
  88098. * FLAC__metadata_iterator_init()
  88099. * \retval FLAC__MetadataType
  88100. * The type of the metadata block at the current iterator position.
  88101. */
  88102. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88103. /** Get the metadata block at the current position. You can modify
  88104. * the block in place but must write the chain before the changes
  88105. * are reflected to the FLAC file. You do not need to call
  88106. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88107. * the pointer returned by FLAC__metadata_iterator_get_block()
  88108. * points directly into the chain.
  88109. *
  88110. * \warning
  88111. * Do not call FLAC__metadata_object_delete() on the returned object;
  88112. * to delete a block use FLAC__metadata_iterator_delete_block().
  88113. *
  88114. * \param iterator A pointer to an existing initialized iterator.
  88115. * \assert
  88116. * \code iterator != NULL \endcode
  88117. * \a iterator has been successfully initialized with
  88118. * FLAC__metadata_iterator_init()
  88119. * \retval FLAC__StreamMetadata*
  88120. * The current metadata block.
  88121. */
  88122. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88123. /** Set the metadata block at the current position, replacing the existing
  88124. * block. The new block passed in becomes owned by the chain and it will be
  88125. * deleted when the chain is deleted.
  88126. *
  88127. * \param iterator A pointer to an existing initialized iterator.
  88128. * \param block A pointer to a metadata block.
  88129. * \assert
  88130. * \code iterator != NULL \endcode
  88131. * \a iterator has been successfully initialized with
  88132. * FLAC__metadata_iterator_init()
  88133. * \code block != NULL \endcode
  88134. * \retval FLAC__bool
  88135. * \c false if the conditions in the above description are not met, or
  88136. * a memory allocation error occurs, otherwise \c true.
  88137. */
  88138. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88139. /** Removes the current block from the chain. If \a replace_with_padding is
  88140. * \c true, the block will instead be replaced with a padding block of equal
  88141. * size. You can not delete the STREAMINFO block. The iterator will be
  88142. * left pointing to the block before the one just "deleted", even if
  88143. * \a replace_with_padding is \c true.
  88144. *
  88145. * \param iterator A pointer to an existing initialized iterator.
  88146. * \param replace_with_padding See above.
  88147. * \assert
  88148. * \code iterator != NULL \endcode
  88149. * \a iterator has been successfully initialized with
  88150. * FLAC__metadata_iterator_init()
  88151. * \retval FLAC__bool
  88152. * \c false if the conditions in the above description are not met,
  88153. * otherwise \c true.
  88154. */
  88155. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88156. /** Insert a new block before the current block. You cannot insert a block
  88157. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88158. * as there can be only one, the one that already exists at the head when you
  88159. * read in a chain. The chain takes ownership of the new block and it will be
  88160. * deleted when the chain is deleted. The iterator will be left pointing to
  88161. * the new block.
  88162. *
  88163. * \param iterator A pointer to an existing initialized iterator.
  88164. * \param block A pointer to a metadata block to insert.
  88165. * \assert
  88166. * \code iterator != NULL \endcode
  88167. * \a iterator has been successfully initialized with
  88168. * FLAC__metadata_iterator_init()
  88169. * \retval FLAC__bool
  88170. * \c false if the conditions in the above description are not met, or
  88171. * a memory allocation error occurs, otherwise \c true.
  88172. */
  88173. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88174. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88175. * block as there can be only one, the one that already exists at the head when
  88176. * you read in a chain. The chain takes ownership of the new block and it will
  88177. * be deleted when the chain is deleted. The iterator will be left pointing to
  88178. * the new block.
  88179. *
  88180. * \param iterator A pointer to an existing initialized iterator.
  88181. * \param block A pointer to a metadata block to insert.
  88182. * \assert
  88183. * \code iterator != NULL \endcode
  88184. * \a iterator has been successfully initialized with
  88185. * FLAC__metadata_iterator_init()
  88186. * \retval FLAC__bool
  88187. * \c false if the conditions in the above description are not met, or
  88188. * a memory allocation error occurs, otherwise \c true.
  88189. */
  88190. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88191. /* \} */
  88192. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88193. * \ingroup flac_metadata
  88194. *
  88195. * \brief
  88196. * This module contains methods for manipulating FLAC metadata objects.
  88197. *
  88198. * Since many are variable length we have to be careful about the memory
  88199. * management. We decree that all pointers to data in the object are
  88200. * owned by the object and memory-managed by the object.
  88201. *
  88202. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88203. * functions to create all instances. When using the
  88204. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88205. * \a copy to \c true to have the function make it's own copy of the data, or
  88206. * to \c false to give the object ownership of your data. In the latter case
  88207. * your pointer must be freeable by free() and will be free()d when the object
  88208. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88209. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88210. * the length argument is 0 and the \a copy argument is \c false.
  88211. *
  88212. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88213. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88214. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88215. * case of a memory allocation error.
  88216. *
  88217. * We don't have the convenience of C++ here, so note that the library relies
  88218. * on you to keep the types straight. In other words, if you pass, for
  88219. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88220. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88221. * failure.
  88222. *
  88223. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88224. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88225. * toward the length or stored in the stream, but it can make working with plain
  88226. * comments (those that don't contain embedded-NULs in the value) easier.
  88227. * Entries passed into these functions have trailing NULs added if missing, and
  88228. * returned entries are guaranteed to have a trailing NUL.
  88229. *
  88230. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88231. * comment entry/name/value will first validate that it complies with the Vorbis
  88232. * comment specification and return false if it does not.
  88233. *
  88234. * There is no need to recalculate the length field on metadata blocks you
  88235. * have modified. They will be calculated automatically before they are
  88236. * written back to a file.
  88237. *
  88238. * \{
  88239. */
  88240. /** Create a new metadata object instance of the given type.
  88241. *
  88242. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88243. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88244. * the vendor string set (but zero comments).
  88245. *
  88246. * Do not pass in a value greater than or equal to
  88247. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88248. * doing.
  88249. *
  88250. * \param type Type of object to create
  88251. * \retval FLAC__StreamMetadata*
  88252. * \c NULL if there was an error allocating memory or the type code is
  88253. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88254. */
  88255. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88256. /** Create a copy of an existing metadata object.
  88257. *
  88258. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88259. * object is also copied. The caller takes ownership of the new block and
  88260. * is responsible for freeing it with FLAC__metadata_object_delete().
  88261. *
  88262. * \param object Pointer to object to copy.
  88263. * \assert
  88264. * \code object != NULL \endcode
  88265. * \retval FLAC__StreamMetadata*
  88266. * \c NULL if there was an error allocating memory, else the new instance.
  88267. */
  88268. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88269. /** Free a metadata object. Deletes the object pointed to by \a object.
  88270. *
  88271. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88272. * object is also deleted.
  88273. *
  88274. * \param object A pointer to an existing object.
  88275. * \assert
  88276. * \code object != NULL \endcode
  88277. */
  88278. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88279. /** Compares two metadata objects.
  88280. *
  88281. * The compare is "deep", i.e. dynamically allocated data within the
  88282. * object is also compared.
  88283. *
  88284. * \param block1 A pointer to an existing object.
  88285. * \param block2 A pointer to an existing object.
  88286. * \assert
  88287. * \code block1 != NULL \endcode
  88288. * \code block2 != NULL \endcode
  88289. * \retval FLAC__bool
  88290. * \c true if objects are identical, else \c false.
  88291. */
  88292. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88293. /** Sets the application data of an APPLICATION block.
  88294. *
  88295. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88296. * takes ownership of the pointer. The existing data will be freed if this
  88297. * function is successful, otherwise the original data will remain if \a copy
  88298. * is \c true and malloc() fails.
  88299. *
  88300. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88301. *
  88302. * \param object A pointer to an existing APPLICATION object.
  88303. * \param data A pointer to the data to set.
  88304. * \param length The length of \a data in bytes.
  88305. * \param copy See above.
  88306. * \assert
  88307. * \code object != NULL \endcode
  88308. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88309. * \code (data != NULL && length > 0) ||
  88310. * (data == NULL && length == 0 && copy == false) \endcode
  88311. * \retval FLAC__bool
  88312. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88313. */
  88314. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88315. /** Resize the seekpoint array.
  88316. *
  88317. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88318. * points will be added to the end.
  88319. *
  88320. * \param object A pointer to an existing SEEKTABLE object.
  88321. * \param new_num_points The desired length of the array; may be \c 0.
  88322. * \assert
  88323. * \code object != NULL \endcode
  88324. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88325. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88326. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88327. * \retval FLAC__bool
  88328. * \c false if memory allocation error, else \c true.
  88329. */
  88330. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88331. /** Set a seekpoint in a seektable.
  88332. *
  88333. * \param object A pointer to an existing SEEKTABLE object.
  88334. * \param point_num Index into seekpoint array to set.
  88335. * \param point The point to set.
  88336. * \assert
  88337. * \code object != NULL \endcode
  88338. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88339. * \code object->data.seek_table.num_points > point_num \endcode
  88340. */
  88341. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88342. /** Insert a seekpoint into a seektable.
  88343. *
  88344. * \param object A pointer to an existing SEEKTABLE object.
  88345. * \param point_num Index into seekpoint array to set.
  88346. * \param point The point to set.
  88347. * \assert
  88348. * \code object != NULL \endcode
  88349. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88350. * \code object->data.seek_table.num_points >= point_num \endcode
  88351. * \retval FLAC__bool
  88352. * \c false if memory allocation error, else \c true.
  88353. */
  88354. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88355. /** Delete a seekpoint from a seektable.
  88356. *
  88357. * \param object A pointer to an existing SEEKTABLE object.
  88358. * \param point_num Index into seekpoint array to set.
  88359. * \assert
  88360. * \code object != NULL \endcode
  88361. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88362. * \code object->data.seek_table.num_points > point_num \endcode
  88363. * \retval FLAC__bool
  88364. * \c false if memory allocation error, else \c true.
  88365. */
  88366. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88367. /** Check a seektable to see if it conforms to the FLAC specification.
  88368. * See the format specification for limits on the contents of the
  88369. * seektable.
  88370. *
  88371. * \param object A pointer to an existing SEEKTABLE object.
  88372. * \assert
  88373. * \code object != NULL \endcode
  88374. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88375. * \retval FLAC__bool
  88376. * \c false if seek table is illegal, else \c true.
  88377. */
  88378. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88379. /** Append a number of placeholder points to the end of a seek table.
  88380. *
  88381. * \note
  88382. * As with the other ..._seektable_template_... functions, you should
  88383. * call FLAC__metadata_object_seektable_template_sort() when finished
  88384. * to make the seek table legal.
  88385. *
  88386. * \param object A pointer to an existing SEEKTABLE object.
  88387. * \param num The number of placeholder points to append.
  88388. * \assert
  88389. * \code object != NULL \endcode
  88390. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88391. * \retval FLAC__bool
  88392. * \c false if memory allocation fails, else \c true.
  88393. */
  88394. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88395. /** Append a specific seek point template to the end of a seek table.
  88396. *
  88397. * \note
  88398. * As with the other ..._seektable_template_... functions, you should
  88399. * call FLAC__metadata_object_seektable_template_sort() when finished
  88400. * to make the seek table legal.
  88401. *
  88402. * \param object A pointer to an existing SEEKTABLE object.
  88403. * \param sample_number The sample number of the seek point template.
  88404. * \assert
  88405. * \code object != NULL \endcode
  88406. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88407. * \retval FLAC__bool
  88408. * \c false if memory allocation fails, else \c true.
  88409. */
  88410. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88411. /** Append specific seek point templates to the end of a seek table.
  88412. *
  88413. * \note
  88414. * As with the other ..._seektable_template_... functions, you should
  88415. * call FLAC__metadata_object_seektable_template_sort() when finished
  88416. * to make the seek table legal.
  88417. *
  88418. * \param object A pointer to an existing SEEKTABLE object.
  88419. * \param sample_numbers An array of sample numbers for the seek points.
  88420. * \param num The number of seek point templates to append.
  88421. * \assert
  88422. * \code object != NULL \endcode
  88423. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88424. * \retval FLAC__bool
  88425. * \c false if memory allocation fails, else \c true.
  88426. */
  88427. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88428. /** Append a set of evenly-spaced seek point templates to the end of a
  88429. * seek table.
  88430. *
  88431. * \note
  88432. * As with the other ..._seektable_template_... functions, you should
  88433. * call FLAC__metadata_object_seektable_template_sort() when finished
  88434. * to make the seek table legal.
  88435. *
  88436. * \param object A pointer to an existing SEEKTABLE object.
  88437. * \param num The number of placeholder points to append.
  88438. * \param total_samples The total number of samples to be encoded;
  88439. * the seekpoints will be spaced approximately
  88440. * \a total_samples / \a num samples apart.
  88441. * \assert
  88442. * \code object != NULL \endcode
  88443. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88444. * \code total_samples > 0 \endcode
  88445. * \retval FLAC__bool
  88446. * \c false if memory allocation fails, else \c true.
  88447. */
  88448. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88449. /** Append a set of evenly-spaced seek point templates to the end of a
  88450. * seek table.
  88451. *
  88452. * \note
  88453. * As with the other ..._seektable_template_... functions, you should
  88454. * call FLAC__metadata_object_seektable_template_sort() when finished
  88455. * to make the seek table legal.
  88456. *
  88457. * \param object A pointer to an existing SEEKTABLE object.
  88458. * \param samples The number of samples apart to space the placeholder
  88459. * points. The first point will be at sample \c 0, the
  88460. * second at sample \a samples, then 2*\a samples, and
  88461. * so on. As long as \a samples and \a total_samples
  88462. * are greater than \c 0, there will always be at least
  88463. * one seekpoint at sample \c 0.
  88464. * \param total_samples The total number of samples to be encoded;
  88465. * the seekpoints will be spaced
  88466. * \a samples samples apart.
  88467. * \assert
  88468. * \code object != NULL \endcode
  88469. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88470. * \code samples > 0 \endcode
  88471. * \code total_samples > 0 \endcode
  88472. * \retval FLAC__bool
  88473. * \c false if memory allocation fails, else \c true.
  88474. */
  88475. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88476. /** Sort a seek table's seek points according to the format specification,
  88477. * removing duplicates.
  88478. *
  88479. * \param object A pointer to a seek table to be sorted.
  88480. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88481. * If \c true, duplicates are deleted and the seek table is
  88482. * shrunk appropriately; the number of placeholder points
  88483. * present in the seek table will be the same after the call
  88484. * as before.
  88485. * \assert
  88486. * \code object != NULL \endcode
  88487. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88488. * \retval FLAC__bool
  88489. * \c false if realloc() fails, else \c true.
  88490. */
  88491. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88492. /** Sets the vendor string in a VORBIS_COMMENT block.
  88493. *
  88494. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88495. * one already.
  88496. *
  88497. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88498. * takes ownership of the \c entry.entry pointer.
  88499. *
  88500. * \note If this function returns \c false, the caller still owns the
  88501. * pointer.
  88502. *
  88503. * \param object A pointer to an existing VORBIS_COMMENT object.
  88504. * \param entry The entry to set the vendor string to.
  88505. * \param copy See above.
  88506. * \assert
  88507. * \code object != NULL \endcode
  88508. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88509. * \code (entry.entry != NULL && entry.length > 0) ||
  88510. * (entry.entry == NULL && entry.length == 0) \endcode
  88511. * \retval FLAC__bool
  88512. * \c false if memory allocation fails or \a entry does not comply with the
  88513. * Vorbis comment specification, else \c true.
  88514. */
  88515. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88516. /** Resize the comment array.
  88517. *
  88518. * If the size shrinks, elements will truncated; if it grows, new empty
  88519. * fields will be added to the end.
  88520. *
  88521. * \param object A pointer to an existing VORBIS_COMMENT object.
  88522. * \param new_num_comments The desired length of the array; may be \c 0.
  88523. * \assert
  88524. * \code object != NULL \endcode
  88525. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88526. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88527. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88528. * \retval FLAC__bool
  88529. * \c false if memory allocation fails, else \c true.
  88530. */
  88531. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88532. /** Sets a comment in a VORBIS_COMMENT block.
  88533. *
  88534. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88535. * one already.
  88536. *
  88537. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88538. * takes ownership of the \c entry.entry pointer.
  88539. *
  88540. * \note If this function returns \c false, the caller still owns the
  88541. * pointer.
  88542. *
  88543. * \param object A pointer to an existing VORBIS_COMMENT object.
  88544. * \param comment_num Index into comment array to set.
  88545. * \param entry The entry to set the comment to.
  88546. * \param copy See above.
  88547. * \assert
  88548. * \code object != NULL \endcode
  88549. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88550. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88551. * \code (entry.entry != NULL && entry.length > 0) ||
  88552. * (entry.entry == NULL && entry.length == 0) \endcode
  88553. * \retval FLAC__bool
  88554. * \c false if memory allocation fails or \a entry does not comply with the
  88555. * Vorbis comment specification, else \c true.
  88556. */
  88557. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88558. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88559. *
  88560. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88561. * one already.
  88562. *
  88563. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88564. * takes ownership of the \c entry.entry pointer.
  88565. *
  88566. * \note If this function returns \c false, the caller still owns the
  88567. * pointer.
  88568. *
  88569. * \param object A pointer to an existing VORBIS_COMMENT object.
  88570. * \param comment_num The index at which to insert the comment. The comments
  88571. * at and after \a comment_num move right one position.
  88572. * To append a comment to the end, set \a comment_num to
  88573. * \c object->data.vorbis_comment.num_comments .
  88574. * \param entry The comment to insert.
  88575. * \param copy See above.
  88576. * \assert
  88577. * \code object != NULL \endcode
  88578. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88579. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88580. * \code (entry.entry != NULL && entry.length > 0) ||
  88581. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88582. * \retval FLAC__bool
  88583. * \c false if memory allocation fails or \a entry does not comply with the
  88584. * Vorbis comment specification, else \c true.
  88585. */
  88586. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88587. /** Appends a comment to a VORBIS_COMMENT block.
  88588. *
  88589. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88590. * one already.
  88591. *
  88592. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88593. * takes ownership of the \c entry.entry pointer.
  88594. *
  88595. * \note If this function returns \c false, the caller still owns the
  88596. * pointer.
  88597. *
  88598. * \param object A pointer to an existing VORBIS_COMMENT object.
  88599. * \param entry The comment to insert.
  88600. * \param copy See above.
  88601. * \assert
  88602. * \code object != NULL \endcode
  88603. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88604. * \code (entry.entry != NULL && entry.length > 0) ||
  88605. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88606. * \retval FLAC__bool
  88607. * \c false if memory allocation fails or \a entry does not comply with the
  88608. * Vorbis comment specification, else \c true.
  88609. */
  88610. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88611. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88612. *
  88613. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88614. * one already.
  88615. *
  88616. * Depending on the the value of \a all, either all or just the first comment
  88617. * whose field name(s) match the given entry's name will be replaced by the
  88618. * given entry. If no comments match, \a entry will simply be appended.
  88619. *
  88620. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88621. * takes ownership of the \c entry.entry pointer.
  88622. *
  88623. * \note If this function returns \c false, the caller still owns the
  88624. * pointer.
  88625. *
  88626. * \param object A pointer to an existing VORBIS_COMMENT object.
  88627. * \param entry The comment to insert.
  88628. * \param all If \c true, all comments whose field name matches
  88629. * \a entry's field name will be removed, and \a entry will
  88630. * be inserted at the position of the first matching
  88631. * comment. If \c false, only the first comment whose
  88632. * field name matches \a entry's field name will be
  88633. * replaced with \a entry.
  88634. * \param copy See above.
  88635. * \assert
  88636. * \code object != NULL \endcode
  88637. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88638. * \code (entry.entry != NULL && entry.length > 0) ||
  88639. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88640. * \retval FLAC__bool
  88641. * \c false if memory allocation fails or \a entry does not comply with the
  88642. * Vorbis comment specification, else \c true.
  88643. */
  88644. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88645. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88646. *
  88647. * \param object A pointer to an existing VORBIS_COMMENT object.
  88648. * \param comment_num The index of the comment to delete.
  88649. * \assert
  88650. * \code object != NULL \endcode
  88651. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88652. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88653. * \retval FLAC__bool
  88654. * \c false if realloc() fails, else \c true.
  88655. */
  88656. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88657. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88658. *
  88659. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88660. * memory and shall be owned by the caller. For convenience the entry will
  88661. * have a terminating NUL.
  88662. *
  88663. * \param entry A pointer to a Vorbis comment entry. The entry's
  88664. * \c entry pointer should not point to allocated
  88665. * memory as it will be overwritten.
  88666. * \param field_name The field name in ASCII, \c NUL terminated.
  88667. * \param field_value The field value in UTF-8, \c NUL terminated.
  88668. * \assert
  88669. * \code entry != NULL \endcode
  88670. * \code field_name != NULL \endcode
  88671. * \code field_value != NULL \endcode
  88672. * \retval FLAC__bool
  88673. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88674. * not comply with the Vorbis comment specification, else \c true.
  88675. */
  88676. 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);
  88677. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88678. *
  88679. * The returned pointers to name and value will be allocated by malloc()
  88680. * and shall be owned by the caller.
  88681. *
  88682. * \param entry An existing Vorbis comment entry.
  88683. * \param field_name The address of where the returned pointer to the
  88684. * field name will be stored.
  88685. * \param field_value The address of where the returned pointer to the
  88686. * field value will be stored.
  88687. * \assert
  88688. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88689. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88690. * \code field_name != NULL \endcode
  88691. * \code field_value != NULL \endcode
  88692. * \retval FLAC__bool
  88693. * \c false if memory allocation fails or \a entry does not comply with the
  88694. * Vorbis comment specification, else \c true.
  88695. */
  88696. 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);
  88697. /** Check if the given Vorbis comment entry's field name matches the given
  88698. * field name.
  88699. *
  88700. * \param entry An existing Vorbis comment entry.
  88701. * \param field_name The field name to check.
  88702. * \param field_name_length The length of \a field_name, not including the
  88703. * terminating \c NUL.
  88704. * \assert
  88705. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88706. * \retval FLAC__bool
  88707. * \c true if the field names match, else \c false
  88708. */
  88709. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88710. /** Find a Vorbis comment with the given field name.
  88711. *
  88712. * The search begins at entry number \a offset; use an offset of 0 to
  88713. * search from the beginning of the comment array.
  88714. *
  88715. * \param object A pointer to an existing VORBIS_COMMENT object.
  88716. * \param offset The offset into the comment array from where to start
  88717. * the search.
  88718. * \param field_name The field name of the comment to find.
  88719. * \assert
  88720. * \code object != NULL \endcode
  88721. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88722. * \code field_name != NULL \endcode
  88723. * \retval int
  88724. * The offset in the comment array of the first comment whose field
  88725. * name matches \a field_name, or \c -1 if no match was found.
  88726. */
  88727. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88728. /** Remove first Vorbis comment matching the given field name.
  88729. *
  88730. * \param object A pointer to an existing VORBIS_COMMENT object.
  88731. * \param field_name The field name of comment to delete.
  88732. * \assert
  88733. * \code object != NULL \endcode
  88734. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88735. * \retval int
  88736. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88737. * \c 1 for one matching entry deleted.
  88738. */
  88739. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88740. /** Remove all Vorbis comments matching the given field name.
  88741. *
  88742. * \param object A pointer to an existing VORBIS_COMMENT object.
  88743. * \param field_name The field name of comments to delete.
  88744. * \assert
  88745. * \code object != NULL \endcode
  88746. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88747. * \retval int
  88748. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88749. * else the number of matching entries deleted.
  88750. */
  88751. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88752. /** Create a new CUESHEET track instance.
  88753. *
  88754. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88755. *
  88756. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88757. * \c NULL if there was an error allocating memory, else the new instance.
  88758. */
  88759. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88760. /** Create a copy of an existing CUESHEET track object.
  88761. *
  88762. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88763. * object is also copied. The caller takes ownership of the new object and
  88764. * is responsible for freeing it with
  88765. * FLAC__metadata_object_cuesheet_track_delete().
  88766. *
  88767. * \param object Pointer to object to copy.
  88768. * \assert
  88769. * \code object != NULL \endcode
  88770. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88771. * \c NULL if there was an error allocating memory, else the new instance.
  88772. */
  88773. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88774. /** Delete a CUESHEET track object
  88775. *
  88776. * \param object A pointer to an existing CUESHEET track object.
  88777. * \assert
  88778. * \code object != NULL \endcode
  88779. */
  88780. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88781. /** Resize a track's index point array.
  88782. *
  88783. * If the size shrinks, elements will truncated; if it grows, new blank
  88784. * indices will be added to the end.
  88785. *
  88786. * \param object A pointer to an existing CUESHEET object.
  88787. * \param track_num The index of the track to modify. NOTE: this is not
  88788. * necessarily the same as the track's \a number field.
  88789. * \param new_num_indices The desired length of the array; may be \c 0.
  88790. * \assert
  88791. * \code object != NULL \endcode
  88792. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88793. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88794. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88795. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88796. * \retval FLAC__bool
  88797. * \c false if memory allocation error, else \c true.
  88798. */
  88799. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88800. /** Insert an index point in a CUESHEET track at the given index.
  88801. *
  88802. * \param object A pointer to an existing CUESHEET object.
  88803. * \param track_num The index of the track to modify. NOTE: this is not
  88804. * necessarily the same as the track's \a number field.
  88805. * \param index_num The index into the track's index array at which to
  88806. * insert the index point. NOTE: this is not necessarily
  88807. * the same as the index point's \a number field. The
  88808. * indices at and after \a index_num move right one
  88809. * position. To append an index point to the end, set
  88810. * \a index_num to
  88811. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88812. * \param index The index point to insert.
  88813. * \assert
  88814. * \code object != NULL \endcode
  88815. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88816. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88817. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88818. * \retval FLAC__bool
  88819. * \c false if realloc() fails, else \c true.
  88820. */
  88821. 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);
  88822. /** Insert a blank index point in a CUESHEET track at the given index.
  88823. *
  88824. * A blank index point is one in which all field values are zero.
  88825. *
  88826. * \param object A pointer to an existing CUESHEET object.
  88827. * \param track_num The index of the track to modify. NOTE: this is not
  88828. * necessarily the same as the track's \a number field.
  88829. * \param index_num The index into the track's index array at which to
  88830. * insert the index point. NOTE: this is not necessarily
  88831. * the same as the index point's \a number field. The
  88832. * indices at and after \a index_num move right one
  88833. * position. To append an index point to the end, set
  88834. * \a index_num to
  88835. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88836. * \assert
  88837. * \code object != NULL \endcode
  88838. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88839. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88840. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88841. * \retval FLAC__bool
  88842. * \c false if realloc() fails, else \c true.
  88843. */
  88844. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88845. /** Delete an index point in a CUESHEET track at the given index.
  88846. *
  88847. * \param object A pointer to an existing CUESHEET object.
  88848. * \param track_num The index into the track array of the track to
  88849. * modify. NOTE: this is not necessarily the same
  88850. * as the track's \a number field.
  88851. * \param index_num The index into the track's index array of the index
  88852. * to delete. NOTE: this is not necessarily the same
  88853. * as the index's \a number field.
  88854. * \assert
  88855. * \code object != NULL \endcode
  88856. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88857. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88858. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88859. * \retval FLAC__bool
  88860. * \c false if realloc() fails, else \c true.
  88861. */
  88862. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88863. /** Resize the track array.
  88864. *
  88865. * If the size shrinks, elements will truncated; if it grows, new blank
  88866. * tracks will be added to the end.
  88867. *
  88868. * \param object A pointer to an existing CUESHEET object.
  88869. * \param new_num_tracks The desired length of the array; may be \c 0.
  88870. * \assert
  88871. * \code object != NULL \endcode
  88872. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88873. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88874. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88875. * \retval FLAC__bool
  88876. * \c false if memory allocation error, else \c true.
  88877. */
  88878. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88879. /** Sets a track in a CUESHEET block.
  88880. *
  88881. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88882. * takes ownership of the \a track pointer.
  88883. *
  88884. * \param object A pointer to an existing CUESHEET object.
  88885. * \param track_num Index into track array to set. NOTE: this is not
  88886. * necessarily the same as the track's \a number field.
  88887. * \param track The track to set the track to. You may safely pass in
  88888. * a const pointer if \a copy is \c true.
  88889. * \param copy See above.
  88890. * \assert
  88891. * \code object != NULL \endcode
  88892. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88893. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88894. * \code (track->indices != NULL && track->num_indices > 0) ||
  88895. * (track->indices == NULL && track->num_indices == 0)
  88896. * \retval FLAC__bool
  88897. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88898. */
  88899. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88900. /** Insert a track in a CUESHEET block at the given index.
  88901. *
  88902. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88903. * takes ownership of the \a track pointer.
  88904. *
  88905. * \param object A pointer to an existing CUESHEET object.
  88906. * \param track_num The index at which to insert the track. NOTE: this
  88907. * is not necessarily the same as the track's \a number
  88908. * field. The tracks at and after \a track_num move right
  88909. * one position. To append a track to the end, set
  88910. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88911. * \param track The track to insert. You may safely pass in a const
  88912. * pointer if \a copy is \c true.
  88913. * \param copy See above.
  88914. * \assert
  88915. * \code object != NULL \endcode
  88916. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88917. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88918. * \retval FLAC__bool
  88919. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88920. */
  88921. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88922. /** Insert a blank track in a CUESHEET block at the given index.
  88923. *
  88924. * A blank track is one in which all field values are zero.
  88925. *
  88926. * \param object A pointer to an existing CUESHEET object.
  88927. * \param track_num The index at which to insert the track. NOTE: this
  88928. * is not necessarily the same as the track's \a number
  88929. * field. The tracks at and after \a track_num move right
  88930. * one position. To append a track to the end, set
  88931. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88932. * \assert
  88933. * \code object != NULL \endcode
  88934. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88935. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88936. * \retval FLAC__bool
  88937. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88938. */
  88939. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88940. /** Delete a track in a CUESHEET block at the given index.
  88941. *
  88942. * \param object A pointer to an existing CUESHEET object.
  88943. * \param track_num The index into the track array of the track to
  88944. * delete. NOTE: this is not necessarily the same
  88945. * as the track's \a number field.
  88946. * \assert
  88947. * \code object != NULL \endcode
  88948. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88949. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88950. * \retval FLAC__bool
  88951. * \c false if realloc() fails, else \c true.
  88952. */
  88953. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88954. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88955. * See the format specification for limits on the contents of the
  88956. * cue sheet.
  88957. *
  88958. * \param object A pointer to an existing CUESHEET object.
  88959. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88960. * stringent requirements for a CD-DA (audio) disc.
  88961. * \param violation Address of a pointer to a string. If there is a
  88962. * violation, a pointer to a string explanation of the
  88963. * violation will be returned here. \a violation may be
  88964. * \c NULL if you don't need the returned string. Do not
  88965. * free the returned string; it will always point to static
  88966. * data.
  88967. * \assert
  88968. * \code object != NULL \endcode
  88969. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88970. * \retval FLAC__bool
  88971. * \c false if cue sheet is illegal, else \c true.
  88972. */
  88973. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88974. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88975. * assumes the cue sheet corresponds to a CD; the result is undefined
  88976. * if the cuesheet's is_cd bit is not set.
  88977. *
  88978. * \param object A pointer to an existing CUESHEET object.
  88979. * \assert
  88980. * \code object != NULL \endcode
  88981. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88982. * \retval FLAC__uint32
  88983. * The unsigned integer representation of the CDDB/freedb ID
  88984. */
  88985. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88986. /** Sets the MIME type of a PICTURE block.
  88987. *
  88988. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88989. * takes ownership of the pointer. The existing string will be freed if this
  88990. * function is successful, otherwise the original string will remain if \a copy
  88991. * is \c true and malloc() fails.
  88992. *
  88993. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88994. *
  88995. * \param object A pointer to an existing PICTURE object.
  88996. * \param mime_type A pointer to the MIME type string. The string must be
  88997. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88998. * is done.
  88999. * \param copy See above.
  89000. * \assert
  89001. * \code object != NULL \endcode
  89002. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89003. * \code (mime_type != NULL) \endcode
  89004. * \retval FLAC__bool
  89005. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89006. */
  89007. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89008. /** Sets the description of a PICTURE block.
  89009. *
  89010. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89011. * takes ownership of the pointer. The existing string will be freed if this
  89012. * function is successful, otherwise the original string will remain if \a copy
  89013. * is \c true and malloc() fails.
  89014. *
  89015. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89016. *
  89017. * \param object A pointer to an existing PICTURE object.
  89018. * \param description A pointer to the description string. The string must be
  89019. * valid UTF-8, NUL-terminated. No validation is done.
  89020. * \param copy See above.
  89021. * \assert
  89022. * \code object != NULL \endcode
  89023. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89024. * \code (description != NULL) \endcode
  89025. * \retval FLAC__bool
  89026. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89027. */
  89028. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89029. /** Sets the picture data of a PICTURE block.
  89030. *
  89031. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89032. * takes ownership of the pointer. Also sets the \a data_length field of the
  89033. * metadata object to what is passed in as the \a length parameter. The
  89034. * existing data will be freed if this function is successful, otherwise the
  89035. * original data and data_length will remain if \a copy is \c true and
  89036. * malloc() fails.
  89037. *
  89038. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89039. *
  89040. * \param object A pointer to an existing PICTURE object.
  89041. * \param data A pointer to the data to set.
  89042. * \param length The length of \a data in bytes.
  89043. * \param copy See above.
  89044. * \assert
  89045. * \code object != NULL \endcode
  89046. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89047. * \code (data != NULL && length > 0) ||
  89048. * (data == NULL && length == 0 && copy == false) \endcode
  89049. * \retval FLAC__bool
  89050. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89051. */
  89052. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89053. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89054. * See the format specification for limits on the contents of the
  89055. * PICTURE block.
  89056. *
  89057. * \param object A pointer to existing PICTURE block to be checked.
  89058. * \param violation Address of a pointer to a string. If there is a
  89059. * violation, a pointer to a string explanation of the
  89060. * violation will be returned here. \a violation may be
  89061. * \c NULL if you don't need the returned string. Do not
  89062. * free the returned string; it will always point to static
  89063. * data.
  89064. * \assert
  89065. * \code object != NULL \endcode
  89066. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89067. * \retval FLAC__bool
  89068. * \c false if PICTURE block is illegal, else \c true.
  89069. */
  89070. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89071. /* \} */
  89072. #ifdef __cplusplus
  89073. }
  89074. #endif
  89075. #endif
  89076. /*** End of inlined file: metadata.h ***/
  89077. /*** Start of inlined file: stream_decoder.h ***/
  89078. #ifndef FLAC__STREAM_DECODER_H
  89079. #define FLAC__STREAM_DECODER_H
  89080. #include <stdio.h> /* for FILE */
  89081. #ifdef __cplusplus
  89082. extern "C" {
  89083. #endif
  89084. /** \file include/FLAC/stream_decoder.h
  89085. *
  89086. * \brief
  89087. * This module contains the functions which implement the stream
  89088. * decoder.
  89089. *
  89090. * See the detailed documentation in the
  89091. * \link flac_stream_decoder stream decoder \endlink module.
  89092. */
  89093. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89094. * \ingroup flac
  89095. *
  89096. * \brief
  89097. * This module describes the decoder layers provided by libFLAC.
  89098. *
  89099. * The stream decoder can be used to decode complete streams either from
  89100. * the client via callbacks, or directly from a file, depending on how
  89101. * it is initialized. When decoding via callbacks, the client provides
  89102. * callbacks for reading FLAC data and writing decoded samples, and
  89103. * handling metadata and errors. If the client also supplies seek-related
  89104. * callback, the decoder function for sample-accurate seeking within the
  89105. * FLAC input is also available. When decoding from a file, the client
  89106. * needs only supply a filename or open \c FILE* and write/metadata/error
  89107. * callbacks; the rest of the callbacks are supplied internally. For more
  89108. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89109. */
  89110. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89111. * \ingroup flac_decoder
  89112. *
  89113. * \brief
  89114. * This module contains the functions which implement the stream
  89115. * decoder.
  89116. *
  89117. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89118. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89119. *
  89120. * The basic usage of this decoder is as follows:
  89121. * - The program creates an instance of a decoder using
  89122. * FLAC__stream_decoder_new().
  89123. * - The program overrides the default settings using
  89124. * FLAC__stream_decoder_set_*() functions.
  89125. * - The program initializes the instance to validate the settings and
  89126. * prepare for decoding using
  89127. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89128. * or FLAC__stream_decoder_init_file() for native FLAC,
  89129. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89130. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89131. * - The program calls the FLAC__stream_decoder_process_*() functions
  89132. * to decode data, which subsequently calls the callbacks.
  89133. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89134. * which flushes the input and output and resets the decoder to the
  89135. * uninitialized state.
  89136. * - The instance may be used again or deleted with
  89137. * FLAC__stream_decoder_delete().
  89138. *
  89139. * In more detail, the program will create a new instance by calling
  89140. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89141. * functions to override the default decoder options, and call
  89142. * one of the FLAC__stream_decoder_init_*() functions.
  89143. *
  89144. * There are three initialization functions for native FLAC, one for
  89145. * setting up the decoder to decode FLAC data from the client via
  89146. * callbacks, and two for decoding directly from a FLAC file.
  89147. *
  89148. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89149. * You must also supply several callbacks for handling I/O. Some (like
  89150. * seeking) are optional, depending on the capabilities of the input.
  89151. *
  89152. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89153. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89154. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89155. * the other callbacks internally.
  89156. *
  89157. * There are three similarly-named init functions for decoding from Ogg
  89158. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89159. * library has been built with Ogg support.
  89160. *
  89161. * Once the decoder is initialized, your program will call one of several
  89162. * functions to start the decoding process:
  89163. *
  89164. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89165. * most one metadata block or audio frame and return, calling either the
  89166. * metadata callback or write callback, respectively, once. If the decoder
  89167. * loses sync it will return with only the error callback being called.
  89168. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89169. * to process the stream from the current location and stop upon reaching
  89170. * the first audio frame. The client will get one metadata, write, or error
  89171. * callback per metadata block, audio frame, or sync error, respectively.
  89172. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89173. * to process the stream from the current location until the read callback
  89174. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89175. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89176. * write, or error callback per metadata block, audio frame, or sync error,
  89177. * respectively.
  89178. *
  89179. * When the decoder has finished decoding (normally or through an abort),
  89180. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89181. * ensures the decoder is in the correct state and frees memory. Then the
  89182. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89183. * again to decode another stream.
  89184. *
  89185. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89186. * At any point after the stream decoder has been initialized, the client can
  89187. * call this function to seek to an exact sample within the stream.
  89188. * Subsequently, the first time the write callback is called it will be
  89189. * passed a (possibly partial) block starting at that sample.
  89190. *
  89191. * If the client cannot seek via the callback interface provided, but still
  89192. * has another way of seeking, it can flush the decoder using
  89193. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89194. * through the read callback.
  89195. *
  89196. * The stream decoder also provides MD5 signature checking. If this is
  89197. * turned on before initialization, FLAC__stream_decoder_finish() will
  89198. * report when the decoded MD5 signature does not match the one stored
  89199. * in the STREAMINFO block. MD5 checking is automatically turned off
  89200. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89201. * in the STREAMINFO block or when a seek is attempted.
  89202. *
  89203. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89204. * attention. By default, the decoder only calls the metadata_callback for
  89205. * the STREAMINFO block. These functions allow you to tell the decoder
  89206. * explicitly which blocks to parse and return via the metadata_callback
  89207. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89208. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89209. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89210. * which blocks to return. Remember that metadata blocks can potentially
  89211. * be big (for example, cover art) so filtering out the ones you don't
  89212. * use can reduce the memory requirements of the decoder. Also note the
  89213. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89214. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89215. * filtering APPLICATION blocks based on the application ID.
  89216. *
  89217. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89218. * they still can legally be filtered from the metadata_callback.
  89219. *
  89220. * \note
  89221. * The "set" functions may only be called when the decoder is in the
  89222. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89223. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89224. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89225. * return \c true, otherwise \c false.
  89226. *
  89227. * \note
  89228. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89229. * defaults, including the callbacks.
  89230. *
  89231. * \{
  89232. */
  89233. /** State values for a FLAC__StreamDecoder
  89234. *
  89235. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89236. */
  89237. typedef enum {
  89238. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89239. /**< The decoder is ready to search for metadata. */
  89240. FLAC__STREAM_DECODER_READ_METADATA,
  89241. /**< The decoder is ready to or is in the process of reading metadata. */
  89242. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89243. /**< The decoder is ready to or is in the process of searching for the
  89244. * frame sync code.
  89245. */
  89246. FLAC__STREAM_DECODER_READ_FRAME,
  89247. /**< The decoder is ready to or is in the process of reading a frame. */
  89248. FLAC__STREAM_DECODER_END_OF_STREAM,
  89249. /**< The decoder has reached the end of the stream. */
  89250. FLAC__STREAM_DECODER_OGG_ERROR,
  89251. /**< An error occurred in the underlying Ogg layer. */
  89252. FLAC__STREAM_DECODER_SEEK_ERROR,
  89253. /**< An error occurred while seeking. The decoder must be flushed
  89254. * with FLAC__stream_decoder_flush() or reset with
  89255. * FLAC__stream_decoder_reset() before decoding can continue.
  89256. */
  89257. FLAC__STREAM_DECODER_ABORTED,
  89258. /**< The decoder was aborted by the read callback. */
  89259. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89260. /**< An error occurred allocating memory. The decoder is in an invalid
  89261. * state and can no longer be used.
  89262. */
  89263. FLAC__STREAM_DECODER_UNINITIALIZED
  89264. /**< The decoder is in the uninitialized state; one of the
  89265. * FLAC__stream_decoder_init_*() functions must be called before samples
  89266. * can be processed.
  89267. */
  89268. } FLAC__StreamDecoderState;
  89269. /** Maps a FLAC__StreamDecoderState to a C string.
  89270. *
  89271. * Using a FLAC__StreamDecoderState as the index to this array
  89272. * will give the string equivalent. The contents should not be modified.
  89273. */
  89274. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89275. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89276. */
  89277. typedef enum {
  89278. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89279. /**< Initialization was successful. */
  89280. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89281. /**< The library was not compiled with support for the given container
  89282. * format.
  89283. */
  89284. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89285. /**< A required callback was not supplied. */
  89286. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89287. /**< An error occurred allocating memory. */
  89288. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89289. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89290. * FLAC__stream_decoder_init_ogg_file(). */
  89291. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89292. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89293. * already initialized, usually because
  89294. * FLAC__stream_decoder_finish() was not called.
  89295. */
  89296. } FLAC__StreamDecoderInitStatus;
  89297. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89298. *
  89299. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89300. * will give the string equivalent. The contents should not be modified.
  89301. */
  89302. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89303. /** Return values for the FLAC__StreamDecoder read callback.
  89304. */
  89305. typedef enum {
  89306. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89307. /**< The read was OK and decoding can continue. */
  89308. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89309. /**< The read was attempted while at the end of the stream. Note that
  89310. * the client must only return this value when the read callback was
  89311. * called when already at the end of the stream. Otherwise, if the read
  89312. * itself moves to the end of the stream, the client should still return
  89313. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89314. * the next read callback it should return
  89315. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89316. * of \c 0.
  89317. */
  89318. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89319. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89320. } FLAC__StreamDecoderReadStatus;
  89321. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89322. *
  89323. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89324. * will give the string equivalent. The contents should not be modified.
  89325. */
  89326. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89327. /** Return values for the FLAC__StreamDecoder seek callback.
  89328. */
  89329. typedef enum {
  89330. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89331. /**< The seek was OK and decoding can continue. */
  89332. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89333. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89334. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89335. /**< Client does not support seeking. */
  89336. } FLAC__StreamDecoderSeekStatus;
  89337. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89338. *
  89339. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89340. * will give the string equivalent. The contents should not be modified.
  89341. */
  89342. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89343. /** Return values for the FLAC__StreamDecoder tell callback.
  89344. */
  89345. typedef enum {
  89346. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89347. /**< The tell was OK and decoding can continue. */
  89348. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89349. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89350. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89351. /**< Client does not support telling the position. */
  89352. } FLAC__StreamDecoderTellStatus;
  89353. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89354. *
  89355. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89356. * will give the string equivalent. The contents should not be modified.
  89357. */
  89358. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89359. /** Return values for the FLAC__StreamDecoder length callback.
  89360. */
  89361. typedef enum {
  89362. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89363. /**< The length call was OK and decoding can continue. */
  89364. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89365. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89366. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89367. /**< Client does not support reporting the length. */
  89368. } FLAC__StreamDecoderLengthStatus;
  89369. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89370. *
  89371. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89372. * will give the string equivalent. The contents should not be modified.
  89373. */
  89374. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89375. /** Return values for the FLAC__StreamDecoder write callback.
  89376. */
  89377. typedef enum {
  89378. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89379. /**< The write was OK and decoding can continue. */
  89380. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89381. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89382. } FLAC__StreamDecoderWriteStatus;
  89383. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89384. *
  89385. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89386. * will give the string equivalent. The contents should not be modified.
  89387. */
  89388. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89389. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89390. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89391. * all. The rest could be caused by bad sync (false synchronization on
  89392. * data that is not the start of a frame) or corrupted data. The error
  89393. * itself is the decoder's best guess at what happened assuming a correct
  89394. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89395. * could be caused by a correct sync on the start of a frame, but some
  89396. * data in the frame header was corrupted. Or it could be the result of
  89397. * syncing on a point the stream that looked like the starting of a frame
  89398. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89399. * could be because the decoder encountered a valid frame made by a future
  89400. * version of the encoder which it cannot parse, or because of a false
  89401. * sync making it appear as though an encountered frame was generated by
  89402. * a future encoder.
  89403. */
  89404. typedef enum {
  89405. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89406. /**< An error in the stream caused the decoder to lose synchronization. */
  89407. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89408. /**< The decoder encountered a corrupted frame header. */
  89409. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89410. /**< The frame's data did not match the CRC in the footer. */
  89411. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89412. /**< The decoder encountered reserved fields in use in the stream. */
  89413. } FLAC__StreamDecoderErrorStatus;
  89414. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89415. *
  89416. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89417. * will give the string equivalent. The contents should not be modified.
  89418. */
  89419. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89420. /***********************************************************************
  89421. *
  89422. * class FLAC__StreamDecoder
  89423. *
  89424. ***********************************************************************/
  89425. struct FLAC__StreamDecoderProtected;
  89426. struct FLAC__StreamDecoderPrivate;
  89427. /** The opaque structure definition for the stream decoder type.
  89428. * See the \link flac_stream_decoder stream decoder module \endlink
  89429. * for a detailed description.
  89430. */
  89431. typedef struct {
  89432. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89433. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89434. } FLAC__StreamDecoder;
  89435. /** Signature for the read callback.
  89436. *
  89437. * A function pointer matching this signature must be passed to
  89438. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89439. * called when the decoder needs more input data. The address of the
  89440. * buffer to be filled is supplied, along with the number of bytes the
  89441. * buffer can hold. The callback may choose to supply less data and
  89442. * modify the byte count but must be careful not to overflow the buffer.
  89443. * The callback then returns a status code chosen from
  89444. * FLAC__StreamDecoderReadStatus.
  89445. *
  89446. * Here is an example of a read callback for stdio streams:
  89447. * \code
  89448. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89449. * {
  89450. * FILE *file = ((MyClientData*)client_data)->file;
  89451. * if(*bytes > 0) {
  89452. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89453. * if(ferror(file))
  89454. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89455. * else if(*bytes == 0)
  89456. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89457. * else
  89458. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89459. * }
  89460. * else
  89461. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89462. * }
  89463. * \endcode
  89464. *
  89465. * \note In general, FLAC__StreamDecoder functions which change the
  89466. * state should not be called on the \a decoder while in the callback.
  89467. *
  89468. * \param decoder The decoder instance calling the callback.
  89469. * \param buffer A pointer to a location for the callee to store
  89470. * data to be decoded.
  89471. * \param bytes A pointer to the size of the buffer. On entry
  89472. * to the callback, it contains the maximum number
  89473. * of bytes that may be stored in \a buffer. The
  89474. * callee must set it to the actual number of bytes
  89475. * stored (0 in case of error or end-of-stream) before
  89476. * returning.
  89477. * \param client_data The callee's client data set through
  89478. * FLAC__stream_decoder_init_*().
  89479. * \retval FLAC__StreamDecoderReadStatus
  89480. * The callee's return status. Note that the callback should return
  89481. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89482. * zero bytes were read and there is no more data to be read.
  89483. */
  89484. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89485. /** Signature for the seek callback.
  89486. *
  89487. * A function pointer matching this signature may be passed to
  89488. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89489. * called when the decoder needs to seek the input stream. The decoder
  89490. * will pass the absolute byte offset to seek to, 0 meaning the
  89491. * beginning of the stream.
  89492. *
  89493. * Here is an example of a seek callback for stdio streams:
  89494. * \code
  89495. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89496. * {
  89497. * FILE *file = ((MyClientData*)client_data)->file;
  89498. * if(file == stdin)
  89499. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89500. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89501. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89502. * else
  89503. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89504. * }
  89505. * \endcode
  89506. *
  89507. * \note In general, FLAC__StreamDecoder functions which change the
  89508. * state should not be called on the \a decoder while in the callback.
  89509. *
  89510. * \param decoder The decoder instance calling the callback.
  89511. * \param absolute_byte_offset The offset from the beginning of the stream
  89512. * to seek to.
  89513. * \param client_data The callee's client data set through
  89514. * FLAC__stream_decoder_init_*().
  89515. * \retval FLAC__StreamDecoderSeekStatus
  89516. * The callee's return status.
  89517. */
  89518. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89519. /** Signature for the tell callback.
  89520. *
  89521. * A function pointer matching this signature may be passed to
  89522. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89523. * called when the decoder wants to know the current position of the
  89524. * stream. The callback should return the byte offset from the
  89525. * beginning of the stream.
  89526. *
  89527. * Here is an example of a tell callback for stdio streams:
  89528. * \code
  89529. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89530. * {
  89531. * FILE *file = ((MyClientData*)client_data)->file;
  89532. * off_t pos;
  89533. * if(file == stdin)
  89534. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89535. * else if((pos = ftello(file)) < 0)
  89536. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89537. * else {
  89538. * *absolute_byte_offset = (FLAC__uint64)pos;
  89539. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89540. * }
  89541. * }
  89542. * \endcode
  89543. *
  89544. * \note In general, FLAC__StreamDecoder functions which change the
  89545. * state should not be called on the \a decoder while in the callback.
  89546. *
  89547. * \param decoder The decoder instance calling the callback.
  89548. * \param absolute_byte_offset A pointer to storage for the current offset
  89549. * from the beginning of the stream.
  89550. * \param client_data The callee's client data set through
  89551. * FLAC__stream_decoder_init_*().
  89552. * \retval FLAC__StreamDecoderTellStatus
  89553. * The callee's return status.
  89554. */
  89555. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89556. /** Signature for the length callback.
  89557. *
  89558. * A function pointer matching this signature may be passed to
  89559. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89560. * called when the decoder wants to know the total length of the stream
  89561. * in bytes.
  89562. *
  89563. * Here is an example of a length callback for stdio streams:
  89564. * \code
  89565. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89566. * {
  89567. * FILE *file = ((MyClientData*)client_data)->file;
  89568. * struct stat filestats;
  89569. *
  89570. * if(file == stdin)
  89571. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89572. * else if(fstat(fileno(file), &filestats) != 0)
  89573. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89574. * else {
  89575. * *stream_length = (FLAC__uint64)filestats.st_size;
  89576. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89577. * }
  89578. * }
  89579. * \endcode
  89580. *
  89581. * \note In general, FLAC__StreamDecoder functions which change the
  89582. * state should not be called on the \a decoder while in the callback.
  89583. *
  89584. * \param decoder The decoder instance calling the callback.
  89585. * \param stream_length A pointer to storage for the length of the stream
  89586. * in bytes.
  89587. * \param client_data The callee's client data set through
  89588. * FLAC__stream_decoder_init_*().
  89589. * \retval FLAC__StreamDecoderLengthStatus
  89590. * The callee's return status.
  89591. */
  89592. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89593. /** Signature for the EOF callback.
  89594. *
  89595. * A function pointer matching this signature may be passed to
  89596. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89597. * called when the decoder needs to know if the end of the stream has
  89598. * been reached.
  89599. *
  89600. * Here is an example of a EOF callback for stdio streams:
  89601. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89602. * \code
  89603. * {
  89604. * FILE *file = ((MyClientData*)client_data)->file;
  89605. * return feof(file)? true : false;
  89606. * }
  89607. * \endcode
  89608. *
  89609. * \note In general, FLAC__StreamDecoder functions which change the
  89610. * state should not be called on the \a decoder while in the callback.
  89611. *
  89612. * \param decoder The decoder instance calling the callback.
  89613. * \param client_data The callee's client data set through
  89614. * FLAC__stream_decoder_init_*().
  89615. * \retval FLAC__bool
  89616. * \c true if the currently at the end of the stream, else \c false.
  89617. */
  89618. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89619. /** Signature for the write callback.
  89620. *
  89621. * A function pointer matching this signature must be passed to one of
  89622. * the FLAC__stream_decoder_init_*() functions.
  89623. * The supplied function will be called when the decoder has decoded a
  89624. * single audio frame. The decoder will pass the frame metadata as well
  89625. * as an array of pointers (one for each channel) pointing to the
  89626. * decoded audio.
  89627. *
  89628. * \note In general, FLAC__StreamDecoder functions which change the
  89629. * state should not be called on the \a decoder while in the callback.
  89630. *
  89631. * \param decoder The decoder instance calling the callback.
  89632. * \param frame The description of the decoded frame. See
  89633. * FLAC__Frame.
  89634. * \param buffer An array of pointers to decoded channels of data.
  89635. * Each pointer will point to an array of signed
  89636. * samples of length \a frame->header.blocksize.
  89637. * Channels will be ordered according to the FLAC
  89638. * specification; see the documentation for the
  89639. * <A HREF="../format.html#frame_header">frame header</A>.
  89640. * \param client_data The callee's client data set through
  89641. * FLAC__stream_decoder_init_*().
  89642. * \retval FLAC__StreamDecoderWriteStatus
  89643. * The callee's return status.
  89644. */
  89645. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89646. /** Signature for the metadata callback.
  89647. *
  89648. * A function pointer matching this signature must be passed to one of
  89649. * the FLAC__stream_decoder_init_*() functions.
  89650. * The supplied function will be called when the decoder has decoded a
  89651. * metadata block. In a valid FLAC file there will always be one
  89652. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89653. * These will be supplied by the decoder in the same order as they
  89654. * appear in the stream and always before the first audio frame (i.e.
  89655. * write callback). The metadata block that is passed in must not be
  89656. * modified, and it doesn't live beyond the callback, so you should make
  89657. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89658. * elsewhere. Since metadata blocks can potentially be large, by
  89659. * default the decoder only calls the metadata callback for the
  89660. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89661. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89662. *
  89663. * \note In general, FLAC__StreamDecoder functions which change the
  89664. * state should not be called on the \a decoder while in the callback.
  89665. *
  89666. * \param decoder The decoder instance calling the callback.
  89667. * \param metadata The decoded metadata block.
  89668. * \param client_data The callee's client data set through
  89669. * FLAC__stream_decoder_init_*().
  89670. */
  89671. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89672. /** Signature for the error callback.
  89673. *
  89674. * A function pointer matching this signature must be passed to one of
  89675. * the FLAC__stream_decoder_init_*() functions.
  89676. * The supplied function will be called whenever an error occurs during
  89677. * decoding.
  89678. *
  89679. * \note In general, FLAC__StreamDecoder functions which change the
  89680. * state should not be called on the \a decoder while in the callback.
  89681. *
  89682. * \param decoder The decoder instance calling the callback.
  89683. * \param status The error encountered by the decoder.
  89684. * \param client_data The callee's client data set through
  89685. * FLAC__stream_decoder_init_*().
  89686. */
  89687. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89688. /***********************************************************************
  89689. *
  89690. * Class constructor/destructor
  89691. *
  89692. ***********************************************************************/
  89693. /** Create a new stream decoder instance. The instance is created with
  89694. * default settings; see the individual FLAC__stream_decoder_set_*()
  89695. * functions for each setting's default.
  89696. *
  89697. * \retval FLAC__StreamDecoder*
  89698. * \c NULL if there was an error allocating memory, else the new instance.
  89699. */
  89700. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89701. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89702. *
  89703. * \param decoder A pointer to an existing decoder.
  89704. * \assert
  89705. * \code decoder != NULL \endcode
  89706. */
  89707. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89708. /***********************************************************************
  89709. *
  89710. * Public class method prototypes
  89711. *
  89712. ***********************************************************************/
  89713. /** Set the serial number for the FLAC stream within the Ogg container.
  89714. * The default behavior is to use the serial number of the first Ogg
  89715. * page. Setting a serial number here will explicitly specify which
  89716. * stream is to be decoded.
  89717. *
  89718. * \note
  89719. * This does not need to be set for native FLAC decoding.
  89720. *
  89721. * \default \c use serial number of first page
  89722. * \param decoder A decoder instance to set.
  89723. * \param serial_number See above.
  89724. * \assert
  89725. * \code decoder != NULL \endcode
  89726. * \retval FLAC__bool
  89727. * \c false if the decoder is already initialized, else \c true.
  89728. */
  89729. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89730. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89731. * compute the MD5 signature of the unencoded audio data while decoding
  89732. * and compare it to the signature from the STREAMINFO block, if it
  89733. * exists, during FLAC__stream_decoder_finish().
  89734. *
  89735. * MD5 signature checking will be turned off (until the next
  89736. * FLAC__stream_decoder_reset()) if there is no signature in the
  89737. * STREAMINFO block or when a seek is attempted.
  89738. *
  89739. * Clients that do not use the MD5 check should leave this off to speed
  89740. * up decoding.
  89741. *
  89742. * \default \c false
  89743. * \param decoder A decoder instance to set.
  89744. * \param value Flag value (see above).
  89745. * \assert
  89746. * \code decoder != NULL \endcode
  89747. * \retval FLAC__bool
  89748. * \c false if the decoder is already initialized, else \c true.
  89749. */
  89750. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89751. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89752. *
  89753. * \default By default, only the \c STREAMINFO block is returned via the
  89754. * metadata callback.
  89755. * \param decoder A decoder instance to set.
  89756. * \param type See above.
  89757. * \assert
  89758. * \code decoder != NULL \endcode
  89759. * \a type is valid
  89760. * \retval FLAC__bool
  89761. * \c false if the decoder is already initialized, else \c true.
  89762. */
  89763. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89764. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89765. * given \a id.
  89766. *
  89767. * \default By default, only the \c STREAMINFO block is returned via the
  89768. * metadata callback.
  89769. * \param decoder A decoder instance to set.
  89770. * \param id See above.
  89771. * \assert
  89772. * \code decoder != NULL \endcode
  89773. * \code id != NULL \endcode
  89774. * \retval FLAC__bool
  89775. * \c false if the decoder is already initialized, else \c true.
  89776. */
  89777. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89778. /** Direct the decoder to pass on all metadata blocks of any type.
  89779. *
  89780. * \default By default, only the \c STREAMINFO block is returned via the
  89781. * metadata callback.
  89782. * \param decoder A decoder instance to set.
  89783. * \assert
  89784. * \code decoder != NULL \endcode
  89785. * \retval FLAC__bool
  89786. * \c false if the decoder is already initialized, else \c true.
  89787. */
  89788. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89789. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89790. *
  89791. * \default By default, only the \c STREAMINFO block is returned via the
  89792. * metadata callback.
  89793. * \param decoder A decoder instance to set.
  89794. * \param type See above.
  89795. * \assert
  89796. * \code decoder != NULL \endcode
  89797. * \a type is valid
  89798. * \retval FLAC__bool
  89799. * \c false if the decoder is already initialized, else \c true.
  89800. */
  89801. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89802. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89803. * the given \a id.
  89804. *
  89805. * \default By default, only the \c STREAMINFO block is returned via the
  89806. * metadata callback.
  89807. * \param decoder A decoder instance to set.
  89808. * \param id See above.
  89809. * \assert
  89810. * \code decoder != NULL \endcode
  89811. * \code id != NULL \endcode
  89812. * \retval FLAC__bool
  89813. * \c false if the decoder is already initialized, else \c true.
  89814. */
  89815. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89816. /** Direct the decoder to filter out all metadata blocks of any type.
  89817. *
  89818. * \default By default, only the \c STREAMINFO block is returned via the
  89819. * metadata callback.
  89820. * \param decoder A decoder instance to set.
  89821. * \assert
  89822. * \code decoder != NULL \endcode
  89823. * \retval FLAC__bool
  89824. * \c false if the decoder is already initialized, else \c true.
  89825. */
  89826. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89827. /** Get the current decoder state.
  89828. *
  89829. * \param decoder A decoder instance to query.
  89830. * \assert
  89831. * \code decoder != NULL \endcode
  89832. * \retval FLAC__StreamDecoderState
  89833. * The current decoder state.
  89834. */
  89835. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89836. /** Get the current decoder state as a C string.
  89837. *
  89838. * \param decoder A decoder instance to query.
  89839. * \assert
  89840. * \code decoder != NULL \endcode
  89841. * \retval const char *
  89842. * The decoder state as a C string. Do not modify the contents.
  89843. */
  89844. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89845. /** Get the "MD5 signature checking" flag.
  89846. * This is the value of the setting, not whether or not the decoder is
  89847. * currently checking the MD5 (remember, it can be turned off automatically
  89848. * by a seek). When the decoder is reset the flag will be restored to the
  89849. * value returned by this function.
  89850. *
  89851. * \param decoder A decoder instance to query.
  89852. * \assert
  89853. * \code decoder != NULL \endcode
  89854. * \retval FLAC__bool
  89855. * See above.
  89856. */
  89857. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89858. /** Get the total number of samples in the stream being decoded.
  89859. * Will only be valid after decoding has started and will contain the
  89860. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89861. *
  89862. * \param decoder A decoder instance to query.
  89863. * \assert
  89864. * \code decoder != NULL \endcode
  89865. * \retval unsigned
  89866. * See above.
  89867. */
  89868. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89869. /** Get the current number of channels in the stream being decoded.
  89870. * Will only be valid after decoding has started and will contain the
  89871. * value from the most recently decoded frame header.
  89872. *
  89873. * \param decoder A decoder instance to query.
  89874. * \assert
  89875. * \code decoder != NULL \endcode
  89876. * \retval unsigned
  89877. * See above.
  89878. */
  89879. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89880. /** Get the current channel assignment in the stream being decoded.
  89881. * Will only be valid after decoding has started and will contain the
  89882. * value from the most recently decoded frame header.
  89883. *
  89884. * \param decoder A decoder instance to query.
  89885. * \assert
  89886. * \code decoder != NULL \endcode
  89887. * \retval FLAC__ChannelAssignment
  89888. * See above.
  89889. */
  89890. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89891. /** Get the current sample resolution in the stream being decoded.
  89892. * Will only be valid after decoding has started and will contain the
  89893. * value from the most recently decoded frame header.
  89894. *
  89895. * \param decoder A decoder instance to query.
  89896. * \assert
  89897. * \code decoder != NULL \endcode
  89898. * \retval unsigned
  89899. * See above.
  89900. */
  89901. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89902. /** Get the current sample rate in Hz of the stream being decoded.
  89903. * Will only be valid after decoding has started and will contain the
  89904. * value from the most recently decoded frame header.
  89905. *
  89906. * \param decoder A decoder instance to query.
  89907. * \assert
  89908. * \code decoder != NULL \endcode
  89909. * \retval unsigned
  89910. * See above.
  89911. */
  89912. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89913. /** Get the current blocksize of the stream being decoded.
  89914. * Will only be valid after decoding has started and will contain the
  89915. * value from the most recently decoded frame header.
  89916. *
  89917. * \param decoder A decoder instance to query.
  89918. * \assert
  89919. * \code decoder != NULL \endcode
  89920. * \retval unsigned
  89921. * See above.
  89922. */
  89923. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89924. /** Returns the decoder's current read position within the stream.
  89925. * The position is the byte offset from the start of the stream.
  89926. * Bytes before this position have been fully decoded. Note that
  89927. * there may still be undecoded bytes in the decoder's read FIFO.
  89928. * The returned position is correct even after a seek.
  89929. *
  89930. * \warning This function currently only works for native FLAC,
  89931. * not Ogg FLAC streams.
  89932. *
  89933. * \param decoder A decoder instance to query.
  89934. * \param position Address at which to return the desired position.
  89935. * \assert
  89936. * \code decoder != NULL \endcode
  89937. * \code position != NULL \endcode
  89938. * \retval FLAC__bool
  89939. * \c true if successful, \c false if the stream is not native FLAC,
  89940. * or there was an error from the 'tell' callback or it returned
  89941. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89942. */
  89943. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89944. /** Initialize the decoder instance to decode native FLAC streams.
  89945. *
  89946. * This flavor of initialization sets up the decoder to decode from a
  89947. * native FLAC stream. I/O is performed via callbacks to the client.
  89948. * For decoding from a plain file via filename or open FILE*,
  89949. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89950. * provide a simpler interface.
  89951. *
  89952. * This function should be called after FLAC__stream_decoder_new() and
  89953. * FLAC__stream_decoder_set_*() but before any of the
  89954. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89955. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89956. * if initialization succeeded.
  89957. *
  89958. * \param decoder An uninitialized decoder instance.
  89959. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89960. * pointer must not be \c NULL.
  89961. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89962. * pointer may be \c NULL if seeking is not
  89963. * supported. If \a seek_callback is not \c NULL then a
  89964. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89965. * Alternatively, a dummy seek callback that just
  89966. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89967. * may also be supplied, all though this is slightly
  89968. * less efficient for the decoder.
  89969. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89970. * pointer may be \c NULL if not supported by the client. If
  89971. * \a seek_callback is not \c NULL then a
  89972. * \a tell_callback must also be supplied.
  89973. * Alternatively, a dummy tell callback that just
  89974. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89975. * may also be supplied, all though this is slightly
  89976. * less efficient for the decoder.
  89977. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89978. * pointer may be \c NULL if not supported by the client. If
  89979. * \a seek_callback is not \c NULL then a
  89980. * \a length_callback must also be supplied.
  89981. * Alternatively, a dummy length callback that just
  89982. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89983. * may also be supplied, all though this is slightly
  89984. * less efficient for the decoder.
  89985. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89986. * pointer may be \c NULL if not supported by the client. If
  89987. * \a seek_callback is not \c NULL then a
  89988. * \a eof_callback must also be supplied.
  89989. * Alternatively, a dummy length callback that just
  89990. * returns \c false
  89991. * may also be supplied, all though this is slightly
  89992. * less efficient for the decoder.
  89993. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89994. * pointer must not be \c NULL.
  89995. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89996. * pointer may be \c NULL if the callback is not
  89997. * desired.
  89998. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89999. * pointer must not be \c NULL.
  90000. * \param client_data This value will be supplied to callbacks in their
  90001. * \a client_data argument.
  90002. * \assert
  90003. * \code decoder != NULL \endcode
  90004. * \retval FLAC__StreamDecoderInitStatus
  90005. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90006. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90007. */
  90008. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90009. FLAC__StreamDecoder *decoder,
  90010. FLAC__StreamDecoderReadCallback read_callback,
  90011. FLAC__StreamDecoderSeekCallback seek_callback,
  90012. FLAC__StreamDecoderTellCallback tell_callback,
  90013. FLAC__StreamDecoderLengthCallback length_callback,
  90014. FLAC__StreamDecoderEofCallback eof_callback,
  90015. FLAC__StreamDecoderWriteCallback write_callback,
  90016. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90017. FLAC__StreamDecoderErrorCallback error_callback,
  90018. void *client_data
  90019. );
  90020. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90021. *
  90022. * This flavor of initialization sets up the decoder to decode from a
  90023. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90024. * client. For decoding from a plain file via filename or open FILE*,
  90025. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90026. * provide a simpler interface.
  90027. *
  90028. * This function should be called after FLAC__stream_decoder_new() and
  90029. * FLAC__stream_decoder_set_*() but before any of the
  90030. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90031. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90032. * if initialization succeeded.
  90033. *
  90034. * \note Support for Ogg FLAC in the library is optional. If this
  90035. * library has been built without support for Ogg FLAC, this function
  90036. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90037. *
  90038. * \param decoder An uninitialized decoder instance.
  90039. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90040. * pointer must not be \c NULL.
  90041. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90042. * pointer may be \c NULL if seeking is not
  90043. * supported. If \a seek_callback is not \c NULL then a
  90044. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90045. * Alternatively, a dummy seek callback that just
  90046. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90047. * may also be supplied, all though this is slightly
  90048. * less efficient for the decoder.
  90049. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90050. * pointer may be \c NULL if not supported by the client. If
  90051. * \a seek_callback is not \c NULL then a
  90052. * \a tell_callback must also be supplied.
  90053. * Alternatively, a dummy tell callback that just
  90054. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90055. * may also be supplied, all though this is slightly
  90056. * less efficient for the decoder.
  90057. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90058. * pointer may be \c NULL if not supported by the client. If
  90059. * \a seek_callback is not \c NULL then a
  90060. * \a length_callback must also be supplied.
  90061. * Alternatively, a dummy length callback that just
  90062. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90063. * may also be supplied, all though this is slightly
  90064. * less efficient for the decoder.
  90065. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90066. * pointer may be \c NULL if not supported by the client. If
  90067. * \a seek_callback is not \c NULL then a
  90068. * \a eof_callback must also be supplied.
  90069. * Alternatively, a dummy length callback that just
  90070. * returns \c false
  90071. * may also be supplied, all though this is slightly
  90072. * less efficient for the decoder.
  90073. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90074. * pointer must not be \c NULL.
  90075. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90076. * pointer may be \c NULL if the callback is not
  90077. * desired.
  90078. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90079. * pointer must not be \c NULL.
  90080. * \param client_data This value will be supplied to callbacks in their
  90081. * \a client_data argument.
  90082. * \assert
  90083. * \code decoder != NULL \endcode
  90084. * \retval FLAC__StreamDecoderInitStatus
  90085. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90086. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90087. */
  90088. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90089. FLAC__StreamDecoder *decoder,
  90090. FLAC__StreamDecoderReadCallback read_callback,
  90091. FLAC__StreamDecoderSeekCallback seek_callback,
  90092. FLAC__StreamDecoderTellCallback tell_callback,
  90093. FLAC__StreamDecoderLengthCallback length_callback,
  90094. FLAC__StreamDecoderEofCallback eof_callback,
  90095. FLAC__StreamDecoderWriteCallback write_callback,
  90096. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90097. FLAC__StreamDecoderErrorCallback error_callback,
  90098. void *client_data
  90099. );
  90100. /** Initialize the decoder instance to decode native FLAC files.
  90101. *
  90102. * This flavor of initialization sets up the decoder to decode from a
  90103. * plain native FLAC file. For non-stdio streams, you must use
  90104. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90105. *
  90106. * This function should be called after FLAC__stream_decoder_new() and
  90107. * FLAC__stream_decoder_set_*() but before any of the
  90108. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90109. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90110. * if initialization succeeded.
  90111. *
  90112. * \param decoder An uninitialized decoder instance.
  90113. * \param file An open FLAC file. The file should have been
  90114. * opened with mode \c "rb" and rewound. The file
  90115. * becomes owned by the decoder and should not be
  90116. * manipulated by the client while decoding.
  90117. * Unless \a file is \c stdin, it will be closed
  90118. * when FLAC__stream_decoder_finish() is called.
  90119. * Note however that seeking will not work when
  90120. * decoding from \c stdout since it is not seekable.
  90121. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90122. * pointer must not be \c NULL.
  90123. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90124. * pointer may be \c NULL if the callback is not
  90125. * desired.
  90126. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90127. * pointer must not be \c NULL.
  90128. * \param client_data This value will be supplied to callbacks in their
  90129. * \a client_data argument.
  90130. * \assert
  90131. * \code decoder != NULL \endcode
  90132. * \code file != NULL \endcode
  90133. * \retval FLAC__StreamDecoderInitStatus
  90134. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90135. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90136. */
  90137. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90138. FLAC__StreamDecoder *decoder,
  90139. FILE *file,
  90140. FLAC__StreamDecoderWriteCallback write_callback,
  90141. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90142. FLAC__StreamDecoderErrorCallback error_callback,
  90143. void *client_data
  90144. );
  90145. /** Initialize the decoder instance to decode Ogg FLAC files.
  90146. *
  90147. * This flavor of initialization sets up the decoder to decode from a
  90148. * plain Ogg FLAC file. For non-stdio streams, you must use
  90149. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90150. *
  90151. * This function should be called after FLAC__stream_decoder_new() and
  90152. * FLAC__stream_decoder_set_*() but before any of the
  90153. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90154. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90155. * if initialization succeeded.
  90156. *
  90157. * \note Support for Ogg FLAC in the library is optional. If this
  90158. * library has been built without support for Ogg FLAC, this function
  90159. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90160. *
  90161. * \param decoder An uninitialized decoder instance.
  90162. * \param file An open FLAC file. The file should have been
  90163. * opened with mode \c "rb" and rewound. The file
  90164. * becomes owned by the decoder and should not be
  90165. * manipulated by the client while decoding.
  90166. * Unless \a file is \c stdin, it will be closed
  90167. * when FLAC__stream_decoder_finish() is called.
  90168. * Note however that seeking will not work when
  90169. * decoding from \c stdout since it is not seekable.
  90170. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90171. * pointer must not be \c NULL.
  90172. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90173. * pointer may be \c NULL if the callback is not
  90174. * desired.
  90175. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90176. * pointer must not be \c NULL.
  90177. * \param client_data This value will be supplied to callbacks in their
  90178. * \a client_data argument.
  90179. * \assert
  90180. * \code decoder != NULL \endcode
  90181. * \code file != NULL \endcode
  90182. * \retval FLAC__StreamDecoderInitStatus
  90183. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90184. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90185. */
  90186. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90187. FLAC__StreamDecoder *decoder,
  90188. FILE *file,
  90189. FLAC__StreamDecoderWriteCallback write_callback,
  90190. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90191. FLAC__StreamDecoderErrorCallback error_callback,
  90192. void *client_data
  90193. );
  90194. /** Initialize the decoder instance to decode native FLAC files.
  90195. *
  90196. * This flavor of initialization sets up the decoder to decode from a plain
  90197. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90198. * example, with Unicode filenames on Windows), you must use
  90199. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90200. * and provide callbacks for the I/O.
  90201. *
  90202. * This function should be called after FLAC__stream_decoder_new() and
  90203. * FLAC__stream_decoder_set_*() but before any of the
  90204. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90205. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90206. * if initialization succeeded.
  90207. *
  90208. * \param decoder An uninitialized decoder instance.
  90209. * \param filename The name of the file to decode from. The file will
  90210. * be opened with fopen(). Use \c NULL to decode from
  90211. * \c stdin. Note that \c stdin is not seekable.
  90212. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90213. * pointer must not be \c NULL.
  90214. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90215. * pointer may be \c NULL if the callback is not
  90216. * desired.
  90217. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90218. * pointer must not be \c NULL.
  90219. * \param client_data This value will be supplied to callbacks in their
  90220. * \a client_data argument.
  90221. * \assert
  90222. * \code decoder != NULL \endcode
  90223. * \retval FLAC__StreamDecoderInitStatus
  90224. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90225. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90226. */
  90227. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90228. FLAC__StreamDecoder *decoder,
  90229. const char *filename,
  90230. FLAC__StreamDecoderWriteCallback write_callback,
  90231. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90232. FLAC__StreamDecoderErrorCallback error_callback,
  90233. void *client_data
  90234. );
  90235. /** Initialize the decoder instance to decode Ogg FLAC files.
  90236. *
  90237. * This flavor of initialization sets up the decoder to decode from a plain
  90238. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90239. * example, with Unicode filenames on Windows), you must use
  90240. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90241. * and provide callbacks for the I/O.
  90242. *
  90243. * This function should be called after FLAC__stream_decoder_new() and
  90244. * FLAC__stream_decoder_set_*() but before any of the
  90245. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90246. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90247. * if initialization succeeded.
  90248. *
  90249. * \note Support for Ogg FLAC in the library is optional. If this
  90250. * library has been built without support for Ogg FLAC, this function
  90251. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90252. *
  90253. * \param decoder An uninitialized decoder instance.
  90254. * \param filename The name of the file to decode from. The file will
  90255. * be opened with fopen(). Use \c NULL to decode from
  90256. * \c stdin. Note that \c stdin is not seekable.
  90257. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90258. * pointer must not be \c NULL.
  90259. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90260. * pointer may be \c NULL if the callback is not
  90261. * desired.
  90262. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90263. * pointer must not be \c NULL.
  90264. * \param client_data This value will be supplied to callbacks in their
  90265. * \a client_data argument.
  90266. * \assert
  90267. * \code decoder != NULL \endcode
  90268. * \retval FLAC__StreamDecoderInitStatus
  90269. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90270. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90271. */
  90272. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90273. FLAC__StreamDecoder *decoder,
  90274. const char *filename,
  90275. FLAC__StreamDecoderWriteCallback write_callback,
  90276. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90277. FLAC__StreamDecoderErrorCallback error_callback,
  90278. void *client_data
  90279. );
  90280. /** Finish the decoding process.
  90281. * Flushes the decoding buffer, releases resources, resets the decoder
  90282. * settings to their defaults, and returns the decoder state to
  90283. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90284. *
  90285. * In the event of a prematurely-terminated decode, it is not strictly
  90286. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90287. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90288. * with a FLAC__stream_decoder_finish().
  90289. *
  90290. * \param decoder An uninitialized decoder instance.
  90291. * \assert
  90292. * \code decoder != NULL \endcode
  90293. * \retval FLAC__bool
  90294. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90295. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90296. * signature does not match the one computed by the decoder; else
  90297. * \c true.
  90298. */
  90299. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90300. /** Flush the stream input.
  90301. * The decoder's input buffer will be cleared and the state set to
  90302. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90303. * off MD5 checking.
  90304. *
  90305. * \param decoder A decoder instance.
  90306. * \assert
  90307. * \code decoder != NULL \endcode
  90308. * \retval FLAC__bool
  90309. * \c true if successful, else \c false if a memory allocation
  90310. * error occurs (in which case the state will be set to
  90311. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90312. */
  90313. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90314. /** Reset the decoding process.
  90315. * The decoder's input buffer will be cleared and the state set to
  90316. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90317. * FLAC__stream_decoder_finish() except that the settings are
  90318. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90319. * before decoding again. MD5 checking will be restored to its original
  90320. * setting.
  90321. *
  90322. * If the decoder is seekable, or was initialized with
  90323. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90324. * the decoder will also attempt to seek to the beginning of the file.
  90325. * If this rewind fails, this function will return \c false. It follows
  90326. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90327. * \c stdin.
  90328. *
  90329. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90330. * and is not seekable (i.e. no seek callback was provided or the seek
  90331. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90332. * is the duty of the client to start feeding data from the beginning of
  90333. * the stream on the next FLAC__stream_decoder_process() or
  90334. * FLAC__stream_decoder_process_interleaved() call.
  90335. *
  90336. * \param decoder A decoder instance.
  90337. * \assert
  90338. * \code decoder != NULL \endcode
  90339. * \retval FLAC__bool
  90340. * \c true if successful, else \c false if a memory allocation occurs
  90341. * (in which case the state will be set to
  90342. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90343. * occurs (the state will be unchanged).
  90344. */
  90345. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90346. /** Decode one metadata block or audio frame.
  90347. * This version instructs the decoder to decode a either a single metadata
  90348. * block or a single frame and stop, unless the callbacks return a fatal
  90349. * error or the read callback returns
  90350. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90351. *
  90352. * As the decoder needs more input it will call the read callback.
  90353. * Depending on what was decoded, the metadata or write callback will be
  90354. * called with the decoded metadata block or audio frame.
  90355. *
  90356. * Unless there is a fatal read error or end of stream, this function
  90357. * will return once one whole frame is decoded. In other words, if the
  90358. * stream is not synchronized or points to a corrupt frame header, the
  90359. * decoder will continue to try and resync until it gets to a valid
  90360. * frame, then decode one frame, then return. If the decoder points to
  90361. * a frame whose frame CRC in the frame footer does not match the
  90362. * computed frame CRC, this function will issue a
  90363. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90364. * error callback, and return, having decoded one complete, although
  90365. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90366. * correct length to the write callback.)
  90367. *
  90368. * \param decoder An initialized decoder instance.
  90369. * \assert
  90370. * \code decoder != NULL \endcode
  90371. * \retval FLAC__bool
  90372. * \c false if any fatal read, write, or memory allocation error
  90373. * occurred (meaning decoding must stop), else \c true; for more
  90374. * information about the decoder, check the decoder state with
  90375. * FLAC__stream_decoder_get_state().
  90376. */
  90377. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90378. /** Decode until the end of the metadata.
  90379. * This version instructs the decoder to decode from the current position
  90380. * and continue until all the metadata has been read, or until the
  90381. * callbacks return a fatal error or the read callback returns
  90382. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90383. *
  90384. * As the decoder needs more input it will call the read callback.
  90385. * As each metadata block is decoded, the metadata callback will be called
  90386. * with the decoded metadata.
  90387. *
  90388. * \param decoder An initialized decoder instance.
  90389. * \assert
  90390. * \code decoder != NULL \endcode
  90391. * \retval FLAC__bool
  90392. * \c false if any fatal read, write, or memory allocation error
  90393. * occurred (meaning decoding must stop), else \c true; for more
  90394. * information about the decoder, check the decoder state with
  90395. * FLAC__stream_decoder_get_state().
  90396. */
  90397. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90398. /** Decode until the end of the stream.
  90399. * This version instructs the decoder to decode from the current position
  90400. * and continue until the end of stream (the read callback returns
  90401. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90402. * callbacks return a fatal error.
  90403. *
  90404. * As the decoder needs more input it will call the read callback.
  90405. * As each metadata block and frame is decoded, the metadata or write
  90406. * callback will be called with the decoded metadata or frame.
  90407. *
  90408. * \param decoder An initialized decoder instance.
  90409. * \assert
  90410. * \code decoder != NULL \endcode
  90411. * \retval FLAC__bool
  90412. * \c false if any fatal read, write, or memory allocation error
  90413. * occurred (meaning decoding must stop), else \c true; for more
  90414. * information about the decoder, check the decoder state with
  90415. * FLAC__stream_decoder_get_state().
  90416. */
  90417. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90418. /** Skip one audio frame.
  90419. * This version instructs the decoder to 'skip' a single frame and stop,
  90420. * unless the callbacks return a fatal error or the read callback returns
  90421. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90422. *
  90423. * The decoding flow is the same as what occurs when
  90424. * FLAC__stream_decoder_process_single() is called to process an audio
  90425. * frame, except that this function does not decode the parsed data into
  90426. * PCM or call the write callback. The integrity of the frame is still
  90427. * checked the same way as in the other process functions.
  90428. *
  90429. * This function will return once one whole frame is skipped, in the
  90430. * same way that FLAC__stream_decoder_process_single() will return once
  90431. * one whole frame is decoded.
  90432. *
  90433. * This function can be used in more quickly determining FLAC frame
  90434. * boundaries when decoding of the actual data is not needed, for
  90435. * example when an application is separating a FLAC stream into frames
  90436. * for editing or storing in a container. To do this, the application
  90437. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90438. * to the next frame, then use
  90439. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90440. * boundary.
  90441. *
  90442. * This function should only be called when the stream has advanced
  90443. * past all the metadata, otherwise it will return \c false.
  90444. *
  90445. * \param decoder An initialized decoder instance not in a metadata
  90446. * state.
  90447. * \assert
  90448. * \code decoder != NULL \endcode
  90449. * \retval FLAC__bool
  90450. * \c false if any fatal read, write, or memory allocation error
  90451. * occurred (meaning decoding must stop), or if the decoder
  90452. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90453. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90454. * information about the decoder, check the decoder state with
  90455. * FLAC__stream_decoder_get_state().
  90456. */
  90457. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90458. /** Flush the input and seek to an absolute sample.
  90459. * Decoding will resume at the given sample. Note that because of
  90460. * this, the next write callback may contain a partial block. The
  90461. * client must support seeking the input or this function will fail
  90462. * and return \c false. Furthermore, if the decoder state is
  90463. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90464. * with FLAC__stream_decoder_flush() or reset with
  90465. * FLAC__stream_decoder_reset() before decoding can continue.
  90466. *
  90467. * \param decoder A decoder instance.
  90468. * \param sample The target sample number to seek to.
  90469. * \assert
  90470. * \code decoder != NULL \endcode
  90471. * \retval FLAC__bool
  90472. * \c true if successful, else \c false.
  90473. */
  90474. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90475. /* \} */
  90476. #ifdef __cplusplus
  90477. }
  90478. #endif
  90479. #endif
  90480. /*** End of inlined file: stream_decoder.h ***/
  90481. /*** Start of inlined file: stream_encoder.h ***/
  90482. #ifndef FLAC__STREAM_ENCODER_H
  90483. #define FLAC__STREAM_ENCODER_H
  90484. #include <stdio.h> /* for FILE */
  90485. #ifdef __cplusplus
  90486. extern "C" {
  90487. #endif
  90488. /** \file include/FLAC/stream_encoder.h
  90489. *
  90490. * \brief
  90491. * This module contains the functions which implement the stream
  90492. * encoder.
  90493. *
  90494. * See the detailed documentation in the
  90495. * \link flac_stream_encoder stream encoder \endlink module.
  90496. */
  90497. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90498. * \ingroup flac
  90499. *
  90500. * \brief
  90501. * This module describes the encoder layers provided by libFLAC.
  90502. *
  90503. * The stream encoder can be used to encode complete streams either to the
  90504. * client via callbacks, or directly to a file, depending on how it is
  90505. * initialized. When encoding via callbacks, the client provides a write
  90506. * callback which will be called whenever FLAC data is ready to be written.
  90507. * If the client also supplies a seek callback, the encoder will also
  90508. * automatically handle the writing back of metadata discovered while
  90509. * encoding, like stream info, seek points offsets, etc. When encoding to
  90510. * a file, the client needs only supply a filename or open \c FILE* and an
  90511. * optional progress callback for periodic notification of progress; the
  90512. * write and seek callbacks are supplied internally. For more info see the
  90513. * \link flac_stream_encoder stream encoder \endlink module.
  90514. */
  90515. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90516. * \ingroup flac_encoder
  90517. *
  90518. * \brief
  90519. * This module contains the functions which implement the stream
  90520. * encoder.
  90521. *
  90522. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90523. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90524. *
  90525. * The basic usage of this encoder is as follows:
  90526. * - The program creates an instance of an encoder using
  90527. * FLAC__stream_encoder_new().
  90528. * - The program overrides the default settings using
  90529. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90530. * functions should be called:
  90531. * - FLAC__stream_encoder_set_channels()
  90532. * - FLAC__stream_encoder_set_bits_per_sample()
  90533. * - FLAC__stream_encoder_set_sample_rate()
  90534. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90535. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90536. * - If the application wants to control the compression level or set its own
  90537. * metadata, then the following should also be called:
  90538. * - FLAC__stream_encoder_set_compression_level()
  90539. * - FLAC__stream_encoder_set_verify()
  90540. * - FLAC__stream_encoder_set_metadata()
  90541. * - The rest of the set functions should only be called if the client needs
  90542. * exact control over how the audio is compressed; thorough understanding
  90543. * of the FLAC format is necessary to achieve good results.
  90544. * - The program initializes the instance to validate the settings and
  90545. * prepare for encoding using
  90546. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90547. * or FLAC__stream_encoder_init_file() for native FLAC
  90548. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90549. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90550. * - The program calls FLAC__stream_encoder_process() or
  90551. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90552. * subsequently calls the callbacks when there is encoder data ready
  90553. * to be written.
  90554. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90555. * which causes the encoder to encode any data still in its input pipe,
  90556. * update the metadata with the final encoding statistics if output
  90557. * seeking is possible, and finally reset the encoder to the
  90558. * uninitialized state.
  90559. * - The instance may be used again or deleted with
  90560. * FLAC__stream_encoder_delete().
  90561. *
  90562. * In more detail, the stream encoder functions similarly to the
  90563. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90564. * callbacks and more options. Typically the client will create a new
  90565. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90566. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90567. * calling one of the FLAC__stream_encoder_init_*() functions.
  90568. *
  90569. * Unlike the decoders, the stream encoder has many options that can
  90570. * affect the speed and compression ratio. When setting these parameters
  90571. * you should have some basic knowledge of the format (see the
  90572. * <A HREF="../documentation.html#format">user-level documentation</A>
  90573. * or the <A HREF="../format.html">formal description</A>). The
  90574. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90575. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90576. * functions will do this, so make sure to pay attention to the state
  90577. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90578. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90579. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90580. * the constructor.
  90581. *
  90582. * There are three initialization functions for native FLAC, one for
  90583. * setting up the encoder to encode FLAC data to the client via
  90584. * callbacks, and two for encoding directly to a file.
  90585. *
  90586. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90587. * You must also supply a write callback which will be called anytime
  90588. * there is raw encoded data to write. If the client can seek the output
  90589. * it is best to also supply seek and tell callbacks, as this allows the
  90590. * encoder to go back after encoding is finished to write back
  90591. * information that was collected while encoding, like seek point offsets,
  90592. * frame sizes, etc.
  90593. *
  90594. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90595. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90596. * filename or open \c FILE*; the encoder will handle all the callbacks
  90597. * internally. You may also supply a progress callback for periodic
  90598. * notification of the encoding progress.
  90599. *
  90600. * There are three similarly-named init functions for encoding to Ogg
  90601. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90602. * library has been built with Ogg support.
  90603. *
  90604. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90605. * call the write callback several times, once with the \c fLaC signature,
  90606. * and once for each encoded metadata block. Note that for Ogg FLAC
  90607. * encoding you will usually get at least twice the number of callbacks than
  90608. * with native FLAC, one for the Ogg page header and one for the page body.
  90609. *
  90610. * After initializing the instance, the client may feed audio data to the
  90611. * encoder in one of two ways:
  90612. *
  90613. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90614. * will pass an array of pointers to buffers, one for each channel, to
  90615. * the encoder, each of the same length. The samples need not be
  90616. * block-aligned, but each channel should have the same number of samples.
  90617. * - Channel interleaved, through
  90618. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90619. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90620. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90621. * Again, the samples need not be block-aligned but they must be
  90622. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90623. * the last value channelN_sampleM.
  90624. *
  90625. * Note that for either process call, each sample in the buffers should be a
  90626. * signed integer, right-justified to the resolution set by
  90627. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90628. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90629. *
  90630. * When the client is finished encoding data, it calls
  90631. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90632. * data still in its input pipe, and call the metadata callback with the
  90633. * final encoding statistics. Then the instance may be deleted with
  90634. * FLAC__stream_encoder_delete() or initialized again to encode another
  90635. * stream.
  90636. *
  90637. * For programs that write their own metadata, but that do not know the
  90638. * actual metadata until after encoding, it is advantageous to instruct
  90639. * the encoder to write a PADDING block of the correct size, so that
  90640. * instead of rewriting the whole stream after encoding, the program can
  90641. * just overwrite the PADDING block. If only the maximum size of the
  90642. * metadata is known, the program can write a slightly larger padding
  90643. * block, then split it after encoding.
  90644. *
  90645. * Make sure you understand how lengths are calculated. All FLAC metadata
  90646. * blocks have a 4 byte header which contains the type and length. This
  90647. * length does not include the 4 bytes of the header. See the format page
  90648. * for the specification of metadata blocks and their lengths.
  90649. *
  90650. * \note
  90651. * If you are writing the FLAC data to a file via callbacks, make sure it
  90652. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90653. * after the first encoding pass, the encoder will try to seek back to the
  90654. * beginning of the stream, to the STREAMINFO block, to write some data
  90655. * there. (If using FLAC__stream_encoder_init*_file() or
  90656. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90657. *
  90658. * \note
  90659. * The "set" functions may only be called when the encoder is in the
  90660. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90661. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90662. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90663. * return \c true, otherwise \c false.
  90664. *
  90665. * \note
  90666. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90667. * defaults.
  90668. *
  90669. * \{
  90670. */
  90671. /** State values for a FLAC__StreamEncoder.
  90672. *
  90673. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90674. *
  90675. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90676. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90677. * must be deleted with FLAC__stream_encoder_delete().
  90678. */
  90679. typedef enum {
  90680. FLAC__STREAM_ENCODER_OK = 0,
  90681. /**< The encoder is in the normal OK state and samples can be processed. */
  90682. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90683. /**< The encoder is in the uninitialized state; one of the
  90684. * FLAC__stream_encoder_init_*() functions must be called before samples
  90685. * can be processed.
  90686. */
  90687. FLAC__STREAM_ENCODER_OGG_ERROR,
  90688. /**< An error occurred in the underlying Ogg layer. */
  90689. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90690. /**< An error occurred in the underlying verify stream decoder;
  90691. * check FLAC__stream_encoder_get_verify_decoder_state().
  90692. */
  90693. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90694. /**< The verify decoder detected a mismatch between the original
  90695. * audio signal and the decoded audio signal.
  90696. */
  90697. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90698. /**< One of the callbacks returned a fatal error. */
  90699. FLAC__STREAM_ENCODER_IO_ERROR,
  90700. /**< An I/O error occurred while opening/reading/writing a file.
  90701. * Check \c errno.
  90702. */
  90703. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90704. /**< An error occurred while writing the stream; usually, the
  90705. * write_callback returned an error.
  90706. */
  90707. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90708. /**< Memory allocation failed. */
  90709. } FLAC__StreamEncoderState;
  90710. /** Maps a FLAC__StreamEncoderState to a C string.
  90711. *
  90712. * Using a FLAC__StreamEncoderState as the index to this array
  90713. * will give the string equivalent. The contents should not be modified.
  90714. */
  90715. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90716. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90717. */
  90718. typedef enum {
  90719. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90720. /**< Initialization was successful. */
  90721. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90722. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90723. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90724. /**< The library was not compiled with support for the given container
  90725. * format.
  90726. */
  90727. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90728. /**< A required callback was not supplied. */
  90729. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90730. /**< The encoder has an invalid setting for number of channels. */
  90731. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90732. /**< The encoder has an invalid setting for bits-per-sample.
  90733. * FLAC supports 4-32 bps but the reference encoder currently supports
  90734. * only up to 24 bps.
  90735. */
  90736. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90737. /**< The encoder has an invalid setting for the input sample rate. */
  90738. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90739. /**< The encoder has an invalid setting for the block size. */
  90740. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90741. /**< The encoder has an invalid setting for the maximum LPC order. */
  90742. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90743. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90744. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90745. /**< The specified block size is less than the maximum LPC order. */
  90746. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90747. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90748. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90749. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90750. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90751. * - One of the metadata blocks contains an undefined type
  90752. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90753. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90754. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90755. */
  90756. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90757. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90758. * already initialized, usually because
  90759. * FLAC__stream_encoder_finish() was not called.
  90760. */
  90761. } FLAC__StreamEncoderInitStatus;
  90762. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90763. *
  90764. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90765. * will give the string equivalent. The contents should not be modified.
  90766. */
  90767. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90768. /** Return values for the FLAC__StreamEncoder read callback.
  90769. */
  90770. typedef enum {
  90771. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90772. /**< The read was OK and decoding can continue. */
  90773. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90774. /**< The read was attempted at the end of the stream. */
  90775. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90776. /**< An unrecoverable error occurred. */
  90777. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90778. /**< Client does not support reading back from the output. */
  90779. } FLAC__StreamEncoderReadStatus;
  90780. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90781. *
  90782. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90783. * will give the string equivalent. The contents should not be modified.
  90784. */
  90785. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90786. /** Return values for the FLAC__StreamEncoder write callback.
  90787. */
  90788. typedef enum {
  90789. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90790. /**< The write was OK and encoding can continue. */
  90791. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90792. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90793. } FLAC__StreamEncoderWriteStatus;
  90794. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90795. *
  90796. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90797. * will give the string equivalent. The contents should not be modified.
  90798. */
  90799. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90800. /** Return values for the FLAC__StreamEncoder seek callback.
  90801. */
  90802. typedef enum {
  90803. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90804. /**< The seek was OK and encoding can continue. */
  90805. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90806. /**< An unrecoverable error occurred. */
  90807. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90808. /**< Client does not support seeking. */
  90809. } FLAC__StreamEncoderSeekStatus;
  90810. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90811. *
  90812. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90813. * will give the string equivalent. The contents should not be modified.
  90814. */
  90815. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90816. /** Return values for the FLAC__StreamEncoder tell callback.
  90817. */
  90818. typedef enum {
  90819. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90820. /**< The tell was OK and encoding can continue. */
  90821. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90822. /**< An unrecoverable error occurred. */
  90823. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90824. /**< Client does not support seeking. */
  90825. } FLAC__StreamEncoderTellStatus;
  90826. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90827. *
  90828. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90829. * will give the string equivalent. The contents should not be modified.
  90830. */
  90831. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90832. /***********************************************************************
  90833. *
  90834. * class FLAC__StreamEncoder
  90835. *
  90836. ***********************************************************************/
  90837. struct FLAC__StreamEncoderProtected;
  90838. struct FLAC__StreamEncoderPrivate;
  90839. /** The opaque structure definition for the stream encoder type.
  90840. * See the \link flac_stream_encoder stream encoder module \endlink
  90841. * for a detailed description.
  90842. */
  90843. typedef struct {
  90844. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90845. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90846. } FLAC__StreamEncoder;
  90847. /** Signature for the read callback.
  90848. *
  90849. * A function pointer matching this signature must be passed to
  90850. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90851. * The supplied function will be called when the encoder needs to read back
  90852. * encoded data. This happens during the metadata callback, when the encoder
  90853. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90854. * while encoding. The address of the buffer to be filled is supplied, along
  90855. * with the number of bytes the buffer can hold. The callback may choose to
  90856. * supply less data and modify the byte count but must be careful not to
  90857. * overflow the buffer. The callback then returns a status code chosen from
  90858. * FLAC__StreamEncoderReadStatus.
  90859. *
  90860. * Here is an example of a read callback for stdio streams:
  90861. * \code
  90862. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90863. * {
  90864. * FILE *file = ((MyClientData*)client_data)->file;
  90865. * if(*bytes > 0) {
  90866. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90867. * if(ferror(file))
  90868. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90869. * else if(*bytes == 0)
  90870. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90871. * else
  90872. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90873. * }
  90874. * else
  90875. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90876. * }
  90877. * \endcode
  90878. *
  90879. * \note In general, FLAC__StreamEncoder functions which change the
  90880. * state should not be called on the \a encoder while in the callback.
  90881. *
  90882. * \param encoder The encoder instance calling the callback.
  90883. * \param buffer A pointer to a location for the callee to store
  90884. * data to be encoded.
  90885. * \param bytes A pointer to the size of the buffer. On entry
  90886. * to the callback, it contains the maximum number
  90887. * of bytes that may be stored in \a buffer. The
  90888. * callee must set it to the actual number of bytes
  90889. * stored (0 in case of error or end-of-stream) before
  90890. * returning.
  90891. * \param client_data The callee's client data set through
  90892. * FLAC__stream_encoder_set_client_data().
  90893. * \retval FLAC__StreamEncoderReadStatus
  90894. * The callee's return status.
  90895. */
  90896. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90897. /** Signature for the write callback.
  90898. *
  90899. * A function pointer matching this signature must be passed to
  90900. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90901. * by the encoder anytime there is raw encoded data ready to write. It may
  90902. * include metadata mixed with encoded audio frames and the data is not
  90903. * guaranteed to be aligned on frame or metadata block boundaries.
  90904. *
  90905. * The only duty of the callback is to write out the \a bytes worth of data
  90906. * in \a buffer to the current position in the output stream. The arguments
  90907. * \a samples and \a current_frame are purely informational. If \a samples
  90908. * is greater than \c 0, then \a current_frame will hold the current frame
  90909. * number that is being written; otherwise it indicates that the write
  90910. * callback is being called to write metadata.
  90911. *
  90912. * \note
  90913. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90914. * write callback will be called twice when writing each audio
  90915. * frame; once for the page header, and once for the page body.
  90916. * When writing the page header, the \a samples argument to the
  90917. * write callback will be \c 0.
  90918. *
  90919. * \note In general, FLAC__StreamEncoder functions which change the
  90920. * state should not be called on the \a encoder while in the callback.
  90921. *
  90922. * \param encoder The encoder instance calling the callback.
  90923. * \param buffer An array of encoded data of length \a bytes.
  90924. * \param bytes The byte length of \a buffer.
  90925. * \param samples The number of samples encoded by \a buffer.
  90926. * \c 0 has a special meaning; see above.
  90927. * \param current_frame The number of the current frame being encoded.
  90928. * \param client_data The callee's client data set through
  90929. * FLAC__stream_encoder_init_*().
  90930. * \retval FLAC__StreamEncoderWriteStatus
  90931. * The callee's return status.
  90932. */
  90933. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90934. /** Signature for the seek callback.
  90935. *
  90936. * A function pointer matching this signature may be passed to
  90937. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90938. * when the encoder needs to seek the output stream. The encoder will pass
  90939. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90940. *
  90941. * Here is an example of a seek callback for stdio streams:
  90942. * \code
  90943. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90944. * {
  90945. * FILE *file = ((MyClientData*)client_data)->file;
  90946. * if(file == stdin)
  90947. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90948. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90949. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90950. * else
  90951. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90952. * }
  90953. * \endcode
  90954. *
  90955. * \note In general, FLAC__StreamEncoder functions which change the
  90956. * state should not be called on the \a encoder while in the callback.
  90957. *
  90958. * \param encoder The encoder instance calling the callback.
  90959. * \param absolute_byte_offset The offset from the beginning of the stream
  90960. * to seek to.
  90961. * \param client_data The callee's client data set through
  90962. * FLAC__stream_encoder_init_*().
  90963. * \retval FLAC__StreamEncoderSeekStatus
  90964. * The callee's return status.
  90965. */
  90966. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90967. /** Signature for the tell callback.
  90968. *
  90969. * A function pointer matching this signature may be passed to
  90970. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90971. * when the encoder needs to know the current position of the output stream.
  90972. *
  90973. * \warning
  90974. * The callback must return the true current byte offset of the output to
  90975. * which the encoder is writing. If you are buffering the output, make
  90976. * sure and take this into account. If you are writing directly to a
  90977. * FILE* from your write callback, ftell() is sufficient. If you are
  90978. * writing directly to a file descriptor from your write callback, you
  90979. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90980. * these points to rewrite metadata after encoding.
  90981. *
  90982. * Here is an example of a tell callback for stdio streams:
  90983. * \code
  90984. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90985. * {
  90986. * FILE *file = ((MyClientData*)client_data)->file;
  90987. * off_t pos;
  90988. * if(file == stdin)
  90989. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90990. * else if((pos = ftello(file)) < 0)
  90991. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90992. * else {
  90993. * *absolute_byte_offset = (FLAC__uint64)pos;
  90994. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90995. * }
  90996. * }
  90997. * \endcode
  90998. *
  90999. * \note In general, FLAC__StreamEncoder functions which change the
  91000. * state should not be called on the \a encoder while in the callback.
  91001. *
  91002. * \param encoder The encoder instance calling the callback.
  91003. * \param absolute_byte_offset The address at which to store the current
  91004. * position of the output.
  91005. * \param client_data The callee's client data set through
  91006. * FLAC__stream_encoder_init_*().
  91007. * \retval FLAC__StreamEncoderTellStatus
  91008. * The callee's return status.
  91009. */
  91010. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91011. /** Signature for the metadata callback.
  91012. *
  91013. * A function pointer matching this signature may be passed to
  91014. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91015. * once at the end of encoding with the populated STREAMINFO structure. This
  91016. * is so the client can seek back to the beginning of the file and write the
  91017. * STREAMINFO block with the correct statistics after encoding (like
  91018. * minimum/maximum frame size and total samples).
  91019. *
  91020. * \note In general, FLAC__StreamEncoder functions which change the
  91021. * state should not be called on the \a encoder while in the callback.
  91022. *
  91023. * \param encoder The encoder instance calling the callback.
  91024. * \param metadata The final populated STREAMINFO block.
  91025. * \param client_data The callee's client data set through
  91026. * FLAC__stream_encoder_init_*().
  91027. */
  91028. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91029. /** Signature for the progress callback.
  91030. *
  91031. * A function pointer matching this signature may be passed to
  91032. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91033. * The supplied function will be called when the encoder has finished
  91034. * writing a frame. The \c total_frames_estimate argument to the
  91035. * callback will be based on the value from
  91036. * FLAC__stream_encoder_set_total_samples_estimate().
  91037. *
  91038. * \note In general, FLAC__StreamEncoder functions which change the
  91039. * state should not be called on the \a encoder while in the callback.
  91040. *
  91041. * \param encoder The encoder instance calling the callback.
  91042. * \param bytes_written Bytes written so far.
  91043. * \param samples_written Samples written so far.
  91044. * \param frames_written Frames written so far.
  91045. * \param total_frames_estimate The estimate of the total number of
  91046. * frames to be written.
  91047. * \param client_data The callee's client data set through
  91048. * FLAC__stream_encoder_init_*().
  91049. */
  91050. 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);
  91051. /***********************************************************************
  91052. *
  91053. * Class constructor/destructor
  91054. *
  91055. ***********************************************************************/
  91056. /** Create a new stream encoder instance. The instance is created with
  91057. * default settings; see the individual FLAC__stream_encoder_set_*()
  91058. * functions for each setting's default.
  91059. *
  91060. * \retval FLAC__StreamEncoder*
  91061. * \c NULL if there was an error allocating memory, else the new instance.
  91062. */
  91063. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91064. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91065. *
  91066. * \param encoder A pointer to an existing encoder.
  91067. * \assert
  91068. * \code encoder != NULL \endcode
  91069. */
  91070. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91071. /***********************************************************************
  91072. *
  91073. * Public class method prototypes
  91074. *
  91075. ***********************************************************************/
  91076. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91077. *
  91078. * \note
  91079. * This does not need to be set for native FLAC encoding.
  91080. *
  91081. * \note
  91082. * It is recommended to set a serial number explicitly as the default of '0'
  91083. * may collide with other streams.
  91084. *
  91085. * \default \c 0
  91086. * \param encoder An encoder instance to set.
  91087. * \param serial_number See above.
  91088. * \assert
  91089. * \code encoder != NULL \endcode
  91090. * \retval FLAC__bool
  91091. * \c false if the encoder is already initialized, else \c true.
  91092. */
  91093. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91094. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91095. * encoded output by feeding it through an internal decoder and comparing
  91096. * the original signal against the decoded signal. If a mismatch occurs,
  91097. * the process call will return \c false. Note that this will slow the
  91098. * encoding process by the extra time required for decoding and comparison.
  91099. *
  91100. * \default \c false
  91101. * \param encoder An encoder instance to set.
  91102. * \param value Flag value (see above).
  91103. * \assert
  91104. * \code encoder != NULL \endcode
  91105. * \retval FLAC__bool
  91106. * \c false if the encoder is already initialized, else \c true.
  91107. */
  91108. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91109. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91110. * the encoder will comply with the Subset and will check the
  91111. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91112. * comply. If \c false, the settings may take advantage of the full
  91113. * range that the format allows.
  91114. *
  91115. * Make sure you know what it entails before setting this to \c false.
  91116. *
  91117. * \default \c true
  91118. * \param encoder An encoder instance to set.
  91119. * \param value Flag value (see above).
  91120. * \assert
  91121. * \code encoder != NULL \endcode
  91122. * \retval FLAC__bool
  91123. * \c false if the encoder is already initialized, else \c true.
  91124. */
  91125. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91126. /** Set the number of channels to be encoded.
  91127. *
  91128. * \default \c 2
  91129. * \param encoder An encoder instance to set.
  91130. * \param value See above.
  91131. * \assert
  91132. * \code encoder != NULL \endcode
  91133. * \retval FLAC__bool
  91134. * \c false if the encoder is already initialized, else \c true.
  91135. */
  91136. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91137. /** Set the sample resolution of the input to be encoded.
  91138. *
  91139. * \warning
  91140. * Do not feed the encoder data that is wider than the value you
  91141. * set here or you will generate an invalid stream.
  91142. *
  91143. * \default \c 16
  91144. * \param encoder An encoder instance to set.
  91145. * \param value See above.
  91146. * \assert
  91147. * \code encoder != NULL \endcode
  91148. * \retval FLAC__bool
  91149. * \c false if the encoder is already initialized, else \c true.
  91150. */
  91151. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91152. /** Set the sample rate (in Hz) of the input to be encoded.
  91153. *
  91154. * \default \c 44100
  91155. * \param encoder An encoder instance to set.
  91156. * \param value See above.
  91157. * \assert
  91158. * \code encoder != NULL \endcode
  91159. * \retval FLAC__bool
  91160. * \c false if the encoder is already initialized, else \c true.
  91161. */
  91162. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91163. /** Set the compression level
  91164. *
  91165. * The compression level is roughly proportional to the amount of effort
  91166. * the encoder expends to compress the file. A higher level usually
  91167. * means more computation but higher compression. The default level is
  91168. * suitable for most applications.
  91169. *
  91170. * Currently the levels range from \c 0 (fastest, least compression) to
  91171. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91172. * treated as \c 8.
  91173. *
  91174. * This function automatically calls the following other \c _set_
  91175. * functions with appropriate values, so the client does not need to
  91176. * unless it specifically wants to override them:
  91177. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91178. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91179. * - FLAC__stream_encoder_set_apodization()
  91180. * - FLAC__stream_encoder_set_max_lpc_order()
  91181. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91182. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91183. * - FLAC__stream_encoder_set_do_escape_coding()
  91184. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91185. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91186. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91187. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91188. *
  91189. * The actual values set for each level are:
  91190. * <table>
  91191. * <tr>
  91192. * <td><b>level</b><td>
  91193. * <td>do mid-side stereo<td>
  91194. * <td>loose mid-side stereo<td>
  91195. * <td>apodization<td>
  91196. * <td>max lpc order<td>
  91197. * <td>qlp coeff precision<td>
  91198. * <td>qlp coeff prec search<td>
  91199. * <td>escape coding<td>
  91200. * <td>exhaustive model search<td>
  91201. * <td>min residual partition order<td>
  91202. * <td>max residual partition order<td>
  91203. * <td>rice parameter search dist<td>
  91204. * </tr>
  91205. * <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>
  91206. * <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>
  91207. * <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>
  91208. * <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>
  91209. * <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>
  91210. * <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>
  91211. * <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>
  91212. * <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>
  91213. * <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>
  91214. * </table>
  91215. *
  91216. * \default \c 5
  91217. * \param encoder An encoder instance to set.
  91218. * \param value See above.
  91219. * \assert
  91220. * \code encoder != NULL \endcode
  91221. * \retval FLAC__bool
  91222. * \c false if the encoder is already initialized, else \c true.
  91223. */
  91224. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91225. /** Set the blocksize to use while encoding.
  91226. *
  91227. * The number of samples to use per frame. Use \c 0 to let the encoder
  91228. * estimate a blocksize; this is usually best.
  91229. *
  91230. * \default \c 0
  91231. * \param encoder An encoder instance to set.
  91232. * \param value See above.
  91233. * \assert
  91234. * \code encoder != NULL \endcode
  91235. * \retval FLAC__bool
  91236. * \c false if the encoder is already initialized, else \c true.
  91237. */
  91238. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91239. /** Set to \c true to enable mid-side encoding on stereo input. The
  91240. * number of channels must be 2 for this to have any effect. Set to
  91241. * \c false to use only independent channel coding.
  91242. *
  91243. * \default \c false
  91244. * \param encoder An encoder instance to set.
  91245. * \param value Flag value (see above).
  91246. * \assert
  91247. * \code encoder != NULL \endcode
  91248. * \retval FLAC__bool
  91249. * \c false if the encoder is already initialized, else \c true.
  91250. */
  91251. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91252. /** Set to \c true to enable adaptive switching between mid-side and
  91253. * left-right encoding on stereo input. Set to \c false to use
  91254. * exhaustive searching. Setting this to \c true requires
  91255. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91256. * \c true in order to have any effect.
  91257. *
  91258. * \default \c false
  91259. * \param encoder An encoder instance to set.
  91260. * \param value Flag value (see above).
  91261. * \assert
  91262. * \code encoder != NULL \endcode
  91263. * \retval FLAC__bool
  91264. * \c false if the encoder is already initialized, else \c true.
  91265. */
  91266. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91267. /** Sets the apodization function(s) the encoder will use when windowing
  91268. * audio data for LPC analysis.
  91269. *
  91270. * The \a specification is a plain ASCII string which specifies exactly
  91271. * which functions to use. There may be more than one (up to 32),
  91272. * separated by \c ';' characters. Some functions take one or more
  91273. * comma-separated arguments in parentheses.
  91274. *
  91275. * The available functions are \c bartlett, \c bartlett_hann,
  91276. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91277. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91278. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91279. *
  91280. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91281. * (0<STDDEV<=0.5).
  91282. *
  91283. * For \c tukey(P), P specifies the fraction of the window that is
  91284. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91285. * corresponds to \c hann.
  91286. *
  91287. * Example specifications are \c "blackman" or
  91288. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91289. *
  91290. * Any function that is specified erroneously is silently dropped. Up
  91291. * to 32 functions are kept, the rest are dropped. If the specification
  91292. * is empty the encoder defaults to \c "tukey(0.5)".
  91293. *
  91294. * When more than one function is specified, then for every subframe the
  91295. * encoder will try each of them separately and choose the window that
  91296. * results in the smallest compressed subframe.
  91297. *
  91298. * Note that each function specified causes the encoder to occupy a
  91299. * floating point array in which to store the window.
  91300. *
  91301. * \default \c "tukey(0.5)"
  91302. * \param encoder An encoder instance to set.
  91303. * \param specification See above.
  91304. * \assert
  91305. * \code encoder != NULL \endcode
  91306. * \code specification != NULL \endcode
  91307. * \retval FLAC__bool
  91308. * \c false if the encoder is already initialized, else \c true.
  91309. */
  91310. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91311. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91312. *
  91313. * \default \c 0
  91314. * \param encoder An encoder instance to set.
  91315. * \param value 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_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91322. /** Set the precision, in bits, of the quantized linear predictor
  91323. * coefficients, or \c 0 to let the encoder select it based on the
  91324. * blocksize.
  91325. *
  91326. * \note
  91327. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91328. * be less than 32.
  91329. *
  91330. * \default \c 0
  91331. * \param encoder An encoder instance to set.
  91332. * \param value See above.
  91333. * \assert
  91334. * \code encoder != NULL \endcode
  91335. * \retval FLAC__bool
  91336. * \c false if the encoder is already initialized, else \c true.
  91337. */
  91338. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91339. /** Set to \c false to use only the specified quantized linear predictor
  91340. * coefficient precision, or \c true to search neighboring precision
  91341. * values and use the best one.
  91342. *
  91343. * \default \c false
  91344. * \param encoder An encoder instance to set.
  91345. * \param value See above.
  91346. * \assert
  91347. * \code encoder != NULL \endcode
  91348. * \retval FLAC__bool
  91349. * \c false if the encoder is already initialized, else \c true.
  91350. */
  91351. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91352. /** Deprecated. Setting this value has no effect.
  91353. *
  91354. * \default \c false
  91355. * \param encoder An encoder instance to set.
  91356. * \param value See above.
  91357. * \assert
  91358. * \code encoder != NULL \endcode
  91359. * \retval FLAC__bool
  91360. * \c false if the encoder is already initialized, else \c true.
  91361. */
  91362. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91363. /** Set to \c false to let the encoder estimate the best model order
  91364. * based on the residual signal energy, or \c true to force the
  91365. * encoder to evaluate all order models and select the best.
  91366. *
  91367. * \default \c false
  91368. * \param encoder An encoder instance to set.
  91369. * \param value See above.
  91370. * \assert
  91371. * \code encoder != NULL \endcode
  91372. * \retval FLAC__bool
  91373. * \c false if the encoder is already initialized, else \c true.
  91374. */
  91375. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91376. /** Set the minimum partition order to search when coding the residual.
  91377. * This is used in tandem with
  91378. * FLAC__stream_encoder_set_max_residual_partition_order().
  91379. *
  91380. * The partition order determines the context size in the residual.
  91381. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91382. *
  91383. * Set both min and max values to \c 0 to force a single context,
  91384. * whose Rice parameter is based on the residual signal variance.
  91385. * Otherwise, set a min and max order, and the encoder will search
  91386. * all orders, using the mean of each context for its Rice parameter,
  91387. * and use the best.
  91388. *
  91389. * \default \c 0
  91390. * \param encoder An encoder instance to set.
  91391. * \param value See above.
  91392. * \assert
  91393. * \code encoder != NULL \endcode
  91394. * \retval FLAC__bool
  91395. * \c false if the encoder is already initialized, else \c true.
  91396. */
  91397. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91398. /** Set the maximum partition order to search when coding the residual.
  91399. * This is used in tandem with
  91400. * FLAC__stream_encoder_set_min_residual_partition_order().
  91401. *
  91402. * The partition order determines the context size in the residual.
  91403. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91404. *
  91405. * Set both min and max values to \c 0 to force a single context,
  91406. * whose Rice parameter is based on the residual signal variance.
  91407. * Otherwise, set a min and max order, and the encoder will search
  91408. * all orders, using the mean of each context for its Rice parameter,
  91409. * and use the best.
  91410. *
  91411. * \default \c 0
  91412. * \param encoder An encoder instance to set.
  91413. * \param value See above.
  91414. * \assert
  91415. * \code encoder != NULL \endcode
  91416. * \retval FLAC__bool
  91417. * \c false if the encoder is already initialized, else \c true.
  91418. */
  91419. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91420. /** Deprecated. Setting this value has no effect.
  91421. *
  91422. * \default \c 0
  91423. * \param encoder An encoder instance to set.
  91424. * \param value See above.
  91425. * \assert
  91426. * \code encoder != NULL \endcode
  91427. * \retval FLAC__bool
  91428. * \c false if the encoder is already initialized, else \c true.
  91429. */
  91430. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91431. /** Set an estimate of the total samples that will be encoded.
  91432. * This is merely an estimate and may be set to \c 0 if unknown.
  91433. * This value will be written to the STREAMINFO block before encoding,
  91434. * and can remove the need for the caller to rewrite the value later
  91435. * if the value is known before encoding.
  91436. *
  91437. * \default \c 0
  91438. * \param encoder An encoder instance to set.
  91439. * \param value See above.
  91440. * \assert
  91441. * \code encoder != NULL \endcode
  91442. * \retval FLAC__bool
  91443. * \c false if the encoder is already initialized, else \c true.
  91444. */
  91445. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91446. /** Set the metadata blocks to be emitted to the stream before encoding.
  91447. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91448. * array of pointers to metadata blocks. The array is non-const since
  91449. * the encoder may need to change the \a is_last flag inside them, and
  91450. * in some cases update seek point offsets. Otherwise, the encoder will
  91451. * not modify or free the blocks. It is up to the caller to free the
  91452. * metadata blocks after encoding finishes.
  91453. *
  91454. * \note
  91455. * The encoder stores only copies of the pointers in the \a metadata array;
  91456. * the metadata blocks themselves must survive at least until after
  91457. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91458. *
  91459. * \note
  91460. * The STREAMINFO block is always written and no STREAMINFO block may
  91461. * occur in the supplied array.
  91462. *
  91463. * \note
  91464. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91465. * in the \a metadata array, but the client has specified that it does not
  91466. * support seeking, then the SEEKTABLE will be written verbatim. However
  91467. * by itself this is not very useful as the client will not know the stream
  91468. * offsets for the seekpoints ahead of time. In order to get a proper
  91469. * seektable the client must support seeking. See next note.
  91470. *
  91471. * \note
  91472. * SEEKTABLE blocks are handled specially. Since you will not know
  91473. * the values for the seek point stream offsets, you should pass in
  91474. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91475. * required sample numbers (or placeholder points), with \c 0 for the
  91476. * \a frame_samples and \a stream_offset fields for each point. If the
  91477. * client has specified that it supports seeking by providing a seek
  91478. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91479. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91480. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91481. * then while it is encoding the encoder will fill the stream offsets in
  91482. * for you and when encoding is finished, it will seek back and write the
  91483. * real values into the SEEKTABLE block in the stream. There are helper
  91484. * routines for manipulating seektable template blocks; see metadata.h:
  91485. * FLAC__metadata_object_seektable_template_*(). If the client does
  91486. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91487. * will slow down or remove the ability to seek in the FLAC stream.
  91488. *
  91489. * \note
  91490. * The encoder instance \b will modify the first \c SEEKTABLE block
  91491. * as it transforms the template to a valid seektable while encoding,
  91492. * but it is still up to the caller to free all metadata blocks after
  91493. * encoding.
  91494. *
  91495. * \note
  91496. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91497. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91498. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91499. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91500. * block is present in the \a metadata array, libFLAC will write an
  91501. * empty one, containing only the vendor string.
  91502. *
  91503. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91504. * the second metadata block of the stream. The encoder already supplies
  91505. * the STREAMINFO block automatically. If \a metadata does not contain a
  91506. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91507. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91508. * first, the init function will reorder \a metadata by moving the
  91509. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91510. * blocks will remain as they were.
  91511. *
  91512. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91513. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91514. * return \c false.
  91515. *
  91516. * \default \c NULL, 0
  91517. * \param encoder An encoder instance to set.
  91518. * \param metadata See above.
  91519. * \param num_blocks See above.
  91520. * \assert
  91521. * \code encoder != NULL \endcode
  91522. * \retval FLAC__bool
  91523. * \c false if the encoder is already initialized, else \c true.
  91524. * \c false if the encoder is already initialized, or if
  91525. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91526. */
  91527. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91528. /** Get the current encoder state.
  91529. *
  91530. * \param encoder An encoder instance to query.
  91531. * \assert
  91532. * \code encoder != NULL \endcode
  91533. * \retval FLAC__StreamEncoderState
  91534. * The current encoder state.
  91535. */
  91536. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91537. /** Get the state of the verify stream decoder.
  91538. * Useful when the stream encoder state is
  91539. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91540. *
  91541. * \param encoder An encoder instance to query.
  91542. * \assert
  91543. * \code encoder != NULL \endcode
  91544. * \retval FLAC__StreamDecoderState
  91545. * The verify stream decoder state.
  91546. */
  91547. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91548. /** Get the current encoder state as a C string.
  91549. * This version automatically resolves
  91550. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91551. * verify decoder's state.
  91552. *
  91553. * \param encoder A encoder instance to query.
  91554. * \assert
  91555. * \code encoder != NULL \endcode
  91556. * \retval const char *
  91557. * The encoder state as a C string. Do not modify the contents.
  91558. */
  91559. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91560. /** Get relevant values about the nature of a verify decoder error.
  91561. * Useful when the stream encoder state is
  91562. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91563. * be addresses in which the stats will be returned, or NULL if value
  91564. * is not desired.
  91565. *
  91566. * \param encoder An encoder instance to query.
  91567. * \param absolute_sample The absolute sample number of the mismatch.
  91568. * \param frame_number The number of the frame in which the mismatch occurred.
  91569. * \param channel The channel in which the mismatch occurred.
  91570. * \param sample The number of the sample (relative to the frame) in
  91571. * which the mismatch occurred.
  91572. * \param expected The expected value for the sample in question.
  91573. * \param got The actual value returned by the decoder.
  91574. * \assert
  91575. * \code encoder != NULL \endcode
  91576. */
  91577. 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);
  91578. /** Get the "verify" flag.
  91579. *
  91580. * \param encoder An encoder instance to query.
  91581. * \assert
  91582. * \code encoder != NULL \endcode
  91583. * \retval FLAC__bool
  91584. * See FLAC__stream_encoder_set_verify().
  91585. */
  91586. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91587. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91588. *
  91589. * \param encoder An encoder instance to query.
  91590. * \assert
  91591. * \code encoder != NULL \endcode
  91592. * \retval FLAC__bool
  91593. * See FLAC__stream_encoder_set_streamable_subset().
  91594. */
  91595. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91596. /** Get the number of input channels being processed.
  91597. *
  91598. * \param encoder An encoder instance to query.
  91599. * \assert
  91600. * \code encoder != NULL \endcode
  91601. * \retval unsigned
  91602. * See FLAC__stream_encoder_set_channels().
  91603. */
  91604. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91605. /** Get the input sample resolution setting.
  91606. *
  91607. * \param encoder An encoder instance to query.
  91608. * \assert
  91609. * \code encoder != NULL \endcode
  91610. * \retval unsigned
  91611. * See FLAC__stream_encoder_set_bits_per_sample().
  91612. */
  91613. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91614. /** Get the input sample rate setting.
  91615. *
  91616. * \param encoder An encoder instance to query.
  91617. * \assert
  91618. * \code encoder != NULL \endcode
  91619. * \retval unsigned
  91620. * See FLAC__stream_encoder_set_sample_rate().
  91621. */
  91622. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91623. /** Get the blocksize setting.
  91624. *
  91625. * \param encoder An encoder instance to query.
  91626. * \assert
  91627. * \code encoder != NULL \endcode
  91628. * \retval unsigned
  91629. * See FLAC__stream_encoder_set_blocksize().
  91630. */
  91631. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91632. /** Get the "mid/side stereo coding" flag.
  91633. *
  91634. * \param encoder An encoder instance to query.
  91635. * \assert
  91636. * \code encoder != NULL \endcode
  91637. * \retval FLAC__bool
  91638. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91639. */
  91640. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91641. /** Get the "adaptive mid/side switching" flag.
  91642. *
  91643. * \param encoder An encoder instance to query.
  91644. * \assert
  91645. * \code encoder != NULL \endcode
  91646. * \retval FLAC__bool
  91647. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91648. */
  91649. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91650. /** Get the maximum LPC order setting.
  91651. *
  91652. * \param encoder An encoder instance to query.
  91653. * \assert
  91654. * \code encoder != NULL \endcode
  91655. * \retval unsigned
  91656. * See FLAC__stream_encoder_set_max_lpc_order().
  91657. */
  91658. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91659. /** Get the quantized linear predictor coefficient precision setting.
  91660. *
  91661. * \param encoder An encoder instance to query.
  91662. * \assert
  91663. * \code encoder != NULL \endcode
  91664. * \retval unsigned
  91665. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91666. */
  91667. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91668. /** Get the qlp coefficient precision search flag.
  91669. *
  91670. * \param encoder An encoder instance to query.
  91671. * \assert
  91672. * \code encoder != NULL \endcode
  91673. * \retval FLAC__bool
  91674. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91675. */
  91676. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91677. /** Get the "escape coding" flag.
  91678. *
  91679. * \param encoder An encoder instance to query.
  91680. * \assert
  91681. * \code encoder != NULL \endcode
  91682. * \retval FLAC__bool
  91683. * See FLAC__stream_encoder_set_do_escape_coding().
  91684. */
  91685. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91686. /** Get the exhaustive model search flag.
  91687. *
  91688. * \param encoder An encoder instance to query.
  91689. * \assert
  91690. * \code encoder != NULL \endcode
  91691. * \retval FLAC__bool
  91692. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91693. */
  91694. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91695. /** Get the minimum residual partition order setting.
  91696. *
  91697. * \param encoder An encoder instance to query.
  91698. * \assert
  91699. * \code encoder != NULL \endcode
  91700. * \retval unsigned
  91701. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91702. */
  91703. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91704. /** Get maximum residual partition order setting.
  91705. *
  91706. * \param encoder An encoder instance to query.
  91707. * \assert
  91708. * \code encoder != NULL \endcode
  91709. * \retval unsigned
  91710. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91711. */
  91712. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91713. /** Get the Rice parameter search distance setting.
  91714. *
  91715. * \param encoder An encoder instance to query.
  91716. * \assert
  91717. * \code encoder != NULL \endcode
  91718. * \retval unsigned
  91719. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91720. */
  91721. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91722. /** Get the previously set estimate of the total samples to be encoded.
  91723. * The encoder merely mimics back the value given to
  91724. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91725. * other way of knowing how many samples the client will encode.
  91726. *
  91727. * \param encoder An encoder instance to set.
  91728. * \assert
  91729. * \code encoder != NULL \endcode
  91730. * \retval FLAC__uint64
  91731. * See FLAC__stream_encoder_get_total_samples_estimate().
  91732. */
  91733. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91734. /** Initialize the encoder instance to encode native FLAC streams.
  91735. *
  91736. * This flavor of initialization sets up the encoder to encode to a
  91737. * native FLAC stream. I/O is performed via callbacks to the client.
  91738. * For encoding to a plain file via filename or open \c FILE*,
  91739. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91740. * provide a simpler interface.
  91741. *
  91742. * This function should be called after FLAC__stream_encoder_new() and
  91743. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91744. * or FLAC__stream_encoder_process_interleaved().
  91745. * initialization succeeded.
  91746. *
  91747. * The call to FLAC__stream_encoder_init_stream() currently will also
  91748. * immediately call the write callback several times, once with the \c fLaC
  91749. * signature, and once for each encoded metadata block.
  91750. *
  91751. * \param encoder An uninitialized encoder instance.
  91752. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91753. * pointer must not be \c NULL.
  91754. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91755. * pointer may be \c NULL if seeking is not
  91756. * supported. The encoder uses seeking to go back
  91757. * and write some some stream statistics to the
  91758. * STREAMINFO block; this is recommended but not
  91759. * necessary to create a valid FLAC stream. If
  91760. * \a seek_callback is not \c NULL then a
  91761. * \a tell_callback must also be supplied.
  91762. * Alternatively, a dummy seek callback that just
  91763. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91764. * may also be supplied, all though this is slightly
  91765. * less efficient for the encoder.
  91766. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91767. * pointer may be \c NULL if seeking is not
  91768. * supported. If \a seek_callback is \c NULL then
  91769. * this argument will be ignored. If
  91770. * \a seek_callback is not \c NULL then a
  91771. * \a tell_callback must also be supplied.
  91772. * Alternatively, a dummy tell callback that just
  91773. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91774. * may also be supplied, all though this is slightly
  91775. * less efficient for the encoder.
  91776. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91777. * pointer may be \c NULL if the callback is not
  91778. * desired. If the client provides a seek callback,
  91779. * this function is not necessary as the encoder
  91780. * will automatically seek back and update the
  91781. * STREAMINFO block. It may also be \c NULL if the
  91782. * client does not support seeking, since it will
  91783. * have no way of going back to update the
  91784. * STREAMINFO. However the client can still supply
  91785. * a callback if it would like to know the details
  91786. * from the STREAMINFO.
  91787. * \param client_data This value will be supplied to callbacks in their
  91788. * \a client_data argument.
  91789. * \assert
  91790. * \code encoder != NULL \endcode
  91791. * \retval FLAC__StreamEncoderInitStatus
  91792. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91793. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91794. */
  91795. 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);
  91796. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91797. *
  91798. * This flavor of initialization sets up the encoder to encode to a FLAC
  91799. * stream in an Ogg container. I/O is performed via callbacks to the
  91800. * client. For encoding to a plain file via filename or open \c FILE*,
  91801. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91802. * provide a simpler interface.
  91803. *
  91804. * This function should be called after FLAC__stream_encoder_new() and
  91805. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91806. * or FLAC__stream_encoder_process_interleaved().
  91807. * initialization succeeded.
  91808. *
  91809. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91810. * immediately call the write callback several times to write the metadata
  91811. * packets.
  91812. *
  91813. * \param encoder An uninitialized encoder instance.
  91814. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91815. * pointer must not be \c NULL if \a seek_callback
  91816. * is non-NULL since they are both needed to be
  91817. * able to write data back to the Ogg FLAC stream
  91818. * in the post-encode phase.
  91819. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91820. * pointer must not be \c NULL.
  91821. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91822. * pointer may be \c NULL if seeking is not
  91823. * supported. The encoder uses seeking to go back
  91824. * and write some some stream statistics to the
  91825. * STREAMINFO block; this is recommended but not
  91826. * necessary to create a valid FLAC stream. If
  91827. * \a seek_callback is not \c NULL then a
  91828. * \a tell_callback must also be supplied.
  91829. * Alternatively, a dummy seek callback that just
  91830. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91831. * may also be supplied, all though this is slightly
  91832. * less efficient for the encoder.
  91833. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91834. * pointer may be \c NULL if seeking is not
  91835. * supported. If \a seek_callback is \c NULL then
  91836. * this argument will be ignored. If
  91837. * \a seek_callback is not \c NULL then a
  91838. * \a tell_callback must also be supplied.
  91839. * Alternatively, a dummy tell callback that just
  91840. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91841. * may also be supplied, all though this is slightly
  91842. * less efficient for the encoder.
  91843. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91844. * pointer may be \c NULL if the callback is not
  91845. * desired. If the client provides a seek callback,
  91846. * this function is not necessary as the encoder
  91847. * will automatically seek back and update the
  91848. * STREAMINFO block. It may also be \c NULL if the
  91849. * client does not support seeking, since it will
  91850. * have no way of going back to update the
  91851. * STREAMINFO. However the client can still supply
  91852. * a callback if it would like to know the details
  91853. * from the STREAMINFO.
  91854. * \param client_data This value will be supplied to callbacks in their
  91855. * \a client_data argument.
  91856. * \assert
  91857. * \code encoder != NULL \endcode
  91858. * \retval FLAC__StreamEncoderInitStatus
  91859. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91860. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91861. */
  91862. 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);
  91863. /** Initialize the encoder instance to encode native FLAC files.
  91864. *
  91865. * This flavor of initialization sets up the encoder to encode to a
  91866. * plain native FLAC file. For non-stdio streams, you must use
  91867. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91868. *
  91869. * This function should be called after FLAC__stream_encoder_new() and
  91870. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91871. * or FLAC__stream_encoder_process_interleaved().
  91872. * initialization succeeded.
  91873. *
  91874. * \param encoder An uninitialized encoder instance.
  91875. * \param file An open file. The file should have been opened
  91876. * with mode \c "w+b" and rewound. The file
  91877. * becomes owned by the encoder and should not be
  91878. * manipulated by the client while encoding.
  91879. * Unless \a file is \c stdout, it will be closed
  91880. * when FLAC__stream_encoder_finish() is called.
  91881. * Note however that a proper SEEKTABLE cannot be
  91882. * created when encoding to \c stdout since it is
  91883. * not seekable.
  91884. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91885. * pointer may be \c NULL if the callback is not
  91886. * desired.
  91887. * \param client_data This value will be supplied to callbacks in their
  91888. * \a client_data argument.
  91889. * \assert
  91890. * \code encoder != NULL \endcode
  91891. * \code file != NULL \endcode
  91892. * \retval FLAC__StreamEncoderInitStatus
  91893. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91894. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91895. */
  91896. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91897. /** Initialize the encoder instance to encode Ogg FLAC files.
  91898. *
  91899. * This flavor of initialization sets up the encoder to encode to a
  91900. * plain Ogg FLAC file. For non-stdio streams, you must use
  91901. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91902. *
  91903. * This function should be called after FLAC__stream_encoder_new() and
  91904. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91905. * or FLAC__stream_encoder_process_interleaved().
  91906. * initialization succeeded.
  91907. *
  91908. * \param encoder An uninitialized encoder instance.
  91909. * \param file An open file. The file should have been opened
  91910. * with mode \c "w+b" and rewound. The file
  91911. * becomes owned by the encoder and should not be
  91912. * manipulated by the client while encoding.
  91913. * Unless \a file is \c stdout, it will be closed
  91914. * when FLAC__stream_encoder_finish() is called.
  91915. * Note however that a proper SEEKTABLE cannot be
  91916. * created when encoding to \c stdout since it is
  91917. * not seekable.
  91918. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91919. * pointer may be \c NULL if the callback is not
  91920. * desired.
  91921. * \param client_data This value will be supplied to callbacks in their
  91922. * \a client_data argument.
  91923. * \assert
  91924. * \code encoder != NULL \endcode
  91925. * \code file != NULL \endcode
  91926. * \retval FLAC__StreamEncoderInitStatus
  91927. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91928. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91929. */
  91930. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91931. /** Initialize the encoder instance to encode native FLAC files.
  91932. *
  91933. * This flavor of initialization sets up the encoder to encode to a plain
  91934. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91935. * with Unicode filenames on Windows), you must use
  91936. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91937. * and provide callbacks for the I/O.
  91938. *
  91939. * This function should be called after FLAC__stream_encoder_new() and
  91940. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91941. * or FLAC__stream_encoder_process_interleaved().
  91942. * initialization succeeded.
  91943. *
  91944. * \param encoder An uninitialized encoder instance.
  91945. * \param filename The name of the file to encode to. The file will
  91946. * be opened with fopen(). Use \c NULL to encode to
  91947. * \c stdout. Note however that a proper SEEKTABLE
  91948. * cannot be created when encoding to \c stdout since
  91949. * it is not seekable.
  91950. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91951. * pointer may be \c NULL if the callback is not
  91952. * desired.
  91953. * \param client_data This value will be supplied to callbacks in their
  91954. * \a client_data argument.
  91955. * \assert
  91956. * \code encoder != NULL \endcode
  91957. * \retval FLAC__StreamEncoderInitStatus
  91958. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91959. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91960. */
  91961. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91962. /** Initialize the encoder instance to encode Ogg FLAC files.
  91963. *
  91964. * This flavor of initialization sets up the encoder to encode to a plain
  91965. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91966. * with Unicode filenames on Windows), you must use
  91967. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91968. * and provide callbacks for the I/O.
  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. * \param encoder An uninitialized encoder instance.
  91976. * \param filename The name of the file to encode to. The file will
  91977. * be opened with fopen(). Use \c NULL to encode to
  91978. * \c stdout. Note however that a proper SEEKTABLE
  91979. * cannot be created when encoding to \c stdout since
  91980. * it is not seekable.
  91981. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91982. * pointer may be \c NULL if the callback is not
  91983. * desired.
  91984. * \param client_data This value will be supplied to callbacks in their
  91985. * \a client_data argument.
  91986. * \assert
  91987. * \code encoder != NULL \endcode
  91988. * \retval FLAC__StreamEncoderInitStatus
  91989. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91990. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91991. */
  91992. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91993. /** Finish the encoding process.
  91994. * Flushes the encoding buffer, releases resources, resets the encoder
  91995. * settings to their defaults, and returns the encoder state to
  91996. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91997. * one or more write callbacks before returning, and will generate
  91998. * a metadata callback.
  91999. *
  92000. * Note that in the course of processing the last frame, errors can
  92001. * occur, so the caller should be sure to check the return value to
  92002. * ensure the file was encoded properly.
  92003. *
  92004. * In the event of a prematurely-terminated encode, it is not strictly
  92005. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92006. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92007. * with a FLAC__stream_encoder_finish().
  92008. *
  92009. * \param encoder An uninitialized encoder instance.
  92010. * \assert
  92011. * \code encoder != NULL \endcode
  92012. * \retval FLAC__bool
  92013. * \c false if an error occurred processing the last frame; or if verify
  92014. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92015. * verify mismatch; else \c true. If \c false, caller should check the
  92016. * state with FLAC__stream_encoder_get_state() for more information
  92017. * about the error.
  92018. */
  92019. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92020. /** Submit data for encoding.
  92021. * This version allows you to supply the input data via an array of
  92022. * pointers, each pointer pointing to an array of \a samples samples
  92023. * representing one channel. The samples need not be block-aligned,
  92024. * but each channel should have the same number of samples. Each sample
  92025. * should be a signed integer, right-justified to the resolution set by
  92026. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92027. * resolution is 16 bits per sample, the samples should all be in the
  92028. * range [-32768,32767].
  92029. *
  92030. * For applications where channel order is important, channels must
  92031. * follow the order as described in the
  92032. * <A HREF="../format.html#frame_header">frame header</A>.
  92033. *
  92034. * \param encoder An initialized encoder instance in the OK state.
  92035. * \param buffer An array of pointers to each channel's signal.
  92036. * \param samples The number of samples in one channel.
  92037. * \assert
  92038. * \code encoder != NULL \endcode
  92039. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92040. * \retval FLAC__bool
  92041. * \c true if successful, else \c false; in this case, check the
  92042. * encoder state with FLAC__stream_encoder_get_state() to see what
  92043. * went wrong.
  92044. */
  92045. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92046. /** Submit data for encoding.
  92047. * This version allows you to supply the input data where the channels
  92048. * are interleaved into a single array (i.e. channel0_sample0,
  92049. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92050. * The samples need not be block-aligned but they must be
  92051. * sample-aligned, i.e. the first value should be channel0_sample0
  92052. * and the last value channelN_sampleM. Each sample should be a signed
  92053. * integer, right-justified to the resolution set by
  92054. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92055. * resolution is 16 bits per sample, the samples should all be in the
  92056. * range [-32768,32767].
  92057. *
  92058. * For applications where channel order is important, channels must
  92059. * follow the order as described in the
  92060. * <A HREF="../format.html#frame_header">frame header</A>.
  92061. *
  92062. * \param encoder An initialized encoder instance in the OK state.
  92063. * \param buffer An array of channel-interleaved data (see above).
  92064. * \param samples The number of samples in one channel, the same as for
  92065. * FLAC__stream_encoder_process(). For example, if
  92066. * encoding two channels, \c 1000 \a samples corresponds
  92067. * to a \a buffer of 2000 values.
  92068. * \assert
  92069. * \code encoder != NULL \endcode
  92070. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92071. * \retval FLAC__bool
  92072. * \c true if successful, else \c false; in this case, check the
  92073. * encoder state with FLAC__stream_encoder_get_state() to see what
  92074. * went wrong.
  92075. */
  92076. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92077. /* \} */
  92078. #ifdef __cplusplus
  92079. }
  92080. #endif
  92081. #endif
  92082. /*** End of inlined file: stream_encoder.h ***/
  92083. #ifdef _MSC_VER
  92084. /* OPT: an MSVC built-in would be better */
  92085. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92086. {
  92087. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92088. return (x>>16) | (x<<16);
  92089. }
  92090. #endif
  92091. #if defined(_MSC_VER) && defined(_X86_)
  92092. /* OPT: an MSVC built-in would be better */
  92093. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92094. {
  92095. __asm {
  92096. mov edx, start
  92097. mov ecx, len
  92098. test ecx, ecx
  92099. loop1:
  92100. jz done1
  92101. mov eax, [edx]
  92102. bswap eax
  92103. mov [edx], eax
  92104. add edx, 4
  92105. dec ecx
  92106. jmp short loop1
  92107. done1:
  92108. }
  92109. }
  92110. #endif
  92111. /** \mainpage
  92112. *
  92113. * \section intro Introduction
  92114. *
  92115. * This is the documentation for the FLAC C and C++ APIs. It is
  92116. * highly interconnected; this introduction should give you a top
  92117. * level idea of the structure and how to find the information you
  92118. * need. As a prerequisite you should have at least a basic
  92119. * knowledge of the FLAC format, documented
  92120. * <A HREF="../format.html">here</A>.
  92121. *
  92122. * \section c_api FLAC C API
  92123. *
  92124. * The FLAC C API is the interface to libFLAC, a set of structures
  92125. * describing the components of FLAC streams, and functions for
  92126. * encoding and decoding streams, as well as manipulating FLAC
  92127. * metadata in files. The public include files will be installed
  92128. * in your include area (for example /usr/include/FLAC/...).
  92129. *
  92130. * By writing a little code and linking against libFLAC, it is
  92131. * relatively easy to add FLAC support to another program. The
  92132. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92133. * Complete source code of libFLAC as well as the command-line
  92134. * encoder and plugins is available and is a useful source of
  92135. * examples.
  92136. *
  92137. * Aside from encoders and decoders, libFLAC provides a powerful
  92138. * metadata interface for manipulating metadata in FLAC files. It
  92139. * allows the user to add, delete, and modify FLAC metadata blocks
  92140. * and it can automatically take advantage of PADDING blocks to avoid
  92141. * rewriting the entire FLAC file when changing the size of the
  92142. * metadata.
  92143. *
  92144. * libFLAC usually only requires the standard C library and C math
  92145. * library. In particular, threading is not used so there is no
  92146. * dependency on a thread library. However, libFLAC does not use
  92147. * global variables and should be thread-safe.
  92148. *
  92149. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92150. * However the metadata editing interfaces currently have limited
  92151. * read-only support for Ogg FLAC files.
  92152. *
  92153. * \section cpp_api FLAC C++ API
  92154. *
  92155. * The FLAC C++ API is a set of classes that encapsulate the
  92156. * structures and functions in libFLAC. They provide slightly more
  92157. * functionality with respect to metadata but are otherwise
  92158. * equivalent. For the most part, they share the same usage as
  92159. * their counterparts in libFLAC, and the FLAC C API documentation
  92160. * can be used as a supplement. The public include files
  92161. * for the C++ API will be installed in your include area (for
  92162. * example /usr/include/FLAC++/...).
  92163. *
  92164. * libFLAC++ is also licensed under
  92165. * <A HREF="../license.html">Xiph's BSD license</A>.
  92166. *
  92167. * \section getting_started Getting Started
  92168. *
  92169. * A good starting point for learning the API is to browse through
  92170. * the <A HREF="modules.html">modules</A>. Modules are logical
  92171. * groupings of related functions or classes, which correspond roughly
  92172. * to header files or sections of header files. Each module includes a
  92173. * detailed description of the general usage of its functions or
  92174. * classes.
  92175. *
  92176. * From there you can go on to look at the documentation of
  92177. * individual functions. You can see different views of the individual
  92178. * functions through the links in top bar across this page.
  92179. *
  92180. * If you prefer a more hands-on approach, you can jump right to some
  92181. * <A HREF="../documentation_example_code.html">example code</A>.
  92182. *
  92183. * \section porting_guide Porting Guide
  92184. *
  92185. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92186. * has been introduced which gives detailed instructions on how to
  92187. * port your code to newer versions of FLAC.
  92188. *
  92189. * \section embedded_developers Embedded Developers
  92190. *
  92191. * libFLAC has grown larger over time as more functionality has been
  92192. * included, but much of it may be unnecessary for a particular embedded
  92193. * implementation. Unused parts may be pruned by some simple editing of
  92194. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92195. * metadata interface are all independent from each other.
  92196. *
  92197. * It is easiest to just describe the dependencies:
  92198. *
  92199. * - All modules depend on the \link flac_format Format \endlink module.
  92200. * - The decoders and encoders depend on the bitbuffer.
  92201. * - The decoder is independent of the encoder. The encoder uses the
  92202. * decoder because of the verify feature, but this can be removed if
  92203. * not needed.
  92204. * - Parts of the metadata interface require the stream decoder (but not
  92205. * the encoder).
  92206. * - Ogg support is selectable through the compile time macro
  92207. * \c FLAC__HAS_OGG.
  92208. *
  92209. * For example, if your application only requires the stream decoder, no
  92210. * encoder, and no metadata interface, you can remove the stream encoder
  92211. * and the metadata interface, which will greatly reduce the size of the
  92212. * library.
  92213. *
  92214. * Also, there are several places in the libFLAC code with comments marked
  92215. * with "OPT:" where a #define can be changed to enable code that might be
  92216. * faster on a specific platform. Experimenting with these can yield faster
  92217. * binaries.
  92218. */
  92219. /** \defgroup porting Porting Guide for New Versions
  92220. *
  92221. * This module describes differences in the library interfaces from
  92222. * version to version. It assists in the porting of code that uses
  92223. * the libraries to newer versions of FLAC.
  92224. *
  92225. * One simple facility for making porting easier that has been added
  92226. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92227. * library's includes (e.g. \c include/FLAC/export.h). The
  92228. * \c #defines mirror the libraries'
  92229. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92230. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92231. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92232. * These can be used to support multiple versions of an API during the
  92233. * transition phase, e.g.
  92234. *
  92235. * \code
  92236. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92237. * legacy code
  92238. * #else
  92239. * new code
  92240. * #endif
  92241. * \endcode
  92242. *
  92243. * The the source will work for multiple versions and the legacy code can
  92244. * easily be removed when the transition is complete.
  92245. *
  92246. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92247. * include/FLAC/export.h), which can be used to determine whether or not
  92248. * the library has been compiled with support for Ogg FLAC. This is
  92249. * simpler than trying to call an Ogg init function and catching the
  92250. * error.
  92251. */
  92252. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92253. * \ingroup porting
  92254. *
  92255. * \brief
  92256. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92257. *
  92258. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92259. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92260. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92261. * decoding layers and three encoding layers have been merged into a
  92262. * single stream decoder and stream encoder. That is, the functionality
  92263. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92264. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92265. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92266. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92267. * is there is now a single API that can be used to encode or decode
  92268. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92269. * on both seekable and non-seekable streams.
  92270. *
  92271. * Instead of creating an encoder or decoder of a certain layer, now the
  92272. * client will always create a FLAC__StreamEncoder or
  92273. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92274. * initialization function. For example, for the decoder,
  92275. * FLAC__stream_decoder_init() has been replaced by
  92276. * FLAC__stream_decoder_init_stream(). This init function takes
  92277. * callbacks for the I/O, and the seeking callbacks are optional. This
  92278. * allows the client to use the same object for seekable and
  92279. * non-seekable streams. For decoding a FLAC file directly, the client
  92280. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92281. * and fewer callbacks; most of the other callbacks are supplied
  92282. * internally. For situations where fopen()ing by filename is not
  92283. * possible (e.g. Unicode filenames on Windows) the client can instead
  92284. * open the file itself and supply the FILE* to
  92285. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92286. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92287. * Since the callbacks and client data are now passed to the init
  92288. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92289. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92290. * rest of the calls to the decoder are the same as before.
  92291. *
  92292. * There are counterpart init functions for Ogg FLAC, e.g.
  92293. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92294. * and callbacks are the same as for native FLAC.
  92295. *
  92296. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92297. * been set up like so:
  92298. *
  92299. * \code
  92300. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92301. * if(decoder == NULL) do_something;
  92302. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92303. * [... other settings ...]
  92304. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92305. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92306. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92307. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92308. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92309. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92310. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92311. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92312. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92313. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92314. * \endcode
  92315. *
  92316. * In FLAC 1.1.3 it is like this:
  92317. *
  92318. * \code
  92319. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92320. * if(decoder == NULL) do_something;
  92321. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92322. * [... other settings ...]
  92323. * if(FLAC__stream_decoder_init_stream(
  92324. * decoder,
  92325. * my_read_callback,
  92326. * my_seek_callback, // or NULL
  92327. * my_tell_callback, // or NULL
  92328. * my_length_callback, // or NULL
  92329. * my_eof_callback, // or NULL
  92330. * my_write_callback,
  92331. * my_metadata_callback, // or NULL
  92332. * my_error_callback,
  92333. * my_client_data
  92334. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92335. * \endcode
  92336. *
  92337. * or you could do;
  92338. *
  92339. * \code
  92340. * [...]
  92341. * FILE *file = fopen("somefile.flac","rb");
  92342. * if(file == NULL) do_somthing;
  92343. * if(FLAC__stream_decoder_init_FILE(
  92344. * decoder,
  92345. * file,
  92346. * my_write_callback,
  92347. * my_metadata_callback, // or NULL
  92348. * my_error_callback,
  92349. * my_client_data
  92350. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92351. * \endcode
  92352. *
  92353. * or just:
  92354. *
  92355. * \code
  92356. * [...]
  92357. * if(FLAC__stream_decoder_init_file(
  92358. * decoder,
  92359. * "somefile.flac",
  92360. * my_write_callback,
  92361. * my_metadata_callback, // or NULL
  92362. * my_error_callback,
  92363. * my_client_data
  92364. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92365. * \endcode
  92366. *
  92367. * Another small change to the decoder is in how it handles unparseable
  92368. * streams. Before, when the decoder found an unparseable stream
  92369. * (reserved for when the decoder encounters a stream from a future
  92370. * encoder that it can't parse), it changed the state to
  92371. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92372. * drops sync and calls the error callback with a new error code
  92373. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92374. * more robust. If your error callback does not discriminate on the the
  92375. * error state, your code does not need to be changed.
  92376. *
  92377. * The encoder now has a new setting:
  92378. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92379. * method used to window the data before LPC analysis. You only need to
  92380. * add a call to this function if the default is not suitable. There
  92381. * are also two new convenience functions that may be useful:
  92382. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92383. * FLAC__metadata_get_cuesheet().
  92384. *
  92385. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92386. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92387. * is now \c size_t instead of \c unsigned.
  92388. */
  92389. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92390. * \ingroup porting
  92391. *
  92392. * \brief
  92393. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92394. *
  92395. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92396. * There was a slight change in the implementation of
  92397. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92398. * of the \a metadata array of pointers so the client no longer needs
  92399. * to maintain it after the call. The objects themselves that are
  92400. * pointed to by the array are still not copied though and must be
  92401. * maintained until the call to FLAC__stream_encoder_finish().
  92402. */
  92403. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92404. * \ingroup porting
  92405. *
  92406. * \brief
  92407. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92408. *
  92409. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92410. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92411. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92412. *
  92413. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92414. * has changed to reflect the conversion of one of the reserved bits
  92415. * into active use. It used to be \c 2 and now is \c 1. However the
  92416. * FLAC frame header length has not changed, so to skip the proper
  92417. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92418. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92419. */
  92420. /** \defgroup flac FLAC C API
  92421. *
  92422. * The FLAC C API is the interface to libFLAC, a set of structures
  92423. * describing the components of FLAC streams, and functions for
  92424. * encoding and decoding streams, as well as manipulating FLAC
  92425. * metadata in files.
  92426. *
  92427. * You should start with the format components as all other modules
  92428. * are dependent on it.
  92429. */
  92430. #endif
  92431. /*** End of inlined file: all.h ***/
  92432. /*** Start of inlined file: bitmath.c ***/
  92433. /*** Start of inlined file: juce_FlacHeader.h ***/
  92434. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92435. // tasks..
  92436. #define VERSION "1.2.1"
  92437. #define FLAC__NO_DLL 1
  92438. #if JUCE_MSVC
  92439. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92440. #endif
  92441. #if JUCE_MAC
  92442. #define FLAC__SYS_DARWIN 1
  92443. #endif
  92444. /*** End of inlined file: juce_FlacHeader.h ***/
  92445. #if JUCE_USE_FLAC
  92446. #if HAVE_CONFIG_H
  92447. # include <config.h>
  92448. #endif
  92449. /*** Start of inlined file: bitmath.h ***/
  92450. #ifndef FLAC__PRIVATE__BITMATH_H
  92451. #define FLAC__PRIVATE__BITMATH_H
  92452. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92453. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92454. unsigned FLAC__bitmath_silog2(int v);
  92455. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92456. #endif
  92457. /*** End of inlined file: bitmath.h ***/
  92458. /* An example of what FLAC__bitmath_ilog2() computes:
  92459. *
  92460. * ilog2( 0) = assertion failure
  92461. * ilog2( 1) = 0
  92462. * ilog2( 2) = 1
  92463. * ilog2( 3) = 1
  92464. * ilog2( 4) = 2
  92465. * ilog2( 5) = 2
  92466. * ilog2( 6) = 2
  92467. * ilog2( 7) = 2
  92468. * ilog2( 8) = 3
  92469. * ilog2( 9) = 3
  92470. * ilog2(10) = 3
  92471. * ilog2(11) = 3
  92472. * ilog2(12) = 3
  92473. * ilog2(13) = 3
  92474. * ilog2(14) = 3
  92475. * ilog2(15) = 3
  92476. * ilog2(16) = 4
  92477. * ilog2(17) = 4
  92478. * ilog2(18) = 4
  92479. */
  92480. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92481. {
  92482. unsigned l = 0;
  92483. FLAC__ASSERT(v > 0);
  92484. while(v >>= 1)
  92485. l++;
  92486. return l;
  92487. }
  92488. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92489. {
  92490. unsigned l = 0;
  92491. FLAC__ASSERT(v > 0);
  92492. while(v >>= 1)
  92493. l++;
  92494. return l;
  92495. }
  92496. /* An example of what FLAC__bitmath_silog2() computes:
  92497. *
  92498. * silog2(-10) = 5
  92499. * silog2(- 9) = 5
  92500. * silog2(- 8) = 4
  92501. * silog2(- 7) = 4
  92502. * silog2(- 6) = 4
  92503. * silog2(- 5) = 4
  92504. * silog2(- 4) = 3
  92505. * silog2(- 3) = 3
  92506. * silog2(- 2) = 2
  92507. * silog2(- 1) = 2
  92508. * silog2( 0) = 0
  92509. * silog2( 1) = 2
  92510. * silog2( 2) = 3
  92511. * silog2( 3) = 3
  92512. * silog2( 4) = 4
  92513. * silog2( 5) = 4
  92514. * silog2( 6) = 4
  92515. * silog2( 7) = 4
  92516. * silog2( 8) = 5
  92517. * silog2( 9) = 5
  92518. * silog2( 10) = 5
  92519. */
  92520. unsigned FLAC__bitmath_silog2(int v)
  92521. {
  92522. while(1) {
  92523. if(v == 0) {
  92524. return 0;
  92525. }
  92526. else if(v > 0) {
  92527. unsigned l = 0;
  92528. while(v) {
  92529. l++;
  92530. v >>= 1;
  92531. }
  92532. return l+1;
  92533. }
  92534. else if(v == -1) {
  92535. return 2;
  92536. }
  92537. else {
  92538. v++;
  92539. v = -v;
  92540. }
  92541. }
  92542. }
  92543. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92544. {
  92545. while(1) {
  92546. if(v == 0) {
  92547. return 0;
  92548. }
  92549. else if(v > 0) {
  92550. unsigned l = 0;
  92551. while(v) {
  92552. l++;
  92553. v >>= 1;
  92554. }
  92555. return l+1;
  92556. }
  92557. else if(v == -1) {
  92558. return 2;
  92559. }
  92560. else {
  92561. v++;
  92562. v = -v;
  92563. }
  92564. }
  92565. }
  92566. #endif
  92567. /*** End of inlined file: bitmath.c ***/
  92568. /*** Start of inlined file: bitreader.c ***/
  92569. /*** Start of inlined file: juce_FlacHeader.h ***/
  92570. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92571. // tasks..
  92572. #define VERSION "1.2.1"
  92573. #define FLAC__NO_DLL 1
  92574. #if JUCE_MSVC
  92575. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92576. #endif
  92577. #if JUCE_MAC
  92578. #define FLAC__SYS_DARWIN 1
  92579. #endif
  92580. /*** End of inlined file: juce_FlacHeader.h ***/
  92581. #if JUCE_USE_FLAC
  92582. #if HAVE_CONFIG_H
  92583. # include <config.h>
  92584. #endif
  92585. #include <stdlib.h> /* for malloc() */
  92586. #include <string.h> /* for memcpy(), memset() */
  92587. #ifdef _MSC_VER
  92588. #include <winsock.h> /* for ntohl() */
  92589. #elif defined FLAC__SYS_DARWIN
  92590. #include <machine/endian.h> /* for ntohl() */
  92591. #elif defined __MINGW32__
  92592. #include <winsock.h> /* for ntohl() */
  92593. #else
  92594. #include <netinet/in.h> /* for ntohl() */
  92595. #endif
  92596. /*** Start of inlined file: bitreader.h ***/
  92597. #ifndef FLAC__PRIVATE__BITREADER_H
  92598. #define FLAC__PRIVATE__BITREADER_H
  92599. #include <stdio.h> /* for FILE */
  92600. /*** Start of inlined file: cpu.h ***/
  92601. #ifndef FLAC__PRIVATE__CPU_H
  92602. #define FLAC__PRIVATE__CPU_H
  92603. #ifdef HAVE_CONFIG_H
  92604. #include <config.h>
  92605. #endif
  92606. typedef enum {
  92607. FLAC__CPUINFO_TYPE_IA32,
  92608. FLAC__CPUINFO_TYPE_PPC,
  92609. FLAC__CPUINFO_TYPE_UNKNOWN
  92610. } FLAC__CPUInfo_Type;
  92611. typedef struct {
  92612. FLAC__bool cpuid;
  92613. FLAC__bool bswap;
  92614. FLAC__bool cmov;
  92615. FLAC__bool mmx;
  92616. FLAC__bool fxsr;
  92617. FLAC__bool sse;
  92618. FLAC__bool sse2;
  92619. FLAC__bool sse3;
  92620. FLAC__bool ssse3;
  92621. FLAC__bool _3dnow;
  92622. FLAC__bool ext3dnow;
  92623. FLAC__bool extmmx;
  92624. } FLAC__CPUInfo_IA32;
  92625. typedef struct {
  92626. FLAC__bool altivec;
  92627. FLAC__bool ppc64;
  92628. } FLAC__CPUInfo_PPC;
  92629. typedef struct {
  92630. FLAC__bool use_asm;
  92631. FLAC__CPUInfo_Type type;
  92632. union {
  92633. FLAC__CPUInfo_IA32 ia32;
  92634. FLAC__CPUInfo_PPC ppc;
  92635. } data;
  92636. } FLAC__CPUInfo;
  92637. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92638. #ifndef FLAC__NO_ASM
  92639. #ifdef FLAC__CPU_IA32
  92640. #ifdef FLAC__HAS_NASM
  92641. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92642. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92643. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92644. #endif
  92645. #endif
  92646. #endif
  92647. #endif
  92648. /*** End of inlined file: cpu.h ***/
  92649. /*
  92650. * opaque structure definition
  92651. */
  92652. struct FLAC__BitReader;
  92653. typedef struct FLAC__BitReader FLAC__BitReader;
  92654. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92655. /*
  92656. * construction, deletion, initialization, etc functions
  92657. */
  92658. FLAC__BitReader *FLAC__bitreader_new(void);
  92659. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92660. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92661. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92662. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92663. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92664. /*
  92665. * CRC functions
  92666. */
  92667. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92668. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92669. /*
  92670. * info functions
  92671. */
  92672. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92673. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92674. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92675. /*
  92676. * read functions
  92677. */
  92678. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92679. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92680. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92681. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92682. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92683. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92684. 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! */
  92685. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92686. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92687. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92688. #ifndef FLAC__NO_ASM
  92689. # ifdef FLAC__CPU_IA32
  92690. # ifdef FLAC__HAS_NASM
  92691. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92692. # endif
  92693. # endif
  92694. #endif
  92695. #if 0 /* UNUSED */
  92696. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92697. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92698. #endif
  92699. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92700. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92701. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92702. #endif
  92703. /*** End of inlined file: bitreader.h ***/
  92704. /*** Start of inlined file: crc.h ***/
  92705. #ifndef FLAC__PRIVATE__CRC_H
  92706. #define FLAC__PRIVATE__CRC_H
  92707. /* 8 bit CRC generator, MSB shifted first
  92708. ** polynomial = x^8 + x^2 + x^1 + x^0
  92709. ** init = 0
  92710. */
  92711. extern FLAC__byte const FLAC__crc8_table[256];
  92712. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92713. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92714. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92715. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92716. /* 16 bit CRC generator, MSB shifted first
  92717. ** polynomial = x^16 + x^15 + x^2 + x^0
  92718. ** init = 0
  92719. */
  92720. extern unsigned FLAC__crc16_table[256];
  92721. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92722. /* this alternate may be faster on some systems/compilers */
  92723. #if 0
  92724. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92725. #endif
  92726. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92727. #endif
  92728. /*** End of inlined file: crc.h ***/
  92729. /* Things should be fastest when this matches the machine word size */
  92730. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92731. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92732. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92733. typedef FLAC__uint32 brword;
  92734. #define FLAC__BYTES_PER_WORD 4
  92735. #define FLAC__BITS_PER_WORD 32
  92736. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92737. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92738. #if WORDS_BIGENDIAN
  92739. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92740. #else
  92741. #if defined (_MSC_VER) && defined (_X86_)
  92742. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92743. #else
  92744. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92745. #endif
  92746. #endif
  92747. /* counts the # of zero MSBs in a word */
  92748. #define COUNT_ZERO_MSBS(word) ( \
  92749. (word) <= 0xffff ? \
  92750. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92751. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92752. )
  92753. /* this alternate might be slightly faster on some systems/compilers: */
  92754. #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])) )
  92755. /*
  92756. * This should be at least twice as large as the largest number of words
  92757. * required to represent any 'number' (in any encoding) you are going to
  92758. * read. With FLAC this is on the order of maybe a few hundred bits.
  92759. * If the buffer is smaller than that, the decoder won't be able to read
  92760. * in a whole number that is in a variable length encoding (e.g. Rice).
  92761. * But to be practical it should be at least 1K bytes.
  92762. *
  92763. * Increase this number to decrease the number of read callbacks, at the
  92764. * expense of using more memory. Or decrease for the reverse effect,
  92765. * keeping in mind the limit from the first paragraph. The optimal size
  92766. * also depends on the CPU cache size and other factors; some twiddling
  92767. * may be necessary to squeeze out the best performance.
  92768. */
  92769. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92770. static const unsigned char byte_to_unary_table[] = {
  92771. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92772. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92773. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92774. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92775. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92776. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92777. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92778. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92787. };
  92788. #ifdef min
  92789. #undef min
  92790. #endif
  92791. #define min(x,y) ((x)<(y)?(x):(y))
  92792. #ifdef max
  92793. #undef max
  92794. #endif
  92795. #define max(x,y) ((x)>(y)?(x):(y))
  92796. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92797. #ifdef _MSC_VER
  92798. #define FLAC__U64L(x) x
  92799. #else
  92800. #define FLAC__U64L(x) x##LLU
  92801. #endif
  92802. #ifndef FLaC__INLINE
  92803. #define FLaC__INLINE
  92804. #endif
  92805. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92806. struct FLAC__BitReader {
  92807. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92808. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92809. brword *buffer;
  92810. unsigned capacity; /* in words */
  92811. unsigned words; /* # of completed words in buffer */
  92812. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92813. unsigned consumed_words; /* #words ... */
  92814. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92815. unsigned read_crc16; /* the running frame CRC */
  92816. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92817. FLAC__BitReaderReadCallback read_callback;
  92818. void *client_data;
  92819. FLAC__CPUInfo cpu_info;
  92820. };
  92821. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92822. {
  92823. register unsigned crc = br->read_crc16;
  92824. #if FLAC__BYTES_PER_WORD == 4
  92825. switch(br->crc16_align) {
  92826. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92827. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92828. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92829. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92830. }
  92831. #elif FLAC__BYTES_PER_WORD == 8
  92832. switch(br->crc16_align) {
  92833. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92834. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92835. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92836. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92837. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92838. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92839. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92840. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92841. }
  92842. #else
  92843. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92844. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92845. br->read_crc16 = crc;
  92846. #endif
  92847. br->crc16_align = 0;
  92848. }
  92849. /* would be static except it needs to be called by asm routines */
  92850. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92851. {
  92852. unsigned start, end;
  92853. size_t bytes;
  92854. FLAC__byte *target;
  92855. /* first shift the unconsumed buffer data toward the front as much as possible */
  92856. if(br->consumed_words > 0) {
  92857. start = br->consumed_words;
  92858. end = br->words + (br->bytes? 1:0);
  92859. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92860. br->words -= start;
  92861. br->consumed_words = 0;
  92862. }
  92863. /*
  92864. * set the target for reading, taking into account word alignment and endianness
  92865. */
  92866. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92867. if(bytes == 0)
  92868. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92869. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92870. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92871. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92872. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92873. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92874. * ^^-------target, bytes=3
  92875. * on LE machines, have to byteswap the odd tail word so nothing is
  92876. * overwritten:
  92877. */
  92878. #if WORDS_BIGENDIAN
  92879. #else
  92880. if(br->bytes)
  92881. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92882. #endif
  92883. /* now it looks like:
  92884. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92885. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92886. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92887. * ^^-------target, bytes=3
  92888. */
  92889. /* read in the data; note that the callback may return a smaller number of bytes */
  92890. if(!br->read_callback(target, &bytes, br->client_data))
  92891. return false;
  92892. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92893. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92894. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92895. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92896. * now have to byteswap on LE machines:
  92897. */
  92898. #if WORDS_BIGENDIAN
  92899. #else
  92900. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92901. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92902. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92903. start = br->words;
  92904. local_swap32_block_(br->buffer + start, end - start);
  92905. }
  92906. else
  92907. # endif
  92908. for(start = br->words; start < end; start++)
  92909. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92910. #endif
  92911. /* now it looks like:
  92912. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92913. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92914. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92915. * finally we'll update the reader values:
  92916. */
  92917. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92918. br->words = end / FLAC__BYTES_PER_WORD;
  92919. br->bytes = end % FLAC__BYTES_PER_WORD;
  92920. return true;
  92921. }
  92922. /***********************************************************************
  92923. *
  92924. * Class constructor/destructor
  92925. *
  92926. ***********************************************************************/
  92927. FLAC__BitReader *FLAC__bitreader_new(void)
  92928. {
  92929. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92930. /* calloc() implies:
  92931. memset(br, 0, sizeof(FLAC__BitReader));
  92932. br->buffer = 0;
  92933. br->capacity = 0;
  92934. br->words = br->bytes = 0;
  92935. br->consumed_words = br->consumed_bits = 0;
  92936. br->read_callback = 0;
  92937. br->client_data = 0;
  92938. */
  92939. return br;
  92940. }
  92941. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92942. {
  92943. FLAC__ASSERT(0 != br);
  92944. FLAC__bitreader_free(br);
  92945. free(br);
  92946. }
  92947. /***********************************************************************
  92948. *
  92949. * Public class methods
  92950. *
  92951. ***********************************************************************/
  92952. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92953. {
  92954. FLAC__ASSERT(0 != br);
  92955. br->words = br->bytes = 0;
  92956. br->consumed_words = br->consumed_bits = 0;
  92957. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92958. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92959. if(br->buffer == 0)
  92960. return false;
  92961. br->read_callback = rcb;
  92962. br->client_data = cd;
  92963. br->cpu_info = cpu;
  92964. return true;
  92965. }
  92966. void FLAC__bitreader_free(FLAC__BitReader *br)
  92967. {
  92968. FLAC__ASSERT(0 != br);
  92969. if(0 != br->buffer)
  92970. free(br->buffer);
  92971. br->buffer = 0;
  92972. br->capacity = 0;
  92973. br->words = br->bytes = 0;
  92974. br->consumed_words = br->consumed_bits = 0;
  92975. br->read_callback = 0;
  92976. br->client_data = 0;
  92977. }
  92978. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92979. {
  92980. br->words = br->bytes = 0;
  92981. br->consumed_words = br->consumed_bits = 0;
  92982. return true;
  92983. }
  92984. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92985. {
  92986. unsigned i, j;
  92987. if(br == 0) {
  92988. fprintf(out, "bitreader is NULL\n");
  92989. }
  92990. else {
  92991. 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);
  92992. for(i = 0; i < br->words; i++) {
  92993. fprintf(out, "%08X: ", i);
  92994. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92995. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92996. fprintf(out, ".");
  92997. else
  92998. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92999. fprintf(out, "\n");
  93000. }
  93001. if(br->bytes > 0) {
  93002. fprintf(out, "%08X: ", i);
  93003. for(j = 0; j < br->bytes*8; j++)
  93004. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93005. fprintf(out, ".");
  93006. else
  93007. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93008. fprintf(out, "\n");
  93009. }
  93010. }
  93011. }
  93012. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93013. {
  93014. FLAC__ASSERT(0 != br);
  93015. FLAC__ASSERT(0 != br->buffer);
  93016. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93017. br->read_crc16 = (unsigned)seed;
  93018. br->crc16_align = br->consumed_bits;
  93019. }
  93020. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93021. {
  93022. FLAC__ASSERT(0 != br);
  93023. FLAC__ASSERT(0 != br->buffer);
  93024. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93025. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93026. /* CRC any tail bytes in a partially-consumed word */
  93027. if(br->consumed_bits) {
  93028. const brword tail = br->buffer[br->consumed_words];
  93029. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93030. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93031. }
  93032. return br->read_crc16;
  93033. }
  93034. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93035. {
  93036. return ((br->consumed_bits & 7) == 0);
  93037. }
  93038. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93039. {
  93040. return 8 - (br->consumed_bits & 7);
  93041. }
  93042. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93043. {
  93044. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93045. }
  93046. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93047. {
  93048. FLAC__ASSERT(0 != br);
  93049. FLAC__ASSERT(0 != br->buffer);
  93050. FLAC__ASSERT(bits <= 32);
  93051. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93052. FLAC__ASSERT(br->consumed_words <= br->words);
  93053. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93054. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93055. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93056. *val = 0;
  93057. return true;
  93058. }
  93059. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93060. if(!bitreader_read_from_client_(br))
  93061. return false;
  93062. }
  93063. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93064. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93065. if(br->consumed_bits) {
  93066. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93067. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93068. const brword word = br->buffer[br->consumed_words];
  93069. if(bits < n) {
  93070. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93071. br->consumed_bits += bits;
  93072. return true;
  93073. }
  93074. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93075. bits -= n;
  93076. crc16_update_word_(br, word);
  93077. br->consumed_words++;
  93078. br->consumed_bits = 0;
  93079. 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 */
  93080. *val <<= bits;
  93081. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93082. br->consumed_bits = bits;
  93083. }
  93084. return true;
  93085. }
  93086. else {
  93087. const brword word = br->buffer[br->consumed_words];
  93088. if(bits < FLAC__BITS_PER_WORD) {
  93089. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93090. br->consumed_bits = bits;
  93091. return true;
  93092. }
  93093. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93094. *val = word;
  93095. crc16_update_word_(br, word);
  93096. br->consumed_words++;
  93097. return true;
  93098. }
  93099. }
  93100. else {
  93101. /* in this case we're starting our read at a partial tail word;
  93102. * the reader has guaranteed that we have at least 'bits' bits
  93103. * available to read, which makes this case simpler.
  93104. */
  93105. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93106. if(br->consumed_bits) {
  93107. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93108. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93109. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93110. br->consumed_bits += bits;
  93111. return true;
  93112. }
  93113. else {
  93114. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93115. br->consumed_bits += bits;
  93116. return true;
  93117. }
  93118. }
  93119. }
  93120. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93121. {
  93122. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93123. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93124. return false;
  93125. /* sign-extend: */
  93126. *val <<= (32-bits);
  93127. *val >>= (32-bits);
  93128. return true;
  93129. }
  93130. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93131. {
  93132. FLAC__uint32 hi, lo;
  93133. if(bits > 32) {
  93134. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93135. return false;
  93136. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93137. return false;
  93138. *val = hi;
  93139. *val <<= 32;
  93140. *val |= lo;
  93141. }
  93142. else {
  93143. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93144. return false;
  93145. *val = lo;
  93146. }
  93147. return true;
  93148. }
  93149. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93150. {
  93151. FLAC__uint32 x8, x32 = 0;
  93152. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93153. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93154. return false;
  93155. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93156. return false;
  93157. x32 |= (x8 << 8);
  93158. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93159. return false;
  93160. x32 |= (x8 << 16);
  93161. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93162. return false;
  93163. x32 |= (x8 << 24);
  93164. *val = x32;
  93165. return true;
  93166. }
  93167. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93168. {
  93169. /*
  93170. * OPT: a faster implementation is possible but probably not that useful
  93171. * since this is only called a couple of times in the metadata readers.
  93172. */
  93173. FLAC__ASSERT(0 != br);
  93174. FLAC__ASSERT(0 != br->buffer);
  93175. if(bits > 0) {
  93176. const unsigned n = br->consumed_bits & 7;
  93177. unsigned m;
  93178. FLAC__uint32 x;
  93179. if(n != 0) {
  93180. m = min(8-n, bits);
  93181. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93182. return false;
  93183. bits -= m;
  93184. }
  93185. m = bits / 8;
  93186. if(m > 0) {
  93187. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93188. return false;
  93189. bits %= 8;
  93190. }
  93191. if(bits > 0) {
  93192. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93193. return false;
  93194. }
  93195. }
  93196. return true;
  93197. }
  93198. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93199. {
  93200. FLAC__uint32 x;
  93201. FLAC__ASSERT(0 != br);
  93202. FLAC__ASSERT(0 != br->buffer);
  93203. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93204. /* step 1: skip over partial head word to get word aligned */
  93205. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93206. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93207. return false;
  93208. nvals--;
  93209. }
  93210. if(0 == nvals)
  93211. return true;
  93212. /* step 2: skip whole words in chunks */
  93213. while(nvals >= FLAC__BYTES_PER_WORD) {
  93214. if(br->consumed_words < br->words) {
  93215. br->consumed_words++;
  93216. nvals -= FLAC__BYTES_PER_WORD;
  93217. }
  93218. else if(!bitreader_read_from_client_(br))
  93219. return false;
  93220. }
  93221. /* step 3: skip any remainder from partial tail bytes */
  93222. while(nvals) {
  93223. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93224. return false;
  93225. nvals--;
  93226. }
  93227. return true;
  93228. }
  93229. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93230. {
  93231. FLAC__uint32 x;
  93232. FLAC__ASSERT(0 != br);
  93233. FLAC__ASSERT(0 != br->buffer);
  93234. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93235. /* step 1: read from partial head word to get word aligned */
  93236. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93237. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93238. return false;
  93239. *val++ = (FLAC__byte)x;
  93240. nvals--;
  93241. }
  93242. if(0 == nvals)
  93243. return true;
  93244. /* step 2: read whole words in chunks */
  93245. while(nvals >= FLAC__BYTES_PER_WORD) {
  93246. if(br->consumed_words < br->words) {
  93247. const brword word = br->buffer[br->consumed_words++];
  93248. #if FLAC__BYTES_PER_WORD == 4
  93249. val[0] = (FLAC__byte)(word >> 24);
  93250. val[1] = (FLAC__byte)(word >> 16);
  93251. val[2] = (FLAC__byte)(word >> 8);
  93252. val[3] = (FLAC__byte)word;
  93253. #elif FLAC__BYTES_PER_WORD == 8
  93254. val[0] = (FLAC__byte)(word >> 56);
  93255. val[1] = (FLAC__byte)(word >> 48);
  93256. val[2] = (FLAC__byte)(word >> 40);
  93257. val[3] = (FLAC__byte)(word >> 32);
  93258. val[4] = (FLAC__byte)(word >> 24);
  93259. val[5] = (FLAC__byte)(word >> 16);
  93260. val[6] = (FLAC__byte)(word >> 8);
  93261. val[7] = (FLAC__byte)word;
  93262. #else
  93263. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93264. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93265. #endif
  93266. val += FLAC__BYTES_PER_WORD;
  93267. nvals -= FLAC__BYTES_PER_WORD;
  93268. }
  93269. else if(!bitreader_read_from_client_(br))
  93270. return false;
  93271. }
  93272. /* step 3: read any remainder from partial tail bytes */
  93273. while(nvals) {
  93274. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93275. return false;
  93276. *val++ = (FLAC__byte)x;
  93277. nvals--;
  93278. }
  93279. return true;
  93280. }
  93281. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93282. #if 0 /* slow but readable version */
  93283. {
  93284. unsigned bit;
  93285. FLAC__ASSERT(0 != br);
  93286. FLAC__ASSERT(0 != br->buffer);
  93287. *val = 0;
  93288. while(1) {
  93289. if(!FLAC__bitreader_read_bit(br, &bit))
  93290. return false;
  93291. if(bit)
  93292. break;
  93293. else
  93294. *val++;
  93295. }
  93296. return true;
  93297. }
  93298. #else
  93299. {
  93300. unsigned i;
  93301. FLAC__ASSERT(0 != br);
  93302. FLAC__ASSERT(0 != br->buffer);
  93303. *val = 0;
  93304. while(1) {
  93305. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93306. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93307. if(b) {
  93308. i = COUNT_ZERO_MSBS(b);
  93309. *val += i;
  93310. i++;
  93311. br->consumed_bits += i;
  93312. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93313. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93314. br->consumed_words++;
  93315. br->consumed_bits = 0;
  93316. }
  93317. return true;
  93318. }
  93319. else {
  93320. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93321. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93322. br->consumed_words++;
  93323. br->consumed_bits = 0;
  93324. /* didn't find stop bit yet, have to keep going... */
  93325. }
  93326. }
  93327. /* at this point we've eaten up all the whole words; have to try
  93328. * reading through any tail bytes before calling the read callback.
  93329. * this is a repeat of the above logic adjusted for the fact we
  93330. * don't have a whole word. note though if the client is feeding
  93331. * us data a byte at a time (unlikely), br->consumed_bits may not
  93332. * be zero.
  93333. */
  93334. if(br->bytes) {
  93335. const unsigned end = br->bytes * 8;
  93336. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93337. if(b) {
  93338. i = COUNT_ZERO_MSBS(b);
  93339. *val += i;
  93340. i++;
  93341. br->consumed_bits += i;
  93342. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93343. return true;
  93344. }
  93345. else {
  93346. *val += end - br->consumed_bits;
  93347. br->consumed_bits += end;
  93348. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93349. /* didn't find stop bit yet, have to keep going... */
  93350. }
  93351. }
  93352. if(!bitreader_read_from_client_(br))
  93353. return false;
  93354. }
  93355. }
  93356. #endif
  93357. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93358. {
  93359. FLAC__uint32 lsbs = 0, msbs = 0;
  93360. unsigned uval;
  93361. FLAC__ASSERT(0 != br);
  93362. FLAC__ASSERT(0 != br->buffer);
  93363. FLAC__ASSERT(parameter <= 31);
  93364. /* read the unary MSBs and end bit */
  93365. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93366. return false;
  93367. /* read the binary LSBs */
  93368. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93369. return false;
  93370. /* compose the value */
  93371. uval = (msbs << parameter) | lsbs;
  93372. if(uval & 1)
  93373. *val = -((int)(uval >> 1)) - 1;
  93374. else
  93375. *val = (int)(uval >> 1);
  93376. return true;
  93377. }
  93378. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93379. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93380. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93381. /* OPT: possibly faster version for use with MSVC */
  93382. #ifdef _MSC_VER
  93383. {
  93384. unsigned i;
  93385. unsigned uval = 0;
  93386. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93387. /* try and get br->consumed_words and br->consumed_bits into register;
  93388. * must remember to flush them back to *br before calling other
  93389. * bitwriter functions that use them, and before returning */
  93390. register unsigned cwords;
  93391. register unsigned cbits;
  93392. FLAC__ASSERT(0 != br);
  93393. FLAC__ASSERT(0 != br->buffer);
  93394. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93395. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93396. FLAC__ASSERT(parameter < 32);
  93397. /* 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 */
  93398. if(nvals == 0)
  93399. return true;
  93400. cbits = br->consumed_bits;
  93401. cwords = br->consumed_words;
  93402. while(1) {
  93403. /* read unary part */
  93404. while(1) {
  93405. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93406. brword b = br->buffer[cwords] << cbits;
  93407. if(b) {
  93408. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93409. __asm {
  93410. bsr eax, b
  93411. not eax
  93412. and eax, 31
  93413. mov i, eax
  93414. }
  93415. #else
  93416. i = COUNT_ZERO_MSBS(b);
  93417. #endif
  93418. uval += i;
  93419. bits = parameter;
  93420. i++;
  93421. cbits += i;
  93422. if(cbits == FLAC__BITS_PER_WORD) {
  93423. crc16_update_word_(br, br->buffer[cwords]);
  93424. cwords++;
  93425. cbits = 0;
  93426. }
  93427. goto break1;
  93428. }
  93429. else {
  93430. uval += FLAC__BITS_PER_WORD - cbits;
  93431. crc16_update_word_(br, br->buffer[cwords]);
  93432. cwords++;
  93433. cbits = 0;
  93434. /* didn't find stop bit yet, have to keep going... */
  93435. }
  93436. }
  93437. /* at this point we've eaten up all the whole words; have to try
  93438. * reading through any tail bytes before calling the read callback.
  93439. * this is a repeat of the above logic adjusted for the fact we
  93440. * don't have a whole word. note though if the client is feeding
  93441. * us data a byte at a time (unlikely), br->consumed_bits may not
  93442. * be zero.
  93443. */
  93444. if(br->bytes) {
  93445. const unsigned end = br->bytes * 8;
  93446. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93447. if(b) {
  93448. i = COUNT_ZERO_MSBS(b);
  93449. uval += i;
  93450. bits = parameter;
  93451. i++;
  93452. cbits += i;
  93453. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93454. goto break1;
  93455. }
  93456. else {
  93457. uval += end - cbits;
  93458. cbits += end;
  93459. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93460. /* didn't find stop bit yet, have to keep going... */
  93461. }
  93462. }
  93463. /* flush registers and read; bitreader_read_from_client_() does
  93464. * not touch br->consumed_bits at all but we still need to set
  93465. * it in case it fails and we have to return false.
  93466. */
  93467. br->consumed_bits = cbits;
  93468. br->consumed_words = cwords;
  93469. if(!bitreader_read_from_client_(br))
  93470. return false;
  93471. cwords = br->consumed_words;
  93472. }
  93473. break1:
  93474. /* read binary part */
  93475. FLAC__ASSERT(cwords <= br->words);
  93476. if(bits) {
  93477. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93478. /* flush registers and read; bitreader_read_from_client_() does
  93479. * not touch br->consumed_bits at all but we still need to set
  93480. * it in case it fails and we have to return false.
  93481. */
  93482. br->consumed_bits = cbits;
  93483. br->consumed_words = cwords;
  93484. if(!bitreader_read_from_client_(br))
  93485. return false;
  93486. cwords = br->consumed_words;
  93487. }
  93488. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93489. if(cbits) {
  93490. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93491. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93492. const brword word = br->buffer[cwords];
  93493. if(bits < n) {
  93494. uval <<= bits;
  93495. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93496. cbits += bits;
  93497. goto break2;
  93498. }
  93499. uval <<= n;
  93500. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93501. bits -= n;
  93502. crc16_update_word_(br, word);
  93503. cwords++;
  93504. cbits = 0;
  93505. 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 */
  93506. uval <<= bits;
  93507. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93508. cbits = bits;
  93509. }
  93510. goto break2;
  93511. }
  93512. else {
  93513. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93514. uval <<= bits;
  93515. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93516. cbits = bits;
  93517. goto break2;
  93518. }
  93519. }
  93520. else {
  93521. /* in this case we're starting our read at a partial tail word;
  93522. * the reader has guaranteed that we have at least 'bits' bits
  93523. * available to read, which makes this case simpler.
  93524. */
  93525. uval <<= bits;
  93526. if(cbits) {
  93527. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93528. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93529. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93530. cbits += bits;
  93531. goto break2;
  93532. }
  93533. else {
  93534. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93535. cbits += bits;
  93536. goto break2;
  93537. }
  93538. }
  93539. }
  93540. break2:
  93541. /* compose the value */
  93542. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93543. /* are we done? */
  93544. --nvals;
  93545. if(nvals == 0) {
  93546. br->consumed_bits = cbits;
  93547. br->consumed_words = cwords;
  93548. return true;
  93549. }
  93550. uval = 0;
  93551. ++vals;
  93552. }
  93553. }
  93554. #else
  93555. {
  93556. unsigned i;
  93557. unsigned uval = 0;
  93558. /* try and get br->consumed_words and br->consumed_bits into register;
  93559. * must remember to flush them back to *br before calling other
  93560. * bitwriter functions that use them, and before returning */
  93561. register unsigned cwords;
  93562. register unsigned cbits;
  93563. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93564. FLAC__ASSERT(0 != br);
  93565. FLAC__ASSERT(0 != br->buffer);
  93566. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93567. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93568. FLAC__ASSERT(parameter < 32);
  93569. /* 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 */
  93570. if(nvals == 0)
  93571. return true;
  93572. cbits = br->consumed_bits;
  93573. cwords = br->consumed_words;
  93574. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93575. while(1) {
  93576. /* read unary part */
  93577. while(1) {
  93578. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93579. brword b = br->buffer[cwords] << cbits;
  93580. if(b) {
  93581. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93582. asm volatile (
  93583. "bsrl %1, %0;"
  93584. "notl %0;"
  93585. "andl $31, %0;"
  93586. : "=r"(i)
  93587. : "r"(b)
  93588. );
  93589. #else
  93590. i = COUNT_ZERO_MSBS(b);
  93591. #endif
  93592. uval += i;
  93593. cbits += i;
  93594. cbits++; /* skip over stop bit */
  93595. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93596. crc16_update_word_(br, br->buffer[cwords]);
  93597. cwords++;
  93598. cbits = 0;
  93599. }
  93600. goto break1;
  93601. }
  93602. else {
  93603. uval += FLAC__BITS_PER_WORD - cbits;
  93604. crc16_update_word_(br, br->buffer[cwords]);
  93605. cwords++;
  93606. cbits = 0;
  93607. /* didn't find stop bit yet, have to keep going... */
  93608. }
  93609. }
  93610. /* at this point we've eaten up all the whole words; have to try
  93611. * reading through any tail bytes before calling the read callback.
  93612. * this is a repeat of the above logic adjusted for the fact we
  93613. * don't have a whole word. note though if the client is feeding
  93614. * us data a byte at a time (unlikely), br->consumed_bits may not
  93615. * be zero.
  93616. */
  93617. if(br->bytes) {
  93618. const unsigned end = br->bytes * 8;
  93619. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93620. if(b) {
  93621. i = COUNT_ZERO_MSBS(b);
  93622. uval += i;
  93623. cbits += i;
  93624. cbits++; /* skip over stop bit */
  93625. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93626. goto break1;
  93627. }
  93628. else {
  93629. uval += end - cbits;
  93630. cbits += end;
  93631. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93632. /* didn't find stop bit yet, have to keep going... */
  93633. }
  93634. }
  93635. /* flush registers and read; bitreader_read_from_client_() does
  93636. * not touch br->consumed_bits at all but we still need to set
  93637. * it in case it fails and we have to return false.
  93638. */
  93639. br->consumed_bits = cbits;
  93640. br->consumed_words = cwords;
  93641. if(!bitreader_read_from_client_(br))
  93642. return false;
  93643. cwords = br->consumed_words;
  93644. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93645. /* + uval to offset our count by the # of unary bits already
  93646. * consumed before the read, because we will add these back
  93647. * in all at once at break1
  93648. */
  93649. }
  93650. break1:
  93651. ucbits -= uval;
  93652. ucbits--; /* account for stop bit */
  93653. /* read binary part */
  93654. FLAC__ASSERT(cwords <= br->words);
  93655. if(parameter) {
  93656. while(ucbits < parameter) {
  93657. /* flush registers and read; bitreader_read_from_client_() does
  93658. * not touch br->consumed_bits at all but we still need to set
  93659. * it in case it fails and we have to return false.
  93660. */
  93661. br->consumed_bits = cbits;
  93662. br->consumed_words = cwords;
  93663. if(!bitreader_read_from_client_(br))
  93664. return false;
  93665. cwords = br->consumed_words;
  93666. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93667. }
  93668. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93669. if(cbits) {
  93670. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93671. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93672. const brword word = br->buffer[cwords];
  93673. if(parameter < n) {
  93674. uval <<= parameter;
  93675. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93676. cbits += parameter;
  93677. }
  93678. else {
  93679. uval <<= n;
  93680. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93681. crc16_update_word_(br, word);
  93682. cwords++;
  93683. cbits = parameter - n;
  93684. 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 */
  93685. uval <<= cbits;
  93686. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93687. }
  93688. }
  93689. }
  93690. else {
  93691. cbits = parameter;
  93692. uval <<= parameter;
  93693. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93694. }
  93695. }
  93696. else {
  93697. /* in this case we're starting our read at a partial tail word;
  93698. * the reader has guaranteed that we have at least 'parameter'
  93699. * bits available to read, which makes this case simpler.
  93700. */
  93701. uval <<= parameter;
  93702. if(cbits) {
  93703. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93704. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93705. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93706. cbits += parameter;
  93707. }
  93708. else {
  93709. cbits = parameter;
  93710. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93711. }
  93712. }
  93713. }
  93714. ucbits -= parameter;
  93715. /* compose the value */
  93716. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93717. /* are we done? */
  93718. --nvals;
  93719. if(nvals == 0) {
  93720. br->consumed_bits = cbits;
  93721. br->consumed_words = cwords;
  93722. return true;
  93723. }
  93724. uval = 0;
  93725. ++vals;
  93726. }
  93727. }
  93728. #endif
  93729. #if 0 /* UNUSED */
  93730. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93731. {
  93732. FLAC__uint32 lsbs = 0, msbs = 0;
  93733. unsigned bit, uval, k;
  93734. FLAC__ASSERT(0 != br);
  93735. FLAC__ASSERT(0 != br->buffer);
  93736. k = FLAC__bitmath_ilog2(parameter);
  93737. /* read the unary MSBs and end bit */
  93738. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93739. return false;
  93740. /* read the binary LSBs */
  93741. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93742. return false;
  93743. if(parameter == 1u<<k) {
  93744. /* compose the value */
  93745. uval = (msbs << k) | lsbs;
  93746. }
  93747. else {
  93748. unsigned d = (1 << (k+1)) - parameter;
  93749. if(lsbs >= d) {
  93750. if(!FLAC__bitreader_read_bit(br, &bit))
  93751. return false;
  93752. lsbs <<= 1;
  93753. lsbs |= bit;
  93754. lsbs -= d;
  93755. }
  93756. /* compose the value */
  93757. uval = msbs * parameter + lsbs;
  93758. }
  93759. /* unfold unsigned to signed */
  93760. if(uval & 1)
  93761. *val = -((int)(uval >> 1)) - 1;
  93762. else
  93763. *val = (int)(uval >> 1);
  93764. return true;
  93765. }
  93766. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93767. {
  93768. FLAC__uint32 lsbs, msbs = 0;
  93769. unsigned bit, k;
  93770. FLAC__ASSERT(0 != br);
  93771. FLAC__ASSERT(0 != br->buffer);
  93772. k = FLAC__bitmath_ilog2(parameter);
  93773. /* read the unary MSBs and end bit */
  93774. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93775. return false;
  93776. /* read the binary LSBs */
  93777. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93778. return false;
  93779. if(parameter == 1u<<k) {
  93780. /* compose the value */
  93781. *val = (msbs << k) | lsbs;
  93782. }
  93783. else {
  93784. unsigned d = (1 << (k+1)) - parameter;
  93785. if(lsbs >= d) {
  93786. if(!FLAC__bitreader_read_bit(br, &bit))
  93787. return false;
  93788. lsbs <<= 1;
  93789. lsbs |= bit;
  93790. lsbs -= d;
  93791. }
  93792. /* compose the value */
  93793. *val = msbs * parameter + lsbs;
  93794. }
  93795. return true;
  93796. }
  93797. #endif /* UNUSED */
  93798. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93799. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93800. {
  93801. FLAC__uint32 v = 0;
  93802. FLAC__uint32 x;
  93803. unsigned i;
  93804. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93805. return false;
  93806. if(raw)
  93807. raw[(*rawlen)++] = (FLAC__byte)x;
  93808. if(!(x & 0x80)) { /* 0xxxxxxx */
  93809. v = x;
  93810. i = 0;
  93811. }
  93812. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93813. v = x & 0x1F;
  93814. i = 1;
  93815. }
  93816. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93817. v = x & 0x0F;
  93818. i = 2;
  93819. }
  93820. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93821. v = x & 0x07;
  93822. i = 3;
  93823. }
  93824. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93825. v = x & 0x03;
  93826. i = 4;
  93827. }
  93828. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93829. v = x & 0x01;
  93830. i = 5;
  93831. }
  93832. else {
  93833. *val = 0xffffffff;
  93834. return true;
  93835. }
  93836. for( ; i; i--) {
  93837. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93838. return false;
  93839. if(raw)
  93840. raw[(*rawlen)++] = (FLAC__byte)x;
  93841. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93842. *val = 0xffffffff;
  93843. return true;
  93844. }
  93845. v <<= 6;
  93846. v |= (x & 0x3F);
  93847. }
  93848. *val = v;
  93849. return true;
  93850. }
  93851. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93852. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93853. {
  93854. FLAC__uint64 v = 0;
  93855. FLAC__uint32 x;
  93856. unsigned i;
  93857. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93858. return false;
  93859. if(raw)
  93860. raw[(*rawlen)++] = (FLAC__byte)x;
  93861. if(!(x & 0x80)) { /* 0xxxxxxx */
  93862. v = x;
  93863. i = 0;
  93864. }
  93865. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93866. v = x & 0x1F;
  93867. i = 1;
  93868. }
  93869. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93870. v = x & 0x0F;
  93871. i = 2;
  93872. }
  93873. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93874. v = x & 0x07;
  93875. i = 3;
  93876. }
  93877. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93878. v = x & 0x03;
  93879. i = 4;
  93880. }
  93881. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93882. v = x & 0x01;
  93883. i = 5;
  93884. }
  93885. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93886. v = 0;
  93887. i = 6;
  93888. }
  93889. else {
  93890. *val = FLAC__U64L(0xffffffffffffffff);
  93891. return true;
  93892. }
  93893. for( ; i; i--) {
  93894. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93895. return false;
  93896. if(raw)
  93897. raw[(*rawlen)++] = (FLAC__byte)x;
  93898. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93899. *val = FLAC__U64L(0xffffffffffffffff);
  93900. return true;
  93901. }
  93902. v <<= 6;
  93903. v |= (x & 0x3F);
  93904. }
  93905. *val = v;
  93906. return true;
  93907. }
  93908. #endif
  93909. /*** End of inlined file: bitreader.c ***/
  93910. /*** Start of inlined file: bitwriter.c ***/
  93911. /*** Start of inlined file: juce_FlacHeader.h ***/
  93912. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93913. // tasks..
  93914. #define VERSION "1.2.1"
  93915. #define FLAC__NO_DLL 1
  93916. #if JUCE_MSVC
  93917. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93918. #endif
  93919. #if JUCE_MAC
  93920. #define FLAC__SYS_DARWIN 1
  93921. #endif
  93922. /*** End of inlined file: juce_FlacHeader.h ***/
  93923. #if JUCE_USE_FLAC
  93924. #if HAVE_CONFIG_H
  93925. # include <config.h>
  93926. #endif
  93927. #include <stdlib.h> /* for malloc() */
  93928. #include <string.h> /* for memcpy(), memset() */
  93929. #ifdef _MSC_VER
  93930. #include <winsock.h> /* for ntohl() */
  93931. #elif defined FLAC__SYS_DARWIN
  93932. #include <machine/endian.h> /* for ntohl() */
  93933. #elif defined __MINGW32__
  93934. #include <winsock.h> /* for ntohl() */
  93935. #else
  93936. #include <netinet/in.h> /* for ntohl() */
  93937. #endif
  93938. #if 0 /* UNUSED */
  93939. #endif
  93940. /*** Start of inlined file: bitwriter.h ***/
  93941. #ifndef FLAC__PRIVATE__BITWRITER_H
  93942. #define FLAC__PRIVATE__BITWRITER_H
  93943. #include <stdio.h> /* for FILE */
  93944. /*
  93945. * opaque structure definition
  93946. */
  93947. struct FLAC__BitWriter;
  93948. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93949. /*
  93950. * construction, deletion, initialization, etc functions
  93951. */
  93952. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93953. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93954. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93955. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93956. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93957. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93958. /*
  93959. * CRC functions
  93960. *
  93961. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93962. */
  93963. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93964. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93965. /*
  93966. * info functions
  93967. */
  93968. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93969. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93970. /*
  93971. * direct buffer access
  93972. *
  93973. * there may be no calls on the bitwriter between get and release.
  93974. * the bitwriter continues to own the returned buffer.
  93975. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93976. */
  93977. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93978. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93979. /*
  93980. * write functions
  93981. */
  93982. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93983. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93984. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93985. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93986. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93987. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93988. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93989. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93990. #if 0 /* UNUSED */
  93991. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93992. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93993. #endif
  93994. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93995. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93996. #if 0 /* UNUSED */
  93997. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93998. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93999. #endif
  94000. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94001. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94002. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94003. #endif
  94004. /*** End of inlined file: bitwriter.h ***/
  94005. /*** Start of inlined file: alloc.h ***/
  94006. #ifndef FLAC__SHARE__ALLOC_H
  94007. #define FLAC__SHARE__ALLOC_H
  94008. #if HAVE_CONFIG_H
  94009. # include <config.h>
  94010. #endif
  94011. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94012. * before #including this file, otherwise SIZE_MAX might not be defined
  94013. */
  94014. #include <limits.h> /* for SIZE_MAX */
  94015. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94016. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94017. #endif
  94018. #include <stdlib.h> /* for size_t, malloc(), etc */
  94019. #ifndef SIZE_MAX
  94020. # ifndef SIZE_T_MAX
  94021. # ifdef _MSC_VER
  94022. # define SIZE_T_MAX UINT_MAX
  94023. # else
  94024. # error
  94025. # endif
  94026. # endif
  94027. # define SIZE_MAX SIZE_T_MAX
  94028. #endif
  94029. #ifndef FLaC__INLINE
  94030. #define FLaC__INLINE
  94031. #endif
  94032. /* avoid malloc()ing 0 bytes, see:
  94033. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94034. */
  94035. static FLaC__INLINE void *safe_malloc_(size_t size)
  94036. {
  94037. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94038. if(!size)
  94039. size++;
  94040. return malloc(size);
  94041. }
  94042. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94043. {
  94044. if(!nmemb || !size)
  94045. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94046. return calloc(nmemb, size);
  94047. }
  94048. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94049. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94050. {
  94051. size2 += size1;
  94052. if(size2 < size1)
  94053. return 0;
  94054. return safe_malloc_(size2);
  94055. }
  94056. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94057. {
  94058. size2 += size1;
  94059. if(size2 < size1)
  94060. return 0;
  94061. size3 += size2;
  94062. if(size3 < size2)
  94063. return 0;
  94064. return safe_malloc_(size3);
  94065. }
  94066. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94067. {
  94068. size2 += size1;
  94069. if(size2 < size1)
  94070. return 0;
  94071. size3 += size2;
  94072. if(size3 < size2)
  94073. return 0;
  94074. size4 += size3;
  94075. if(size4 < size3)
  94076. return 0;
  94077. return safe_malloc_(size4);
  94078. }
  94079. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94080. #if 0
  94081. needs support for cases where sizeof(size_t) != 4
  94082. {
  94083. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94084. if(sizeof(size_t) == 4) {
  94085. if ((double)size1 * (double)size2 < 4294967296.0)
  94086. return malloc(size1*size2);
  94087. }
  94088. return 0;
  94089. }
  94090. #else
  94091. /* better? */
  94092. {
  94093. if(!size1 || !size2)
  94094. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94095. if(size1 > SIZE_MAX / size2)
  94096. return 0;
  94097. return malloc(size1*size2);
  94098. }
  94099. #endif
  94100. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94101. {
  94102. if(!size1 || !size2 || !size3)
  94103. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94104. if(size1 > SIZE_MAX / size2)
  94105. return 0;
  94106. size1 *= size2;
  94107. if(size1 > SIZE_MAX / size3)
  94108. return 0;
  94109. return malloc(size1*size3);
  94110. }
  94111. /* size1*size2 + size3 */
  94112. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94113. {
  94114. if(!size1 || !size2)
  94115. return safe_malloc_(size3);
  94116. if(size1 > SIZE_MAX / size2)
  94117. return 0;
  94118. return safe_malloc_add_2op_(size1*size2, size3);
  94119. }
  94120. /* size1 * (size2 + size3) */
  94121. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94122. {
  94123. if(!size1 || (!size2 && !size3))
  94124. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94125. size2 += size3;
  94126. if(size2 < size3)
  94127. return 0;
  94128. return safe_malloc_mul_2op_(size1, size2);
  94129. }
  94130. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94131. {
  94132. size2 += size1;
  94133. if(size2 < size1)
  94134. return 0;
  94135. return realloc(ptr, size2);
  94136. }
  94137. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94138. {
  94139. size2 += size1;
  94140. if(size2 < size1)
  94141. return 0;
  94142. size3 += size2;
  94143. if(size3 < size2)
  94144. return 0;
  94145. return realloc(ptr, size3);
  94146. }
  94147. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94148. {
  94149. size2 += size1;
  94150. if(size2 < size1)
  94151. return 0;
  94152. size3 += size2;
  94153. if(size3 < size2)
  94154. return 0;
  94155. size4 += size3;
  94156. if(size4 < size3)
  94157. return 0;
  94158. return realloc(ptr, size4);
  94159. }
  94160. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94161. {
  94162. if(!size1 || !size2)
  94163. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94164. if(size1 > SIZE_MAX / size2)
  94165. return 0;
  94166. return realloc(ptr, size1*size2);
  94167. }
  94168. /* size1 * (size2 + size3) */
  94169. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94170. {
  94171. if(!size1 || (!size2 && !size3))
  94172. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94173. size2 += size3;
  94174. if(size2 < size3)
  94175. return 0;
  94176. return safe_realloc_mul_2op_(ptr, size1, size2);
  94177. }
  94178. #endif
  94179. /*** End of inlined file: alloc.h ***/
  94180. /* Things should be fastest when this matches the machine word size */
  94181. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94182. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94183. typedef FLAC__uint32 bwword;
  94184. #define FLAC__BYTES_PER_WORD 4
  94185. #define FLAC__BITS_PER_WORD 32
  94186. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94187. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94188. #if WORDS_BIGENDIAN
  94189. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94190. #else
  94191. #ifdef _MSC_VER
  94192. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94193. #else
  94194. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94195. #endif
  94196. #endif
  94197. /*
  94198. * The default capacity here doesn't matter too much. The buffer always grows
  94199. * to hold whatever is written to it. Usually the encoder will stop adding at
  94200. * a frame or metadata block, then write that out and clear the buffer for the
  94201. * next one.
  94202. */
  94203. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94204. /* When growing, increment 4K at a time */
  94205. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94206. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94207. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94208. #ifdef min
  94209. #undef min
  94210. #endif
  94211. #define min(x,y) ((x)<(y)?(x):(y))
  94212. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94213. #ifdef _MSC_VER
  94214. #define FLAC__U64L(x) x
  94215. #else
  94216. #define FLAC__U64L(x) x##LLU
  94217. #endif
  94218. #ifndef FLaC__INLINE
  94219. #define FLaC__INLINE
  94220. #endif
  94221. struct FLAC__BitWriter {
  94222. bwword *buffer;
  94223. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94224. unsigned capacity; /* capacity of buffer in words */
  94225. unsigned words; /* # of complete words in buffer */
  94226. unsigned bits; /* # of used bits in accum */
  94227. };
  94228. /* * WATCHOUT: The current implementation only grows the buffer. */
  94229. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94230. {
  94231. unsigned new_capacity;
  94232. bwword *new_buffer;
  94233. FLAC__ASSERT(0 != bw);
  94234. FLAC__ASSERT(0 != bw->buffer);
  94235. /* calculate total words needed to store 'bits_to_add' additional bits */
  94236. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94237. /* it's possible (due to pessimism in the growth estimation that
  94238. * leads to this call) that we don't actually need to grow
  94239. */
  94240. if(bw->capacity >= new_capacity)
  94241. return true;
  94242. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94243. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94244. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94245. /* make sure we got everything right */
  94246. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94247. FLAC__ASSERT(new_capacity > bw->capacity);
  94248. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94249. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94250. if(new_buffer == 0)
  94251. return false;
  94252. bw->buffer = new_buffer;
  94253. bw->capacity = new_capacity;
  94254. return true;
  94255. }
  94256. /***********************************************************************
  94257. *
  94258. * Class constructor/destructor
  94259. *
  94260. ***********************************************************************/
  94261. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94262. {
  94263. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94264. /* note that calloc() sets all members to 0 for us */
  94265. return bw;
  94266. }
  94267. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94268. {
  94269. FLAC__ASSERT(0 != bw);
  94270. FLAC__bitwriter_free(bw);
  94271. free(bw);
  94272. }
  94273. /***********************************************************************
  94274. *
  94275. * Public class methods
  94276. *
  94277. ***********************************************************************/
  94278. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94279. {
  94280. FLAC__ASSERT(0 != bw);
  94281. bw->words = bw->bits = 0;
  94282. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94283. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94284. if(bw->buffer == 0)
  94285. return false;
  94286. return true;
  94287. }
  94288. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94289. {
  94290. FLAC__ASSERT(0 != bw);
  94291. if(0 != bw->buffer)
  94292. free(bw->buffer);
  94293. bw->buffer = 0;
  94294. bw->capacity = 0;
  94295. bw->words = bw->bits = 0;
  94296. }
  94297. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94298. {
  94299. bw->words = bw->bits = 0;
  94300. }
  94301. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94302. {
  94303. unsigned i, j;
  94304. if(bw == 0) {
  94305. fprintf(out, "bitwriter is NULL\n");
  94306. }
  94307. else {
  94308. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94309. for(i = 0; i < bw->words; i++) {
  94310. fprintf(out, "%08X: ", i);
  94311. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94312. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94313. fprintf(out, "\n");
  94314. }
  94315. if(bw->bits > 0) {
  94316. fprintf(out, "%08X: ", i);
  94317. for(j = 0; j < bw->bits; j++)
  94318. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94319. fprintf(out, "\n");
  94320. }
  94321. }
  94322. }
  94323. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94324. {
  94325. const FLAC__byte *buffer;
  94326. size_t bytes;
  94327. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94328. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94329. return false;
  94330. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94331. FLAC__bitwriter_release_buffer(bw);
  94332. return true;
  94333. }
  94334. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94335. {
  94336. const FLAC__byte *buffer;
  94337. size_t bytes;
  94338. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94339. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94340. return false;
  94341. *crc = FLAC__crc8(buffer, bytes);
  94342. FLAC__bitwriter_release_buffer(bw);
  94343. return true;
  94344. }
  94345. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94346. {
  94347. return ((bw->bits & 7) == 0);
  94348. }
  94349. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94350. {
  94351. return FLAC__TOTAL_BITS(bw);
  94352. }
  94353. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94354. {
  94355. FLAC__ASSERT((bw->bits & 7) == 0);
  94356. /* double protection */
  94357. if(bw->bits & 7)
  94358. return false;
  94359. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94360. if(bw->bits) {
  94361. FLAC__ASSERT(bw->words <= bw->capacity);
  94362. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94363. return false;
  94364. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94365. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94366. }
  94367. /* now we can just return what we have */
  94368. *buffer = (FLAC__byte*)bw->buffer;
  94369. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94370. return true;
  94371. }
  94372. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94373. {
  94374. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94375. * get-mode' flag could be added everywhere and then cleared here
  94376. */
  94377. (void)bw;
  94378. }
  94379. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94380. {
  94381. unsigned n;
  94382. FLAC__ASSERT(0 != bw);
  94383. FLAC__ASSERT(0 != bw->buffer);
  94384. if(bits == 0)
  94385. return true;
  94386. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94387. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94388. return false;
  94389. /* first part gets to word alignment */
  94390. if(bw->bits) {
  94391. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94392. bw->accum <<= n;
  94393. bits -= n;
  94394. bw->bits += n;
  94395. if(bw->bits == FLAC__BITS_PER_WORD) {
  94396. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94397. bw->bits = 0;
  94398. }
  94399. else
  94400. return true;
  94401. }
  94402. /* do whole words */
  94403. while(bits >= FLAC__BITS_PER_WORD) {
  94404. bw->buffer[bw->words++] = 0;
  94405. bits -= FLAC__BITS_PER_WORD;
  94406. }
  94407. /* do any leftovers */
  94408. if(bits > 0) {
  94409. bw->accum = 0;
  94410. bw->bits = bits;
  94411. }
  94412. return true;
  94413. }
  94414. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94415. {
  94416. register unsigned left;
  94417. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94418. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94419. FLAC__ASSERT(0 != bw);
  94420. FLAC__ASSERT(0 != bw->buffer);
  94421. FLAC__ASSERT(bits <= 32);
  94422. if(bits == 0)
  94423. return true;
  94424. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94425. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94426. return false;
  94427. left = FLAC__BITS_PER_WORD - bw->bits;
  94428. if(bits < left) {
  94429. bw->accum <<= bits;
  94430. bw->accum |= val;
  94431. bw->bits += bits;
  94432. }
  94433. 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 */
  94434. bw->accum <<= left;
  94435. bw->accum |= val >> (bw->bits = bits - left);
  94436. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94437. bw->accum = val;
  94438. }
  94439. else {
  94440. bw->accum = val;
  94441. bw->bits = 0;
  94442. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94443. }
  94444. return true;
  94445. }
  94446. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94447. {
  94448. /* zero-out unused bits */
  94449. if(bits < 32)
  94450. val &= (~(0xffffffff << bits));
  94451. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94452. }
  94453. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94454. {
  94455. /* this could be a little faster but it's not used for much */
  94456. if(bits > 32) {
  94457. return
  94458. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94459. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94460. }
  94461. else
  94462. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94463. }
  94464. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94465. {
  94466. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94467. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94468. return false;
  94469. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94470. return false;
  94471. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94472. return false;
  94473. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94474. return false;
  94475. return true;
  94476. }
  94477. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94478. {
  94479. unsigned i;
  94480. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94481. for(i = 0; i < nvals; i++) {
  94482. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94483. return false;
  94484. }
  94485. return true;
  94486. }
  94487. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94488. {
  94489. if(val < 32)
  94490. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94491. else
  94492. return
  94493. FLAC__bitwriter_write_zeroes(bw, val) &&
  94494. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94495. }
  94496. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94497. {
  94498. FLAC__uint32 uval;
  94499. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94500. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94501. uval = (val<<1) ^ (val>>31);
  94502. return 1 + parameter + (uval >> parameter);
  94503. }
  94504. #if 0 /* UNUSED */
  94505. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94506. {
  94507. unsigned bits, msbs, uval;
  94508. unsigned k;
  94509. FLAC__ASSERT(parameter > 0);
  94510. /* fold signed to unsigned */
  94511. if(val < 0)
  94512. uval = (unsigned)(((-(++val)) << 1) + 1);
  94513. else
  94514. uval = (unsigned)(val << 1);
  94515. k = FLAC__bitmath_ilog2(parameter);
  94516. if(parameter == 1u<<k) {
  94517. FLAC__ASSERT(k <= 30);
  94518. msbs = uval >> k;
  94519. bits = 1 + k + msbs;
  94520. }
  94521. else {
  94522. unsigned q, r, d;
  94523. d = (1 << (k+1)) - parameter;
  94524. q = uval / parameter;
  94525. r = uval - (q * parameter);
  94526. bits = 1 + q + k;
  94527. if(r >= d)
  94528. bits++;
  94529. }
  94530. return bits;
  94531. }
  94532. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94533. {
  94534. unsigned bits, msbs;
  94535. unsigned k;
  94536. FLAC__ASSERT(parameter > 0);
  94537. k = FLAC__bitmath_ilog2(parameter);
  94538. if(parameter == 1u<<k) {
  94539. FLAC__ASSERT(k <= 30);
  94540. msbs = uval >> k;
  94541. bits = 1 + k + msbs;
  94542. }
  94543. else {
  94544. unsigned q, r, d;
  94545. d = (1 << (k+1)) - parameter;
  94546. q = uval / parameter;
  94547. r = uval - (q * parameter);
  94548. bits = 1 + q + k;
  94549. if(r >= d)
  94550. bits++;
  94551. }
  94552. return bits;
  94553. }
  94554. #endif /* UNUSED */
  94555. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94556. {
  94557. unsigned total_bits, interesting_bits, msbs;
  94558. FLAC__uint32 uval, pattern;
  94559. FLAC__ASSERT(0 != bw);
  94560. FLAC__ASSERT(0 != bw->buffer);
  94561. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94562. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94563. uval = (val<<1) ^ (val>>31);
  94564. msbs = uval >> parameter;
  94565. interesting_bits = 1 + parameter;
  94566. total_bits = interesting_bits + msbs;
  94567. pattern = 1 << parameter; /* the unary end bit */
  94568. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94569. if(total_bits <= 32)
  94570. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94571. else
  94572. return
  94573. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94574. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94575. }
  94576. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94577. {
  94578. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94579. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94580. FLAC__uint32 uval;
  94581. unsigned left;
  94582. const unsigned lsbits = 1 + parameter;
  94583. unsigned msbits;
  94584. FLAC__ASSERT(0 != bw);
  94585. FLAC__ASSERT(0 != bw->buffer);
  94586. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94587. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94588. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94589. while(nvals) {
  94590. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94591. uval = (*vals<<1) ^ (*vals>>31);
  94592. msbits = uval >> parameter;
  94593. #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) */
  94594. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94595. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94596. bw->bits = bw->bits + msbits + lsbits;
  94597. uval |= mask1; /* set stop bit */
  94598. uval &= mask2; /* mask off unused top bits */
  94599. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94600. bw->accum <<= msbits;
  94601. bw->accum <<= lsbits;
  94602. bw->accum |= uval;
  94603. if(bw->bits == FLAC__BITS_PER_WORD) {
  94604. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94605. bw->bits = 0;
  94606. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94607. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94608. FLAC__ASSERT(bw->capacity == bw->words);
  94609. return false;
  94610. }
  94611. }
  94612. }
  94613. else {
  94614. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94615. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94616. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94617. bw->bits = bw->bits + msbits + lsbits;
  94618. uval |= mask1; /* set stop bit */
  94619. uval &= mask2; /* mask off unused top bits */
  94620. bw->accum <<= msbits + lsbits;
  94621. bw->accum |= uval;
  94622. }
  94623. else {
  94624. #endif
  94625. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94626. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94627. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94628. return false;
  94629. if(msbits) {
  94630. /* first part gets to word alignment */
  94631. if(bw->bits) {
  94632. left = FLAC__BITS_PER_WORD - bw->bits;
  94633. if(msbits < left) {
  94634. bw->accum <<= msbits;
  94635. bw->bits += msbits;
  94636. goto break1;
  94637. }
  94638. else {
  94639. bw->accum <<= left;
  94640. msbits -= left;
  94641. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94642. bw->bits = 0;
  94643. }
  94644. }
  94645. /* do whole words */
  94646. while(msbits >= FLAC__BITS_PER_WORD) {
  94647. bw->buffer[bw->words++] = 0;
  94648. msbits -= FLAC__BITS_PER_WORD;
  94649. }
  94650. /* do any leftovers */
  94651. if(msbits > 0) {
  94652. bw->accum = 0;
  94653. bw->bits = msbits;
  94654. }
  94655. }
  94656. break1:
  94657. uval |= mask1; /* set stop bit */
  94658. uval &= mask2; /* mask off unused top bits */
  94659. left = FLAC__BITS_PER_WORD - bw->bits;
  94660. if(lsbits < left) {
  94661. bw->accum <<= lsbits;
  94662. bw->accum |= uval;
  94663. bw->bits += lsbits;
  94664. }
  94665. else {
  94666. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94667. * be > lsbits (because of previous assertions) so it would have
  94668. * triggered the (lsbits<left) case above.
  94669. */
  94670. FLAC__ASSERT(bw->bits);
  94671. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94672. bw->accum <<= left;
  94673. bw->accum |= uval >> (bw->bits = lsbits - left);
  94674. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94675. bw->accum = uval;
  94676. }
  94677. #if 1
  94678. }
  94679. #endif
  94680. vals++;
  94681. nvals--;
  94682. }
  94683. return true;
  94684. }
  94685. #if 0 /* UNUSED */
  94686. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94687. {
  94688. unsigned total_bits, msbs, uval;
  94689. unsigned k;
  94690. FLAC__ASSERT(0 != bw);
  94691. FLAC__ASSERT(0 != bw->buffer);
  94692. FLAC__ASSERT(parameter > 0);
  94693. /* fold signed to unsigned */
  94694. if(val < 0)
  94695. uval = (unsigned)(((-(++val)) << 1) + 1);
  94696. else
  94697. uval = (unsigned)(val << 1);
  94698. k = FLAC__bitmath_ilog2(parameter);
  94699. if(parameter == 1u<<k) {
  94700. unsigned pattern;
  94701. FLAC__ASSERT(k <= 30);
  94702. msbs = uval >> k;
  94703. total_bits = 1 + k + msbs;
  94704. pattern = 1 << k; /* the unary end bit */
  94705. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94706. if(total_bits <= 32) {
  94707. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94708. return false;
  94709. }
  94710. else {
  94711. /* write the unary MSBs */
  94712. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94713. return false;
  94714. /* write the unary end bit and binary LSBs */
  94715. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94716. return false;
  94717. }
  94718. }
  94719. else {
  94720. unsigned q, r, d;
  94721. d = (1 << (k+1)) - parameter;
  94722. q = uval / parameter;
  94723. r = uval - (q * parameter);
  94724. /* write the unary MSBs */
  94725. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94726. return false;
  94727. /* write the unary end bit */
  94728. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94729. return false;
  94730. /* write the binary LSBs */
  94731. if(r >= d) {
  94732. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94733. return false;
  94734. }
  94735. else {
  94736. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94737. return false;
  94738. }
  94739. }
  94740. return true;
  94741. }
  94742. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94743. {
  94744. unsigned total_bits, msbs;
  94745. unsigned k;
  94746. FLAC__ASSERT(0 != bw);
  94747. FLAC__ASSERT(0 != bw->buffer);
  94748. FLAC__ASSERT(parameter > 0);
  94749. k = FLAC__bitmath_ilog2(parameter);
  94750. if(parameter == 1u<<k) {
  94751. unsigned pattern;
  94752. FLAC__ASSERT(k <= 30);
  94753. msbs = uval >> k;
  94754. total_bits = 1 + k + msbs;
  94755. pattern = 1 << k; /* the unary end bit */
  94756. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94757. if(total_bits <= 32) {
  94758. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94759. return false;
  94760. }
  94761. else {
  94762. /* write the unary MSBs */
  94763. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94764. return false;
  94765. /* write the unary end bit and binary LSBs */
  94766. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94767. return false;
  94768. }
  94769. }
  94770. else {
  94771. unsigned q, r, d;
  94772. d = (1 << (k+1)) - parameter;
  94773. q = uval / parameter;
  94774. r = uval - (q * parameter);
  94775. /* write the unary MSBs */
  94776. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94777. return false;
  94778. /* write the unary end bit */
  94779. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94780. return false;
  94781. /* write the binary LSBs */
  94782. if(r >= d) {
  94783. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94784. return false;
  94785. }
  94786. else {
  94787. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94788. return false;
  94789. }
  94790. }
  94791. return true;
  94792. }
  94793. #endif /* UNUSED */
  94794. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94795. {
  94796. FLAC__bool ok = 1;
  94797. FLAC__ASSERT(0 != bw);
  94798. FLAC__ASSERT(0 != bw->buffer);
  94799. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94800. if(val < 0x80) {
  94801. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94802. }
  94803. else if(val < 0x800) {
  94804. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94805. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94806. }
  94807. else if(val < 0x10000) {
  94808. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94809. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94810. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94811. }
  94812. else if(val < 0x200000) {
  94813. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94814. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94815. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94816. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94817. }
  94818. else if(val < 0x4000000) {
  94819. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94820. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94821. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94822. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94823. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94824. }
  94825. else {
  94826. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94827. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94828. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94829. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94830. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94831. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94832. }
  94833. return ok;
  94834. }
  94835. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94836. {
  94837. FLAC__bool ok = 1;
  94838. FLAC__ASSERT(0 != bw);
  94839. FLAC__ASSERT(0 != bw->buffer);
  94840. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94841. if(val < 0x80) {
  94842. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94843. }
  94844. else if(val < 0x800) {
  94845. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94846. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94847. }
  94848. else if(val < 0x10000) {
  94849. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94850. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94851. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94852. }
  94853. else if(val < 0x200000) {
  94854. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94855. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94856. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94857. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94858. }
  94859. else if(val < 0x4000000) {
  94860. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94861. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94862. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94863. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94864. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94865. }
  94866. else if(val < 0x80000000) {
  94867. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94868. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94869. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94870. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94871. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94872. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94873. }
  94874. else {
  94875. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94876. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94877. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94878. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94879. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94880. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94881. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94882. }
  94883. return ok;
  94884. }
  94885. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94886. {
  94887. /* 0-pad to byte boundary */
  94888. if(bw->bits & 7u)
  94889. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94890. else
  94891. return true;
  94892. }
  94893. #endif
  94894. /*** End of inlined file: bitwriter.c ***/
  94895. /*** Start of inlined file: cpu.c ***/
  94896. /*** Start of inlined file: juce_FlacHeader.h ***/
  94897. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94898. // tasks..
  94899. #define VERSION "1.2.1"
  94900. #define FLAC__NO_DLL 1
  94901. #if JUCE_MSVC
  94902. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94903. #endif
  94904. #if JUCE_MAC
  94905. #define FLAC__SYS_DARWIN 1
  94906. #endif
  94907. /*** End of inlined file: juce_FlacHeader.h ***/
  94908. #if JUCE_USE_FLAC
  94909. #if HAVE_CONFIG_H
  94910. # include <config.h>
  94911. #endif
  94912. #include <stdlib.h>
  94913. #include <stdio.h>
  94914. #if defined FLAC__CPU_IA32
  94915. # include <signal.h>
  94916. #elif defined FLAC__CPU_PPC
  94917. # if !defined FLAC__NO_ASM
  94918. # if defined FLAC__SYS_DARWIN
  94919. # include <sys/sysctl.h>
  94920. # include <mach/mach.h>
  94921. # include <mach/mach_host.h>
  94922. # include <mach/host_info.h>
  94923. # include <mach/machine.h>
  94924. # ifndef CPU_SUBTYPE_POWERPC_970
  94925. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94926. # endif
  94927. # else /* FLAC__SYS_DARWIN */
  94928. # include <signal.h>
  94929. # include <setjmp.h>
  94930. static sigjmp_buf jmpbuf;
  94931. static volatile sig_atomic_t canjump = 0;
  94932. static void sigill_handler (int sig)
  94933. {
  94934. if (!canjump) {
  94935. signal (sig, SIG_DFL);
  94936. raise (sig);
  94937. }
  94938. canjump = 0;
  94939. siglongjmp (jmpbuf, 1);
  94940. }
  94941. # endif /* FLAC__SYS_DARWIN */
  94942. # endif /* FLAC__NO_ASM */
  94943. #endif /* FLAC__CPU_PPC */
  94944. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94945. #include <sys/param.h>
  94946. #include <sys/sysctl.h>
  94947. #include <machine/cpu.h>
  94948. #endif
  94949. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94950. #include <sys/types.h>
  94951. #include <sys/sysctl.h>
  94952. #endif
  94953. #if defined(__APPLE__)
  94954. /* how to get sysctlbyname()? */
  94955. #endif
  94956. /* these are flags in EDX of CPUID AX=00000001 */
  94957. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94958. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94959. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94960. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94961. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94962. /* these are flags in ECX of CPUID AX=00000001 */
  94963. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94964. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94965. /* these are flags in EDX of CPUID AX=80000001 */
  94966. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94967. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94968. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94969. /*
  94970. * Extra stuff needed for detection of OS support for SSE on IA-32
  94971. */
  94972. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94973. # if defined(__linux__)
  94974. /*
  94975. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94976. * modify the return address to jump over the offending SSE instruction
  94977. * and also the operation following it that indicates the instruction
  94978. * executed successfully. In this way we use no global variables and
  94979. * stay thread-safe.
  94980. *
  94981. * 3 + 3 + 6:
  94982. * 3 bytes for "xorps xmm0,xmm0"
  94983. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94984. * 6 bytes extra in case our estimate is wrong
  94985. * 12 bytes puts us in the NOP "landing zone"
  94986. */
  94987. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94988. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94989. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94990. {
  94991. (void)signal;
  94992. sc.eip += 3 + 3 + 6;
  94993. }
  94994. # else
  94995. # include <sys/ucontext.h>
  94996. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94997. {
  94998. (void)signal, (void)si;
  94999. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95000. }
  95001. # endif
  95002. # elif defined(_MSC_VER)
  95003. # include <windows.h>
  95004. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95005. # ifdef USE_TRY_CATCH_FLAVOR
  95006. # else
  95007. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95008. {
  95009. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95010. ep->ContextRecord->Eip += 3 + 3 + 6;
  95011. return EXCEPTION_CONTINUE_EXECUTION;
  95012. }
  95013. return EXCEPTION_CONTINUE_SEARCH;
  95014. }
  95015. # endif
  95016. # endif
  95017. #endif
  95018. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95019. {
  95020. /*
  95021. * IA32-specific
  95022. */
  95023. #ifdef FLAC__CPU_IA32
  95024. info->type = FLAC__CPUINFO_TYPE_IA32;
  95025. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95026. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95027. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95028. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95029. info->data.ia32.cmov = false;
  95030. info->data.ia32.mmx = false;
  95031. info->data.ia32.fxsr = false;
  95032. info->data.ia32.sse = false;
  95033. info->data.ia32.sse2 = false;
  95034. info->data.ia32.sse3 = false;
  95035. info->data.ia32.ssse3 = false;
  95036. info->data.ia32._3dnow = false;
  95037. info->data.ia32.ext3dnow = false;
  95038. info->data.ia32.extmmx = false;
  95039. if(info->data.ia32.cpuid) {
  95040. /* http://www.sandpile.org/ia32/cpuid.htm */
  95041. FLAC__uint32 flags_edx, flags_ecx;
  95042. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95043. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95044. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95045. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95046. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95047. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95048. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95049. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95050. #ifdef FLAC__USE_3DNOW
  95051. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95052. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95053. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95054. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95055. #else
  95056. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95057. #endif
  95058. #ifdef DEBUG
  95059. fprintf(stderr, "CPU info (IA-32):\n");
  95060. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95061. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95062. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95063. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95064. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95065. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95066. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95067. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95068. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95069. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95070. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95071. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95072. #endif
  95073. /*
  95074. * now have to check for OS support of SSE/SSE2
  95075. */
  95076. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95077. #if defined FLAC__NO_SSE_OS
  95078. /* assume user knows better than us; turn it off */
  95079. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95080. #elif defined FLAC__SSE_OS
  95081. /* assume user knows better than us; leave as detected above */
  95082. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95083. int sse = 0;
  95084. size_t len;
  95085. /* at least one of these must work: */
  95086. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95087. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95088. if(!sse)
  95089. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95090. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95091. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95092. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95093. size_t len = sizeof(val);
  95094. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95095. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95096. else { /* double-check SSE2 */
  95097. mib[1] = CPU_SSE2;
  95098. len = sizeof(val);
  95099. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95100. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95101. }
  95102. # else
  95103. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95104. # endif
  95105. #elif defined(__linux__)
  95106. int sse = 0;
  95107. struct sigaction sigill_save;
  95108. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95109. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95110. #else
  95111. struct sigaction sigill_sse;
  95112. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95113. __sigemptyset(&sigill_sse.sa_mask);
  95114. 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 */
  95115. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95116. #endif
  95117. {
  95118. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95119. /* see sigill_handler_sse_os() for an explanation of the following: */
  95120. asm volatile (
  95121. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95122. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95123. "incl %0\n\t" /* SIGILL handler will jump over this */
  95124. /* landing zone */
  95125. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95126. "nop\n\t"
  95127. "nop\n\t"
  95128. "nop\n\t"
  95129. "nop\n\t"
  95130. "nop\n\t"
  95131. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95132. "nop\n\t"
  95133. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95134. : "=r"(sse)
  95135. : "r"(sse)
  95136. );
  95137. sigaction(SIGILL, &sigill_save, NULL);
  95138. }
  95139. if(!sse)
  95140. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95141. #elif defined(_MSC_VER)
  95142. # ifdef USE_TRY_CATCH_FLAVOR
  95143. _try {
  95144. __asm {
  95145. # if _MSC_VER <= 1200
  95146. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95147. _emit 0x0F
  95148. _emit 0x57
  95149. _emit 0xC0
  95150. # else
  95151. xorps xmm0,xmm0
  95152. # endif
  95153. }
  95154. }
  95155. _except(EXCEPTION_EXECUTE_HANDLER) {
  95156. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95157. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95158. }
  95159. # else
  95160. int sse = 0;
  95161. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95162. /* see GCC version above for explanation */
  95163. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95164. /* http://www.codeproject.com/cpp/gccasm.asp */
  95165. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95166. __asm {
  95167. # if _MSC_VER <= 1200
  95168. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95169. _emit 0x0F
  95170. _emit 0x57
  95171. _emit 0xC0
  95172. # else
  95173. xorps xmm0,xmm0
  95174. # endif
  95175. inc sse
  95176. nop
  95177. nop
  95178. nop
  95179. nop
  95180. nop
  95181. nop
  95182. nop
  95183. nop
  95184. nop
  95185. }
  95186. SetUnhandledExceptionFilter(save);
  95187. if(!sse)
  95188. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95189. # endif
  95190. #else
  95191. /* no way to test, disable to be safe */
  95192. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95193. #endif
  95194. #ifdef DEBUG
  95195. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95196. #endif
  95197. }
  95198. }
  95199. #else
  95200. info->use_asm = false;
  95201. #endif
  95202. /*
  95203. * PPC-specific
  95204. */
  95205. #elif defined FLAC__CPU_PPC
  95206. info->type = FLAC__CPUINFO_TYPE_PPC;
  95207. # if !defined FLAC__NO_ASM
  95208. info->use_asm = true;
  95209. # ifdef FLAC__USE_ALTIVEC
  95210. # if defined FLAC__SYS_DARWIN
  95211. {
  95212. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95213. size_t len = sizeof(val);
  95214. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95215. }
  95216. {
  95217. host_basic_info_data_t hostInfo;
  95218. mach_msg_type_number_t infoCount;
  95219. infoCount = HOST_BASIC_INFO_COUNT;
  95220. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95221. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95222. }
  95223. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95224. {
  95225. /* no Darwin, do it the brute-force way */
  95226. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95227. info->data.ppc.altivec = 0;
  95228. info->data.ppc.ppc64 = 0;
  95229. signal (SIGILL, sigill_handler);
  95230. canjump = 0;
  95231. if (!sigsetjmp (jmpbuf, 1)) {
  95232. canjump = 1;
  95233. asm volatile (
  95234. "mtspr 256, %0\n\t"
  95235. "vand %%v0, %%v0, %%v0"
  95236. :
  95237. : "r" (-1)
  95238. );
  95239. info->data.ppc.altivec = 1;
  95240. }
  95241. canjump = 0;
  95242. if (!sigsetjmp (jmpbuf, 1)) {
  95243. int x = 0;
  95244. canjump = 1;
  95245. /* PPC64 hardware implements the cntlzd instruction */
  95246. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95247. info->data.ppc.ppc64 = 1;
  95248. }
  95249. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95250. }
  95251. # endif
  95252. # else /* !FLAC__USE_ALTIVEC */
  95253. info->data.ppc.altivec = 0;
  95254. info->data.ppc.ppc64 = 0;
  95255. # endif
  95256. # else
  95257. info->use_asm = false;
  95258. # endif
  95259. /*
  95260. * unknown CPI
  95261. */
  95262. #else
  95263. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95264. info->use_asm = false;
  95265. #endif
  95266. }
  95267. #endif
  95268. /*** End of inlined file: cpu.c ***/
  95269. /*** Start of inlined file: crc.c ***/
  95270. /*** Start of inlined file: juce_FlacHeader.h ***/
  95271. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95272. // tasks..
  95273. #define VERSION "1.2.1"
  95274. #define FLAC__NO_DLL 1
  95275. #if JUCE_MSVC
  95276. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95277. #endif
  95278. #if JUCE_MAC
  95279. #define FLAC__SYS_DARWIN 1
  95280. #endif
  95281. /*** End of inlined file: juce_FlacHeader.h ***/
  95282. #if JUCE_USE_FLAC
  95283. #if HAVE_CONFIG_H
  95284. # include <config.h>
  95285. #endif
  95286. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95287. FLAC__byte const FLAC__crc8_table[256] = {
  95288. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95289. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95290. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95291. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95292. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95293. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95294. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95295. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95296. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95297. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95298. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95299. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95300. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95301. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95302. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95303. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95304. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95305. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95306. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95307. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95308. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95309. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95310. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95311. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95312. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95313. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95314. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95315. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95316. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95317. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95318. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95319. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95320. };
  95321. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95322. unsigned FLAC__crc16_table[256] = {
  95323. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95324. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95325. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95326. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95327. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95328. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95329. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95330. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95331. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95332. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95333. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95334. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95335. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95336. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95337. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95338. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95339. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95340. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95341. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95342. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95343. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95344. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95345. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95346. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95347. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95348. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95349. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95350. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95351. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95352. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95353. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95354. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95355. };
  95356. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95357. {
  95358. *crc = FLAC__crc8_table[*crc ^ data];
  95359. }
  95360. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95361. {
  95362. while(len--)
  95363. *crc = FLAC__crc8_table[*crc ^ *data++];
  95364. }
  95365. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95366. {
  95367. FLAC__uint8 crc = 0;
  95368. while(len--)
  95369. crc = FLAC__crc8_table[crc ^ *data++];
  95370. return crc;
  95371. }
  95372. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95373. {
  95374. unsigned crc = 0;
  95375. while(len--)
  95376. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95377. return crc;
  95378. }
  95379. #endif
  95380. /*** End of inlined file: crc.c ***/
  95381. /*** Start of inlined file: fixed.c ***/
  95382. /*** Start of inlined file: juce_FlacHeader.h ***/
  95383. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95384. // tasks..
  95385. #define VERSION "1.2.1"
  95386. #define FLAC__NO_DLL 1
  95387. #if JUCE_MSVC
  95388. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95389. #endif
  95390. #if JUCE_MAC
  95391. #define FLAC__SYS_DARWIN 1
  95392. #endif
  95393. /*** End of inlined file: juce_FlacHeader.h ***/
  95394. #if JUCE_USE_FLAC
  95395. #if HAVE_CONFIG_H
  95396. # include <config.h>
  95397. #endif
  95398. #include <math.h>
  95399. #include <string.h>
  95400. /*** Start of inlined file: fixed.h ***/
  95401. #ifndef FLAC__PRIVATE__FIXED_H
  95402. #define FLAC__PRIVATE__FIXED_H
  95403. #ifdef HAVE_CONFIG_H
  95404. #include <config.h>
  95405. #endif
  95406. /*** Start of inlined file: float.h ***/
  95407. #ifndef FLAC__PRIVATE__FLOAT_H
  95408. #define FLAC__PRIVATE__FLOAT_H
  95409. #ifdef HAVE_CONFIG_H
  95410. #include <config.h>
  95411. #endif
  95412. /*
  95413. * These typedefs make it easier to ensure that integer versions of
  95414. * the library really only contain integer operations. All the code
  95415. * in libFLAC should use FLAC__float and FLAC__double in place of
  95416. * float and double, and be protected by checks of the macro
  95417. * FLAC__INTEGER_ONLY_LIBRARY.
  95418. *
  95419. * FLAC__real is the basic floating point type used in LPC analysis.
  95420. */
  95421. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95422. typedef double FLAC__double;
  95423. typedef float FLAC__float;
  95424. /*
  95425. * WATCHOUT: changing FLAC__real will change the signatures of many
  95426. * functions that have assembly language equivalents and break them.
  95427. */
  95428. typedef float FLAC__real;
  95429. #else
  95430. /*
  95431. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95432. * for the integer part and lower 16 bits for the fractional part.
  95433. */
  95434. typedef FLAC__int32 FLAC__fixedpoint;
  95435. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95436. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95437. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95438. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95439. extern const FLAC__fixedpoint FLAC__FP_E;
  95440. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95441. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95442. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95443. /*
  95444. * FLAC__fixedpoint_log2()
  95445. * --------------------------------------------------------------------
  95446. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95447. * algorithm by Knuth for x >= 1.0
  95448. *
  95449. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95450. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95451. *
  95452. * 'precision' roughly limits the number of iterations that are done;
  95453. * use (unsigned)(-1) for maximum precision.
  95454. *
  95455. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95456. * function will punt and return 0.
  95457. *
  95458. * The return value will also have 'fracbits' fractional bits.
  95459. */
  95460. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95461. #endif
  95462. #endif
  95463. /*** End of inlined file: float.h ***/
  95464. /*** Start of inlined file: format.h ***/
  95465. #ifndef FLAC__PRIVATE__FORMAT_H
  95466. #define FLAC__PRIVATE__FORMAT_H
  95467. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95468. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95469. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95470. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95471. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95472. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95473. #endif
  95474. /*** End of inlined file: format.h ***/
  95475. /*
  95476. * FLAC__fixed_compute_best_predictor()
  95477. * --------------------------------------------------------------------
  95478. * Compute the best fixed predictor and the expected bits-per-sample
  95479. * of the residual signal for each order. The _wide() version uses
  95480. * 64-bit integers which is statistically necessary when bits-per-
  95481. * sample + log2(blocksize) > 30
  95482. *
  95483. * IN data[0,data_len-1]
  95484. * IN data_len
  95485. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95486. */
  95487. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95488. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95489. # ifndef FLAC__NO_ASM
  95490. # ifdef FLAC__CPU_IA32
  95491. # ifdef FLAC__HAS_NASM
  95492. 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]);
  95493. # endif
  95494. # endif
  95495. # endif
  95496. 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]);
  95497. #else
  95498. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95499. 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]);
  95500. #endif
  95501. /*
  95502. * FLAC__fixed_compute_residual()
  95503. * --------------------------------------------------------------------
  95504. * Compute the residual signal obtained from sutracting the predicted
  95505. * signal from the original.
  95506. *
  95507. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95508. * IN data_len length of original signal
  95509. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95510. * OUT residual[0,data_len-1] residual signal
  95511. */
  95512. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95513. /*
  95514. * FLAC__fixed_restore_signal()
  95515. * --------------------------------------------------------------------
  95516. * Restore the original signal by summing the residual and the
  95517. * predictor.
  95518. *
  95519. * IN residual[0,data_len-1] residual signal
  95520. * IN data_len length of original signal
  95521. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95522. * *** IMPORTANT: the caller must pass in the historical samples:
  95523. * IN data[-order,-1] previously-reconstructed historical samples
  95524. * OUT data[0,data_len-1] original signal
  95525. */
  95526. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95527. #endif
  95528. /*** End of inlined file: fixed.h ***/
  95529. #ifndef M_LN2
  95530. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95531. #define M_LN2 0.69314718055994530942
  95532. #endif
  95533. #ifdef min
  95534. #undef min
  95535. #endif
  95536. #define min(x,y) ((x) < (y)? (x) : (y))
  95537. #ifdef local_abs
  95538. #undef local_abs
  95539. #endif
  95540. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95541. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95542. /* rbps stands for residual bits per sample
  95543. *
  95544. * (ln(2) * err)
  95545. * rbps = log (-----------)
  95546. * 2 ( n )
  95547. */
  95548. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95549. {
  95550. FLAC__uint32 rbps;
  95551. unsigned bits; /* the number of bits required to represent a number */
  95552. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95553. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95554. FLAC__ASSERT(err > 0);
  95555. FLAC__ASSERT(n > 0);
  95556. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95557. if(err <= n)
  95558. return 0;
  95559. /*
  95560. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95561. * These allow us later to know we won't lose too much precision in the
  95562. * fixed-point division (err<<fracbits)/n.
  95563. */
  95564. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95565. err <<= fracbits;
  95566. err /= n;
  95567. /* err now holds err/n with fracbits fractional bits */
  95568. /*
  95569. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95570. * our purposes.
  95571. */
  95572. FLAC__ASSERT(err > 0);
  95573. bits = FLAC__bitmath_ilog2(err)+1;
  95574. if(bits > 16) {
  95575. err >>= (bits-16);
  95576. fracbits -= (bits-16);
  95577. }
  95578. rbps = (FLAC__uint32)err;
  95579. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95580. rbps *= FLAC__FP_LN2;
  95581. fracbits += 16;
  95582. FLAC__ASSERT(fracbits >= 0);
  95583. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95584. {
  95585. const int f = fracbits & 3;
  95586. if(f) {
  95587. rbps >>= f;
  95588. fracbits -= f;
  95589. }
  95590. }
  95591. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95592. if(rbps == 0)
  95593. return 0;
  95594. /*
  95595. * The return value must have 16 fractional bits. Since the whole part
  95596. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95597. * must be >= -3, these assertion allows us to be able to shift rbps
  95598. * left if necessary to get 16 fracbits without losing any bits of the
  95599. * whole part of rbps.
  95600. *
  95601. * There is a slight chance due to accumulated error that the whole part
  95602. * will require 6 bits, so we use 6 in the assertion. Really though as
  95603. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95604. */
  95605. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95606. FLAC__ASSERT(fracbits >= -3);
  95607. /* now shift the decimal point into place */
  95608. if(fracbits < 16)
  95609. return rbps << (16-fracbits);
  95610. else if(fracbits > 16)
  95611. return rbps >> (fracbits-16);
  95612. else
  95613. return rbps;
  95614. }
  95615. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95616. {
  95617. FLAC__uint32 rbps;
  95618. unsigned bits; /* the number of bits required to represent a number */
  95619. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95620. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95621. FLAC__ASSERT(err > 0);
  95622. FLAC__ASSERT(n > 0);
  95623. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95624. if(err <= n)
  95625. return 0;
  95626. /*
  95627. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95628. * These allow us later to know we won't lose too much precision in the
  95629. * fixed-point division (err<<fracbits)/n.
  95630. */
  95631. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95632. err <<= fracbits;
  95633. err /= n;
  95634. /* err now holds err/n with fracbits fractional bits */
  95635. /*
  95636. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95637. * our purposes.
  95638. */
  95639. FLAC__ASSERT(err > 0);
  95640. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95641. if(bits > 16) {
  95642. err >>= (bits-16);
  95643. fracbits -= (bits-16);
  95644. }
  95645. rbps = (FLAC__uint32)err;
  95646. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95647. rbps *= FLAC__FP_LN2;
  95648. fracbits += 16;
  95649. FLAC__ASSERT(fracbits >= 0);
  95650. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95651. {
  95652. const int f = fracbits & 3;
  95653. if(f) {
  95654. rbps >>= f;
  95655. fracbits -= f;
  95656. }
  95657. }
  95658. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95659. if(rbps == 0)
  95660. return 0;
  95661. /*
  95662. * The return value must have 16 fractional bits. Since the whole part
  95663. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95664. * must be >= -3, these assertion allows us to be able to shift rbps
  95665. * left if necessary to get 16 fracbits without losing any bits of the
  95666. * whole part of rbps.
  95667. *
  95668. * There is a slight chance due to accumulated error that the whole part
  95669. * will require 6 bits, so we use 6 in the assertion. Really though as
  95670. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95671. */
  95672. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95673. FLAC__ASSERT(fracbits >= -3);
  95674. /* now shift the decimal point into place */
  95675. if(fracbits < 16)
  95676. return rbps << (16-fracbits);
  95677. else if(fracbits > 16)
  95678. return rbps >> (fracbits-16);
  95679. else
  95680. return rbps;
  95681. }
  95682. #endif
  95683. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95684. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95685. #else
  95686. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95687. #endif
  95688. {
  95689. FLAC__int32 last_error_0 = data[-1];
  95690. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95691. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95692. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95693. FLAC__int32 error, save;
  95694. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95695. unsigned i, order;
  95696. for(i = 0; i < data_len; i++) {
  95697. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95698. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95699. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95700. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95701. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95702. }
  95703. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95704. order = 0;
  95705. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95706. order = 1;
  95707. else if(total_error_2 < min(total_error_3, total_error_4))
  95708. order = 2;
  95709. else if(total_error_3 < total_error_4)
  95710. order = 3;
  95711. else
  95712. order = 4;
  95713. /* Estimate the expected number of bits per residual signal sample. */
  95714. /* 'total_error*' is linearly related to the variance of the residual */
  95715. /* signal, so we use it directly to compute E(|x|) */
  95716. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95717. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95718. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95719. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95720. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95721. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95722. 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);
  95723. 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);
  95724. 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);
  95725. 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);
  95726. 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);
  95727. #else
  95728. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95729. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95730. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95731. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95732. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95733. #endif
  95734. return order;
  95735. }
  95736. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95737. 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])
  95738. #else
  95739. 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])
  95740. #endif
  95741. {
  95742. FLAC__int32 last_error_0 = data[-1];
  95743. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95744. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95745. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95746. FLAC__int32 error, save;
  95747. /* total_error_* are 64-bits to avoid overflow when encoding
  95748. * erratic signals when the bits-per-sample and blocksize are
  95749. * large.
  95750. */
  95751. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95752. unsigned i, order;
  95753. for(i = 0; i < data_len; i++) {
  95754. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95755. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95756. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95757. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95758. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95759. }
  95760. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95761. order = 0;
  95762. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95763. order = 1;
  95764. else if(total_error_2 < min(total_error_3, total_error_4))
  95765. order = 2;
  95766. else if(total_error_3 < total_error_4)
  95767. order = 3;
  95768. else
  95769. order = 4;
  95770. /* Estimate the expected number of bits per residual signal sample. */
  95771. /* 'total_error*' is linearly related to the variance of the residual */
  95772. /* signal, so we use it directly to compute E(|x|) */
  95773. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95774. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95775. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95776. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95777. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95778. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95779. #if defined _MSC_VER || defined __MINGW32__
  95780. /* with MSVC you have to spoon feed it the casting */
  95781. 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);
  95782. 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);
  95783. 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);
  95784. 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);
  95785. 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);
  95786. #else
  95787. 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);
  95788. 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);
  95789. 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);
  95790. 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);
  95791. 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);
  95792. #endif
  95793. #else
  95794. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95795. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95796. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95797. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95798. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95799. #endif
  95800. return order;
  95801. }
  95802. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95803. {
  95804. const int idata_len = (int)data_len;
  95805. int i;
  95806. switch(order) {
  95807. case 0:
  95808. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95809. memcpy(residual, data, sizeof(residual[0])*data_len);
  95810. break;
  95811. case 1:
  95812. for(i = 0; i < idata_len; i++)
  95813. residual[i] = data[i] - data[i-1];
  95814. break;
  95815. case 2:
  95816. for(i = 0; i < idata_len; i++)
  95817. #if 1 /* OPT: may be faster with some compilers on some systems */
  95818. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95819. #else
  95820. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95821. #endif
  95822. break;
  95823. case 3:
  95824. for(i = 0; i < idata_len; i++)
  95825. #if 1 /* OPT: may be faster with some compilers on some systems */
  95826. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95827. #else
  95828. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95829. #endif
  95830. break;
  95831. case 4:
  95832. for(i = 0; i < idata_len; i++)
  95833. #if 1 /* OPT: may be faster with some compilers on some systems */
  95834. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95835. #else
  95836. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95837. #endif
  95838. break;
  95839. default:
  95840. FLAC__ASSERT(0);
  95841. }
  95842. }
  95843. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95844. {
  95845. int i, idata_len = (int)data_len;
  95846. switch(order) {
  95847. case 0:
  95848. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95849. memcpy(data, residual, sizeof(residual[0])*data_len);
  95850. break;
  95851. case 1:
  95852. for(i = 0; i < idata_len; i++)
  95853. data[i] = residual[i] + data[i-1];
  95854. break;
  95855. case 2:
  95856. for(i = 0; i < idata_len; i++)
  95857. #if 1 /* OPT: may be faster with some compilers on some systems */
  95858. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95859. #else
  95860. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95861. #endif
  95862. break;
  95863. case 3:
  95864. for(i = 0; i < idata_len; i++)
  95865. #if 1 /* OPT: may be faster with some compilers on some systems */
  95866. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95867. #else
  95868. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95869. #endif
  95870. break;
  95871. case 4:
  95872. for(i = 0; i < idata_len; i++)
  95873. #if 1 /* OPT: may be faster with some compilers on some systems */
  95874. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95875. #else
  95876. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95877. #endif
  95878. break;
  95879. default:
  95880. FLAC__ASSERT(0);
  95881. }
  95882. }
  95883. #endif
  95884. /*** End of inlined file: fixed.c ***/
  95885. /*** Start of inlined file: float.c ***/
  95886. /*** Start of inlined file: juce_FlacHeader.h ***/
  95887. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95888. // tasks..
  95889. #define VERSION "1.2.1"
  95890. #define FLAC__NO_DLL 1
  95891. #if JUCE_MSVC
  95892. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95893. #endif
  95894. #if JUCE_MAC
  95895. #define FLAC__SYS_DARWIN 1
  95896. #endif
  95897. /*** End of inlined file: juce_FlacHeader.h ***/
  95898. #if JUCE_USE_FLAC
  95899. #if HAVE_CONFIG_H
  95900. # include <config.h>
  95901. #endif
  95902. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95903. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95904. #ifdef _MSC_VER
  95905. #define FLAC__U64L(x) x
  95906. #else
  95907. #define FLAC__U64L(x) x##LLU
  95908. #endif
  95909. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95910. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95911. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95912. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95913. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95914. /* Lookup tables for Knuth's logarithm algorithm */
  95915. #define LOG2_LOOKUP_PRECISION 16
  95916. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95917. {
  95918. /*
  95919. * 0 fraction bits
  95920. */
  95921. /* undefined */ 0x00000000,
  95922. /* lg(2/1) = */ 0x00000001,
  95923. /* lg(4/3) = */ 0x00000000,
  95924. /* lg(8/7) = */ 0x00000000,
  95925. /* lg(16/15) = */ 0x00000000,
  95926. /* lg(32/31) = */ 0x00000000,
  95927. /* lg(64/63) = */ 0x00000000,
  95928. /* lg(128/127) = */ 0x00000000,
  95929. /* lg(256/255) = */ 0x00000000,
  95930. /* lg(512/511) = */ 0x00000000,
  95931. /* lg(1024/1023) = */ 0x00000000,
  95932. /* lg(2048/2047) = */ 0x00000000,
  95933. /* lg(4096/4095) = */ 0x00000000,
  95934. /* lg(8192/8191) = */ 0x00000000,
  95935. /* lg(16384/16383) = */ 0x00000000,
  95936. /* lg(32768/32767) = */ 0x00000000
  95937. },
  95938. {
  95939. /*
  95940. * 4 fraction bits
  95941. */
  95942. /* undefined */ 0x00000000,
  95943. /* lg(2/1) = */ 0x00000010,
  95944. /* lg(4/3) = */ 0x00000007,
  95945. /* lg(8/7) = */ 0x00000003,
  95946. /* lg(16/15) = */ 0x00000001,
  95947. /* lg(32/31) = */ 0x00000001,
  95948. /* lg(64/63) = */ 0x00000000,
  95949. /* lg(128/127) = */ 0x00000000,
  95950. /* lg(256/255) = */ 0x00000000,
  95951. /* lg(512/511) = */ 0x00000000,
  95952. /* lg(1024/1023) = */ 0x00000000,
  95953. /* lg(2048/2047) = */ 0x00000000,
  95954. /* lg(4096/4095) = */ 0x00000000,
  95955. /* lg(8192/8191) = */ 0x00000000,
  95956. /* lg(16384/16383) = */ 0x00000000,
  95957. /* lg(32768/32767) = */ 0x00000000
  95958. },
  95959. {
  95960. /*
  95961. * 8 fraction bits
  95962. */
  95963. /* undefined */ 0x00000000,
  95964. /* lg(2/1) = */ 0x00000100,
  95965. /* lg(4/3) = */ 0x0000006a,
  95966. /* lg(8/7) = */ 0x00000031,
  95967. /* lg(16/15) = */ 0x00000018,
  95968. /* lg(32/31) = */ 0x0000000c,
  95969. /* lg(64/63) = */ 0x00000006,
  95970. /* lg(128/127) = */ 0x00000003,
  95971. /* lg(256/255) = */ 0x00000001,
  95972. /* lg(512/511) = */ 0x00000001,
  95973. /* lg(1024/1023) = */ 0x00000000,
  95974. /* lg(2048/2047) = */ 0x00000000,
  95975. /* lg(4096/4095) = */ 0x00000000,
  95976. /* lg(8192/8191) = */ 0x00000000,
  95977. /* lg(16384/16383) = */ 0x00000000,
  95978. /* lg(32768/32767) = */ 0x00000000
  95979. },
  95980. {
  95981. /*
  95982. * 12 fraction bits
  95983. */
  95984. /* undefined */ 0x00000000,
  95985. /* lg(2/1) = */ 0x00001000,
  95986. /* lg(4/3) = */ 0x000006a4,
  95987. /* lg(8/7) = */ 0x00000315,
  95988. /* lg(16/15) = */ 0x0000017d,
  95989. /* lg(32/31) = */ 0x000000bc,
  95990. /* lg(64/63) = */ 0x0000005d,
  95991. /* lg(128/127) = */ 0x0000002e,
  95992. /* lg(256/255) = */ 0x00000017,
  95993. /* lg(512/511) = */ 0x0000000c,
  95994. /* lg(1024/1023) = */ 0x00000006,
  95995. /* lg(2048/2047) = */ 0x00000003,
  95996. /* lg(4096/4095) = */ 0x00000001,
  95997. /* lg(8192/8191) = */ 0x00000001,
  95998. /* lg(16384/16383) = */ 0x00000000,
  95999. /* lg(32768/32767) = */ 0x00000000
  96000. },
  96001. {
  96002. /*
  96003. * 16 fraction bits
  96004. */
  96005. /* undefined */ 0x00000000,
  96006. /* lg(2/1) = */ 0x00010000,
  96007. /* lg(4/3) = */ 0x00006a40,
  96008. /* lg(8/7) = */ 0x00003151,
  96009. /* lg(16/15) = */ 0x000017d6,
  96010. /* lg(32/31) = */ 0x00000bba,
  96011. /* lg(64/63) = */ 0x000005d1,
  96012. /* lg(128/127) = */ 0x000002e6,
  96013. /* lg(256/255) = */ 0x00000172,
  96014. /* lg(512/511) = */ 0x000000b9,
  96015. /* lg(1024/1023) = */ 0x0000005c,
  96016. /* lg(2048/2047) = */ 0x0000002e,
  96017. /* lg(4096/4095) = */ 0x00000017,
  96018. /* lg(8192/8191) = */ 0x0000000c,
  96019. /* lg(16384/16383) = */ 0x00000006,
  96020. /* lg(32768/32767) = */ 0x00000003
  96021. },
  96022. {
  96023. /*
  96024. * 20 fraction bits
  96025. */
  96026. /* undefined */ 0x00000000,
  96027. /* lg(2/1) = */ 0x00100000,
  96028. /* lg(4/3) = */ 0x0006a3fe,
  96029. /* lg(8/7) = */ 0x00031513,
  96030. /* lg(16/15) = */ 0x00017d60,
  96031. /* lg(32/31) = */ 0x0000bb9d,
  96032. /* lg(64/63) = */ 0x00005d10,
  96033. /* lg(128/127) = */ 0x00002e59,
  96034. /* lg(256/255) = */ 0x00001721,
  96035. /* lg(512/511) = */ 0x00000b8e,
  96036. /* lg(1024/1023) = */ 0x000005c6,
  96037. /* lg(2048/2047) = */ 0x000002e3,
  96038. /* lg(4096/4095) = */ 0x00000171,
  96039. /* lg(8192/8191) = */ 0x000000b9,
  96040. /* lg(16384/16383) = */ 0x0000005c,
  96041. /* lg(32768/32767) = */ 0x0000002e
  96042. },
  96043. {
  96044. /*
  96045. * 24 fraction bits
  96046. */
  96047. /* undefined */ 0x00000000,
  96048. /* lg(2/1) = */ 0x01000000,
  96049. /* lg(4/3) = */ 0x006a3fe6,
  96050. /* lg(8/7) = */ 0x00315130,
  96051. /* lg(16/15) = */ 0x0017d605,
  96052. /* lg(32/31) = */ 0x000bb9ca,
  96053. /* lg(64/63) = */ 0x0005d0fc,
  96054. /* lg(128/127) = */ 0x0002e58f,
  96055. /* lg(256/255) = */ 0x0001720e,
  96056. /* lg(512/511) = */ 0x0000b8d8,
  96057. /* lg(1024/1023) = */ 0x00005c61,
  96058. /* lg(2048/2047) = */ 0x00002e2d,
  96059. /* lg(4096/4095) = */ 0x00001716,
  96060. /* lg(8192/8191) = */ 0x00000b8b,
  96061. /* lg(16384/16383) = */ 0x000005c5,
  96062. /* lg(32768/32767) = */ 0x000002e3
  96063. },
  96064. {
  96065. /*
  96066. * 28 fraction bits
  96067. */
  96068. /* undefined */ 0x00000000,
  96069. /* lg(2/1) = */ 0x10000000,
  96070. /* lg(4/3) = */ 0x06a3fe5c,
  96071. /* lg(8/7) = */ 0x03151301,
  96072. /* lg(16/15) = */ 0x017d6049,
  96073. /* lg(32/31) = */ 0x00bb9ca6,
  96074. /* lg(64/63) = */ 0x005d0fba,
  96075. /* lg(128/127) = */ 0x002e58f7,
  96076. /* lg(256/255) = */ 0x001720da,
  96077. /* lg(512/511) = */ 0x000b8d87,
  96078. /* lg(1024/1023) = */ 0x0005c60b,
  96079. /* lg(2048/2047) = */ 0x0002e2d7,
  96080. /* lg(4096/4095) = */ 0x00017160,
  96081. /* lg(8192/8191) = */ 0x0000b8ad,
  96082. /* lg(16384/16383) = */ 0x00005c56,
  96083. /* lg(32768/32767) = */ 0x00002e2b
  96084. }
  96085. };
  96086. #if 0
  96087. static const FLAC__uint64 log2_lookup_wide[] = {
  96088. {
  96089. /*
  96090. * 32 fraction bits
  96091. */
  96092. /* undefined */ 0x00000000,
  96093. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96094. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96095. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96096. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96097. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96098. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96099. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96100. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96101. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96102. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96103. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96104. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96105. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96106. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96107. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96108. },
  96109. {
  96110. /*
  96111. * 48 fraction bits
  96112. */
  96113. /* undefined */ 0x00000000,
  96114. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96115. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96116. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96117. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96118. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96119. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96120. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96121. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96122. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96123. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96124. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96125. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96126. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96127. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96128. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96129. }
  96130. };
  96131. #endif
  96132. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96133. {
  96134. const FLAC__uint32 ONE = (1u << fracbits);
  96135. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96136. FLAC__ASSERT(fracbits < 32);
  96137. FLAC__ASSERT((fracbits & 0x3) == 0);
  96138. if(x < ONE)
  96139. return 0;
  96140. if(precision > LOG2_LOOKUP_PRECISION)
  96141. precision = LOG2_LOOKUP_PRECISION;
  96142. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96143. {
  96144. FLAC__uint32 y = 0;
  96145. FLAC__uint32 z = x >> 1, k = 1;
  96146. while (x > ONE && k < precision) {
  96147. if (x - z >= ONE) {
  96148. x -= z;
  96149. z = x >> k;
  96150. y += table[k];
  96151. }
  96152. else {
  96153. z >>= 1;
  96154. k++;
  96155. }
  96156. }
  96157. return y;
  96158. }
  96159. }
  96160. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96161. #endif
  96162. /*** End of inlined file: float.c ***/
  96163. /*** Start of inlined file: format.c ***/
  96164. /*** Start of inlined file: juce_FlacHeader.h ***/
  96165. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96166. // tasks..
  96167. #define VERSION "1.2.1"
  96168. #define FLAC__NO_DLL 1
  96169. #if JUCE_MSVC
  96170. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96171. #endif
  96172. #if JUCE_MAC
  96173. #define FLAC__SYS_DARWIN 1
  96174. #endif
  96175. /*** End of inlined file: juce_FlacHeader.h ***/
  96176. #if JUCE_USE_FLAC
  96177. #if HAVE_CONFIG_H
  96178. # include <config.h>
  96179. #endif
  96180. #include <stdio.h>
  96181. #include <stdlib.h> /* for qsort() */
  96182. #include <string.h> /* for memset() */
  96183. #ifndef FLaC__INLINE
  96184. #define FLaC__INLINE
  96185. #endif
  96186. #ifdef min
  96187. #undef min
  96188. #endif
  96189. #define min(a,b) ((a)<(b)?(a):(b))
  96190. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96191. #ifdef _MSC_VER
  96192. #define FLAC__U64L(x) x
  96193. #else
  96194. #define FLAC__U64L(x) x##LLU
  96195. #endif
  96196. /* VERSION should come from configure */
  96197. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96198. ;
  96199. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96200. /* yet one more hack because of MSVC6: */
  96201. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96202. #else
  96203. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96204. #endif
  96205. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96206. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96207. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96208. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96209. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96210. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96211. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96212. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96213. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96214. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96215. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96216. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96217. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96218. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96219. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96220. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96221. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96222. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96223. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96224. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96225. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96226. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96227. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96228. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96229. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96230. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96231. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96232. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96233. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96234. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96235. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96236. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96237. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96238. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96239. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96240. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96241. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96242. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96243. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96244. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96245. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96246. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96247. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96248. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96249. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96250. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96251. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96252. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96253. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96254. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96255. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96256. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96257. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96258. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96259. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96260. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96261. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96262. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96263. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96264. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96265. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96266. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96267. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96268. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96269. "PARTITIONED_RICE",
  96270. "PARTITIONED_RICE2"
  96271. };
  96272. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96273. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96274. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96275. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96276. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96277. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96278. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96279. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96280. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96281. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96282. "CONSTANT",
  96283. "VERBATIM",
  96284. "FIXED",
  96285. "LPC"
  96286. };
  96287. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96288. "INDEPENDENT",
  96289. "LEFT_SIDE",
  96290. "RIGHT_SIDE",
  96291. "MID_SIDE"
  96292. };
  96293. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96294. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96295. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96296. };
  96297. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96298. "STREAMINFO",
  96299. "PADDING",
  96300. "APPLICATION",
  96301. "SEEKTABLE",
  96302. "VORBIS_COMMENT",
  96303. "CUESHEET",
  96304. "PICTURE"
  96305. };
  96306. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96307. "Other",
  96308. "32x32 pixels 'file icon' (PNG only)",
  96309. "Other file icon",
  96310. "Cover (front)",
  96311. "Cover (back)",
  96312. "Leaflet page",
  96313. "Media (e.g. label side of CD)",
  96314. "Lead artist/lead performer/soloist",
  96315. "Artist/performer",
  96316. "Conductor",
  96317. "Band/Orchestra",
  96318. "Composer",
  96319. "Lyricist/text writer",
  96320. "Recording Location",
  96321. "During recording",
  96322. "During performance",
  96323. "Movie/video screen capture",
  96324. "A bright coloured fish",
  96325. "Illustration",
  96326. "Band/artist logotype",
  96327. "Publisher/Studio logotype"
  96328. };
  96329. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96330. {
  96331. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96332. return false;
  96333. }
  96334. else
  96335. return true;
  96336. }
  96337. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96338. {
  96339. if(
  96340. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96341. (
  96342. sample_rate >= (1u << 16) &&
  96343. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96344. )
  96345. ) {
  96346. return false;
  96347. }
  96348. else
  96349. return true;
  96350. }
  96351. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96352. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96353. {
  96354. unsigned i;
  96355. FLAC__uint64 prev_sample_number = 0;
  96356. FLAC__bool got_prev = false;
  96357. FLAC__ASSERT(0 != seek_table);
  96358. for(i = 0; i < seek_table->num_points; i++) {
  96359. if(got_prev) {
  96360. if(
  96361. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96362. seek_table->points[i].sample_number <= prev_sample_number
  96363. )
  96364. return false;
  96365. }
  96366. prev_sample_number = seek_table->points[i].sample_number;
  96367. got_prev = true;
  96368. }
  96369. return true;
  96370. }
  96371. /* used as the sort predicate for qsort() */
  96372. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96373. {
  96374. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96375. if(l->sample_number == r->sample_number)
  96376. return 0;
  96377. else if(l->sample_number < r->sample_number)
  96378. return -1;
  96379. else
  96380. return 1;
  96381. }
  96382. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96383. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96384. {
  96385. unsigned i, j;
  96386. FLAC__bool first;
  96387. FLAC__ASSERT(0 != seek_table);
  96388. /* sort the seekpoints */
  96389. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96390. /* uniquify the seekpoints */
  96391. first = true;
  96392. for(i = j = 0; i < seek_table->num_points; i++) {
  96393. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96394. if(!first) {
  96395. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96396. continue;
  96397. }
  96398. }
  96399. first = false;
  96400. seek_table->points[j++] = seek_table->points[i];
  96401. }
  96402. for(i = j; i < seek_table->num_points; i++) {
  96403. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96404. seek_table->points[i].stream_offset = 0;
  96405. seek_table->points[i].frame_samples = 0;
  96406. }
  96407. return j;
  96408. }
  96409. /*
  96410. * also disallows non-shortest-form encodings, c.f.
  96411. * http://www.unicode.org/versions/corrigendum1.html
  96412. * and a more clear explanation at the end of this section:
  96413. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96414. */
  96415. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96416. {
  96417. FLAC__ASSERT(0 != utf8);
  96418. if ((utf8[0] & 0x80) == 0) {
  96419. return 1;
  96420. }
  96421. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96422. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96423. return 0;
  96424. return 2;
  96425. }
  96426. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96427. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96428. return 0;
  96429. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96430. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96431. return 0;
  96432. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96433. return 0;
  96434. return 3;
  96435. }
  96436. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96437. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96438. return 0;
  96439. return 4;
  96440. }
  96441. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96442. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96443. return 0;
  96444. return 5;
  96445. }
  96446. 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) {
  96447. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96448. return 0;
  96449. return 6;
  96450. }
  96451. else {
  96452. return 0;
  96453. }
  96454. }
  96455. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96456. {
  96457. char c;
  96458. for(c = *name; c; c = *(++name))
  96459. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96460. return false;
  96461. return true;
  96462. }
  96463. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96464. {
  96465. if(length == (unsigned)(-1)) {
  96466. while(*value) {
  96467. unsigned n = utf8len_(value);
  96468. if(n == 0)
  96469. return false;
  96470. value += n;
  96471. }
  96472. }
  96473. else {
  96474. const FLAC__byte *end = value + length;
  96475. while(value < end) {
  96476. unsigned n = utf8len_(value);
  96477. if(n == 0)
  96478. return false;
  96479. value += n;
  96480. }
  96481. if(value != end)
  96482. return false;
  96483. }
  96484. return true;
  96485. }
  96486. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96487. {
  96488. const FLAC__byte *s, *end;
  96489. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96490. if(*s < 0x20 || *s > 0x7D)
  96491. return false;
  96492. }
  96493. if(s == end)
  96494. return false;
  96495. s++; /* skip '=' */
  96496. while(s < end) {
  96497. unsigned n = utf8len_(s);
  96498. if(n == 0)
  96499. return false;
  96500. s += n;
  96501. }
  96502. if(s != end)
  96503. return false;
  96504. return true;
  96505. }
  96506. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96507. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96508. {
  96509. unsigned i, j;
  96510. if(check_cd_da_subset) {
  96511. if(cue_sheet->lead_in < 2 * 44100) {
  96512. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96513. return false;
  96514. }
  96515. if(cue_sheet->lead_in % 588 != 0) {
  96516. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96517. return false;
  96518. }
  96519. }
  96520. if(cue_sheet->num_tracks == 0) {
  96521. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96522. return false;
  96523. }
  96524. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96525. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96526. return false;
  96527. }
  96528. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96529. if(cue_sheet->tracks[i].number == 0) {
  96530. if(violation) *violation = "cue sheet may not have a track number 0";
  96531. return false;
  96532. }
  96533. if(check_cd_da_subset) {
  96534. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96535. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96536. return false;
  96537. }
  96538. }
  96539. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96540. if(violation) {
  96541. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96542. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96543. else
  96544. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96545. }
  96546. return false;
  96547. }
  96548. if(i < cue_sheet->num_tracks - 1) {
  96549. if(cue_sheet->tracks[i].num_indices == 0) {
  96550. if(violation) *violation = "cue sheet track must have at least one index point";
  96551. return false;
  96552. }
  96553. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96554. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96555. return false;
  96556. }
  96557. }
  96558. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96559. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96560. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96561. return false;
  96562. }
  96563. if(j > 0) {
  96564. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96565. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96566. return false;
  96567. }
  96568. }
  96569. }
  96570. }
  96571. return true;
  96572. }
  96573. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96574. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96575. {
  96576. char *p;
  96577. FLAC__byte *b;
  96578. for(p = picture->mime_type; *p; p++) {
  96579. if(*p < 0x20 || *p > 0x7e) {
  96580. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96581. return false;
  96582. }
  96583. }
  96584. for(b = picture->description; *b; ) {
  96585. unsigned n = utf8len_(b);
  96586. if(n == 0) {
  96587. if(violation) *violation = "description string must be valid UTF-8";
  96588. return false;
  96589. }
  96590. b += n;
  96591. }
  96592. return true;
  96593. }
  96594. /*
  96595. * These routines are private to libFLAC
  96596. */
  96597. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96598. {
  96599. return
  96600. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96601. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96602. blocksize,
  96603. predictor_order
  96604. );
  96605. }
  96606. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96607. {
  96608. unsigned max_rice_partition_order = 0;
  96609. while(!(blocksize & 1)) {
  96610. max_rice_partition_order++;
  96611. blocksize >>= 1;
  96612. }
  96613. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96614. }
  96615. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96616. {
  96617. unsigned max_rice_partition_order = limit;
  96618. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96619. max_rice_partition_order--;
  96620. FLAC__ASSERT(
  96621. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96622. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96623. );
  96624. return max_rice_partition_order;
  96625. }
  96626. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96627. {
  96628. FLAC__ASSERT(0 != object);
  96629. object->parameters = 0;
  96630. object->raw_bits = 0;
  96631. object->capacity_by_order = 0;
  96632. }
  96633. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96634. {
  96635. FLAC__ASSERT(0 != object);
  96636. if(0 != object->parameters)
  96637. free(object->parameters);
  96638. if(0 != object->raw_bits)
  96639. free(object->raw_bits);
  96640. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96641. }
  96642. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96643. {
  96644. FLAC__ASSERT(0 != object);
  96645. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96646. if(object->capacity_by_order < max_partition_order) {
  96647. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96648. return false;
  96649. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96650. return false;
  96651. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96652. object->capacity_by_order = max_partition_order;
  96653. }
  96654. return true;
  96655. }
  96656. #endif
  96657. /*** End of inlined file: format.c ***/
  96658. /*** Start of inlined file: lpc_flac.c ***/
  96659. /*** Start of inlined file: juce_FlacHeader.h ***/
  96660. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96661. // tasks..
  96662. #define VERSION "1.2.1"
  96663. #define FLAC__NO_DLL 1
  96664. #if JUCE_MSVC
  96665. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96666. #endif
  96667. #if JUCE_MAC
  96668. #define FLAC__SYS_DARWIN 1
  96669. #endif
  96670. /*** End of inlined file: juce_FlacHeader.h ***/
  96671. #if JUCE_USE_FLAC
  96672. #if HAVE_CONFIG_H
  96673. # include <config.h>
  96674. #endif
  96675. #include <math.h>
  96676. /*** Start of inlined file: lpc.h ***/
  96677. #ifndef FLAC__PRIVATE__LPC_H
  96678. #define FLAC__PRIVATE__LPC_H
  96679. #ifdef HAVE_CONFIG_H
  96680. #include <config.h>
  96681. #endif
  96682. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96683. /*
  96684. * FLAC__lpc_window_data()
  96685. * --------------------------------------------------------------------
  96686. * Applies the given window to the data.
  96687. * OPT: asm implementation
  96688. *
  96689. * IN in[0,data_len-1]
  96690. * IN window[0,data_len-1]
  96691. * OUT out[0,lag-1]
  96692. * IN data_len
  96693. */
  96694. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96695. /*
  96696. * FLAC__lpc_compute_autocorrelation()
  96697. * --------------------------------------------------------------------
  96698. * Compute the autocorrelation for lags between 0 and lag-1.
  96699. * Assumes data[] outside of [0,data_len-1] == 0.
  96700. * Asserts that lag > 0.
  96701. *
  96702. * IN data[0,data_len-1]
  96703. * IN data_len
  96704. * IN 0 < lag <= data_len
  96705. * OUT autoc[0,lag-1]
  96706. */
  96707. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96708. #ifndef FLAC__NO_ASM
  96709. # ifdef FLAC__CPU_IA32
  96710. # ifdef FLAC__HAS_NASM
  96711. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96712. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96713. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96714. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96715. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96716. # endif
  96717. # endif
  96718. #endif
  96719. /*
  96720. * FLAC__lpc_compute_lp_coefficients()
  96721. * --------------------------------------------------------------------
  96722. * Computes LP coefficients for orders 1..max_order.
  96723. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96724. * and there is no point in calculating a predictor.
  96725. *
  96726. * IN autoc[0,max_order] autocorrelation values
  96727. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96728. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96729. * *** IMPORTANT:
  96730. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96731. * OUT error[0,max_order-1] error for each order (more
  96732. * specifically, the variance of
  96733. * the error signal times # of
  96734. * samples in the signal)
  96735. *
  96736. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96737. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96738. * in lp_coeff[7][0,7], etc.
  96739. */
  96740. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96741. /*
  96742. * FLAC__lpc_quantize_coefficients()
  96743. * --------------------------------------------------------------------
  96744. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96745. * must be less than 32 (sizeof(FLAC__int32)*8).
  96746. *
  96747. * IN lp_coeff[0,order-1] LP coefficients
  96748. * IN order LP order
  96749. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96750. * desired precision (in bits, including sign
  96751. * bit) of largest coefficient
  96752. * OUT qlp_coeff[0,order-1] quantized coefficients
  96753. * OUT shift # of bits to shift right to get approximated
  96754. * LP coefficients. NOTE: could be negative.
  96755. * RETURN 0 => quantization OK
  96756. * 1 => coefficients require too much shifting for *shift to
  96757. * fit in the LPC subframe header. 'shift' is unset.
  96758. * 2 => coefficients are all zero, which is bad. 'shift' is
  96759. * unset.
  96760. */
  96761. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96762. /*
  96763. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96764. * --------------------------------------------------------------------
  96765. * Compute the residual signal obtained from sutracting the predicted
  96766. * signal from the original.
  96767. *
  96768. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96769. * IN data_len length of original signal
  96770. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96771. * IN order > 0 LP order
  96772. * IN lp_quantization quantization of LP coefficients in bits
  96773. * OUT residual[0,data_len-1] residual signal
  96774. */
  96775. 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[]);
  96776. 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[]);
  96777. #ifndef FLAC__NO_ASM
  96778. # ifdef FLAC__CPU_IA32
  96779. # ifdef FLAC__HAS_NASM
  96780. 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[]);
  96781. 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[]);
  96782. # endif
  96783. # endif
  96784. #endif
  96785. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96786. /*
  96787. * FLAC__lpc_restore_signal()
  96788. * --------------------------------------------------------------------
  96789. * Restore the original signal by summing the residual and the
  96790. * predictor.
  96791. *
  96792. * IN residual[0,data_len-1] residual signal
  96793. * IN data_len length of original signal
  96794. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96795. * IN order > 0 LP order
  96796. * IN lp_quantization quantization of LP coefficients in bits
  96797. * *** IMPORTANT: the caller must pass in the historical samples:
  96798. * IN data[-order,-1] previously-reconstructed historical samples
  96799. * OUT data[0,data_len-1] original signal
  96800. */
  96801. 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[]);
  96802. 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[]);
  96803. #ifndef FLAC__NO_ASM
  96804. # ifdef FLAC__CPU_IA32
  96805. # ifdef FLAC__HAS_NASM
  96806. 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[]);
  96807. 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[]);
  96808. # endif /* FLAC__HAS_NASM */
  96809. # elif defined FLAC__CPU_PPC
  96810. 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[]);
  96811. 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[]);
  96812. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96813. #endif /* FLAC__NO_ASM */
  96814. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96815. /*
  96816. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96817. * --------------------------------------------------------------------
  96818. * Compute the expected number of bits per residual signal sample
  96819. * based on the LP error (which is related to the residual variance).
  96820. *
  96821. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96822. * IN total_samples > 0 # of samples in residual signal
  96823. * RETURN expected bits per sample
  96824. */
  96825. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96826. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96827. /*
  96828. * FLAC__lpc_compute_best_order()
  96829. * --------------------------------------------------------------------
  96830. * Compute the best order from the array of signal errors returned
  96831. * during coefficient computation.
  96832. *
  96833. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96834. * IN max_order > 0 max LP order
  96835. * IN total_samples > 0 # of samples in residual signal
  96836. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96837. * (includes warmup sample size and quantized LP coefficient)
  96838. * RETURN [1,max_order] best order
  96839. */
  96840. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96841. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96842. #endif
  96843. /*** End of inlined file: lpc.h ***/
  96844. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96845. #include <stdio.h>
  96846. #endif
  96847. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96848. #ifndef M_LN2
  96849. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96850. #define M_LN2 0.69314718055994530942
  96851. #endif
  96852. /* OPT: #undef'ing this may improve the speed on some architectures */
  96853. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96854. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96855. {
  96856. unsigned i;
  96857. for(i = 0; i < data_len; i++)
  96858. out[i] = in[i] * window[i];
  96859. }
  96860. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96861. {
  96862. /* a readable, but slower, version */
  96863. #if 0
  96864. FLAC__real d;
  96865. unsigned i;
  96866. FLAC__ASSERT(lag > 0);
  96867. FLAC__ASSERT(lag <= data_len);
  96868. /*
  96869. * Technically we should subtract the mean first like so:
  96870. * for(i = 0; i < data_len; i++)
  96871. * data[i] -= mean;
  96872. * but it appears not to make enough of a difference to matter, and
  96873. * most signals are already closely centered around zero
  96874. */
  96875. while(lag--) {
  96876. for(i = lag, d = 0.0; i < data_len; i++)
  96877. d += data[i] * data[i - lag];
  96878. autoc[lag] = d;
  96879. }
  96880. #endif
  96881. /*
  96882. * this version tends to run faster because of better data locality
  96883. * ('data_len' is usually much larger than 'lag')
  96884. */
  96885. FLAC__real d;
  96886. unsigned sample, coeff;
  96887. const unsigned limit = data_len - lag;
  96888. FLAC__ASSERT(lag > 0);
  96889. FLAC__ASSERT(lag <= data_len);
  96890. for(coeff = 0; coeff < lag; coeff++)
  96891. autoc[coeff] = 0.0;
  96892. for(sample = 0; sample <= limit; sample++) {
  96893. d = data[sample];
  96894. for(coeff = 0; coeff < lag; coeff++)
  96895. autoc[coeff] += d * data[sample+coeff];
  96896. }
  96897. for(; sample < data_len; sample++) {
  96898. d = data[sample];
  96899. for(coeff = 0; coeff < data_len - sample; coeff++)
  96900. autoc[coeff] += d * data[sample+coeff];
  96901. }
  96902. }
  96903. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96904. {
  96905. unsigned i, j;
  96906. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96907. FLAC__ASSERT(0 != max_order);
  96908. FLAC__ASSERT(0 < *max_order);
  96909. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96910. FLAC__ASSERT(autoc[0] != 0.0);
  96911. err = autoc[0];
  96912. for(i = 0; i < *max_order; i++) {
  96913. /* Sum up this iteration's reflection coefficient. */
  96914. r = -autoc[i+1];
  96915. for(j = 0; j < i; j++)
  96916. r -= lpc[j] * autoc[i-j];
  96917. ref[i] = (r/=err);
  96918. /* Update LPC coefficients and total error. */
  96919. lpc[i]=r;
  96920. for(j = 0; j < (i>>1); j++) {
  96921. FLAC__double tmp = lpc[j];
  96922. lpc[j] += r * lpc[i-1-j];
  96923. lpc[i-1-j] += r * tmp;
  96924. }
  96925. if(i & 1)
  96926. lpc[j] += lpc[j] * r;
  96927. err *= (1.0 - r * r);
  96928. /* save this order */
  96929. for(j = 0; j <= i; j++)
  96930. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96931. error[i] = err;
  96932. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96933. if(err == 0.0) {
  96934. *max_order = i+1;
  96935. return;
  96936. }
  96937. }
  96938. }
  96939. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96940. {
  96941. unsigned i;
  96942. FLAC__double cmax;
  96943. FLAC__int32 qmax, qmin;
  96944. FLAC__ASSERT(precision > 0);
  96945. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96946. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96947. precision--;
  96948. qmax = 1 << precision;
  96949. qmin = -qmax;
  96950. qmax--;
  96951. /* calc cmax = max( |lp_coeff[i]| ) */
  96952. cmax = 0.0;
  96953. for(i = 0; i < order; i++) {
  96954. const FLAC__double d = fabs(lp_coeff[i]);
  96955. if(d > cmax)
  96956. cmax = d;
  96957. }
  96958. if(cmax <= 0.0) {
  96959. /* => coefficients are all 0, which means our constant-detect didn't work */
  96960. return 2;
  96961. }
  96962. else {
  96963. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96964. const int min_shiftlimit = -max_shiftlimit - 1;
  96965. int log2cmax;
  96966. (void)frexp(cmax, &log2cmax);
  96967. log2cmax--;
  96968. *shift = (int)precision - log2cmax - 1;
  96969. if(*shift > max_shiftlimit)
  96970. *shift = max_shiftlimit;
  96971. else if(*shift < min_shiftlimit)
  96972. return 1;
  96973. }
  96974. if(*shift >= 0) {
  96975. FLAC__double error = 0.0;
  96976. FLAC__int32 q;
  96977. for(i = 0; i < order; i++) {
  96978. error += lp_coeff[i] * (1 << *shift);
  96979. #if 1 /* unfortunately lround() is C99 */
  96980. if(error >= 0.0)
  96981. q = (FLAC__int32)(error + 0.5);
  96982. else
  96983. q = (FLAC__int32)(error - 0.5);
  96984. #else
  96985. q = lround(error);
  96986. #endif
  96987. #ifdef FLAC__OVERFLOW_DETECT
  96988. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96989. 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]);
  96990. else if(q < qmin)
  96991. 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]);
  96992. #endif
  96993. if(q > qmax)
  96994. q = qmax;
  96995. else if(q < qmin)
  96996. q = qmin;
  96997. error -= q;
  96998. qlp_coeff[i] = q;
  96999. }
  97000. }
  97001. /* negative shift is very rare but due to design flaw, negative shift is
  97002. * a NOP in the decoder, so it must be handled specially by scaling down
  97003. * coeffs
  97004. */
  97005. else {
  97006. const int nshift = -(*shift);
  97007. FLAC__double error = 0.0;
  97008. FLAC__int32 q;
  97009. #ifdef DEBUG
  97010. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97011. #endif
  97012. for(i = 0; i < order; i++) {
  97013. error += lp_coeff[i] / (1 << nshift);
  97014. #if 1 /* unfortunately lround() is C99 */
  97015. if(error >= 0.0)
  97016. q = (FLAC__int32)(error + 0.5);
  97017. else
  97018. q = (FLAC__int32)(error - 0.5);
  97019. #else
  97020. q = lround(error);
  97021. #endif
  97022. #ifdef FLAC__OVERFLOW_DETECT
  97023. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97024. 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]);
  97025. else if(q < qmin)
  97026. 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]);
  97027. #endif
  97028. if(q > qmax)
  97029. q = qmax;
  97030. else if(q < qmin)
  97031. q = qmin;
  97032. error -= q;
  97033. qlp_coeff[i] = q;
  97034. }
  97035. *shift = 0;
  97036. }
  97037. return 0;
  97038. }
  97039. 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[])
  97040. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97041. {
  97042. FLAC__int64 sumo;
  97043. unsigned i, j;
  97044. FLAC__int32 sum;
  97045. const FLAC__int32 *history;
  97046. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97047. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97048. for(i=0;i<order;i++)
  97049. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97050. fprintf(stderr,"\n");
  97051. #endif
  97052. FLAC__ASSERT(order > 0);
  97053. for(i = 0; i < data_len; i++) {
  97054. sumo = 0;
  97055. sum = 0;
  97056. history = data;
  97057. for(j = 0; j < order; j++) {
  97058. sum += qlp_coeff[j] * (*(--history));
  97059. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97060. #if defined _MSC_VER
  97061. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97062. 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);
  97063. #else
  97064. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97065. 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);
  97066. #endif
  97067. }
  97068. *(residual++) = *(data++) - (sum >> lp_quantization);
  97069. }
  97070. /* Here's a slower but clearer version:
  97071. for(i = 0; i < data_len; i++) {
  97072. sum = 0;
  97073. for(j = 0; j < order; j++)
  97074. sum += qlp_coeff[j] * data[i-j-1];
  97075. residual[i] = data[i] - (sum >> lp_quantization);
  97076. }
  97077. */
  97078. }
  97079. #else /* fully unrolled version for normal use */
  97080. {
  97081. int i;
  97082. FLAC__int32 sum;
  97083. FLAC__ASSERT(order > 0);
  97084. FLAC__ASSERT(order <= 32);
  97085. /*
  97086. * We do unique versions up to 12th order since that's the subset limit.
  97087. * Also they are roughly ordered to match frequency of occurrence to
  97088. * minimize branching.
  97089. */
  97090. if(order <= 12) {
  97091. if(order > 8) {
  97092. if(order > 10) {
  97093. if(order == 12) {
  97094. for(i = 0; i < (int)data_len; i++) {
  97095. sum = 0;
  97096. sum += qlp_coeff[11] * data[i-12];
  97097. sum += qlp_coeff[10] * data[i-11];
  97098. sum += qlp_coeff[9] * data[i-10];
  97099. sum += qlp_coeff[8] * data[i-9];
  97100. sum += qlp_coeff[7] * data[i-8];
  97101. sum += qlp_coeff[6] * data[i-7];
  97102. sum += qlp_coeff[5] * data[i-6];
  97103. sum += qlp_coeff[4] * data[i-5];
  97104. sum += qlp_coeff[3] * data[i-4];
  97105. sum += qlp_coeff[2] * data[i-3];
  97106. sum += qlp_coeff[1] * data[i-2];
  97107. sum += qlp_coeff[0] * data[i-1];
  97108. residual[i] = data[i] - (sum >> lp_quantization);
  97109. }
  97110. }
  97111. else { /* order == 11 */
  97112. for(i = 0; i < (int)data_len; i++) {
  97113. sum = 0;
  97114. sum += qlp_coeff[10] * data[i-11];
  97115. sum += qlp_coeff[9] * data[i-10];
  97116. sum += qlp_coeff[8] * data[i-9];
  97117. sum += qlp_coeff[7] * data[i-8];
  97118. sum += qlp_coeff[6] * data[i-7];
  97119. sum += qlp_coeff[5] * data[i-6];
  97120. sum += qlp_coeff[4] * data[i-5];
  97121. sum += qlp_coeff[3] * data[i-4];
  97122. sum += qlp_coeff[2] * data[i-3];
  97123. sum += qlp_coeff[1] * data[i-2];
  97124. sum += qlp_coeff[0] * data[i-1];
  97125. residual[i] = data[i] - (sum >> lp_quantization);
  97126. }
  97127. }
  97128. }
  97129. else {
  97130. if(order == 10) {
  97131. for(i = 0; i < (int)data_len; i++) {
  97132. sum = 0;
  97133. sum += qlp_coeff[9] * data[i-10];
  97134. sum += qlp_coeff[8] * data[i-9];
  97135. sum += qlp_coeff[7] * data[i-8];
  97136. sum += qlp_coeff[6] * data[i-7];
  97137. sum += qlp_coeff[5] * data[i-6];
  97138. sum += qlp_coeff[4] * data[i-5];
  97139. sum += qlp_coeff[3] * data[i-4];
  97140. sum += qlp_coeff[2] * data[i-3];
  97141. sum += qlp_coeff[1] * data[i-2];
  97142. sum += qlp_coeff[0] * data[i-1];
  97143. residual[i] = data[i] - (sum >> lp_quantization);
  97144. }
  97145. }
  97146. else { /* order == 9 */
  97147. for(i = 0; i < (int)data_len; i++) {
  97148. sum = 0;
  97149. sum += qlp_coeff[8] * data[i-9];
  97150. sum += qlp_coeff[7] * data[i-8];
  97151. sum += qlp_coeff[6] * data[i-7];
  97152. sum += qlp_coeff[5] * data[i-6];
  97153. sum += qlp_coeff[4] * data[i-5];
  97154. sum += qlp_coeff[3] * data[i-4];
  97155. sum += qlp_coeff[2] * data[i-3];
  97156. sum += qlp_coeff[1] * data[i-2];
  97157. sum += qlp_coeff[0] * data[i-1];
  97158. residual[i] = data[i] - (sum >> lp_quantization);
  97159. }
  97160. }
  97161. }
  97162. }
  97163. else if(order > 4) {
  97164. if(order > 6) {
  97165. if(order == 8) {
  97166. for(i = 0; i < (int)data_len; i++) {
  97167. sum = 0;
  97168. sum += qlp_coeff[7] * data[i-8];
  97169. sum += qlp_coeff[6] * data[i-7];
  97170. sum += qlp_coeff[5] * data[i-6];
  97171. sum += qlp_coeff[4] * data[i-5];
  97172. sum += qlp_coeff[3] * data[i-4];
  97173. sum += qlp_coeff[2] * data[i-3];
  97174. sum += qlp_coeff[1] * data[i-2];
  97175. sum += qlp_coeff[0] * data[i-1];
  97176. residual[i] = data[i] - (sum >> lp_quantization);
  97177. }
  97178. }
  97179. else { /* order == 7 */
  97180. for(i = 0; i < (int)data_len; i++) {
  97181. sum = 0;
  97182. sum += qlp_coeff[6] * data[i-7];
  97183. sum += qlp_coeff[5] * data[i-6];
  97184. sum += qlp_coeff[4] * data[i-5];
  97185. sum += qlp_coeff[3] * data[i-4];
  97186. sum += qlp_coeff[2] * data[i-3];
  97187. sum += qlp_coeff[1] * data[i-2];
  97188. sum += qlp_coeff[0] * data[i-1];
  97189. residual[i] = data[i] - (sum >> lp_quantization);
  97190. }
  97191. }
  97192. }
  97193. else {
  97194. if(order == 6) {
  97195. for(i = 0; i < (int)data_len; i++) {
  97196. sum = 0;
  97197. sum += qlp_coeff[5] * data[i-6];
  97198. sum += qlp_coeff[4] * data[i-5];
  97199. sum += qlp_coeff[3] * data[i-4];
  97200. sum += qlp_coeff[2] * data[i-3];
  97201. sum += qlp_coeff[1] * data[i-2];
  97202. sum += qlp_coeff[0] * data[i-1];
  97203. residual[i] = data[i] - (sum >> lp_quantization);
  97204. }
  97205. }
  97206. else { /* order == 5 */
  97207. for(i = 0; i < (int)data_len; i++) {
  97208. sum = 0;
  97209. sum += qlp_coeff[4] * data[i-5];
  97210. sum += qlp_coeff[3] * data[i-4];
  97211. sum += qlp_coeff[2] * data[i-3];
  97212. sum += qlp_coeff[1] * data[i-2];
  97213. sum += qlp_coeff[0] * data[i-1];
  97214. residual[i] = data[i] - (sum >> lp_quantization);
  97215. }
  97216. }
  97217. }
  97218. }
  97219. else {
  97220. if(order > 2) {
  97221. if(order == 4) {
  97222. for(i = 0; i < (int)data_len; i++) {
  97223. sum = 0;
  97224. sum += qlp_coeff[3] * data[i-4];
  97225. sum += qlp_coeff[2] * data[i-3];
  97226. sum += qlp_coeff[1] * data[i-2];
  97227. sum += qlp_coeff[0] * data[i-1];
  97228. residual[i] = data[i] - (sum >> lp_quantization);
  97229. }
  97230. }
  97231. else { /* order == 3 */
  97232. for(i = 0; i < (int)data_len; i++) {
  97233. sum = 0;
  97234. sum += qlp_coeff[2] * data[i-3];
  97235. sum += qlp_coeff[1] * data[i-2];
  97236. sum += qlp_coeff[0] * data[i-1];
  97237. residual[i] = data[i] - (sum >> lp_quantization);
  97238. }
  97239. }
  97240. }
  97241. else {
  97242. if(order == 2) {
  97243. for(i = 0; i < (int)data_len; i++) {
  97244. sum = 0;
  97245. sum += qlp_coeff[1] * data[i-2];
  97246. sum += qlp_coeff[0] * data[i-1];
  97247. residual[i] = data[i] - (sum >> lp_quantization);
  97248. }
  97249. }
  97250. else { /* order == 1 */
  97251. for(i = 0; i < (int)data_len; i++)
  97252. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97253. }
  97254. }
  97255. }
  97256. }
  97257. else { /* order > 12 */
  97258. for(i = 0; i < (int)data_len; i++) {
  97259. sum = 0;
  97260. switch(order) {
  97261. case 32: sum += qlp_coeff[31] * data[i-32];
  97262. case 31: sum += qlp_coeff[30] * data[i-31];
  97263. case 30: sum += qlp_coeff[29] * data[i-30];
  97264. case 29: sum += qlp_coeff[28] * data[i-29];
  97265. case 28: sum += qlp_coeff[27] * data[i-28];
  97266. case 27: sum += qlp_coeff[26] * data[i-27];
  97267. case 26: sum += qlp_coeff[25] * data[i-26];
  97268. case 25: sum += qlp_coeff[24] * data[i-25];
  97269. case 24: sum += qlp_coeff[23] * data[i-24];
  97270. case 23: sum += qlp_coeff[22] * data[i-23];
  97271. case 22: sum += qlp_coeff[21] * data[i-22];
  97272. case 21: sum += qlp_coeff[20] * data[i-21];
  97273. case 20: sum += qlp_coeff[19] * data[i-20];
  97274. case 19: sum += qlp_coeff[18] * data[i-19];
  97275. case 18: sum += qlp_coeff[17] * data[i-18];
  97276. case 17: sum += qlp_coeff[16] * data[i-17];
  97277. case 16: sum += qlp_coeff[15] * data[i-16];
  97278. case 15: sum += qlp_coeff[14] * data[i-15];
  97279. case 14: sum += qlp_coeff[13] * data[i-14];
  97280. case 13: sum += qlp_coeff[12] * data[i-13];
  97281. sum += qlp_coeff[11] * data[i-12];
  97282. sum += qlp_coeff[10] * data[i-11];
  97283. sum += qlp_coeff[ 9] * data[i-10];
  97284. sum += qlp_coeff[ 8] * data[i- 9];
  97285. sum += qlp_coeff[ 7] * data[i- 8];
  97286. sum += qlp_coeff[ 6] * data[i- 7];
  97287. sum += qlp_coeff[ 5] * data[i- 6];
  97288. sum += qlp_coeff[ 4] * data[i- 5];
  97289. sum += qlp_coeff[ 3] * data[i- 4];
  97290. sum += qlp_coeff[ 2] * data[i- 3];
  97291. sum += qlp_coeff[ 1] * data[i- 2];
  97292. sum += qlp_coeff[ 0] * data[i- 1];
  97293. }
  97294. residual[i] = data[i] - (sum >> lp_quantization);
  97295. }
  97296. }
  97297. }
  97298. #endif
  97299. 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[])
  97300. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97301. {
  97302. unsigned i, j;
  97303. FLAC__int64 sum;
  97304. const FLAC__int32 *history;
  97305. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97306. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97307. for(i=0;i<order;i++)
  97308. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97309. fprintf(stderr,"\n");
  97310. #endif
  97311. FLAC__ASSERT(order > 0);
  97312. for(i = 0; i < data_len; i++) {
  97313. sum = 0;
  97314. history = data;
  97315. for(j = 0; j < order; j++)
  97316. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97317. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97318. #if defined _MSC_VER
  97319. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97320. #else
  97321. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97322. #endif
  97323. break;
  97324. }
  97325. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97326. #if defined _MSC_VER
  97327. 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));
  97328. #else
  97329. 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)));
  97330. #endif
  97331. break;
  97332. }
  97333. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97334. }
  97335. }
  97336. #else /* fully unrolled version for normal use */
  97337. {
  97338. int i;
  97339. FLAC__int64 sum;
  97340. FLAC__ASSERT(order > 0);
  97341. FLAC__ASSERT(order <= 32);
  97342. /*
  97343. * We do unique versions up to 12th order since that's the subset limit.
  97344. * Also they are roughly ordered to match frequency of occurrence to
  97345. * minimize branching.
  97346. */
  97347. if(order <= 12) {
  97348. if(order > 8) {
  97349. if(order > 10) {
  97350. if(order == 12) {
  97351. for(i = 0; i < (int)data_len; i++) {
  97352. sum = 0;
  97353. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97354. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97355. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97356. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97357. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97358. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97359. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97360. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97361. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97362. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97363. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97364. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97365. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97366. }
  97367. }
  97368. else { /* order == 11 */
  97369. for(i = 0; i < (int)data_len; i++) {
  97370. sum = 0;
  97371. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97372. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97373. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97374. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97375. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97376. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97377. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97378. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97379. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97380. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97381. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97382. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97383. }
  97384. }
  97385. }
  97386. else {
  97387. if(order == 10) {
  97388. for(i = 0; i < (int)data_len; i++) {
  97389. sum = 0;
  97390. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97391. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97392. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97393. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97394. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97395. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97396. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97397. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97398. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97399. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97400. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97401. }
  97402. }
  97403. else { /* order == 9 */
  97404. for(i = 0; i < (int)data_len; i++) {
  97405. sum = 0;
  97406. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97407. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97408. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97409. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97410. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97411. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97412. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97413. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97414. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97415. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97416. }
  97417. }
  97418. }
  97419. }
  97420. else if(order > 4) {
  97421. if(order > 6) {
  97422. if(order == 8) {
  97423. for(i = 0; i < (int)data_len; i++) {
  97424. sum = 0;
  97425. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97426. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97427. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97428. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97429. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97430. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97431. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97432. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97433. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97434. }
  97435. }
  97436. else { /* order == 7 */
  97437. for(i = 0; i < (int)data_len; i++) {
  97438. sum = 0;
  97439. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97440. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97441. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97442. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97443. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97444. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97445. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97446. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97447. }
  97448. }
  97449. }
  97450. else {
  97451. if(order == 6) {
  97452. for(i = 0; i < (int)data_len; i++) {
  97453. sum = 0;
  97454. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97455. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97456. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97457. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97458. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97459. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97460. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97461. }
  97462. }
  97463. else { /* order == 5 */
  97464. for(i = 0; i < (int)data_len; i++) {
  97465. sum = 0;
  97466. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97467. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97468. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97469. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97470. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97471. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97472. }
  97473. }
  97474. }
  97475. }
  97476. else {
  97477. if(order > 2) {
  97478. if(order == 4) {
  97479. for(i = 0; i < (int)data_len; i++) {
  97480. sum = 0;
  97481. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97482. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97483. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97484. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97485. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97486. }
  97487. }
  97488. else { /* order == 3 */
  97489. for(i = 0; i < (int)data_len; i++) {
  97490. sum = 0;
  97491. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97492. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97493. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97494. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97495. }
  97496. }
  97497. }
  97498. else {
  97499. if(order == 2) {
  97500. for(i = 0; i < (int)data_len; i++) {
  97501. sum = 0;
  97502. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97503. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97504. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97505. }
  97506. }
  97507. else { /* order == 1 */
  97508. for(i = 0; i < (int)data_len; i++)
  97509. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97510. }
  97511. }
  97512. }
  97513. }
  97514. else { /* order > 12 */
  97515. for(i = 0; i < (int)data_len; i++) {
  97516. sum = 0;
  97517. switch(order) {
  97518. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97519. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97520. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97521. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97522. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97523. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97524. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97525. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97526. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97527. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97528. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97529. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97530. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97531. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97532. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97533. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97534. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97535. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97536. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97537. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97538. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97539. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97540. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97541. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97542. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97543. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97544. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97545. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97546. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97547. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97548. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97549. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97550. }
  97551. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97552. }
  97553. }
  97554. }
  97555. #endif
  97556. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97557. 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[])
  97558. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97559. {
  97560. FLAC__int64 sumo;
  97561. unsigned i, j;
  97562. FLAC__int32 sum;
  97563. const FLAC__int32 *r = residual, *history;
  97564. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97565. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97566. for(i=0;i<order;i++)
  97567. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97568. fprintf(stderr,"\n");
  97569. #endif
  97570. FLAC__ASSERT(order > 0);
  97571. for(i = 0; i < data_len; i++) {
  97572. sumo = 0;
  97573. sum = 0;
  97574. history = data;
  97575. for(j = 0; j < order; j++) {
  97576. sum += qlp_coeff[j] * (*(--history));
  97577. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97578. #if defined _MSC_VER
  97579. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97580. 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);
  97581. #else
  97582. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97583. 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);
  97584. #endif
  97585. }
  97586. *(data++) = *(r++) + (sum >> lp_quantization);
  97587. }
  97588. /* Here's a slower but clearer version:
  97589. for(i = 0; i < data_len; i++) {
  97590. sum = 0;
  97591. for(j = 0; j < order; j++)
  97592. sum += qlp_coeff[j] * data[i-j-1];
  97593. data[i] = residual[i] + (sum >> lp_quantization);
  97594. }
  97595. */
  97596. }
  97597. #else /* fully unrolled version for normal use */
  97598. {
  97599. int i;
  97600. FLAC__int32 sum;
  97601. FLAC__ASSERT(order > 0);
  97602. FLAC__ASSERT(order <= 32);
  97603. /*
  97604. * We do unique versions up to 12th order since that's the subset limit.
  97605. * Also they are roughly ordered to match frequency of occurrence to
  97606. * minimize branching.
  97607. */
  97608. if(order <= 12) {
  97609. if(order > 8) {
  97610. if(order > 10) {
  97611. if(order == 12) {
  97612. for(i = 0; i < (int)data_len; i++) {
  97613. sum = 0;
  97614. sum += qlp_coeff[11] * data[i-12];
  97615. sum += qlp_coeff[10] * data[i-11];
  97616. sum += qlp_coeff[9] * data[i-10];
  97617. sum += qlp_coeff[8] * data[i-9];
  97618. sum += qlp_coeff[7] * data[i-8];
  97619. sum += qlp_coeff[6] * data[i-7];
  97620. sum += qlp_coeff[5] * data[i-6];
  97621. sum += qlp_coeff[4] * data[i-5];
  97622. sum += qlp_coeff[3] * data[i-4];
  97623. sum += qlp_coeff[2] * data[i-3];
  97624. sum += qlp_coeff[1] * data[i-2];
  97625. sum += qlp_coeff[0] * data[i-1];
  97626. data[i] = residual[i] + (sum >> lp_quantization);
  97627. }
  97628. }
  97629. else { /* order == 11 */
  97630. for(i = 0; i < (int)data_len; i++) {
  97631. sum = 0;
  97632. sum += qlp_coeff[10] * data[i-11];
  97633. sum += qlp_coeff[9] * data[i-10];
  97634. sum += qlp_coeff[8] * data[i-9];
  97635. sum += qlp_coeff[7] * data[i-8];
  97636. sum += qlp_coeff[6] * data[i-7];
  97637. sum += qlp_coeff[5] * data[i-6];
  97638. sum += qlp_coeff[4] * data[i-5];
  97639. sum += qlp_coeff[3] * data[i-4];
  97640. sum += qlp_coeff[2] * data[i-3];
  97641. sum += qlp_coeff[1] * data[i-2];
  97642. sum += qlp_coeff[0] * data[i-1];
  97643. data[i] = residual[i] + (sum >> lp_quantization);
  97644. }
  97645. }
  97646. }
  97647. else {
  97648. if(order == 10) {
  97649. for(i = 0; i < (int)data_len; i++) {
  97650. sum = 0;
  97651. sum += qlp_coeff[9] * data[i-10];
  97652. sum += qlp_coeff[8] * data[i-9];
  97653. sum += qlp_coeff[7] * data[i-8];
  97654. sum += qlp_coeff[6] * data[i-7];
  97655. sum += qlp_coeff[5] * data[i-6];
  97656. sum += qlp_coeff[4] * data[i-5];
  97657. sum += qlp_coeff[3] * data[i-4];
  97658. sum += qlp_coeff[2] * data[i-3];
  97659. sum += qlp_coeff[1] * data[i-2];
  97660. sum += qlp_coeff[0] * data[i-1];
  97661. data[i] = residual[i] + (sum >> lp_quantization);
  97662. }
  97663. }
  97664. else { /* order == 9 */
  97665. for(i = 0; i < (int)data_len; i++) {
  97666. sum = 0;
  97667. sum += qlp_coeff[8] * data[i-9];
  97668. sum += qlp_coeff[7] * data[i-8];
  97669. sum += qlp_coeff[6] * data[i-7];
  97670. sum += qlp_coeff[5] * data[i-6];
  97671. sum += qlp_coeff[4] * data[i-5];
  97672. sum += qlp_coeff[3] * data[i-4];
  97673. sum += qlp_coeff[2] * data[i-3];
  97674. sum += qlp_coeff[1] * data[i-2];
  97675. sum += qlp_coeff[0] * data[i-1];
  97676. data[i] = residual[i] + (sum >> lp_quantization);
  97677. }
  97678. }
  97679. }
  97680. }
  97681. else if(order > 4) {
  97682. if(order > 6) {
  97683. if(order == 8) {
  97684. for(i = 0; i < (int)data_len; i++) {
  97685. sum = 0;
  97686. sum += qlp_coeff[7] * data[i-8];
  97687. sum += qlp_coeff[6] * data[i-7];
  97688. sum += qlp_coeff[5] * data[i-6];
  97689. sum += qlp_coeff[4] * data[i-5];
  97690. sum += qlp_coeff[3] * data[i-4];
  97691. sum += qlp_coeff[2] * data[i-3];
  97692. sum += qlp_coeff[1] * data[i-2];
  97693. sum += qlp_coeff[0] * data[i-1];
  97694. data[i] = residual[i] + (sum >> lp_quantization);
  97695. }
  97696. }
  97697. else { /* order == 7 */
  97698. for(i = 0; i < (int)data_len; i++) {
  97699. sum = 0;
  97700. sum += qlp_coeff[6] * data[i-7];
  97701. sum += qlp_coeff[5] * data[i-6];
  97702. sum += qlp_coeff[4] * data[i-5];
  97703. sum += qlp_coeff[3] * data[i-4];
  97704. sum += qlp_coeff[2] * data[i-3];
  97705. sum += qlp_coeff[1] * data[i-2];
  97706. sum += qlp_coeff[0] * data[i-1];
  97707. data[i] = residual[i] + (sum >> lp_quantization);
  97708. }
  97709. }
  97710. }
  97711. else {
  97712. if(order == 6) {
  97713. for(i = 0; i < (int)data_len; i++) {
  97714. sum = 0;
  97715. sum += qlp_coeff[5] * data[i-6];
  97716. sum += qlp_coeff[4] * data[i-5];
  97717. sum += qlp_coeff[3] * data[i-4];
  97718. sum += qlp_coeff[2] * data[i-3];
  97719. sum += qlp_coeff[1] * data[i-2];
  97720. sum += qlp_coeff[0] * data[i-1];
  97721. data[i] = residual[i] + (sum >> lp_quantization);
  97722. }
  97723. }
  97724. else { /* order == 5 */
  97725. for(i = 0; i < (int)data_len; i++) {
  97726. sum = 0;
  97727. sum += qlp_coeff[4] * data[i-5];
  97728. sum += qlp_coeff[3] * data[i-4];
  97729. sum += qlp_coeff[2] * data[i-3];
  97730. sum += qlp_coeff[1] * data[i-2];
  97731. sum += qlp_coeff[0] * data[i-1];
  97732. data[i] = residual[i] + (sum >> lp_quantization);
  97733. }
  97734. }
  97735. }
  97736. }
  97737. else {
  97738. if(order > 2) {
  97739. if(order == 4) {
  97740. for(i = 0; i < (int)data_len; i++) {
  97741. sum = 0;
  97742. sum += qlp_coeff[3] * data[i-4];
  97743. sum += qlp_coeff[2] * data[i-3];
  97744. sum += qlp_coeff[1] * data[i-2];
  97745. sum += qlp_coeff[0] * data[i-1];
  97746. data[i] = residual[i] + (sum >> lp_quantization);
  97747. }
  97748. }
  97749. else { /* order == 3 */
  97750. for(i = 0; i < (int)data_len; i++) {
  97751. sum = 0;
  97752. sum += qlp_coeff[2] * data[i-3];
  97753. sum += qlp_coeff[1] * data[i-2];
  97754. sum += qlp_coeff[0] * data[i-1];
  97755. data[i] = residual[i] + (sum >> lp_quantization);
  97756. }
  97757. }
  97758. }
  97759. else {
  97760. if(order == 2) {
  97761. for(i = 0; i < (int)data_len; i++) {
  97762. sum = 0;
  97763. sum += qlp_coeff[1] * data[i-2];
  97764. sum += qlp_coeff[0] * data[i-1];
  97765. data[i] = residual[i] + (sum >> lp_quantization);
  97766. }
  97767. }
  97768. else { /* order == 1 */
  97769. for(i = 0; i < (int)data_len; i++)
  97770. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97771. }
  97772. }
  97773. }
  97774. }
  97775. else { /* order > 12 */
  97776. for(i = 0; i < (int)data_len; i++) {
  97777. sum = 0;
  97778. switch(order) {
  97779. case 32: sum += qlp_coeff[31] * data[i-32];
  97780. case 31: sum += qlp_coeff[30] * data[i-31];
  97781. case 30: sum += qlp_coeff[29] * data[i-30];
  97782. case 29: sum += qlp_coeff[28] * data[i-29];
  97783. case 28: sum += qlp_coeff[27] * data[i-28];
  97784. case 27: sum += qlp_coeff[26] * data[i-27];
  97785. case 26: sum += qlp_coeff[25] * data[i-26];
  97786. case 25: sum += qlp_coeff[24] * data[i-25];
  97787. case 24: sum += qlp_coeff[23] * data[i-24];
  97788. case 23: sum += qlp_coeff[22] * data[i-23];
  97789. case 22: sum += qlp_coeff[21] * data[i-22];
  97790. case 21: sum += qlp_coeff[20] * data[i-21];
  97791. case 20: sum += qlp_coeff[19] * data[i-20];
  97792. case 19: sum += qlp_coeff[18] * data[i-19];
  97793. case 18: sum += qlp_coeff[17] * data[i-18];
  97794. case 17: sum += qlp_coeff[16] * data[i-17];
  97795. case 16: sum += qlp_coeff[15] * data[i-16];
  97796. case 15: sum += qlp_coeff[14] * data[i-15];
  97797. case 14: sum += qlp_coeff[13] * data[i-14];
  97798. case 13: sum += qlp_coeff[12] * data[i-13];
  97799. sum += qlp_coeff[11] * data[i-12];
  97800. sum += qlp_coeff[10] * data[i-11];
  97801. sum += qlp_coeff[ 9] * data[i-10];
  97802. sum += qlp_coeff[ 8] * data[i- 9];
  97803. sum += qlp_coeff[ 7] * data[i- 8];
  97804. sum += qlp_coeff[ 6] * data[i- 7];
  97805. sum += qlp_coeff[ 5] * data[i- 6];
  97806. sum += qlp_coeff[ 4] * data[i- 5];
  97807. sum += qlp_coeff[ 3] * data[i- 4];
  97808. sum += qlp_coeff[ 2] * data[i- 3];
  97809. sum += qlp_coeff[ 1] * data[i- 2];
  97810. sum += qlp_coeff[ 0] * data[i- 1];
  97811. }
  97812. data[i] = residual[i] + (sum >> lp_quantization);
  97813. }
  97814. }
  97815. }
  97816. #endif
  97817. 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[])
  97818. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97819. {
  97820. unsigned i, j;
  97821. FLAC__int64 sum;
  97822. const FLAC__int32 *r = residual, *history;
  97823. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97824. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97825. for(i=0;i<order;i++)
  97826. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97827. fprintf(stderr,"\n");
  97828. #endif
  97829. FLAC__ASSERT(order > 0);
  97830. for(i = 0; i < data_len; i++) {
  97831. sum = 0;
  97832. history = data;
  97833. for(j = 0; j < order; j++)
  97834. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97835. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97836. #ifdef _MSC_VER
  97837. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97838. #else
  97839. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97840. #endif
  97841. break;
  97842. }
  97843. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97844. #ifdef _MSC_VER
  97845. 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));
  97846. #else
  97847. 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)));
  97848. #endif
  97849. break;
  97850. }
  97851. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97852. }
  97853. }
  97854. #else /* fully unrolled version for normal use */
  97855. {
  97856. int i;
  97857. FLAC__int64 sum;
  97858. FLAC__ASSERT(order > 0);
  97859. FLAC__ASSERT(order <= 32);
  97860. /*
  97861. * We do unique versions up to 12th order since that's the subset limit.
  97862. * Also they are roughly ordered to match frequency of occurrence to
  97863. * minimize branching.
  97864. */
  97865. if(order <= 12) {
  97866. if(order > 8) {
  97867. if(order > 10) {
  97868. if(order == 12) {
  97869. for(i = 0; i < (int)data_len; i++) {
  97870. sum = 0;
  97871. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97872. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97873. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97874. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97875. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97876. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97877. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97878. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97879. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97880. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97881. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97882. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97883. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97884. }
  97885. }
  97886. else { /* order == 11 */
  97887. for(i = 0; i < (int)data_len; i++) {
  97888. sum = 0;
  97889. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97890. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97891. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97892. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97893. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97894. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97895. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97896. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97897. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97898. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97899. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97900. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97901. }
  97902. }
  97903. }
  97904. else {
  97905. if(order == 10) {
  97906. for(i = 0; i < (int)data_len; i++) {
  97907. sum = 0;
  97908. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97909. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97910. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97911. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97912. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97913. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97914. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97915. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97916. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97917. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97918. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97919. }
  97920. }
  97921. else { /* order == 9 */
  97922. for(i = 0; i < (int)data_len; i++) {
  97923. sum = 0;
  97924. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97925. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97926. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97927. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97928. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97929. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97930. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97931. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97932. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97933. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97934. }
  97935. }
  97936. }
  97937. }
  97938. else if(order > 4) {
  97939. if(order > 6) {
  97940. if(order == 8) {
  97941. for(i = 0; i < (int)data_len; i++) {
  97942. sum = 0;
  97943. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97944. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97945. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97946. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97947. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97948. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97949. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97950. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97951. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97952. }
  97953. }
  97954. else { /* order == 7 */
  97955. for(i = 0; i < (int)data_len; i++) {
  97956. sum = 0;
  97957. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97958. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97959. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97960. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97961. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97962. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97963. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97964. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97965. }
  97966. }
  97967. }
  97968. else {
  97969. if(order == 6) {
  97970. for(i = 0; i < (int)data_len; i++) {
  97971. sum = 0;
  97972. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97973. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97974. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97975. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97976. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97977. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97978. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97979. }
  97980. }
  97981. else { /* order == 5 */
  97982. for(i = 0; i < (int)data_len; i++) {
  97983. sum = 0;
  97984. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97985. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97986. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97987. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97988. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97989. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97990. }
  97991. }
  97992. }
  97993. }
  97994. else {
  97995. if(order > 2) {
  97996. if(order == 4) {
  97997. for(i = 0; i < (int)data_len; i++) {
  97998. sum = 0;
  97999. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98000. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98001. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98002. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98003. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98004. }
  98005. }
  98006. else { /* order == 3 */
  98007. for(i = 0; i < (int)data_len; i++) {
  98008. sum = 0;
  98009. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98010. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98011. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98012. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98013. }
  98014. }
  98015. }
  98016. else {
  98017. if(order == 2) {
  98018. for(i = 0; i < (int)data_len; i++) {
  98019. sum = 0;
  98020. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98021. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98022. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98023. }
  98024. }
  98025. else { /* order == 1 */
  98026. for(i = 0; i < (int)data_len; i++)
  98027. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98028. }
  98029. }
  98030. }
  98031. }
  98032. else { /* order > 12 */
  98033. for(i = 0; i < (int)data_len; i++) {
  98034. sum = 0;
  98035. switch(order) {
  98036. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98037. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98038. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98039. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98040. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98041. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98042. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98043. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98044. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98045. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98046. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98047. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98048. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98049. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98050. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98051. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98052. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98053. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98054. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98055. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98056. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98057. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98058. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98059. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98060. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98061. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98062. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98063. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98064. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98065. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98066. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98067. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98068. }
  98069. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98070. }
  98071. }
  98072. }
  98073. #endif
  98074. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98075. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98076. {
  98077. FLAC__double error_scale;
  98078. FLAC__ASSERT(total_samples > 0);
  98079. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98080. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98081. }
  98082. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98083. {
  98084. if(lpc_error > 0.0) {
  98085. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98086. if(bps >= 0.0)
  98087. return bps;
  98088. else
  98089. return 0.0;
  98090. }
  98091. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98092. return 1e32;
  98093. }
  98094. else {
  98095. return 0.0;
  98096. }
  98097. }
  98098. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98099. {
  98100. 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 */
  98101. FLAC__double bits, best_bits, error_scale;
  98102. FLAC__ASSERT(max_order > 0);
  98103. FLAC__ASSERT(total_samples > 0);
  98104. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98105. best_index = 0;
  98106. best_bits = (unsigned)(-1);
  98107. for(index = 0, order = 1; index < max_order; index++, order++) {
  98108. 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);
  98109. if(bits < best_bits) {
  98110. best_index = index;
  98111. best_bits = bits;
  98112. }
  98113. }
  98114. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98115. }
  98116. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98117. #endif
  98118. /*** End of inlined file: lpc_flac.c ***/
  98119. /*** Start of inlined file: md5.c ***/
  98120. /*** Start of inlined file: juce_FlacHeader.h ***/
  98121. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98122. // tasks..
  98123. #define VERSION "1.2.1"
  98124. #define FLAC__NO_DLL 1
  98125. #if JUCE_MSVC
  98126. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98127. #endif
  98128. #if JUCE_MAC
  98129. #define FLAC__SYS_DARWIN 1
  98130. #endif
  98131. /*** End of inlined file: juce_FlacHeader.h ***/
  98132. #if JUCE_USE_FLAC
  98133. #if HAVE_CONFIG_H
  98134. # include <config.h>
  98135. #endif
  98136. #include <stdlib.h> /* for malloc() */
  98137. #include <string.h> /* for memcpy() */
  98138. /*** Start of inlined file: md5.h ***/
  98139. #ifndef FLAC__PRIVATE__MD5_H
  98140. #define FLAC__PRIVATE__MD5_H
  98141. /*
  98142. * This is the header file for the MD5 message-digest algorithm.
  98143. * The algorithm is due to Ron Rivest. This code was
  98144. * written by Colin Plumb in 1993, no copyright is claimed.
  98145. * This code is in the public domain; do with it what you wish.
  98146. *
  98147. * Equivalent code is available from RSA Data Security, Inc.
  98148. * This code has been tested against that, and is equivalent,
  98149. * except that you don't need to include two pages of legalese
  98150. * with every copy.
  98151. *
  98152. * To compute the message digest of a chunk of bytes, declare an
  98153. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98154. * needed on buffers full of bytes, and then call MD5Final, which
  98155. * will fill a supplied 16-byte array with the digest.
  98156. *
  98157. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98158. * header definitions; now uses stuff from dpkg's config.h
  98159. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98160. * Still in the public domain.
  98161. *
  98162. * Josh Coalson: made some changes to integrate with libFLAC.
  98163. * Still in the public domain, with no warranty.
  98164. */
  98165. typedef struct {
  98166. FLAC__uint32 in[16];
  98167. FLAC__uint32 buf[4];
  98168. FLAC__uint32 bytes[2];
  98169. FLAC__byte *internal_buf;
  98170. size_t capacity;
  98171. } FLAC__MD5Context;
  98172. void FLAC__MD5Init(FLAC__MD5Context *context);
  98173. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98174. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98175. #endif
  98176. /*** End of inlined file: md5.h ***/
  98177. #ifndef FLaC__INLINE
  98178. #define FLaC__INLINE
  98179. #endif
  98180. /*
  98181. * This code implements the MD5 message-digest algorithm.
  98182. * The algorithm is due to Ron Rivest. This code was
  98183. * written by Colin Plumb in 1993, no copyright is claimed.
  98184. * This code is in the public domain; do with it what you wish.
  98185. *
  98186. * Equivalent code is available from RSA Data Security, Inc.
  98187. * This code has been tested against that, and is equivalent,
  98188. * except that you don't need to include two pages of legalese
  98189. * with every copy.
  98190. *
  98191. * To compute the message digest of a chunk of bytes, declare an
  98192. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98193. * needed on buffers full of bytes, and then call MD5Final, which
  98194. * will fill a supplied 16-byte array with the digest.
  98195. *
  98196. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98197. * definitions; now uses stuff from dpkg's config.h.
  98198. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98199. * Still in the public domain.
  98200. *
  98201. * Josh Coalson: made some changes to integrate with libFLAC.
  98202. * Still in the public domain.
  98203. */
  98204. /* The four core functions - F1 is optimized somewhat */
  98205. /* #define F1(x, y, z) (x & y | ~x & z) */
  98206. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98207. #define F2(x, y, z) F1(z, x, y)
  98208. #define F3(x, y, z) (x ^ y ^ z)
  98209. #define F4(x, y, z) (y ^ (x | ~z))
  98210. /* This is the central step in the MD5 algorithm. */
  98211. #define MD5STEP(f,w,x,y,z,in,s) \
  98212. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98213. /*
  98214. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98215. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98216. * the data and converts bytes into longwords for this routine.
  98217. */
  98218. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98219. {
  98220. register FLAC__uint32 a, b, c, d;
  98221. a = buf[0];
  98222. b = buf[1];
  98223. c = buf[2];
  98224. d = buf[3];
  98225. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98226. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98227. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98228. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98229. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98230. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98231. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98232. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98233. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98234. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98235. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98236. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98237. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98238. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98239. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98240. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98241. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98242. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98243. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98244. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98245. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98246. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98247. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98248. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98249. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98250. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98251. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98252. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98253. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98254. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98255. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98256. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98257. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98258. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98259. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98260. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98261. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98262. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98263. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98264. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98265. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98266. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98267. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98268. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98269. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98270. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98271. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98272. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98273. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98274. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98275. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98276. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98277. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98278. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98279. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98280. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98281. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98282. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98283. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98284. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98285. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98286. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98287. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98288. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98289. buf[0] += a;
  98290. buf[1] += b;
  98291. buf[2] += c;
  98292. buf[3] += d;
  98293. }
  98294. #if WORDS_BIGENDIAN
  98295. //@@@@@@ OPT: use bswap/intrinsics
  98296. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98297. {
  98298. register FLAC__uint32 x;
  98299. do {
  98300. x = *buf;
  98301. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98302. *buf++ = (x >> 16) | (x << 16);
  98303. } while (--words);
  98304. }
  98305. static void byteSwapX16(FLAC__uint32 *buf)
  98306. {
  98307. register FLAC__uint32 x;
  98308. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98309. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98310. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98311. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98312. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98313. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98314. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98315. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98316. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98317. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98318. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98319. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98320. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98321. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98322. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98323. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98324. }
  98325. #else
  98326. #define byteSwap(buf, words)
  98327. #define byteSwapX16(buf)
  98328. #endif
  98329. /*
  98330. * Update context to reflect the concatenation of another buffer full
  98331. * of bytes.
  98332. */
  98333. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98334. {
  98335. FLAC__uint32 t;
  98336. /* Update byte count */
  98337. t = ctx->bytes[0];
  98338. if ((ctx->bytes[0] = t + len) < t)
  98339. ctx->bytes[1]++; /* Carry from low to high */
  98340. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98341. if (t > len) {
  98342. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98343. return;
  98344. }
  98345. /* First chunk is an odd size */
  98346. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98347. byteSwapX16(ctx->in);
  98348. FLAC__MD5Transform(ctx->buf, ctx->in);
  98349. buf += t;
  98350. len -= t;
  98351. /* Process data in 64-byte chunks */
  98352. while (len >= 64) {
  98353. memcpy(ctx->in, buf, 64);
  98354. byteSwapX16(ctx->in);
  98355. FLAC__MD5Transform(ctx->buf, ctx->in);
  98356. buf += 64;
  98357. len -= 64;
  98358. }
  98359. /* Handle any remaining bytes of data. */
  98360. memcpy(ctx->in, buf, len);
  98361. }
  98362. /*
  98363. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98364. * initialization constants.
  98365. */
  98366. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98367. {
  98368. ctx->buf[0] = 0x67452301;
  98369. ctx->buf[1] = 0xefcdab89;
  98370. ctx->buf[2] = 0x98badcfe;
  98371. ctx->buf[3] = 0x10325476;
  98372. ctx->bytes[0] = 0;
  98373. ctx->bytes[1] = 0;
  98374. ctx->internal_buf = 0;
  98375. ctx->capacity = 0;
  98376. }
  98377. /*
  98378. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98379. * 1 0* (64-bit count of bits processed, MSB-first)
  98380. */
  98381. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98382. {
  98383. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98384. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98385. /* Set the first char of padding to 0x80. There is always room. */
  98386. *p++ = 0x80;
  98387. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98388. count = 56 - 1 - count;
  98389. if (count < 0) { /* Padding forces an extra block */
  98390. memset(p, 0, count + 8);
  98391. byteSwapX16(ctx->in);
  98392. FLAC__MD5Transform(ctx->buf, ctx->in);
  98393. p = (FLAC__byte *)ctx->in;
  98394. count = 56;
  98395. }
  98396. memset(p, 0, count);
  98397. byteSwap(ctx->in, 14);
  98398. /* Append length in bits and transform */
  98399. ctx->in[14] = ctx->bytes[0] << 3;
  98400. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98401. FLAC__MD5Transform(ctx->buf, ctx->in);
  98402. byteSwap(ctx->buf, 4);
  98403. memcpy(digest, ctx->buf, 16);
  98404. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98405. if(0 != ctx->internal_buf) {
  98406. free(ctx->internal_buf);
  98407. ctx->internal_buf = 0;
  98408. ctx->capacity = 0;
  98409. }
  98410. }
  98411. /*
  98412. * Convert the incoming audio signal to a byte stream
  98413. */
  98414. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98415. {
  98416. unsigned channel, sample;
  98417. register FLAC__int32 a_word;
  98418. register FLAC__byte *buf_ = buf;
  98419. #if WORDS_BIGENDIAN
  98420. #else
  98421. if(channels == 2 && bytes_per_sample == 2) {
  98422. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98423. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98424. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98425. *buf1_ = (FLAC__int16)signal[1][sample];
  98426. }
  98427. else if(channels == 1 && bytes_per_sample == 2) {
  98428. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98429. for(sample = 0; sample < samples; sample++)
  98430. *buf1_++ = (FLAC__int16)signal[0][sample];
  98431. }
  98432. else
  98433. #endif
  98434. if(bytes_per_sample == 2) {
  98435. if(channels == 2) {
  98436. for(sample = 0; sample < samples; sample++) {
  98437. a_word = signal[0][sample];
  98438. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98439. *buf_++ = (FLAC__byte)a_word;
  98440. a_word = signal[1][sample];
  98441. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98442. *buf_++ = (FLAC__byte)a_word;
  98443. }
  98444. }
  98445. else if(channels == 1) {
  98446. for(sample = 0; sample < samples; sample++) {
  98447. a_word = signal[0][sample];
  98448. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98449. *buf_++ = (FLAC__byte)a_word;
  98450. }
  98451. }
  98452. else {
  98453. for(sample = 0; sample < samples; sample++) {
  98454. for(channel = 0; channel < channels; channel++) {
  98455. a_word = signal[channel][sample];
  98456. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98457. *buf_++ = (FLAC__byte)a_word;
  98458. }
  98459. }
  98460. }
  98461. }
  98462. else if(bytes_per_sample == 3) {
  98463. if(channels == 2) {
  98464. for(sample = 0; sample < samples; sample++) {
  98465. a_word = signal[0][sample];
  98466. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98467. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98468. *buf_++ = (FLAC__byte)a_word;
  98469. a_word = signal[1][sample];
  98470. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98471. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98472. *buf_++ = (FLAC__byte)a_word;
  98473. }
  98474. }
  98475. else if(channels == 1) {
  98476. for(sample = 0; sample < samples; sample++) {
  98477. a_word = signal[0][sample];
  98478. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98479. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98480. *buf_++ = (FLAC__byte)a_word;
  98481. }
  98482. }
  98483. else {
  98484. for(sample = 0; sample < samples; sample++) {
  98485. for(channel = 0; channel < channels; channel++) {
  98486. a_word = signal[channel][sample];
  98487. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98488. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98489. *buf_++ = (FLAC__byte)a_word;
  98490. }
  98491. }
  98492. }
  98493. }
  98494. else if(bytes_per_sample == 1) {
  98495. if(channels == 2) {
  98496. for(sample = 0; sample < samples; sample++) {
  98497. a_word = signal[0][sample];
  98498. *buf_++ = (FLAC__byte)a_word;
  98499. a_word = signal[1][sample];
  98500. *buf_++ = (FLAC__byte)a_word;
  98501. }
  98502. }
  98503. else if(channels == 1) {
  98504. for(sample = 0; sample < samples; sample++) {
  98505. a_word = signal[0][sample];
  98506. *buf_++ = (FLAC__byte)a_word;
  98507. }
  98508. }
  98509. else {
  98510. for(sample = 0; sample < samples; sample++) {
  98511. for(channel = 0; channel < channels; channel++) {
  98512. a_word = signal[channel][sample];
  98513. *buf_++ = (FLAC__byte)a_word;
  98514. }
  98515. }
  98516. }
  98517. }
  98518. else { /* bytes_per_sample == 4, maybe optimize more later */
  98519. for(sample = 0; sample < samples; sample++) {
  98520. for(channel = 0; channel < channels; channel++) {
  98521. a_word = signal[channel][sample];
  98522. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98523. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98524. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98525. *buf_++ = (FLAC__byte)a_word;
  98526. }
  98527. }
  98528. }
  98529. }
  98530. /*
  98531. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98532. */
  98533. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98534. {
  98535. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98536. /* overflow check */
  98537. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98538. return false;
  98539. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98540. return false;
  98541. if(ctx->capacity < bytes_needed) {
  98542. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98543. if(0 == tmp) {
  98544. free(ctx->internal_buf);
  98545. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98546. return false;
  98547. }
  98548. ctx->internal_buf = tmp;
  98549. ctx->capacity = bytes_needed;
  98550. }
  98551. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98552. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98553. return true;
  98554. }
  98555. #endif
  98556. /*** End of inlined file: md5.c ***/
  98557. /*** Start of inlined file: memory.c ***/
  98558. /*** Start of inlined file: juce_FlacHeader.h ***/
  98559. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98560. // tasks..
  98561. #define VERSION "1.2.1"
  98562. #define FLAC__NO_DLL 1
  98563. #if JUCE_MSVC
  98564. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98565. #endif
  98566. #if JUCE_MAC
  98567. #define FLAC__SYS_DARWIN 1
  98568. #endif
  98569. /*** End of inlined file: juce_FlacHeader.h ***/
  98570. #if JUCE_USE_FLAC
  98571. #if HAVE_CONFIG_H
  98572. # include <config.h>
  98573. #endif
  98574. /*** Start of inlined file: memory.h ***/
  98575. #ifndef FLAC__PRIVATE__MEMORY_H
  98576. #define FLAC__PRIVATE__MEMORY_H
  98577. #ifdef HAVE_CONFIG_H
  98578. #include <config.h>
  98579. #endif
  98580. #include <stdlib.h> /* for size_t */
  98581. /* Returns the unaligned address returned by malloc.
  98582. * Use free() on this address to deallocate.
  98583. */
  98584. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98585. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98586. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98587. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98588. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98589. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98590. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98591. #endif
  98592. #endif
  98593. /*** End of inlined file: memory.h ***/
  98594. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98595. {
  98596. void *x;
  98597. FLAC__ASSERT(0 != aligned_address);
  98598. #ifdef FLAC__ALIGN_MALLOC_DATA
  98599. /* align on 32-byte (256-bit) boundary */
  98600. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98601. #ifdef SIZEOF_VOIDP
  98602. #if SIZEOF_VOIDP == 4
  98603. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98604. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98605. #elif SIZEOF_VOIDP == 8
  98606. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98607. #else
  98608. # error Unsupported sizeof(void*)
  98609. #endif
  98610. #else
  98611. /* there's got to be a better way to do this right for all archs */
  98612. if(sizeof(void*) == sizeof(unsigned))
  98613. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98614. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98615. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98616. else
  98617. return 0;
  98618. #endif
  98619. #else
  98620. x = safe_malloc_(bytes);
  98621. *aligned_address = x;
  98622. #endif
  98623. return x;
  98624. }
  98625. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98626. {
  98627. FLAC__int32 *pu; /* unaligned pointer */
  98628. union { /* union needed to comply with C99 pointer aliasing rules */
  98629. FLAC__int32 *pa; /* aligned pointer */
  98630. void *pv; /* aligned pointer alias */
  98631. } u;
  98632. FLAC__ASSERT(elements > 0);
  98633. FLAC__ASSERT(0 != unaligned_pointer);
  98634. FLAC__ASSERT(0 != aligned_pointer);
  98635. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98636. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98637. if(0 == pu) {
  98638. return false;
  98639. }
  98640. else {
  98641. if(*unaligned_pointer != 0)
  98642. free(*unaligned_pointer);
  98643. *unaligned_pointer = pu;
  98644. *aligned_pointer = u.pa;
  98645. return true;
  98646. }
  98647. }
  98648. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98649. {
  98650. FLAC__uint32 *pu; /* unaligned pointer */
  98651. union { /* union needed to comply with C99 pointer aliasing rules */
  98652. FLAC__uint32 *pa; /* aligned pointer */
  98653. void *pv; /* aligned pointer alias */
  98654. } u;
  98655. FLAC__ASSERT(elements > 0);
  98656. FLAC__ASSERT(0 != unaligned_pointer);
  98657. FLAC__ASSERT(0 != aligned_pointer);
  98658. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98659. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98660. if(0 == pu) {
  98661. return false;
  98662. }
  98663. else {
  98664. if(*unaligned_pointer != 0)
  98665. free(*unaligned_pointer);
  98666. *unaligned_pointer = pu;
  98667. *aligned_pointer = u.pa;
  98668. return true;
  98669. }
  98670. }
  98671. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98672. {
  98673. FLAC__uint64 *pu; /* unaligned pointer */
  98674. union { /* union needed to comply with C99 pointer aliasing rules */
  98675. FLAC__uint64 *pa; /* aligned pointer */
  98676. void *pv; /* aligned pointer alias */
  98677. } u;
  98678. FLAC__ASSERT(elements > 0);
  98679. FLAC__ASSERT(0 != unaligned_pointer);
  98680. FLAC__ASSERT(0 != aligned_pointer);
  98681. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98682. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98683. if(0 == pu) {
  98684. return false;
  98685. }
  98686. else {
  98687. if(*unaligned_pointer != 0)
  98688. free(*unaligned_pointer);
  98689. *unaligned_pointer = pu;
  98690. *aligned_pointer = u.pa;
  98691. return true;
  98692. }
  98693. }
  98694. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98695. {
  98696. unsigned *pu; /* unaligned pointer */
  98697. union { /* union needed to comply with C99 pointer aliasing rules */
  98698. unsigned *pa; /* aligned pointer */
  98699. void *pv; /* aligned pointer alias */
  98700. } u;
  98701. FLAC__ASSERT(elements > 0);
  98702. FLAC__ASSERT(0 != unaligned_pointer);
  98703. FLAC__ASSERT(0 != aligned_pointer);
  98704. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98705. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98706. if(0 == pu) {
  98707. return false;
  98708. }
  98709. else {
  98710. if(*unaligned_pointer != 0)
  98711. free(*unaligned_pointer);
  98712. *unaligned_pointer = pu;
  98713. *aligned_pointer = u.pa;
  98714. return true;
  98715. }
  98716. }
  98717. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98718. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98719. {
  98720. FLAC__real *pu; /* unaligned pointer */
  98721. union { /* union needed to comply with C99 pointer aliasing rules */
  98722. FLAC__real *pa; /* aligned pointer */
  98723. void *pv; /* aligned pointer alias */
  98724. } u;
  98725. FLAC__ASSERT(elements > 0);
  98726. FLAC__ASSERT(0 != unaligned_pointer);
  98727. FLAC__ASSERT(0 != aligned_pointer);
  98728. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98729. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98730. if(0 == pu) {
  98731. return false;
  98732. }
  98733. else {
  98734. if(*unaligned_pointer != 0)
  98735. free(*unaligned_pointer);
  98736. *unaligned_pointer = pu;
  98737. *aligned_pointer = u.pa;
  98738. return true;
  98739. }
  98740. }
  98741. #endif
  98742. #endif
  98743. /*** End of inlined file: memory.c ***/
  98744. /*** Start of inlined file: stream_decoder.c ***/
  98745. /*** Start of inlined file: juce_FlacHeader.h ***/
  98746. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98747. // tasks..
  98748. #define VERSION "1.2.1"
  98749. #define FLAC__NO_DLL 1
  98750. #if JUCE_MSVC
  98751. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98752. #endif
  98753. #if JUCE_MAC
  98754. #define FLAC__SYS_DARWIN 1
  98755. #endif
  98756. /*** End of inlined file: juce_FlacHeader.h ***/
  98757. #if JUCE_USE_FLAC
  98758. #if HAVE_CONFIG_H
  98759. # include <config.h>
  98760. #endif
  98761. #if defined _MSC_VER || defined __MINGW32__
  98762. #include <io.h> /* for _setmode() */
  98763. #include <fcntl.h> /* for _O_BINARY */
  98764. #endif
  98765. #if defined __CYGWIN__ || defined __EMX__
  98766. #include <io.h> /* for setmode(), O_BINARY */
  98767. #include <fcntl.h> /* for _O_BINARY */
  98768. #endif
  98769. #include <stdio.h>
  98770. #include <stdlib.h> /* for malloc() */
  98771. #include <string.h> /* for memset/memcpy() */
  98772. #include <sys/stat.h> /* for stat() */
  98773. #include <sys/types.h> /* for off_t */
  98774. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98775. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98776. #define fseeko fseek
  98777. #define ftello ftell
  98778. #endif
  98779. #endif
  98780. /*** Start of inlined file: stream_decoder.h ***/
  98781. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98782. #define FLAC__PROTECTED__STREAM_DECODER_H
  98783. #if FLAC__HAS_OGG
  98784. #include "include/private/ogg_decoder_aspect.h"
  98785. #endif
  98786. typedef struct FLAC__StreamDecoderProtected {
  98787. FLAC__StreamDecoderState state;
  98788. unsigned channels;
  98789. FLAC__ChannelAssignment channel_assignment;
  98790. unsigned bits_per_sample;
  98791. unsigned sample_rate; /* in Hz */
  98792. unsigned blocksize; /* in samples (per channel) */
  98793. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98794. #if FLAC__HAS_OGG
  98795. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98796. #endif
  98797. } FLAC__StreamDecoderProtected;
  98798. /*
  98799. * return the number of input bytes consumed
  98800. */
  98801. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98802. #endif
  98803. /*** End of inlined file: stream_decoder.h ***/
  98804. #ifdef max
  98805. #undef max
  98806. #endif
  98807. #define max(a,b) ((a)>(b)?(a):(b))
  98808. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98809. #ifdef _MSC_VER
  98810. #define FLAC__U64L(x) x
  98811. #else
  98812. #define FLAC__U64L(x) x##LLU
  98813. #endif
  98814. /* technically this should be in an "export.c" but this is convenient enough */
  98815. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98816. #if FLAC__HAS_OGG
  98817. 1
  98818. #else
  98819. 0
  98820. #endif
  98821. ;
  98822. /***********************************************************************
  98823. *
  98824. * Private static data
  98825. *
  98826. ***********************************************************************/
  98827. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98828. /***********************************************************************
  98829. *
  98830. * Private class method prototypes
  98831. *
  98832. ***********************************************************************/
  98833. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98834. static FILE *get_binary_stdin_(void);
  98835. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98836. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98837. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98838. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98839. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98840. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98841. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98842. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98843. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98844. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98845. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98846. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98847. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98848. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98849. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98850. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98851. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98852. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98853. 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);
  98854. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98855. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98856. #if FLAC__HAS_OGG
  98857. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98858. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98859. #endif
  98860. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98861. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98862. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98863. #if FLAC__HAS_OGG
  98864. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98865. #endif
  98866. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98867. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98868. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98869. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98870. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98871. /***********************************************************************
  98872. *
  98873. * Private class data
  98874. *
  98875. ***********************************************************************/
  98876. typedef struct FLAC__StreamDecoderPrivate {
  98877. #if FLAC__HAS_OGG
  98878. FLAC__bool is_ogg;
  98879. #endif
  98880. FLAC__StreamDecoderReadCallback read_callback;
  98881. FLAC__StreamDecoderSeekCallback seek_callback;
  98882. FLAC__StreamDecoderTellCallback tell_callback;
  98883. FLAC__StreamDecoderLengthCallback length_callback;
  98884. FLAC__StreamDecoderEofCallback eof_callback;
  98885. FLAC__StreamDecoderWriteCallback write_callback;
  98886. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98887. FLAC__StreamDecoderErrorCallback error_callback;
  98888. /* generic 32-bit datapath: */
  98889. 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[]);
  98890. /* generic 64-bit datapath: */
  98891. 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[]);
  98892. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98893. 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[]);
  98894. /* 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: */
  98895. 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[]);
  98896. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98897. void *client_data;
  98898. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98899. FLAC__BitReader *input;
  98900. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98901. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98902. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98903. unsigned output_capacity, output_channels;
  98904. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98905. FLAC__uint64 samples_decoded;
  98906. FLAC__bool has_stream_info, has_seek_table;
  98907. FLAC__StreamMetadata stream_info;
  98908. FLAC__StreamMetadata seek_table;
  98909. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98910. FLAC__byte *metadata_filter_ids;
  98911. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98912. FLAC__Frame frame;
  98913. FLAC__bool cached; /* true if there is a byte in lookahead */
  98914. FLAC__CPUInfo cpuinfo;
  98915. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98916. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98917. /* unaligned (original) pointers to allocated data */
  98918. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98919. 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 */
  98920. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98921. FLAC__bool is_seeking;
  98922. FLAC__MD5Context md5context;
  98923. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98924. /* (the rest of these are only used for seeking) */
  98925. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98926. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98927. FLAC__uint64 target_sample;
  98928. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98929. #if FLAC__HAS_OGG
  98930. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98931. #endif
  98932. } FLAC__StreamDecoderPrivate;
  98933. /***********************************************************************
  98934. *
  98935. * Public static class data
  98936. *
  98937. ***********************************************************************/
  98938. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98939. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98940. "FLAC__STREAM_DECODER_READ_METADATA",
  98941. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98942. "FLAC__STREAM_DECODER_READ_FRAME",
  98943. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98944. "FLAC__STREAM_DECODER_OGG_ERROR",
  98945. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98946. "FLAC__STREAM_DECODER_ABORTED",
  98947. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98948. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98949. };
  98950. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98951. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98952. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98953. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98954. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98955. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98956. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98957. };
  98958. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98959. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98960. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98961. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98962. };
  98963. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98964. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98965. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98966. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98967. };
  98968. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98969. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98970. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98971. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98972. };
  98973. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98974. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98975. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98976. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98977. };
  98978. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98979. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98980. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98981. };
  98982. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98983. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98984. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98985. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98986. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98987. };
  98988. /***********************************************************************
  98989. *
  98990. * Class constructor/destructor
  98991. *
  98992. ***********************************************************************/
  98993. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98994. {
  98995. FLAC__StreamDecoder *decoder;
  98996. unsigned i;
  98997. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98998. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98999. if(decoder == 0) {
  99000. return 0;
  99001. }
  99002. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99003. if(decoder->protected_ == 0) {
  99004. free(decoder);
  99005. return 0;
  99006. }
  99007. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99008. if(decoder->private_ == 0) {
  99009. free(decoder->protected_);
  99010. free(decoder);
  99011. return 0;
  99012. }
  99013. decoder->private_->input = FLAC__bitreader_new();
  99014. if(decoder->private_->input == 0) {
  99015. free(decoder->private_);
  99016. free(decoder->protected_);
  99017. free(decoder);
  99018. return 0;
  99019. }
  99020. decoder->private_->metadata_filter_ids_capacity = 16;
  99021. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99022. FLAC__bitreader_delete(decoder->private_->input);
  99023. free(decoder->private_);
  99024. free(decoder->protected_);
  99025. free(decoder);
  99026. return 0;
  99027. }
  99028. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99029. decoder->private_->output[i] = 0;
  99030. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99031. }
  99032. decoder->private_->output_capacity = 0;
  99033. decoder->private_->output_channels = 0;
  99034. decoder->private_->has_seek_table = false;
  99035. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99036. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99037. decoder->private_->file = 0;
  99038. set_defaults_dec(decoder);
  99039. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99040. return decoder;
  99041. }
  99042. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99043. {
  99044. unsigned i;
  99045. FLAC__ASSERT(0 != decoder);
  99046. FLAC__ASSERT(0 != decoder->protected_);
  99047. FLAC__ASSERT(0 != decoder->private_);
  99048. FLAC__ASSERT(0 != decoder->private_->input);
  99049. (void)FLAC__stream_decoder_finish(decoder);
  99050. if(0 != decoder->private_->metadata_filter_ids)
  99051. free(decoder->private_->metadata_filter_ids);
  99052. FLAC__bitreader_delete(decoder->private_->input);
  99053. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99054. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99055. free(decoder->private_);
  99056. free(decoder->protected_);
  99057. free(decoder);
  99058. }
  99059. /***********************************************************************
  99060. *
  99061. * Public class methods
  99062. *
  99063. ***********************************************************************/
  99064. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99065. FLAC__StreamDecoder *decoder,
  99066. FLAC__StreamDecoderReadCallback read_callback,
  99067. FLAC__StreamDecoderSeekCallback seek_callback,
  99068. FLAC__StreamDecoderTellCallback tell_callback,
  99069. FLAC__StreamDecoderLengthCallback length_callback,
  99070. FLAC__StreamDecoderEofCallback eof_callback,
  99071. FLAC__StreamDecoderWriteCallback write_callback,
  99072. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99073. FLAC__StreamDecoderErrorCallback error_callback,
  99074. void *client_data,
  99075. FLAC__bool is_ogg
  99076. )
  99077. {
  99078. FLAC__ASSERT(0 != decoder);
  99079. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99080. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99081. #if !FLAC__HAS_OGG
  99082. if(is_ogg)
  99083. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99084. #endif
  99085. if(
  99086. 0 == read_callback ||
  99087. 0 == write_callback ||
  99088. 0 == error_callback ||
  99089. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99090. )
  99091. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99092. #if FLAC__HAS_OGG
  99093. decoder->private_->is_ogg = is_ogg;
  99094. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99095. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99096. #endif
  99097. /*
  99098. * get the CPU info and set the function pointers
  99099. */
  99100. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99101. /* first default to the non-asm routines */
  99102. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99103. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99104. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99105. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99106. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99107. /* now override with asm where appropriate */
  99108. #ifndef FLAC__NO_ASM
  99109. if(decoder->private_->cpuinfo.use_asm) {
  99110. #ifdef FLAC__CPU_IA32
  99111. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99112. #ifdef FLAC__HAS_NASM
  99113. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99114. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99115. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99116. #endif
  99117. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99118. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99119. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99120. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99121. }
  99122. else {
  99123. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99124. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99125. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99126. }
  99127. #endif
  99128. #elif defined FLAC__CPU_PPC
  99129. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99130. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99131. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99132. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99133. }
  99134. #endif
  99135. }
  99136. #endif
  99137. /* from here on, errors are fatal */
  99138. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99139. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99140. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99141. }
  99142. decoder->private_->read_callback = read_callback;
  99143. decoder->private_->seek_callback = seek_callback;
  99144. decoder->private_->tell_callback = tell_callback;
  99145. decoder->private_->length_callback = length_callback;
  99146. decoder->private_->eof_callback = eof_callback;
  99147. decoder->private_->write_callback = write_callback;
  99148. decoder->private_->metadata_callback = metadata_callback;
  99149. decoder->private_->error_callback = error_callback;
  99150. decoder->private_->client_data = client_data;
  99151. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99152. decoder->private_->samples_decoded = 0;
  99153. decoder->private_->has_stream_info = false;
  99154. decoder->private_->cached = false;
  99155. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99156. decoder->private_->is_seeking = false;
  99157. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99158. if(!FLAC__stream_decoder_reset(decoder)) {
  99159. /* above call sets the state for us */
  99160. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99161. }
  99162. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99163. }
  99164. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99165. FLAC__StreamDecoder *decoder,
  99166. FLAC__StreamDecoderReadCallback read_callback,
  99167. FLAC__StreamDecoderSeekCallback seek_callback,
  99168. FLAC__StreamDecoderTellCallback tell_callback,
  99169. FLAC__StreamDecoderLengthCallback length_callback,
  99170. FLAC__StreamDecoderEofCallback eof_callback,
  99171. FLAC__StreamDecoderWriteCallback write_callback,
  99172. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99173. FLAC__StreamDecoderErrorCallback error_callback,
  99174. void *client_data
  99175. )
  99176. {
  99177. return init_stream_internal_dec(
  99178. decoder,
  99179. read_callback,
  99180. seek_callback,
  99181. tell_callback,
  99182. length_callback,
  99183. eof_callback,
  99184. write_callback,
  99185. metadata_callback,
  99186. error_callback,
  99187. client_data,
  99188. /*is_ogg=*/false
  99189. );
  99190. }
  99191. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99192. FLAC__StreamDecoder *decoder,
  99193. FLAC__StreamDecoderReadCallback read_callback,
  99194. FLAC__StreamDecoderSeekCallback seek_callback,
  99195. FLAC__StreamDecoderTellCallback tell_callback,
  99196. FLAC__StreamDecoderLengthCallback length_callback,
  99197. FLAC__StreamDecoderEofCallback eof_callback,
  99198. FLAC__StreamDecoderWriteCallback write_callback,
  99199. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99200. FLAC__StreamDecoderErrorCallback error_callback,
  99201. void *client_data
  99202. )
  99203. {
  99204. return init_stream_internal_dec(
  99205. decoder,
  99206. read_callback,
  99207. seek_callback,
  99208. tell_callback,
  99209. length_callback,
  99210. eof_callback,
  99211. write_callback,
  99212. metadata_callback,
  99213. error_callback,
  99214. client_data,
  99215. /*is_ogg=*/true
  99216. );
  99217. }
  99218. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99219. FLAC__StreamDecoder *decoder,
  99220. FILE *file,
  99221. FLAC__StreamDecoderWriteCallback write_callback,
  99222. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99223. FLAC__StreamDecoderErrorCallback error_callback,
  99224. void *client_data,
  99225. FLAC__bool is_ogg
  99226. )
  99227. {
  99228. FLAC__ASSERT(0 != decoder);
  99229. FLAC__ASSERT(0 != file);
  99230. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99231. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99232. if(0 == write_callback || 0 == error_callback)
  99233. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99234. /*
  99235. * To make sure that our file does not go unclosed after an error, we
  99236. * must assign the FILE pointer before any further error can occur in
  99237. * this routine.
  99238. */
  99239. if(file == stdin)
  99240. file = get_binary_stdin_(); /* just to be safe */
  99241. decoder->private_->file = file;
  99242. return init_stream_internal_dec(
  99243. decoder,
  99244. file_read_callback_dec,
  99245. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99246. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99247. decoder->private_->file == stdin? 0: file_length_callback_,
  99248. file_eof_callback_,
  99249. write_callback,
  99250. metadata_callback,
  99251. error_callback,
  99252. client_data,
  99253. is_ogg
  99254. );
  99255. }
  99256. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99257. FLAC__StreamDecoder *decoder,
  99258. FILE *file,
  99259. FLAC__StreamDecoderWriteCallback write_callback,
  99260. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99261. FLAC__StreamDecoderErrorCallback error_callback,
  99262. void *client_data
  99263. )
  99264. {
  99265. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99266. }
  99267. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99268. FLAC__StreamDecoder *decoder,
  99269. FILE *file,
  99270. FLAC__StreamDecoderWriteCallback write_callback,
  99271. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99272. FLAC__StreamDecoderErrorCallback error_callback,
  99273. void *client_data
  99274. )
  99275. {
  99276. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99277. }
  99278. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99279. FLAC__StreamDecoder *decoder,
  99280. const char *filename,
  99281. FLAC__StreamDecoderWriteCallback write_callback,
  99282. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99283. FLAC__StreamDecoderErrorCallback error_callback,
  99284. void *client_data,
  99285. FLAC__bool is_ogg
  99286. )
  99287. {
  99288. FILE *file;
  99289. FLAC__ASSERT(0 != decoder);
  99290. /*
  99291. * To make sure that our file does not go unclosed after an error, we
  99292. * have to do the same entrance checks here that are later performed
  99293. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99294. */
  99295. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99296. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99297. if(0 == write_callback || 0 == error_callback)
  99298. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99299. file = filename? fopen(filename, "rb") : stdin;
  99300. if(0 == file)
  99301. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99302. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99303. }
  99304. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99305. FLAC__StreamDecoder *decoder,
  99306. const char *filename,
  99307. FLAC__StreamDecoderWriteCallback write_callback,
  99308. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99309. FLAC__StreamDecoderErrorCallback error_callback,
  99310. void *client_data
  99311. )
  99312. {
  99313. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99314. }
  99315. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99316. FLAC__StreamDecoder *decoder,
  99317. const char *filename,
  99318. FLAC__StreamDecoderWriteCallback write_callback,
  99319. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99320. FLAC__StreamDecoderErrorCallback error_callback,
  99321. void *client_data
  99322. )
  99323. {
  99324. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99325. }
  99326. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99327. {
  99328. FLAC__bool md5_failed = false;
  99329. unsigned i;
  99330. FLAC__ASSERT(0 != decoder);
  99331. FLAC__ASSERT(0 != decoder->private_);
  99332. FLAC__ASSERT(0 != decoder->protected_);
  99333. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99334. return true;
  99335. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99336. * always call FLAC__MD5Final()
  99337. */
  99338. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99339. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99340. free(decoder->private_->seek_table.data.seek_table.points);
  99341. decoder->private_->seek_table.data.seek_table.points = 0;
  99342. decoder->private_->has_seek_table = false;
  99343. }
  99344. FLAC__bitreader_free(decoder->private_->input);
  99345. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99346. /* WATCHOUT:
  99347. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99348. * output arrays have a buffer of up to 3 zeroes in front
  99349. * (at negative indices) for alignment purposes; we use 4
  99350. * to keep the data well-aligned.
  99351. */
  99352. if(0 != decoder->private_->output[i]) {
  99353. free(decoder->private_->output[i]-4);
  99354. decoder->private_->output[i] = 0;
  99355. }
  99356. if(0 != decoder->private_->residual_unaligned[i]) {
  99357. free(decoder->private_->residual_unaligned[i]);
  99358. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99359. }
  99360. }
  99361. decoder->private_->output_capacity = 0;
  99362. decoder->private_->output_channels = 0;
  99363. #if FLAC__HAS_OGG
  99364. if(decoder->private_->is_ogg)
  99365. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99366. #endif
  99367. if(0 != decoder->private_->file) {
  99368. if(decoder->private_->file != stdin)
  99369. fclose(decoder->private_->file);
  99370. decoder->private_->file = 0;
  99371. }
  99372. if(decoder->private_->do_md5_checking) {
  99373. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99374. md5_failed = true;
  99375. }
  99376. decoder->private_->is_seeking = false;
  99377. set_defaults_dec(decoder);
  99378. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99379. return !md5_failed;
  99380. }
  99381. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99382. {
  99383. FLAC__ASSERT(0 != decoder);
  99384. FLAC__ASSERT(0 != decoder->private_);
  99385. FLAC__ASSERT(0 != decoder->protected_);
  99386. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99387. return false;
  99388. #if FLAC__HAS_OGG
  99389. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99390. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99391. return true;
  99392. #else
  99393. (void)value;
  99394. return false;
  99395. #endif
  99396. }
  99397. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99398. {
  99399. FLAC__ASSERT(0 != decoder);
  99400. FLAC__ASSERT(0 != decoder->protected_);
  99401. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99402. return false;
  99403. decoder->protected_->md5_checking = value;
  99404. return true;
  99405. }
  99406. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99407. {
  99408. FLAC__ASSERT(0 != decoder);
  99409. FLAC__ASSERT(0 != decoder->private_);
  99410. FLAC__ASSERT(0 != decoder->protected_);
  99411. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99412. /* double protection */
  99413. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99414. return false;
  99415. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99416. return false;
  99417. decoder->private_->metadata_filter[type] = true;
  99418. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99419. decoder->private_->metadata_filter_ids_count = 0;
  99420. return true;
  99421. }
  99422. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99423. {
  99424. FLAC__ASSERT(0 != decoder);
  99425. FLAC__ASSERT(0 != decoder->private_);
  99426. FLAC__ASSERT(0 != decoder->protected_);
  99427. FLAC__ASSERT(0 != id);
  99428. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99429. return false;
  99430. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99431. return true;
  99432. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99433. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99434. 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))) {
  99435. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99436. return false;
  99437. }
  99438. decoder->private_->metadata_filter_ids_capacity *= 2;
  99439. }
  99440. 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));
  99441. decoder->private_->metadata_filter_ids_count++;
  99442. return true;
  99443. }
  99444. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99445. {
  99446. unsigned i;
  99447. FLAC__ASSERT(0 != decoder);
  99448. FLAC__ASSERT(0 != decoder->private_);
  99449. FLAC__ASSERT(0 != decoder->protected_);
  99450. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99451. return false;
  99452. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99453. decoder->private_->metadata_filter[i] = true;
  99454. decoder->private_->metadata_filter_ids_count = 0;
  99455. return true;
  99456. }
  99457. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99458. {
  99459. FLAC__ASSERT(0 != decoder);
  99460. FLAC__ASSERT(0 != decoder->private_);
  99461. FLAC__ASSERT(0 != decoder->protected_);
  99462. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99463. /* double protection */
  99464. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99465. return false;
  99466. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99467. return false;
  99468. decoder->private_->metadata_filter[type] = false;
  99469. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99470. decoder->private_->metadata_filter_ids_count = 0;
  99471. return true;
  99472. }
  99473. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99474. {
  99475. FLAC__ASSERT(0 != decoder);
  99476. FLAC__ASSERT(0 != decoder->private_);
  99477. FLAC__ASSERT(0 != decoder->protected_);
  99478. FLAC__ASSERT(0 != id);
  99479. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99480. return false;
  99481. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99482. return true;
  99483. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99484. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99485. 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))) {
  99486. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99487. return false;
  99488. }
  99489. decoder->private_->metadata_filter_ids_capacity *= 2;
  99490. }
  99491. 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));
  99492. decoder->private_->metadata_filter_ids_count++;
  99493. return true;
  99494. }
  99495. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99496. {
  99497. FLAC__ASSERT(0 != decoder);
  99498. FLAC__ASSERT(0 != decoder->private_);
  99499. FLAC__ASSERT(0 != decoder->protected_);
  99500. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99501. return false;
  99502. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99503. decoder->private_->metadata_filter_ids_count = 0;
  99504. return true;
  99505. }
  99506. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99507. {
  99508. FLAC__ASSERT(0 != decoder);
  99509. FLAC__ASSERT(0 != decoder->protected_);
  99510. return decoder->protected_->state;
  99511. }
  99512. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99513. {
  99514. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99515. }
  99516. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99517. {
  99518. FLAC__ASSERT(0 != decoder);
  99519. FLAC__ASSERT(0 != decoder->protected_);
  99520. return decoder->protected_->md5_checking;
  99521. }
  99522. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99523. {
  99524. FLAC__ASSERT(0 != decoder);
  99525. FLAC__ASSERT(0 != decoder->protected_);
  99526. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99527. }
  99528. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99529. {
  99530. FLAC__ASSERT(0 != decoder);
  99531. FLAC__ASSERT(0 != decoder->protected_);
  99532. return decoder->protected_->channels;
  99533. }
  99534. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99535. {
  99536. FLAC__ASSERT(0 != decoder);
  99537. FLAC__ASSERT(0 != decoder->protected_);
  99538. return decoder->protected_->channel_assignment;
  99539. }
  99540. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99541. {
  99542. FLAC__ASSERT(0 != decoder);
  99543. FLAC__ASSERT(0 != decoder->protected_);
  99544. return decoder->protected_->bits_per_sample;
  99545. }
  99546. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99547. {
  99548. FLAC__ASSERT(0 != decoder);
  99549. FLAC__ASSERT(0 != decoder->protected_);
  99550. return decoder->protected_->sample_rate;
  99551. }
  99552. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99553. {
  99554. FLAC__ASSERT(0 != decoder);
  99555. FLAC__ASSERT(0 != decoder->protected_);
  99556. return decoder->protected_->blocksize;
  99557. }
  99558. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99559. {
  99560. FLAC__ASSERT(0 != decoder);
  99561. FLAC__ASSERT(0 != decoder->private_);
  99562. FLAC__ASSERT(0 != position);
  99563. #if FLAC__HAS_OGG
  99564. if(decoder->private_->is_ogg)
  99565. return false;
  99566. #endif
  99567. if(0 == decoder->private_->tell_callback)
  99568. return false;
  99569. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99570. return false;
  99571. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99572. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99573. return false;
  99574. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99575. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99576. return true;
  99577. }
  99578. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99579. {
  99580. FLAC__ASSERT(0 != decoder);
  99581. FLAC__ASSERT(0 != decoder->private_);
  99582. FLAC__ASSERT(0 != decoder->protected_);
  99583. decoder->private_->samples_decoded = 0;
  99584. decoder->private_->do_md5_checking = false;
  99585. #if FLAC__HAS_OGG
  99586. if(decoder->private_->is_ogg)
  99587. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99588. #endif
  99589. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99590. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99591. return false;
  99592. }
  99593. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99594. return true;
  99595. }
  99596. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99597. {
  99598. FLAC__ASSERT(0 != decoder);
  99599. FLAC__ASSERT(0 != decoder->private_);
  99600. FLAC__ASSERT(0 != decoder->protected_);
  99601. if(!FLAC__stream_decoder_flush(decoder)) {
  99602. /* above call sets the state for us */
  99603. return false;
  99604. }
  99605. #if FLAC__HAS_OGG
  99606. /*@@@ could go in !internal_reset_hack block below */
  99607. if(decoder->private_->is_ogg)
  99608. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99609. #endif
  99610. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99611. * (internal_reset_hack) don't try to rewind since we are already at
  99612. * the beginning of the stream and don't want to fail if the input is
  99613. * not seekable.
  99614. */
  99615. if(!decoder->private_->internal_reset_hack) {
  99616. if(decoder->private_->file == stdin)
  99617. return false; /* can't rewind stdin, reset fails */
  99618. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99619. return false; /* seekable and seek fails, reset fails */
  99620. }
  99621. else
  99622. decoder->private_->internal_reset_hack = false;
  99623. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99624. decoder->private_->has_stream_info = false;
  99625. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99626. free(decoder->private_->seek_table.data.seek_table.points);
  99627. decoder->private_->seek_table.data.seek_table.points = 0;
  99628. decoder->private_->has_seek_table = false;
  99629. }
  99630. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99631. /*
  99632. * This goes in reset() and not flush() because according to the spec, a
  99633. * fixed-blocksize stream must stay that way through the whole stream.
  99634. */
  99635. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99636. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99637. * is because md5 checking may be turned on to start and then turned off if
  99638. * a seek occurs. So we init the context here and finalize it in
  99639. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99640. * properly.
  99641. */
  99642. FLAC__MD5Init(&decoder->private_->md5context);
  99643. decoder->private_->first_frame_offset = 0;
  99644. decoder->private_->unparseable_frame_count = 0;
  99645. return true;
  99646. }
  99647. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99648. {
  99649. FLAC__bool got_a_frame;
  99650. FLAC__ASSERT(0 != decoder);
  99651. FLAC__ASSERT(0 != decoder->protected_);
  99652. while(1) {
  99653. switch(decoder->protected_->state) {
  99654. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99655. if(!find_metadata_(decoder))
  99656. return false; /* above function sets the status for us */
  99657. break;
  99658. case FLAC__STREAM_DECODER_READ_METADATA:
  99659. if(!read_metadata_(decoder))
  99660. return false; /* above function sets the status for us */
  99661. else
  99662. return true;
  99663. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99664. if(!frame_sync_(decoder))
  99665. return true; /* above function sets the status for us */
  99666. break;
  99667. case FLAC__STREAM_DECODER_READ_FRAME:
  99668. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99669. return false; /* above function sets the status for us */
  99670. if(got_a_frame)
  99671. return true; /* above function sets the status for us */
  99672. break;
  99673. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99674. case FLAC__STREAM_DECODER_ABORTED:
  99675. return true;
  99676. default:
  99677. FLAC__ASSERT(0);
  99678. return false;
  99679. }
  99680. }
  99681. }
  99682. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99683. {
  99684. FLAC__ASSERT(0 != decoder);
  99685. FLAC__ASSERT(0 != decoder->protected_);
  99686. while(1) {
  99687. switch(decoder->protected_->state) {
  99688. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99689. if(!find_metadata_(decoder))
  99690. return false; /* above function sets the status for us */
  99691. break;
  99692. case FLAC__STREAM_DECODER_READ_METADATA:
  99693. if(!read_metadata_(decoder))
  99694. return false; /* above function sets the status for us */
  99695. break;
  99696. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99697. case FLAC__STREAM_DECODER_READ_FRAME:
  99698. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99699. case FLAC__STREAM_DECODER_ABORTED:
  99700. return true;
  99701. default:
  99702. FLAC__ASSERT(0);
  99703. return false;
  99704. }
  99705. }
  99706. }
  99707. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99708. {
  99709. FLAC__bool dummy;
  99710. FLAC__ASSERT(0 != decoder);
  99711. FLAC__ASSERT(0 != decoder->protected_);
  99712. while(1) {
  99713. switch(decoder->protected_->state) {
  99714. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99715. if(!find_metadata_(decoder))
  99716. return false; /* above function sets the status for us */
  99717. break;
  99718. case FLAC__STREAM_DECODER_READ_METADATA:
  99719. if(!read_metadata_(decoder))
  99720. return false; /* above function sets the status for us */
  99721. break;
  99722. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99723. if(!frame_sync_(decoder))
  99724. return true; /* above function sets the status for us */
  99725. break;
  99726. case FLAC__STREAM_DECODER_READ_FRAME:
  99727. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99728. return false; /* above function sets the status for us */
  99729. break;
  99730. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99731. case FLAC__STREAM_DECODER_ABORTED:
  99732. return true;
  99733. default:
  99734. FLAC__ASSERT(0);
  99735. return false;
  99736. }
  99737. }
  99738. }
  99739. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99740. {
  99741. FLAC__bool got_a_frame;
  99742. FLAC__ASSERT(0 != decoder);
  99743. FLAC__ASSERT(0 != decoder->protected_);
  99744. while(1) {
  99745. switch(decoder->protected_->state) {
  99746. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99747. case FLAC__STREAM_DECODER_READ_METADATA:
  99748. return false; /* above function sets the status for us */
  99749. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99750. if(!frame_sync_(decoder))
  99751. return true; /* above function sets the status for us */
  99752. break;
  99753. case FLAC__STREAM_DECODER_READ_FRAME:
  99754. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99755. return false; /* above function sets the status for us */
  99756. if(got_a_frame)
  99757. return true; /* above function sets the status for us */
  99758. break;
  99759. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99760. case FLAC__STREAM_DECODER_ABORTED:
  99761. return true;
  99762. default:
  99763. FLAC__ASSERT(0);
  99764. return false;
  99765. }
  99766. }
  99767. }
  99768. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99769. {
  99770. FLAC__uint64 length;
  99771. FLAC__ASSERT(0 != decoder);
  99772. if(
  99773. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99774. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99775. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99776. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99777. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99778. )
  99779. return false;
  99780. if(0 == decoder->private_->seek_callback)
  99781. return false;
  99782. FLAC__ASSERT(decoder->private_->seek_callback);
  99783. FLAC__ASSERT(decoder->private_->tell_callback);
  99784. FLAC__ASSERT(decoder->private_->length_callback);
  99785. FLAC__ASSERT(decoder->private_->eof_callback);
  99786. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99787. return false;
  99788. decoder->private_->is_seeking = true;
  99789. /* turn off md5 checking if a seek is attempted */
  99790. decoder->private_->do_md5_checking = false;
  99791. /* 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) */
  99792. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99793. decoder->private_->is_seeking = false;
  99794. return false;
  99795. }
  99796. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99797. if(
  99798. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99799. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99800. ) {
  99801. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99802. /* above call sets the state for us */
  99803. decoder->private_->is_seeking = false;
  99804. return false;
  99805. }
  99806. /* check this again in case we didn't know total_samples the first time */
  99807. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99808. decoder->private_->is_seeking = false;
  99809. return false;
  99810. }
  99811. }
  99812. {
  99813. const FLAC__bool ok =
  99814. #if FLAC__HAS_OGG
  99815. decoder->private_->is_ogg?
  99816. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99817. #endif
  99818. seek_to_absolute_sample_(decoder, length, sample)
  99819. ;
  99820. decoder->private_->is_seeking = false;
  99821. return ok;
  99822. }
  99823. }
  99824. /***********************************************************************
  99825. *
  99826. * Protected class methods
  99827. *
  99828. ***********************************************************************/
  99829. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99830. {
  99831. FLAC__ASSERT(0 != decoder);
  99832. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99833. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99834. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99835. }
  99836. /***********************************************************************
  99837. *
  99838. * Private class methods
  99839. *
  99840. ***********************************************************************/
  99841. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99842. {
  99843. #if FLAC__HAS_OGG
  99844. decoder->private_->is_ogg = false;
  99845. #endif
  99846. decoder->private_->read_callback = 0;
  99847. decoder->private_->seek_callback = 0;
  99848. decoder->private_->tell_callback = 0;
  99849. decoder->private_->length_callback = 0;
  99850. decoder->private_->eof_callback = 0;
  99851. decoder->private_->write_callback = 0;
  99852. decoder->private_->metadata_callback = 0;
  99853. decoder->private_->error_callback = 0;
  99854. decoder->private_->client_data = 0;
  99855. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99856. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99857. decoder->private_->metadata_filter_ids_count = 0;
  99858. decoder->protected_->md5_checking = false;
  99859. #if FLAC__HAS_OGG
  99860. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99861. #endif
  99862. }
  99863. /*
  99864. * This will forcibly set stdin to binary mode (for OSes that require it)
  99865. */
  99866. FILE *get_binary_stdin_(void)
  99867. {
  99868. /* if something breaks here it is probably due to the presence or
  99869. * absence of an underscore before the identifiers 'setmode',
  99870. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99871. */
  99872. #if defined _MSC_VER || defined __MINGW32__
  99873. _setmode(_fileno(stdin), _O_BINARY);
  99874. #elif defined __CYGWIN__
  99875. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99876. setmode(_fileno(stdin), _O_BINARY);
  99877. #elif defined __EMX__
  99878. setmode(fileno(stdin), O_BINARY);
  99879. #endif
  99880. return stdin;
  99881. }
  99882. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99883. {
  99884. unsigned i;
  99885. FLAC__int32 *tmp;
  99886. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99887. return true;
  99888. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99889. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99890. if(0 != decoder->private_->output[i]) {
  99891. free(decoder->private_->output[i]-4);
  99892. decoder->private_->output[i] = 0;
  99893. }
  99894. if(0 != decoder->private_->residual_unaligned[i]) {
  99895. free(decoder->private_->residual_unaligned[i]);
  99896. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99897. }
  99898. }
  99899. for(i = 0; i < channels; i++) {
  99900. /* WATCHOUT:
  99901. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99902. * output arrays have a buffer of up to 3 zeroes in front
  99903. * (at negative indices) for alignment purposes; we use 4
  99904. * to keep the data well-aligned.
  99905. */
  99906. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99907. if(tmp == 0) {
  99908. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99909. return false;
  99910. }
  99911. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99912. decoder->private_->output[i] = tmp + 4;
  99913. /* WATCHOUT:
  99914. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99915. */
  99916. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99917. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99918. return false;
  99919. }
  99920. }
  99921. decoder->private_->output_capacity = size;
  99922. decoder->private_->output_channels = channels;
  99923. return true;
  99924. }
  99925. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99926. {
  99927. size_t i;
  99928. FLAC__ASSERT(0 != decoder);
  99929. FLAC__ASSERT(0 != decoder->private_);
  99930. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99931. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99932. return true;
  99933. return false;
  99934. }
  99935. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99936. {
  99937. FLAC__uint32 x;
  99938. unsigned i, id_;
  99939. FLAC__bool first = true;
  99940. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99941. for(i = id_ = 0; i < 4; ) {
  99942. if(decoder->private_->cached) {
  99943. x = (FLAC__uint32)decoder->private_->lookahead;
  99944. decoder->private_->cached = false;
  99945. }
  99946. else {
  99947. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99948. return false; /* read_callback_ sets the state for us */
  99949. }
  99950. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99951. first = true;
  99952. i++;
  99953. id_ = 0;
  99954. continue;
  99955. }
  99956. if(x == ID3V2_TAG_[id_]) {
  99957. id_++;
  99958. i = 0;
  99959. if(id_ == 3) {
  99960. if(!skip_id3v2_tag_(decoder))
  99961. return false; /* skip_id3v2_tag_ sets the state for us */
  99962. }
  99963. continue;
  99964. }
  99965. id_ = 0;
  99966. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99967. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99968. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99969. return false; /* read_callback_ sets the state for us */
  99970. /* 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 */
  99971. /* else we have to check if the second byte is the end of a sync code */
  99972. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99973. decoder->private_->lookahead = (FLAC__byte)x;
  99974. decoder->private_->cached = true;
  99975. }
  99976. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99977. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99978. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99979. return true;
  99980. }
  99981. }
  99982. i = 0;
  99983. if(first) {
  99984. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99985. first = false;
  99986. }
  99987. }
  99988. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99989. return true;
  99990. }
  99991. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99992. {
  99993. FLAC__bool is_last;
  99994. FLAC__uint32 i, x, type, length;
  99995. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99996. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99997. return false; /* read_callback_ sets the state for us */
  99998. is_last = x? true : false;
  99999. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100000. return false; /* read_callback_ sets the state for us */
  100001. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100002. return false; /* read_callback_ sets the state for us */
  100003. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100004. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100005. return false;
  100006. decoder->private_->has_stream_info = true;
  100007. 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))
  100008. decoder->private_->do_md5_checking = false;
  100009. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100010. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100011. }
  100012. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100013. if(!read_metadata_seektable_(decoder, is_last, length))
  100014. return false;
  100015. decoder->private_->has_seek_table = true;
  100016. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100017. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100018. }
  100019. else {
  100020. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100021. unsigned real_length = length;
  100022. FLAC__StreamMetadata block;
  100023. block.is_last = is_last;
  100024. block.type = (FLAC__MetadataType)type;
  100025. block.length = length;
  100026. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100027. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100028. return false; /* read_callback_ sets the state for us */
  100029. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100030. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100031. return false;
  100032. }
  100033. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100034. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100035. skip_it = !skip_it;
  100036. }
  100037. if(skip_it) {
  100038. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100039. return false; /* read_callback_ sets the state for us */
  100040. }
  100041. else {
  100042. switch(type) {
  100043. case FLAC__METADATA_TYPE_PADDING:
  100044. /* skip the padding bytes */
  100045. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100046. return false; /* read_callback_ sets the state for us */
  100047. break;
  100048. case FLAC__METADATA_TYPE_APPLICATION:
  100049. /* remember, we read the ID already */
  100050. if(real_length > 0) {
  100051. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100052. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100053. return false;
  100054. }
  100055. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100056. return false; /* read_callback_ sets the state for us */
  100057. }
  100058. else
  100059. block.data.application.data = 0;
  100060. break;
  100061. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100062. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100063. return false;
  100064. break;
  100065. case FLAC__METADATA_TYPE_CUESHEET:
  100066. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100067. return false;
  100068. break;
  100069. case FLAC__METADATA_TYPE_PICTURE:
  100070. if(!read_metadata_picture_(decoder, &block.data.picture))
  100071. return false;
  100072. break;
  100073. case FLAC__METADATA_TYPE_STREAMINFO:
  100074. case FLAC__METADATA_TYPE_SEEKTABLE:
  100075. FLAC__ASSERT(0);
  100076. break;
  100077. default:
  100078. if(real_length > 0) {
  100079. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100080. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100081. return false;
  100082. }
  100083. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100084. return false; /* read_callback_ sets the state for us */
  100085. }
  100086. else
  100087. block.data.unknown.data = 0;
  100088. break;
  100089. }
  100090. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100091. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100092. /* now we have to free any malloc()ed data in the block */
  100093. switch(type) {
  100094. case FLAC__METADATA_TYPE_PADDING:
  100095. break;
  100096. case FLAC__METADATA_TYPE_APPLICATION:
  100097. if(0 != block.data.application.data)
  100098. free(block.data.application.data);
  100099. break;
  100100. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100101. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100102. free(block.data.vorbis_comment.vendor_string.entry);
  100103. if(block.data.vorbis_comment.num_comments > 0)
  100104. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100105. if(0 != block.data.vorbis_comment.comments[i].entry)
  100106. free(block.data.vorbis_comment.comments[i].entry);
  100107. if(0 != block.data.vorbis_comment.comments)
  100108. free(block.data.vorbis_comment.comments);
  100109. break;
  100110. case FLAC__METADATA_TYPE_CUESHEET:
  100111. if(block.data.cue_sheet.num_tracks > 0)
  100112. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100113. if(0 != block.data.cue_sheet.tracks[i].indices)
  100114. free(block.data.cue_sheet.tracks[i].indices);
  100115. if(0 != block.data.cue_sheet.tracks)
  100116. free(block.data.cue_sheet.tracks);
  100117. break;
  100118. case FLAC__METADATA_TYPE_PICTURE:
  100119. if(0 != block.data.picture.mime_type)
  100120. free(block.data.picture.mime_type);
  100121. if(0 != block.data.picture.description)
  100122. free(block.data.picture.description);
  100123. if(0 != block.data.picture.data)
  100124. free(block.data.picture.data);
  100125. break;
  100126. case FLAC__METADATA_TYPE_STREAMINFO:
  100127. case FLAC__METADATA_TYPE_SEEKTABLE:
  100128. FLAC__ASSERT(0);
  100129. default:
  100130. if(0 != block.data.unknown.data)
  100131. free(block.data.unknown.data);
  100132. break;
  100133. }
  100134. }
  100135. }
  100136. if(is_last) {
  100137. /* if this fails, it's OK, it's just a hint for the seek routine */
  100138. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100139. decoder->private_->first_frame_offset = 0;
  100140. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100141. }
  100142. return true;
  100143. }
  100144. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100145. {
  100146. FLAC__uint32 x;
  100147. unsigned bits, used_bits = 0;
  100148. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100149. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100150. decoder->private_->stream_info.is_last = is_last;
  100151. decoder->private_->stream_info.length = length;
  100152. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100153. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100154. return false; /* read_callback_ sets the state for us */
  100155. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100156. used_bits += bits;
  100157. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100158. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100159. return false; /* read_callback_ sets the state for us */
  100160. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100161. used_bits += bits;
  100162. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100163. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100164. return false; /* read_callback_ sets the state for us */
  100165. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100166. used_bits += bits;
  100167. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100168. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100169. return false; /* read_callback_ sets the state for us */
  100170. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100171. used_bits += bits;
  100172. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100173. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100174. return false; /* read_callback_ sets the state for us */
  100175. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100176. used_bits += bits;
  100177. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100178. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100179. return false; /* read_callback_ sets the state for us */
  100180. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100181. used_bits += bits;
  100182. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100183. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100184. return false; /* read_callback_ sets the state for us */
  100185. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100186. used_bits += bits;
  100187. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100188. 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))
  100189. return false; /* read_callback_ sets the state for us */
  100190. used_bits += bits;
  100191. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100192. return false; /* read_callback_ sets the state for us */
  100193. used_bits += 16*8;
  100194. /* skip the rest of the block */
  100195. FLAC__ASSERT(used_bits % 8 == 0);
  100196. length -= (used_bits / 8);
  100197. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100198. return false; /* read_callback_ sets the state for us */
  100199. return true;
  100200. }
  100201. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100202. {
  100203. FLAC__uint32 i, x;
  100204. FLAC__uint64 xx;
  100205. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100206. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100207. decoder->private_->seek_table.is_last = is_last;
  100208. decoder->private_->seek_table.length = length;
  100209. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100210. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100211. 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)))) {
  100212. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100213. return false;
  100214. }
  100215. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100216. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100217. return false; /* read_callback_ sets the state for us */
  100218. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100219. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100220. return false; /* read_callback_ sets the state for us */
  100221. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100222. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100223. return false; /* read_callback_ sets the state for us */
  100224. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100225. }
  100226. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100227. /* if there is a partial point left, skip over it */
  100228. if(length > 0) {
  100229. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100230. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100231. return false; /* read_callback_ sets the state for us */
  100232. }
  100233. return true;
  100234. }
  100235. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100236. {
  100237. FLAC__uint32 i;
  100238. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100239. /* read vendor string */
  100240. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100241. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100242. return false; /* read_callback_ sets the state for us */
  100243. if(obj->vendor_string.length > 0) {
  100244. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100245. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100246. return false;
  100247. }
  100248. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100249. return false; /* read_callback_ sets the state for us */
  100250. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100251. }
  100252. else
  100253. obj->vendor_string.entry = 0;
  100254. /* read num comments */
  100255. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100256. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100257. return false; /* read_callback_ sets the state for us */
  100258. /* read comments */
  100259. if(obj->num_comments > 0) {
  100260. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100261. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100262. return false;
  100263. }
  100264. for(i = 0; i < obj->num_comments; i++) {
  100265. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100266. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100267. return false; /* read_callback_ sets the state for us */
  100268. if(obj->comments[i].length > 0) {
  100269. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100270. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100271. return false;
  100272. }
  100273. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100274. return false; /* read_callback_ sets the state for us */
  100275. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100276. }
  100277. else
  100278. obj->comments[i].entry = 0;
  100279. }
  100280. }
  100281. else {
  100282. obj->comments = 0;
  100283. }
  100284. return true;
  100285. }
  100286. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100287. {
  100288. FLAC__uint32 i, j, x;
  100289. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100290. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100291. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100292. 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))
  100293. return false; /* read_callback_ sets the state for us */
  100294. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100295. return false; /* read_callback_ sets the state for us */
  100296. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100297. return false; /* read_callback_ sets the state for us */
  100298. obj->is_cd = x? true : false;
  100299. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100300. return false; /* read_callback_ sets the state for us */
  100301. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100302. return false; /* read_callback_ sets the state for us */
  100303. obj->num_tracks = x;
  100304. if(obj->num_tracks > 0) {
  100305. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100306. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100307. return false;
  100308. }
  100309. for(i = 0; i < obj->num_tracks; i++) {
  100310. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100311. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100312. return false; /* read_callback_ sets the state for us */
  100313. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100314. return false; /* read_callback_ sets the state for us */
  100315. track->number = (FLAC__byte)x;
  100316. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100317. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100318. return false; /* read_callback_ sets the state for us */
  100319. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100320. return false; /* read_callback_ sets the state for us */
  100321. track->type = x;
  100322. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100323. return false; /* read_callback_ sets the state for us */
  100324. track->pre_emphasis = x;
  100325. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100326. return false; /* read_callback_ sets the state for us */
  100327. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100328. return false; /* read_callback_ sets the state for us */
  100329. track->num_indices = (FLAC__byte)x;
  100330. if(track->num_indices > 0) {
  100331. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100332. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100333. return false;
  100334. }
  100335. for(j = 0; j < track->num_indices; j++) {
  100336. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100337. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100338. return false; /* read_callback_ sets the state for us */
  100339. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100340. return false; /* read_callback_ sets the state for us */
  100341. index->number = (FLAC__byte)x;
  100342. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100343. return false; /* read_callback_ sets the state for us */
  100344. }
  100345. }
  100346. }
  100347. }
  100348. return true;
  100349. }
  100350. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100351. {
  100352. FLAC__uint32 x;
  100353. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100354. /* read type */
  100355. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100356. return false; /* read_callback_ sets the state for us */
  100357. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100358. /* read MIME type */
  100359. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100360. return false; /* read_callback_ sets the state for us */
  100361. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100362. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100363. return false;
  100364. }
  100365. if(x > 0) {
  100366. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100367. return false; /* read_callback_ sets the state for us */
  100368. }
  100369. obj->mime_type[x] = '\0';
  100370. /* read description */
  100371. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100372. return false; /* read_callback_ sets the state for us */
  100373. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100374. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100375. return false;
  100376. }
  100377. if(x > 0) {
  100378. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100379. return false; /* read_callback_ sets the state for us */
  100380. }
  100381. obj->description[x] = '\0';
  100382. /* read width */
  100383. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100384. return false; /* read_callback_ sets the state for us */
  100385. /* read height */
  100386. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100387. return false; /* read_callback_ sets the state for us */
  100388. /* read depth */
  100389. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100390. return false; /* read_callback_ sets the state for us */
  100391. /* read colors */
  100392. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100393. return false; /* read_callback_ sets the state for us */
  100394. /* read data */
  100395. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100396. return false; /* read_callback_ sets the state for us */
  100397. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100398. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100399. return false;
  100400. }
  100401. if(obj->data_length > 0) {
  100402. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100403. return false; /* read_callback_ sets the state for us */
  100404. }
  100405. return true;
  100406. }
  100407. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100408. {
  100409. FLAC__uint32 x;
  100410. unsigned i, skip;
  100411. /* skip the version and flags bytes */
  100412. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100413. return false; /* read_callback_ sets the state for us */
  100414. /* get the size (in bytes) to skip */
  100415. skip = 0;
  100416. for(i = 0; i < 4; i++) {
  100417. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100418. return false; /* read_callback_ sets the state for us */
  100419. skip <<= 7;
  100420. skip |= (x & 0x7f);
  100421. }
  100422. /* skip the rest of the tag */
  100423. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100424. return false; /* read_callback_ sets the state for us */
  100425. return true;
  100426. }
  100427. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100428. {
  100429. FLAC__uint32 x;
  100430. FLAC__bool first = true;
  100431. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100432. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100433. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100434. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100435. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100436. return true;
  100437. }
  100438. }
  100439. /* make sure we're byte aligned */
  100440. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100441. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100442. return false; /* read_callback_ sets the state for us */
  100443. }
  100444. while(1) {
  100445. if(decoder->private_->cached) {
  100446. x = (FLAC__uint32)decoder->private_->lookahead;
  100447. decoder->private_->cached = false;
  100448. }
  100449. else {
  100450. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100451. return false; /* read_callback_ sets the state for us */
  100452. }
  100453. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100454. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100455. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100456. return false; /* read_callback_ sets the state for us */
  100457. /* 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 */
  100458. /* else we have to check if the second byte is the end of a sync code */
  100459. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100460. decoder->private_->lookahead = (FLAC__byte)x;
  100461. decoder->private_->cached = true;
  100462. }
  100463. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100464. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100465. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100466. return true;
  100467. }
  100468. }
  100469. if(first) {
  100470. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100471. first = false;
  100472. }
  100473. }
  100474. return true;
  100475. }
  100476. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100477. {
  100478. unsigned channel;
  100479. unsigned i;
  100480. FLAC__int32 mid, side;
  100481. unsigned frame_crc; /* the one we calculate from the input stream */
  100482. FLAC__uint32 x;
  100483. *got_a_frame = false;
  100484. /* init the CRC */
  100485. frame_crc = 0;
  100486. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100487. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100488. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100489. if(!read_frame_header_(decoder))
  100490. return false;
  100491. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100492. return true;
  100493. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100494. return false;
  100495. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100496. /*
  100497. * first figure the correct bits-per-sample of the subframe
  100498. */
  100499. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100500. switch(decoder->private_->frame.header.channel_assignment) {
  100501. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100502. /* no adjustment needed */
  100503. break;
  100504. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100505. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100506. if(channel == 1)
  100507. bps++;
  100508. break;
  100509. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100510. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100511. if(channel == 0)
  100512. bps++;
  100513. break;
  100514. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100515. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100516. if(channel == 1)
  100517. bps++;
  100518. break;
  100519. default:
  100520. FLAC__ASSERT(0);
  100521. }
  100522. /*
  100523. * now read it
  100524. */
  100525. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100526. return false;
  100527. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100528. return true;
  100529. }
  100530. if(!read_zero_padding_(decoder))
  100531. return false;
  100532. 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) */
  100533. return true;
  100534. /*
  100535. * Read the frame CRC-16 from the footer and check
  100536. */
  100537. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100538. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100539. return false; /* read_callback_ sets the state for us */
  100540. if(frame_crc == x) {
  100541. if(do_full_decode) {
  100542. /* Undo any special channel coding */
  100543. switch(decoder->private_->frame.header.channel_assignment) {
  100544. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100545. /* do nothing */
  100546. break;
  100547. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100548. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100549. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100550. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100551. break;
  100552. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100553. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100554. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100555. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100556. break;
  100557. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100558. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100559. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100560. #if 1
  100561. mid = decoder->private_->output[0][i];
  100562. side = decoder->private_->output[1][i];
  100563. mid <<= 1;
  100564. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100565. decoder->private_->output[0][i] = (mid + side) >> 1;
  100566. decoder->private_->output[1][i] = (mid - side) >> 1;
  100567. #else
  100568. /* OPT: without 'side' temp variable */
  100569. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100570. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100571. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100572. #endif
  100573. }
  100574. break;
  100575. default:
  100576. FLAC__ASSERT(0);
  100577. break;
  100578. }
  100579. }
  100580. }
  100581. else {
  100582. /* Bad frame, emit error and zero the output signal */
  100583. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100584. if(do_full_decode) {
  100585. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100586. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100587. }
  100588. }
  100589. }
  100590. *got_a_frame = true;
  100591. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100592. if(decoder->private_->next_fixed_block_size)
  100593. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100594. /* put the latest values into the public section of the decoder instance */
  100595. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100596. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100597. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100598. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100599. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100600. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100601. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100602. /* write it */
  100603. if(do_full_decode) {
  100604. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100605. return false;
  100606. }
  100607. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100608. return true;
  100609. }
  100610. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100611. {
  100612. FLAC__uint32 x;
  100613. FLAC__uint64 xx;
  100614. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100615. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100616. unsigned raw_header_len;
  100617. FLAC__bool is_unparseable = false;
  100618. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100619. /* init the raw header with the saved bits from synchronization */
  100620. raw_header[0] = decoder->private_->header_warmup[0];
  100621. raw_header[1] = decoder->private_->header_warmup[1];
  100622. raw_header_len = 2;
  100623. /* check to make sure that reserved bit is 0 */
  100624. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100625. is_unparseable = true;
  100626. /*
  100627. * Note that along the way as we read the header, we look for a sync
  100628. * code inside. If we find one it would indicate that our original
  100629. * sync was bad since there cannot be a sync code in a valid header.
  100630. *
  100631. * Three kinds of things can go wrong when reading the frame header:
  100632. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100633. * If we don't find a sync code, it can end up looking like we read
  100634. * a valid but unparseable header, until getting to the frame header
  100635. * CRC. Even then we could get a false positive on the CRC.
  100636. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100637. * future encoder).
  100638. * 3) We may be on a damaged frame which appears valid but unparseable.
  100639. *
  100640. * For all these reasons, we try and read a complete frame header as
  100641. * long as it seems valid, even if unparseable, up until the frame
  100642. * header CRC.
  100643. */
  100644. /*
  100645. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100646. */
  100647. for(i = 0; i < 2; i++) {
  100648. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100649. return false; /* read_callback_ sets the state for us */
  100650. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100651. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100652. decoder->private_->lookahead = (FLAC__byte)x;
  100653. decoder->private_->cached = true;
  100654. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100655. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100656. return true;
  100657. }
  100658. raw_header[raw_header_len++] = (FLAC__byte)x;
  100659. }
  100660. switch(x = raw_header[2] >> 4) {
  100661. case 0:
  100662. is_unparseable = true;
  100663. break;
  100664. case 1:
  100665. decoder->private_->frame.header.blocksize = 192;
  100666. break;
  100667. case 2:
  100668. case 3:
  100669. case 4:
  100670. case 5:
  100671. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100672. break;
  100673. case 6:
  100674. case 7:
  100675. blocksize_hint = x;
  100676. break;
  100677. case 8:
  100678. case 9:
  100679. case 10:
  100680. case 11:
  100681. case 12:
  100682. case 13:
  100683. case 14:
  100684. case 15:
  100685. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100686. break;
  100687. default:
  100688. FLAC__ASSERT(0);
  100689. break;
  100690. }
  100691. switch(x = raw_header[2] & 0x0f) {
  100692. case 0:
  100693. if(decoder->private_->has_stream_info)
  100694. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100695. else
  100696. is_unparseable = true;
  100697. break;
  100698. case 1:
  100699. decoder->private_->frame.header.sample_rate = 88200;
  100700. break;
  100701. case 2:
  100702. decoder->private_->frame.header.sample_rate = 176400;
  100703. break;
  100704. case 3:
  100705. decoder->private_->frame.header.sample_rate = 192000;
  100706. break;
  100707. case 4:
  100708. decoder->private_->frame.header.sample_rate = 8000;
  100709. break;
  100710. case 5:
  100711. decoder->private_->frame.header.sample_rate = 16000;
  100712. break;
  100713. case 6:
  100714. decoder->private_->frame.header.sample_rate = 22050;
  100715. break;
  100716. case 7:
  100717. decoder->private_->frame.header.sample_rate = 24000;
  100718. break;
  100719. case 8:
  100720. decoder->private_->frame.header.sample_rate = 32000;
  100721. break;
  100722. case 9:
  100723. decoder->private_->frame.header.sample_rate = 44100;
  100724. break;
  100725. case 10:
  100726. decoder->private_->frame.header.sample_rate = 48000;
  100727. break;
  100728. case 11:
  100729. decoder->private_->frame.header.sample_rate = 96000;
  100730. break;
  100731. case 12:
  100732. case 13:
  100733. case 14:
  100734. sample_rate_hint = x;
  100735. break;
  100736. case 15:
  100737. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100738. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100739. return true;
  100740. default:
  100741. FLAC__ASSERT(0);
  100742. }
  100743. x = (unsigned)(raw_header[3] >> 4);
  100744. if(x & 8) {
  100745. decoder->private_->frame.header.channels = 2;
  100746. switch(x & 7) {
  100747. case 0:
  100748. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100749. break;
  100750. case 1:
  100751. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100752. break;
  100753. case 2:
  100754. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100755. break;
  100756. default:
  100757. is_unparseable = true;
  100758. break;
  100759. }
  100760. }
  100761. else {
  100762. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100763. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100764. }
  100765. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100766. case 0:
  100767. if(decoder->private_->has_stream_info)
  100768. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100769. else
  100770. is_unparseable = true;
  100771. break;
  100772. case 1:
  100773. decoder->private_->frame.header.bits_per_sample = 8;
  100774. break;
  100775. case 2:
  100776. decoder->private_->frame.header.bits_per_sample = 12;
  100777. break;
  100778. case 4:
  100779. decoder->private_->frame.header.bits_per_sample = 16;
  100780. break;
  100781. case 5:
  100782. decoder->private_->frame.header.bits_per_sample = 20;
  100783. break;
  100784. case 6:
  100785. decoder->private_->frame.header.bits_per_sample = 24;
  100786. break;
  100787. case 3:
  100788. case 7:
  100789. is_unparseable = true;
  100790. break;
  100791. default:
  100792. FLAC__ASSERT(0);
  100793. break;
  100794. }
  100795. /* check to make sure that reserved bit is 0 */
  100796. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100797. is_unparseable = true;
  100798. /* read the frame's starting sample number (or frame number as the case may be) */
  100799. if(
  100800. raw_header[1] & 0x01 ||
  100801. /*@@@ 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 */
  100802. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100803. ) { /* variable blocksize */
  100804. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100805. return false; /* read_callback_ sets the state for us */
  100806. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100807. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100808. decoder->private_->cached = true;
  100809. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100810. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100811. return true;
  100812. }
  100813. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100814. decoder->private_->frame.header.number.sample_number = xx;
  100815. }
  100816. else { /* fixed blocksize */
  100817. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100818. return false; /* read_callback_ sets the state for us */
  100819. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100820. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100821. decoder->private_->cached = true;
  100822. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100823. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100824. return true;
  100825. }
  100826. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100827. decoder->private_->frame.header.number.frame_number = x;
  100828. }
  100829. if(blocksize_hint) {
  100830. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100831. return false; /* read_callback_ sets the state for us */
  100832. raw_header[raw_header_len++] = (FLAC__byte)x;
  100833. if(blocksize_hint == 7) {
  100834. FLAC__uint32 _x;
  100835. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100836. return false; /* read_callback_ sets the state for us */
  100837. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100838. x = (x << 8) | _x;
  100839. }
  100840. decoder->private_->frame.header.blocksize = x+1;
  100841. }
  100842. if(sample_rate_hint) {
  100843. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100844. return false; /* read_callback_ sets the state for us */
  100845. raw_header[raw_header_len++] = (FLAC__byte)x;
  100846. if(sample_rate_hint != 12) {
  100847. FLAC__uint32 _x;
  100848. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100849. return false; /* read_callback_ sets the state for us */
  100850. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100851. x = (x << 8) | _x;
  100852. }
  100853. if(sample_rate_hint == 12)
  100854. decoder->private_->frame.header.sample_rate = x*1000;
  100855. else if(sample_rate_hint == 13)
  100856. decoder->private_->frame.header.sample_rate = x;
  100857. else
  100858. decoder->private_->frame.header.sample_rate = x*10;
  100859. }
  100860. /* read the CRC-8 byte */
  100861. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100862. return false; /* read_callback_ sets the state for us */
  100863. crc8 = (FLAC__byte)x;
  100864. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100865. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100866. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100867. return true;
  100868. }
  100869. /* calculate the sample number from the frame number if needed */
  100870. decoder->private_->next_fixed_block_size = 0;
  100871. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100872. x = decoder->private_->frame.header.number.frame_number;
  100873. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100874. if(decoder->private_->fixed_block_size)
  100875. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100876. else if(decoder->private_->has_stream_info) {
  100877. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100878. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100879. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100880. }
  100881. else
  100882. is_unparseable = true;
  100883. }
  100884. else if(x == 0) {
  100885. decoder->private_->frame.header.number.sample_number = 0;
  100886. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100887. }
  100888. else {
  100889. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100890. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100891. }
  100892. }
  100893. if(is_unparseable) {
  100894. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100895. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100896. return true;
  100897. }
  100898. return true;
  100899. }
  100900. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100901. {
  100902. FLAC__uint32 x;
  100903. FLAC__bool wasted_bits;
  100904. unsigned i;
  100905. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100906. return false; /* read_callback_ sets the state for us */
  100907. wasted_bits = (x & 1);
  100908. x &= 0xfe;
  100909. if(wasted_bits) {
  100910. unsigned u;
  100911. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100912. return false; /* read_callback_ sets the state for us */
  100913. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100914. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100915. }
  100916. else
  100917. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100918. /*
  100919. * Lots of magic numbers here
  100920. */
  100921. if(x & 0x80) {
  100922. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100923. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100924. return true;
  100925. }
  100926. else if(x == 0) {
  100927. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100928. return false;
  100929. }
  100930. else if(x == 2) {
  100931. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100932. return false;
  100933. }
  100934. else if(x < 16) {
  100935. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100936. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100937. return true;
  100938. }
  100939. else if(x <= 24) {
  100940. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100941. return false;
  100942. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100943. return true;
  100944. }
  100945. else if(x < 64) {
  100946. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100947. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100948. return true;
  100949. }
  100950. else {
  100951. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100952. return false;
  100953. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100954. return true;
  100955. }
  100956. if(wasted_bits && do_full_decode) {
  100957. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100958. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100959. decoder->private_->output[channel][i] <<= x;
  100960. }
  100961. return true;
  100962. }
  100963. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100964. {
  100965. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100966. FLAC__int32 x;
  100967. unsigned i;
  100968. FLAC__int32 *output = decoder->private_->output[channel];
  100969. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100970. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100971. return false; /* read_callback_ sets the state for us */
  100972. subframe->value = x;
  100973. /* decode the subframe */
  100974. if(do_full_decode) {
  100975. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100976. output[i] = x;
  100977. }
  100978. return true;
  100979. }
  100980. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100981. {
  100982. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100983. FLAC__int32 i32;
  100984. FLAC__uint32 u32;
  100985. unsigned u;
  100986. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100987. subframe->residual = decoder->private_->residual[channel];
  100988. subframe->order = order;
  100989. /* read warm-up samples */
  100990. for(u = 0; u < order; u++) {
  100991. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100992. return false; /* read_callback_ sets the state for us */
  100993. subframe->warmup[u] = i32;
  100994. }
  100995. /* read entropy coding method info */
  100996. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100997. return false; /* read_callback_ sets the state for us */
  100998. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100999. switch(subframe->entropy_coding_method.type) {
  101000. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101001. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101002. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101003. return false; /* read_callback_ sets the state for us */
  101004. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101005. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101006. break;
  101007. default:
  101008. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101009. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101010. return true;
  101011. }
  101012. /* read residual */
  101013. switch(subframe->entropy_coding_method.type) {
  101014. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101015. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101016. 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))
  101017. return false;
  101018. break;
  101019. default:
  101020. FLAC__ASSERT(0);
  101021. }
  101022. /* decode the subframe */
  101023. if(do_full_decode) {
  101024. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101025. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101026. }
  101027. return true;
  101028. }
  101029. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101030. {
  101031. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101032. FLAC__int32 i32;
  101033. FLAC__uint32 u32;
  101034. unsigned u;
  101035. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101036. subframe->residual = decoder->private_->residual[channel];
  101037. subframe->order = order;
  101038. /* read warm-up samples */
  101039. for(u = 0; u < order; u++) {
  101040. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101041. return false; /* read_callback_ sets the state for us */
  101042. subframe->warmup[u] = i32;
  101043. }
  101044. /* read qlp coeff precision */
  101045. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101046. return false; /* read_callback_ sets the state for us */
  101047. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101048. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101049. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101050. return true;
  101051. }
  101052. subframe->qlp_coeff_precision = u32+1;
  101053. /* read qlp shift */
  101054. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101055. return false; /* read_callback_ sets the state for us */
  101056. subframe->quantization_level = i32;
  101057. /* read quantized lp coefficiencts */
  101058. for(u = 0; u < order; u++) {
  101059. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101060. return false; /* read_callback_ sets the state for us */
  101061. subframe->qlp_coeff[u] = i32;
  101062. }
  101063. /* read entropy coding method info */
  101064. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101065. return false; /* read_callback_ sets the state for us */
  101066. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101067. switch(subframe->entropy_coding_method.type) {
  101068. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101069. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101070. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101071. return false; /* read_callback_ sets the state for us */
  101072. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101073. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101074. break;
  101075. default:
  101076. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101077. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101078. return true;
  101079. }
  101080. /* read residual */
  101081. switch(subframe->entropy_coding_method.type) {
  101082. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101083. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101084. 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))
  101085. return false;
  101086. break;
  101087. default:
  101088. FLAC__ASSERT(0);
  101089. }
  101090. /* decode the subframe */
  101091. if(do_full_decode) {
  101092. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101093. /*@@@@@@ technically not pessimistic enough, should be more like
  101094. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101095. */
  101096. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101097. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101098. if(order <= 8)
  101099. 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);
  101100. else
  101101. 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);
  101102. }
  101103. else
  101104. 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);
  101105. else
  101106. 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);
  101107. }
  101108. return true;
  101109. }
  101110. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101111. {
  101112. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101113. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101114. unsigned i;
  101115. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101116. subframe->data = residual;
  101117. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101118. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101119. return false; /* read_callback_ sets the state for us */
  101120. residual[i] = x;
  101121. }
  101122. /* decode the subframe */
  101123. if(do_full_decode)
  101124. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101125. return true;
  101126. }
  101127. 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)
  101128. {
  101129. FLAC__uint32 rice_parameter;
  101130. int i;
  101131. unsigned partition, sample, u;
  101132. const unsigned partitions = 1u << partition_order;
  101133. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101134. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101135. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101136. /* sanity checks */
  101137. if(partition_order == 0) {
  101138. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101139. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101140. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101141. return true;
  101142. }
  101143. }
  101144. else {
  101145. if(partition_samples < predictor_order) {
  101146. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101147. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101148. return true;
  101149. }
  101150. }
  101151. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101152. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101153. return false;
  101154. }
  101155. sample = 0;
  101156. for(partition = 0; partition < partitions; partition++) {
  101157. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101158. return false; /* read_callback_ sets the state for us */
  101159. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101160. if(rice_parameter < pesc) {
  101161. partitioned_rice_contents->raw_bits[partition] = 0;
  101162. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101163. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101164. return false; /* read_callback_ sets the state for us */
  101165. sample += u;
  101166. }
  101167. else {
  101168. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101169. return false; /* read_callback_ sets the state for us */
  101170. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101171. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101172. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101173. return false; /* read_callback_ sets the state for us */
  101174. residual[sample] = i;
  101175. }
  101176. }
  101177. }
  101178. return true;
  101179. }
  101180. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101181. {
  101182. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101183. FLAC__uint32 zero = 0;
  101184. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101185. return false; /* read_callback_ sets the state for us */
  101186. if(zero != 0) {
  101187. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101188. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101189. }
  101190. }
  101191. return true;
  101192. }
  101193. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101194. {
  101195. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101196. if(
  101197. #if FLAC__HAS_OGG
  101198. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101199. !decoder->private_->is_ogg &&
  101200. #endif
  101201. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101202. ) {
  101203. *bytes = 0;
  101204. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101205. return false;
  101206. }
  101207. else if(*bytes > 0) {
  101208. /* While seeking, it is possible for our seek to land in the
  101209. * middle of audio data that looks exactly like a frame header
  101210. * from a future version of an encoder. When that happens, our
  101211. * error callback will get an
  101212. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101213. * unparseable_frame_count. But there is a remote possibility
  101214. * that it is properly synced at such a "future-codec frame",
  101215. * so to make sure, we wait to see many "unparseable" errors in
  101216. * a row before bailing out.
  101217. */
  101218. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101219. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101220. return false;
  101221. }
  101222. else {
  101223. const FLAC__StreamDecoderReadStatus status =
  101224. #if FLAC__HAS_OGG
  101225. decoder->private_->is_ogg?
  101226. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101227. #endif
  101228. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101229. ;
  101230. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101231. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101232. return false;
  101233. }
  101234. else if(*bytes == 0) {
  101235. if(
  101236. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101237. (
  101238. #if FLAC__HAS_OGG
  101239. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101240. !decoder->private_->is_ogg &&
  101241. #endif
  101242. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101243. )
  101244. ) {
  101245. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101246. return false;
  101247. }
  101248. else
  101249. return true;
  101250. }
  101251. else
  101252. return true;
  101253. }
  101254. }
  101255. else {
  101256. /* abort to avoid a deadlock */
  101257. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101258. return false;
  101259. }
  101260. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101261. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101262. * and at the same time hit the end of the stream (for example, seeking
  101263. * to a point that is after the beginning of the last Ogg page). There
  101264. * is no way to report an Ogg sync loss through the callbacks (see note
  101265. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101266. * So to keep the decoder from stopping at this point we gate the call
  101267. * to the eof_callback and let the Ogg decoder aspect set the
  101268. * end-of-stream state when it is needed.
  101269. */
  101270. }
  101271. #if FLAC__HAS_OGG
  101272. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101273. {
  101274. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101275. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101276. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101277. /* we don't really have a way to handle lost sync via read
  101278. * callback so we'll let it pass and let the underlying
  101279. * FLAC decoder catch the error
  101280. */
  101281. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101282. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101283. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101284. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101285. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101286. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101287. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101288. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101289. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101290. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101291. default:
  101292. FLAC__ASSERT(0);
  101293. /* double protection */
  101294. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101295. }
  101296. }
  101297. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101298. {
  101299. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101300. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101301. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101302. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101303. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101304. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101305. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101306. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101307. default:
  101308. /* double protection: */
  101309. FLAC__ASSERT(0);
  101310. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101311. }
  101312. }
  101313. #endif
  101314. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101315. {
  101316. if(decoder->private_->is_seeking) {
  101317. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101318. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101319. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101320. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101321. #if FLAC__HAS_OGG
  101322. decoder->private_->got_a_frame = true;
  101323. #endif
  101324. decoder->private_->last_frame = *frame; /* save the frame */
  101325. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101326. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101327. /* kick out of seek mode */
  101328. decoder->private_->is_seeking = false;
  101329. /* shift out the samples before target_sample */
  101330. if(delta > 0) {
  101331. unsigned channel;
  101332. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101333. for(channel = 0; channel < frame->header.channels; channel++)
  101334. newbuffer[channel] = buffer[channel] + delta;
  101335. decoder->private_->last_frame.header.blocksize -= delta;
  101336. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101337. /* write the relevant samples */
  101338. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101339. }
  101340. else {
  101341. /* write the relevant samples */
  101342. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101343. }
  101344. }
  101345. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101346. }
  101347. /*
  101348. * If we never got STREAMINFO, turn off MD5 checking to save
  101349. * cycles since we don't have a sum to compare to anyway
  101350. */
  101351. if(!decoder->private_->has_stream_info)
  101352. decoder->private_->do_md5_checking = false;
  101353. if(decoder->private_->do_md5_checking) {
  101354. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101355. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101356. }
  101357. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101358. }
  101359. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101360. {
  101361. if(!decoder->private_->is_seeking)
  101362. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101363. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101364. decoder->private_->unparseable_frame_count++;
  101365. }
  101366. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101367. {
  101368. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101369. FLAC__int64 pos = -1;
  101370. int i;
  101371. unsigned approx_bytes_per_frame;
  101372. FLAC__bool first_seek = true;
  101373. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101374. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101375. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101376. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101377. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101378. /* take these from the current frame in case they've changed mid-stream */
  101379. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101380. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101381. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101382. /* use values from stream info if we didn't decode a frame */
  101383. if(channels == 0)
  101384. channels = decoder->private_->stream_info.data.stream_info.channels;
  101385. if(bps == 0)
  101386. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101387. /* we are just guessing here */
  101388. if(max_framesize > 0)
  101389. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101390. /*
  101391. * Check if it's a known fixed-blocksize stream. Note that though
  101392. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101393. * never get a STREAMINFO block when decoding so the value of
  101394. * min_blocksize might be zero.
  101395. */
  101396. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101397. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101398. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101399. }
  101400. else
  101401. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101402. /*
  101403. * First, we set an upper and lower bound on where in the
  101404. * stream we will search. For now we assume the worst case
  101405. * scenario, which is our best guess at the beginning of
  101406. * the first frame and end of the stream.
  101407. */
  101408. lower_bound = first_frame_offset;
  101409. lower_bound_sample = 0;
  101410. upper_bound = stream_length;
  101411. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101412. /*
  101413. * Now we refine the bounds if we have a seektable with
  101414. * suitable points. Note that according to the spec they
  101415. * must be ordered by ascending sample number.
  101416. *
  101417. * Note: to protect against invalid seek tables we will ignore points
  101418. * that have frame_samples==0 or sample_number>=total_samples
  101419. */
  101420. if(seek_table) {
  101421. FLAC__uint64 new_lower_bound = lower_bound;
  101422. FLAC__uint64 new_upper_bound = upper_bound;
  101423. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101424. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101425. /* find the closest seek point <= target_sample, if it exists */
  101426. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101427. if(
  101428. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101429. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101430. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101431. seek_table->points[i].sample_number <= target_sample
  101432. )
  101433. break;
  101434. }
  101435. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101436. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101437. new_lower_bound_sample = seek_table->points[i].sample_number;
  101438. }
  101439. /* find the closest seek point > target_sample, if it exists */
  101440. for(i = 0; i < (int)seek_table->num_points; i++) {
  101441. if(
  101442. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101443. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101444. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101445. seek_table->points[i].sample_number > target_sample
  101446. )
  101447. break;
  101448. }
  101449. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101450. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101451. new_upper_bound_sample = seek_table->points[i].sample_number;
  101452. }
  101453. /* final protection against unsorted seek tables; keep original values if bogus */
  101454. if(new_upper_bound >= new_lower_bound) {
  101455. lower_bound = new_lower_bound;
  101456. upper_bound = new_upper_bound;
  101457. lower_bound_sample = new_lower_bound_sample;
  101458. upper_bound_sample = new_upper_bound_sample;
  101459. }
  101460. }
  101461. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101462. /* there are 2 insidious ways that the following equality occurs, which
  101463. * we need to fix:
  101464. * 1) total_samples is 0 (unknown) and target_sample is 0
  101465. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101466. * exactly equal to the last seek point in the seek table; this
  101467. * means there is no seek point above it, and upper_bound_samples
  101468. * remains equal to the estimate (of target_samples) we made above
  101469. * in either case it does not hurt to move upper_bound_sample up by 1
  101470. */
  101471. if(upper_bound_sample == lower_bound_sample)
  101472. upper_bound_sample++;
  101473. decoder->private_->target_sample = target_sample;
  101474. while(1) {
  101475. /* check if the bounds are still ok */
  101476. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101477. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101478. return false;
  101479. }
  101480. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101481. #if defined _MSC_VER || defined __MINGW32__
  101482. /* with VC++ you have to spoon feed it the casting */
  101483. 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;
  101484. #else
  101485. 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;
  101486. #endif
  101487. #else
  101488. /* a little less accurate: */
  101489. if(upper_bound - lower_bound < 0xffffffff)
  101490. 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;
  101491. else /* @@@ WATCHOUT, ~2TB limit */
  101492. 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;
  101493. #endif
  101494. if(pos >= (FLAC__int64)upper_bound)
  101495. pos = (FLAC__int64)upper_bound - 1;
  101496. if(pos < (FLAC__int64)lower_bound)
  101497. pos = (FLAC__int64)lower_bound;
  101498. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101499. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101500. return false;
  101501. }
  101502. if(!FLAC__stream_decoder_flush(decoder)) {
  101503. /* above call sets the state for us */
  101504. return false;
  101505. }
  101506. /* Now we need to get a frame. First we need to reset our
  101507. * unparseable_frame_count; if we get too many unparseable
  101508. * frames in a row, the read callback will return
  101509. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101510. * FLAC__stream_decoder_process_single() to return false.
  101511. */
  101512. decoder->private_->unparseable_frame_count = 0;
  101513. if(!FLAC__stream_decoder_process_single(decoder)) {
  101514. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101515. return false;
  101516. }
  101517. /* our write callback will change the state when it gets to the target frame */
  101518. /* 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 */
  101519. #if 0
  101520. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101521. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101522. break;
  101523. #endif
  101524. if(!decoder->private_->is_seeking)
  101525. break;
  101526. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101527. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101528. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101529. if (pos == (FLAC__int64)lower_bound) {
  101530. /* can't move back any more than the first frame, something is fatally wrong */
  101531. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101532. return false;
  101533. }
  101534. /* our last move backwards wasn't big enough, try again */
  101535. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101536. continue;
  101537. }
  101538. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101539. first_seek = false;
  101540. /* make sure we are not seeking in corrupted stream */
  101541. if (this_frame_sample < lower_bound_sample) {
  101542. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101543. return false;
  101544. }
  101545. /* we need to narrow the search */
  101546. if(target_sample < this_frame_sample) {
  101547. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101548. /*@@@@@@ what will decode position be if at end of stream? */
  101549. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101550. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101551. return false;
  101552. }
  101553. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101554. }
  101555. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101556. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101557. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101558. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101559. return false;
  101560. }
  101561. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101562. }
  101563. }
  101564. return true;
  101565. }
  101566. #if FLAC__HAS_OGG
  101567. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101568. {
  101569. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101570. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101571. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101572. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101573. FLAC__bool did_a_seek;
  101574. unsigned iteration = 0;
  101575. /* In the first iterations, we will calculate the target byte position
  101576. * by the distance from the target sample to left_sample and
  101577. * right_sample (let's call it "proportional search"). After that, we
  101578. * will switch to binary search.
  101579. */
  101580. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101581. /* We will switch to a linear search once our current sample is less
  101582. * than this number of samples ahead of the target sample
  101583. */
  101584. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101585. /* If the total number of samples is unknown, use a large value, and
  101586. * force binary search immediately.
  101587. */
  101588. if(right_sample == 0) {
  101589. right_sample = (FLAC__uint64)(-1);
  101590. BINARY_SEARCH_AFTER_ITERATION = 0;
  101591. }
  101592. decoder->private_->target_sample = target_sample;
  101593. for( ; ; iteration++) {
  101594. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101595. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101596. pos = (right_pos + left_pos) / 2;
  101597. }
  101598. else {
  101599. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101600. #if defined _MSC_VER || defined __MINGW32__
  101601. /* with MSVC you have to spoon feed it the casting */
  101602. 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));
  101603. #else
  101604. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101605. #endif
  101606. #else
  101607. /* a little less accurate: */
  101608. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101609. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101610. else /* @@@ WATCHOUT, ~2TB limit */
  101611. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101612. #endif
  101613. /* @@@ TODO: might want to limit pos to some distance
  101614. * before EOF, to make sure we land before the last frame,
  101615. * thereby getting a this_frame_sample and so having a better
  101616. * estimate.
  101617. */
  101618. }
  101619. /* physical seek */
  101620. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101621. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101622. return false;
  101623. }
  101624. if(!FLAC__stream_decoder_flush(decoder)) {
  101625. /* above call sets the state for us */
  101626. return false;
  101627. }
  101628. did_a_seek = true;
  101629. }
  101630. else
  101631. did_a_seek = false;
  101632. decoder->private_->got_a_frame = false;
  101633. if(!FLAC__stream_decoder_process_single(decoder)) {
  101634. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101635. return false;
  101636. }
  101637. if(!decoder->private_->got_a_frame) {
  101638. if(did_a_seek) {
  101639. /* this can happen if we seek to a point after the last frame; we drop
  101640. * to binary search right away in this case to avoid any wasted
  101641. * iterations of proportional search.
  101642. */
  101643. right_pos = pos;
  101644. BINARY_SEARCH_AFTER_ITERATION = 0;
  101645. }
  101646. else {
  101647. /* this can probably only happen if total_samples is unknown and the
  101648. * target_sample is past the end of the stream
  101649. */
  101650. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101651. return false;
  101652. }
  101653. }
  101654. /* our write callback will change the state when it gets to the target frame */
  101655. else if(!decoder->private_->is_seeking) {
  101656. break;
  101657. }
  101658. else {
  101659. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101660. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101661. if (did_a_seek) {
  101662. if (this_frame_sample <= target_sample) {
  101663. /* The 'equal' case should not happen, since
  101664. * FLAC__stream_decoder_process_single()
  101665. * should recognize that it has hit the
  101666. * target sample and we would exit through
  101667. * the 'break' above.
  101668. */
  101669. FLAC__ASSERT(this_frame_sample != target_sample);
  101670. left_sample = this_frame_sample;
  101671. /* sanity check to avoid infinite loop */
  101672. if (left_pos == pos) {
  101673. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101674. return false;
  101675. }
  101676. left_pos = pos;
  101677. }
  101678. else if(this_frame_sample > target_sample) {
  101679. right_sample = this_frame_sample;
  101680. /* sanity check to avoid infinite loop */
  101681. if (right_pos == pos) {
  101682. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101683. return false;
  101684. }
  101685. right_pos = pos;
  101686. }
  101687. }
  101688. }
  101689. }
  101690. return true;
  101691. }
  101692. #endif
  101693. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101694. {
  101695. (void)client_data;
  101696. if(*bytes > 0) {
  101697. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101698. if(ferror(decoder->private_->file))
  101699. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101700. else if(*bytes == 0)
  101701. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101702. else
  101703. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101704. }
  101705. else
  101706. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101707. }
  101708. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101709. {
  101710. (void)client_data;
  101711. if(decoder->private_->file == stdin)
  101712. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101713. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101714. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101715. else
  101716. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101717. }
  101718. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101719. {
  101720. off_t pos;
  101721. (void)client_data;
  101722. if(decoder->private_->file == stdin)
  101723. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101724. else if((pos = ftello(decoder->private_->file)) < 0)
  101725. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101726. else {
  101727. *absolute_byte_offset = (FLAC__uint64)pos;
  101728. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101729. }
  101730. }
  101731. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101732. {
  101733. struct stat filestats;
  101734. (void)client_data;
  101735. if(decoder->private_->file == stdin)
  101736. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101737. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101738. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101739. else {
  101740. *stream_length = (FLAC__uint64)filestats.st_size;
  101741. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101742. }
  101743. }
  101744. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101745. {
  101746. (void)client_data;
  101747. return feof(decoder->private_->file)? true : false;
  101748. }
  101749. #endif
  101750. /*** End of inlined file: stream_decoder.c ***/
  101751. /*** Start of inlined file: stream_encoder.c ***/
  101752. /*** Start of inlined file: juce_FlacHeader.h ***/
  101753. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101754. // tasks..
  101755. #define VERSION "1.2.1"
  101756. #define FLAC__NO_DLL 1
  101757. #if JUCE_MSVC
  101758. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101759. #endif
  101760. #if JUCE_MAC
  101761. #define FLAC__SYS_DARWIN 1
  101762. #endif
  101763. /*** End of inlined file: juce_FlacHeader.h ***/
  101764. #if JUCE_USE_FLAC
  101765. #if HAVE_CONFIG_H
  101766. # include <config.h>
  101767. #endif
  101768. #if defined _MSC_VER || defined __MINGW32__
  101769. #include <io.h> /* for _setmode() */
  101770. #include <fcntl.h> /* for _O_BINARY */
  101771. #endif
  101772. #if defined __CYGWIN__ || defined __EMX__
  101773. #include <io.h> /* for setmode(), O_BINARY */
  101774. #include <fcntl.h> /* for _O_BINARY */
  101775. #endif
  101776. #include <limits.h>
  101777. #include <stdio.h>
  101778. #include <stdlib.h> /* for malloc() */
  101779. #include <string.h> /* for memcpy() */
  101780. #include <sys/types.h> /* for off_t */
  101781. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101782. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101783. #define fseeko fseek
  101784. #define ftello ftell
  101785. #endif
  101786. #endif
  101787. /*** Start of inlined file: stream_encoder.h ***/
  101788. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101789. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101790. #if FLAC__HAS_OGG
  101791. #include "private/ogg_encoder_aspect.h"
  101792. #endif
  101793. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101794. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101795. typedef enum {
  101796. FLAC__APODIZATION_BARTLETT,
  101797. FLAC__APODIZATION_BARTLETT_HANN,
  101798. FLAC__APODIZATION_BLACKMAN,
  101799. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101800. FLAC__APODIZATION_CONNES,
  101801. FLAC__APODIZATION_FLATTOP,
  101802. FLAC__APODIZATION_GAUSS,
  101803. FLAC__APODIZATION_HAMMING,
  101804. FLAC__APODIZATION_HANN,
  101805. FLAC__APODIZATION_KAISER_BESSEL,
  101806. FLAC__APODIZATION_NUTTALL,
  101807. FLAC__APODIZATION_RECTANGLE,
  101808. FLAC__APODIZATION_TRIANGLE,
  101809. FLAC__APODIZATION_TUKEY,
  101810. FLAC__APODIZATION_WELCH
  101811. } FLAC__ApodizationFunction;
  101812. typedef struct {
  101813. FLAC__ApodizationFunction type;
  101814. union {
  101815. struct {
  101816. FLAC__real stddev;
  101817. } gauss;
  101818. struct {
  101819. FLAC__real p;
  101820. } tukey;
  101821. } parameters;
  101822. } FLAC__ApodizationSpecification;
  101823. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101824. typedef struct FLAC__StreamEncoderProtected {
  101825. FLAC__StreamEncoderState state;
  101826. FLAC__bool verify;
  101827. FLAC__bool streamable_subset;
  101828. FLAC__bool do_md5;
  101829. FLAC__bool do_mid_side_stereo;
  101830. FLAC__bool loose_mid_side_stereo;
  101831. unsigned channels;
  101832. unsigned bits_per_sample;
  101833. unsigned sample_rate;
  101834. unsigned blocksize;
  101835. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101836. unsigned num_apodizations;
  101837. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101838. #endif
  101839. unsigned max_lpc_order;
  101840. unsigned qlp_coeff_precision;
  101841. FLAC__bool do_qlp_coeff_prec_search;
  101842. FLAC__bool do_exhaustive_model_search;
  101843. FLAC__bool do_escape_coding;
  101844. unsigned min_residual_partition_order;
  101845. unsigned max_residual_partition_order;
  101846. unsigned rice_parameter_search_dist;
  101847. FLAC__uint64 total_samples_estimate;
  101848. FLAC__StreamMetadata **metadata;
  101849. unsigned num_metadata_blocks;
  101850. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101851. #if FLAC__HAS_OGG
  101852. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101853. #endif
  101854. } FLAC__StreamEncoderProtected;
  101855. #endif
  101856. /*** End of inlined file: stream_encoder.h ***/
  101857. #if FLAC__HAS_OGG
  101858. #include "include/private/ogg_helper.h"
  101859. #include "include/private/ogg_mapping.h"
  101860. #endif
  101861. /*** Start of inlined file: stream_encoder_framing.h ***/
  101862. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101863. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101864. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101865. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101866. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101867. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101868. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101869. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101870. #endif
  101871. /*** End of inlined file: stream_encoder_framing.h ***/
  101872. /*** Start of inlined file: window.h ***/
  101873. #ifndef FLAC__PRIVATE__WINDOW_H
  101874. #define FLAC__PRIVATE__WINDOW_H
  101875. #ifdef HAVE_CONFIG_H
  101876. #include <config.h>
  101877. #endif
  101878. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101879. /*
  101880. * FLAC__window_*()
  101881. * --------------------------------------------------------------------
  101882. * Calculates window coefficients according to different apodization
  101883. * functions.
  101884. *
  101885. * OUT window[0,L-1]
  101886. * IN L (number of points in window)
  101887. */
  101888. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101889. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101890. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101891. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101892. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101893. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101894. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101895. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101896. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101897. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101898. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101899. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101900. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101901. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101902. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101903. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101904. #endif
  101905. /*** End of inlined file: window.h ***/
  101906. #ifndef FLaC__INLINE
  101907. #define FLaC__INLINE
  101908. #endif
  101909. #ifdef min
  101910. #undef min
  101911. #endif
  101912. #define min(x,y) ((x)<(y)?(x):(y))
  101913. #ifdef max
  101914. #undef max
  101915. #endif
  101916. #define max(x,y) ((x)>(y)?(x):(y))
  101917. /* Exact Rice codeword length calculation is off by default. The simple
  101918. * (and fast) estimation (of how many bits a residual value will be
  101919. * encoded with) in this encoder is very good, almost always yielding
  101920. * compression within 0.1% of exact calculation.
  101921. */
  101922. #undef EXACT_RICE_BITS_CALCULATION
  101923. /* Rice parameter searching is off by default. The simple (and fast)
  101924. * parameter estimation in this encoder is very good, almost always
  101925. * yielding compression within 0.1% of the optimal parameters.
  101926. */
  101927. #undef ENABLE_RICE_PARAMETER_SEARCH
  101928. typedef struct {
  101929. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101930. unsigned size; /* of each data[] in samples */
  101931. unsigned tail;
  101932. } verify_input_fifo;
  101933. typedef struct {
  101934. const FLAC__byte *data;
  101935. unsigned capacity;
  101936. unsigned bytes;
  101937. } verify_output;
  101938. typedef enum {
  101939. ENCODER_IN_MAGIC = 0,
  101940. ENCODER_IN_METADATA = 1,
  101941. ENCODER_IN_AUDIO = 2
  101942. } EncoderStateHint;
  101943. static struct CompressionLevels {
  101944. FLAC__bool do_mid_side_stereo;
  101945. FLAC__bool loose_mid_side_stereo;
  101946. unsigned max_lpc_order;
  101947. unsigned qlp_coeff_precision;
  101948. FLAC__bool do_qlp_coeff_prec_search;
  101949. FLAC__bool do_escape_coding;
  101950. FLAC__bool do_exhaustive_model_search;
  101951. unsigned min_residual_partition_order;
  101952. unsigned max_residual_partition_order;
  101953. unsigned rice_parameter_search_dist;
  101954. } compression_levels_[] = {
  101955. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101956. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101957. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101958. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101959. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101960. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101961. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101962. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101963. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101964. };
  101965. /***********************************************************************
  101966. *
  101967. * Private class method prototypes
  101968. *
  101969. ***********************************************************************/
  101970. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101971. static void free_(FLAC__StreamEncoder *encoder);
  101972. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101973. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101974. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101975. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101976. #if FLAC__HAS_OGG
  101977. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101978. #endif
  101979. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101980. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101981. static FLAC__bool process_subframe_(
  101982. FLAC__StreamEncoder *encoder,
  101983. unsigned min_partition_order,
  101984. unsigned max_partition_order,
  101985. const FLAC__FrameHeader *frame_header,
  101986. unsigned subframe_bps,
  101987. const FLAC__int32 integer_signal[],
  101988. FLAC__Subframe *subframe[2],
  101989. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101990. FLAC__int32 *residual[2],
  101991. unsigned *best_subframe,
  101992. unsigned *best_bits
  101993. );
  101994. static FLAC__bool add_subframe_(
  101995. FLAC__StreamEncoder *encoder,
  101996. unsigned blocksize,
  101997. unsigned subframe_bps,
  101998. const FLAC__Subframe *subframe,
  101999. FLAC__BitWriter *frame
  102000. );
  102001. static unsigned evaluate_constant_subframe_(
  102002. FLAC__StreamEncoder *encoder,
  102003. const FLAC__int32 signal,
  102004. unsigned blocksize,
  102005. unsigned subframe_bps,
  102006. FLAC__Subframe *subframe
  102007. );
  102008. static unsigned evaluate_fixed_subframe_(
  102009. FLAC__StreamEncoder *encoder,
  102010. const FLAC__int32 signal[],
  102011. FLAC__int32 residual[],
  102012. FLAC__uint64 abs_residual_partition_sums[],
  102013. unsigned raw_bits_per_partition[],
  102014. unsigned blocksize,
  102015. unsigned subframe_bps,
  102016. unsigned order,
  102017. unsigned rice_parameter,
  102018. unsigned rice_parameter_limit,
  102019. unsigned min_partition_order,
  102020. unsigned max_partition_order,
  102021. FLAC__bool do_escape_coding,
  102022. unsigned rice_parameter_search_dist,
  102023. FLAC__Subframe *subframe,
  102024. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102025. );
  102026. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102027. static unsigned evaluate_lpc_subframe_(
  102028. FLAC__StreamEncoder *encoder,
  102029. const FLAC__int32 signal[],
  102030. FLAC__int32 residual[],
  102031. FLAC__uint64 abs_residual_partition_sums[],
  102032. unsigned raw_bits_per_partition[],
  102033. const FLAC__real lp_coeff[],
  102034. unsigned blocksize,
  102035. unsigned subframe_bps,
  102036. unsigned order,
  102037. unsigned qlp_coeff_precision,
  102038. unsigned rice_parameter,
  102039. unsigned rice_parameter_limit,
  102040. unsigned min_partition_order,
  102041. unsigned max_partition_order,
  102042. FLAC__bool do_escape_coding,
  102043. unsigned rice_parameter_search_dist,
  102044. FLAC__Subframe *subframe,
  102045. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102046. );
  102047. #endif
  102048. static unsigned evaluate_verbatim_subframe_(
  102049. FLAC__StreamEncoder *encoder,
  102050. const FLAC__int32 signal[],
  102051. unsigned blocksize,
  102052. unsigned subframe_bps,
  102053. FLAC__Subframe *subframe
  102054. );
  102055. static unsigned find_best_partition_order_(
  102056. struct FLAC__StreamEncoderPrivate *private_,
  102057. const FLAC__int32 residual[],
  102058. FLAC__uint64 abs_residual_partition_sums[],
  102059. unsigned raw_bits_per_partition[],
  102060. unsigned residual_samples,
  102061. unsigned predictor_order,
  102062. unsigned rice_parameter,
  102063. unsigned rice_parameter_limit,
  102064. unsigned min_partition_order,
  102065. unsigned max_partition_order,
  102066. unsigned bps,
  102067. FLAC__bool do_escape_coding,
  102068. unsigned rice_parameter_search_dist,
  102069. FLAC__EntropyCodingMethod *best_ecm
  102070. );
  102071. static void precompute_partition_info_sums_(
  102072. const FLAC__int32 residual[],
  102073. FLAC__uint64 abs_residual_partition_sums[],
  102074. unsigned residual_samples,
  102075. unsigned predictor_order,
  102076. unsigned min_partition_order,
  102077. unsigned max_partition_order,
  102078. unsigned bps
  102079. );
  102080. static void precompute_partition_info_escapes_(
  102081. const FLAC__int32 residual[],
  102082. unsigned raw_bits_per_partition[],
  102083. unsigned residual_samples,
  102084. unsigned predictor_order,
  102085. unsigned min_partition_order,
  102086. unsigned max_partition_order
  102087. );
  102088. static FLAC__bool set_partitioned_rice_(
  102089. #ifdef EXACT_RICE_BITS_CALCULATION
  102090. const FLAC__int32 residual[],
  102091. #endif
  102092. const FLAC__uint64 abs_residual_partition_sums[],
  102093. const unsigned raw_bits_per_partition[],
  102094. const unsigned residual_samples,
  102095. const unsigned predictor_order,
  102096. const unsigned suggested_rice_parameter,
  102097. const unsigned rice_parameter_limit,
  102098. const unsigned rice_parameter_search_dist,
  102099. const unsigned partition_order,
  102100. const FLAC__bool search_for_escapes,
  102101. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102102. unsigned *bits
  102103. );
  102104. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102105. /* verify-related routines: */
  102106. static void append_to_verify_fifo_(
  102107. verify_input_fifo *fifo,
  102108. const FLAC__int32 * const input[],
  102109. unsigned input_offset,
  102110. unsigned channels,
  102111. unsigned wide_samples
  102112. );
  102113. static void append_to_verify_fifo_interleaved_(
  102114. verify_input_fifo *fifo,
  102115. const FLAC__int32 input[],
  102116. unsigned input_offset,
  102117. unsigned channels,
  102118. unsigned wide_samples
  102119. );
  102120. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102121. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102122. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102123. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102124. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102125. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102126. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102127. 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);
  102128. static FILE *get_binary_stdout_(void);
  102129. /***********************************************************************
  102130. *
  102131. * Private class data
  102132. *
  102133. ***********************************************************************/
  102134. typedef struct FLAC__StreamEncoderPrivate {
  102135. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102136. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102137. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102138. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102139. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102140. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102141. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102142. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102143. #endif
  102144. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102145. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102146. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102147. FLAC__int32 *residual_workspace_mid_side[2][2];
  102148. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102149. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102150. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102151. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102152. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102153. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102154. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102155. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102156. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102157. unsigned best_subframe_mid_side[2];
  102158. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102159. unsigned best_subframe_bits_mid_side[2];
  102160. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102161. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102162. FLAC__BitWriter *frame; /* the current frame being worked on */
  102163. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102164. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102165. FLAC__ChannelAssignment last_channel_assignment;
  102166. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102167. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102168. unsigned current_sample_number;
  102169. unsigned current_frame_number;
  102170. FLAC__MD5Context md5context;
  102171. FLAC__CPUInfo cpuinfo;
  102172. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102173. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102174. #else
  102175. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102176. #endif
  102177. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102178. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102179. 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[]);
  102180. 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[]);
  102181. 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[]);
  102182. #endif
  102183. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102184. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102185. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102186. FLAC__bool disable_constant_subframes;
  102187. FLAC__bool disable_fixed_subframes;
  102188. FLAC__bool disable_verbatim_subframes;
  102189. #if FLAC__HAS_OGG
  102190. FLAC__bool is_ogg;
  102191. #endif
  102192. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102193. FLAC__StreamEncoderSeekCallback seek_callback;
  102194. FLAC__StreamEncoderTellCallback tell_callback;
  102195. FLAC__StreamEncoderWriteCallback write_callback;
  102196. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102197. FLAC__StreamEncoderProgressCallback progress_callback;
  102198. void *client_data;
  102199. unsigned first_seekpoint_to_check;
  102200. FILE *file; /* only used when encoding to a file */
  102201. FLAC__uint64 bytes_written;
  102202. FLAC__uint64 samples_written;
  102203. unsigned frames_written;
  102204. unsigned total_frames_estimate;
  102205. /* unaligned (original) pointers to allocated data */
  102206. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102207. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102208. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102209. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102210. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102211. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102212. FLAC__real *windowed_signal_unaligned;
  102213. #endif
  102214. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102215. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102216. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102217. unsigned *raw_bits_per_partition_unaligned;
  102218. /*
  102219. * These fields have been moved here from private function local
  102220. * declarations merely to save stack space during encoding.
  102221. */
  102222. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102223. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102224. #endif
  102225. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102226. /*
  102227. * The data for the verify section
  102228. */
  102229. struct {
  102230. FLAC__StreamDecoder *decoder;
  102231. EncoderStateHint state_hint;
  102232. FLAC__bool needs_magic_hack;
  102233. verify_input_fifo input_fifo;
  102234. verify_output output;
  102235. struct {
  102236. FLAC__uint64 absolute_sample;
  102237. unsigned frame_number;
  102238. unsigned channel;
  102239. unsigned sample;
  102240. FLAC__int32 expected;
  102241. FLAC__int32 got;
  102242. } error_stats;
  102243. } verify;
  102244. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102245. } FLAC__StreamEncoderPrivate;
  102246. /***********************************************************************
  102247. *
  102248. * Public static class data
  102249. *
  102250. ***********************************************************************/
  102251. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102252. "FLAC__STREAM_ENCODER_OK",
  102253. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102254. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102255. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102256. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102257. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102258. "FLAC__STREAM_ENCODER_IO_ERROR",
  102259. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102260. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102261. };
  102262. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102263. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102264. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102265. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102266. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102267. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102268. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102269. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102270. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102271. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102272. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102273. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102274. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102275. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102276. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102277. };
  102278. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102279. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102280. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102281. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102282. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102283. };
  102284. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102285. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102286. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102287. };
  102288. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102289. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102290. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102291. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102292. };
  102293. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102294. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102295. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102296. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102297. };
  102298. /* Number of samples that will be overread to watch for end of stream. By
  102299. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102300. * always try to read blocksize+1 samples before encoding a block, so that
  102301. * even if the stream has a total sample count that is an integral multiple
  102302. * of the blocksize, we will still notice when we are encoding the last
  102303. * block. This is needed, for example, to correctly set the end-of-stream
  102304. * marker in Ogg FLAC.
  102305. *
  102306. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102307. * not really any reason to change it.
  102308. */
  102309. static const unsigned OVERREAD_ = 1;
  102310. /***********************************************************************
  102311. *
  102312. * Class constructor/destructor
  102313. *
  102314. */
  102315. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102316. {
  102317. FLAC__StreamEncoder *encoder;
  102318. unsigned i;
  102319. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102320. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102321. if(encoder == 0) {
  102322. return 0;
  102323. }
  102324. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102325. if(encoder->protected_ == 0) {
  102326. free(encoder);
  102327. return 0;
  102328. }
  102329. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102330. if(encoder->private_ == 0) {
  102331. free(encoder->protected_);
  102332. free(encoder);
  102333. return 0;
  102334. }
  102335. encoder->private_->frame = FLAC__bitwriter_new();
  102336. if(encoder->private_->frame == 0) {
  102337. free(encoder->private_);
  102338. free(encoder->protected_);
  102339. free(encoder);
  102340. return 0;
  102341. }
  102342. encoder->private_->file = 0;
  102343. set_defaults_enc(encoder);
  102344. encoder->private_->is_being_deleted = false;
  102345. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102346. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102347. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102348. }
  102349. for(i = 0; i < 2; i++) {
  102350. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102351. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102352. }
  102353. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102354. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102355. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102356. }
  102357. for(i = 0; i < 2; i++) {
  102358. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102359. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102360. }
  102361. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102362. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102363. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102364. }
  102365. for(i = 0; i < 2; i++) {
  102366. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102367. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102368. }
  102369. for(i = 0; i < 2; i++)
  102370. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102371. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102372. return encoder;
  102373. }
  102374. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102375. {
  102376. unsigned i;
  102377. FLAC__ASSERT(0 != encoder);
  102378. FLAC__ASSERT(0 != encoder->protected_);
  102379. FLAC__ASSERT(0 != encoder->private_);
  102380. FLAC__ASSERT(0 != encoder->private_->frame);
  102381. encoder->private_->is_being_deleted = true;
  102382. (void)FLAC__stream_encoder_finish(encoder);
  102383. if(0 != encoder->private_->verify.decoder)
  102384. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102385. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102386. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102387. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102388. }
  102389. for(i = 0; i < 2; i++) {
  102390. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102391. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102392. }
  102393. for(i = 0; i < 2; i++)
  102394. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102395. FLAC__bitwriter_delete(encoder->private_->frame);
  102396. free(encoder->private_);
  102397. free(encoder->protected_);
  102398. free(encoder);
  102399. }
  102400. /***********************************************************************
  102401. *
  102402. * Public class methods
  102403. *
  102404. ***********************************************************************/
  102405. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102406. FLAC__StreamEncoder *encoder,
  102407. FLAC__StreamEncoderReadCallback read_callback,
  102408. FLAC__StreamEncoderWriteCallback write_callback,
  102409. FLAC__StreamEncoderSeekCallback seek_callback,
  102410. FLAC__StreamEncoderTellCallback tell_callback,
  102411. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102412. void *client_data,
  102413. FLAC__bool is_ogg
  102414. )
  102415. {
  102416. unsigned i;
  102417. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102418. FLAC__ASSERT(0 != encoder);
  102419. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102420. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102421. #if !FLAC__HAS_OGG
  102422. if(is_ogg)
  102423. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102424. #endif
  102425. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102426. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102427. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102428. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102429. if(encoder->protected_->channels != 2) {
  102430. encoder->protected_->do_mid_side_stereo = false;
  102431. encoder->protected_->loose_mid_side_stereo = false;
  102432. }
  102433. else if(!encoder->protected_->do_mid_side_stereo)
  102434. encoder->protected_->loose_mid_side_stereo = false;
  102435. if(encoder->protected_->bits_per_sample >= 32)
  102436. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102437. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102438. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102439. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102440. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102441. if(encoder->protected_->blocksize == 0) {
  102442. if(encoder->protected_->max_lpc_order == 0)
  102443. encoder->protected_->blocksize = 1152;
  102444. else
  102445. encoder->protected_->blocksize = 4096;
  102446. }
  102447. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102448. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102449. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102450. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102451. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102452. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102453. if(encoder->protected_->qlp_coeff_precision == 0) {
  102454. if(encoder->protected_->bits_per_sample < 16) {
  102455. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102456. /* @@@ until then we'll make a guess */
  102457. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102458. }
  102459. else if(encoder->protected_->bits_per_sample == 16) {
  102460. if(encoder->protected_->blocksize <= 192)
  102461. encoder->protected_->qlp_coeff_precision = 7;
  102462. else if(encoder->protected_->blocksize <= 384)
  102463. encoder->protected_->qlp_coeff_precision = 8;
  102464. else if(encoder->protected_->blocksize <= 576)
  102465. encoder->protected_->qlp_coeff_precision = 9;
  102466. else if(encoder->protected_->blocksize <= 1152)
  102467. encoder->protected_->qlp_coeff_precision = 10;
  102468. else if(encoder->protected_->blocksize <= 2304)
  102469. encoder->protected_->qlp_coeff_precision = 11;
  102470. else if(encoder->protected_->blocksize <= 4608)
  102471. encoder->protected_->qlp_coeff_precision = 12;
  102472. else
  102473. encoder->protected_->qlp_coeff_precision = 13;
  102474. }
  102475. else {
  102476. if(encoder->protected_->blocksize <= 384)
  102477. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102478. else if(encoder->protected_->blocksize <= 1152)
  102479. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102480. else
  102481. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102482. }
  102483. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102484. }
  102485. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102486. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102487. if(encoder->protected_->streamable_subset) {
  102488. if(
  102489. encoder->protected_->blocksize != 192 &&
  102490. encoder->protected_->blocksize != 576 &&
  102491. encoder->protected_->blocksize != 1152 &&
  102492. encoder->protected_->blocksize != 2304 &&
  102493. encoder->protected_->blocksize != 4608 &&
  102494. encoder->protected_->blocksize != 256 &&
  102495. encoder->protected_->blocksize != 512 &&
  102496. encoder->protected_->blocksize != 1024 &&
  102497. encoder->protected_->blocksize != 2048 &&
  102498. encoder->protected_->blocksize != 4096 &&
  102499. encoder->protected_->blocksize != 8192 &&
  102500. encoder->protected_->blocksize != 16384
  102501. )
  102502. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102503. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102504. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102505. if(
  102506. encoder->protected_->bits_per_sample != 8 &&
  102507. encoder->protected_->bits_per_sample != 12 &&
  102508. encoder->protected_->bits_per_sample != 16 &&
  102509. encoder->protected_->bits_per_sample != 20 &&
  102510. encoder->protected_->bits_per_sample != 24
  102511. )
  102512. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102513. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102514. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102515. if(
  102516. encoder->protected_->sample_rate <= 48000 &&
  102517. (
  102518. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102519. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102520. )
  102521. ) {
  102522. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102523. }
  102524. }
  102525. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102526. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102527. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102528. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102529. #if FLAC__HAS_OGG
  102530. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102531. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102532. unsigned i;
  102533. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102534. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102535. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102536. for( ; i > 0; i--)
  102537. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102538. encoder->protected_->metadata[0] = vc;
  102539. break;
  102540. }
  102541. }
  102542. }
  102543. #endif
  102544. /* keep track of any SEEKTABLE block */
  102545. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102546. unsigned i;
  102547. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102548. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102549. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102550. break; /* take only the first one */
  102551. }
  102552. }
  102553. }
  102554. /* validate metadata */
  102555. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102556. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102557. metadata_has_seektable = false;
  102558. metadata_has_vorbis_comment = false;
  102559. metadata_picture_has_type1 = false;
  102560. metadata_picture_has_type2 = false;
  102561. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102562. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102563. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102564. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102565. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102566. if(metadata_has_seektable) /* only one is allowed */
  102567. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102568. metadata_has_seektable = true;
  102569. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102570. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102571. }
  102572. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102573. if(metadata_has_vorbis_comment) /* only one is allowed */
  102574. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102575. metadata_has_vorbis_comment = true;
  102576. }
  102577. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102578. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102579. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102580. }
  102581. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102582. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102583. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102584. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102585. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102586. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102587. metadata_picture_has_type1 = true;
  102588. /* standard icon must be 32x32 pixel PNG */
  102589. if(
  102590. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102591. (
  102592. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102593. m->data.picture.width != 32 ||
  102594. m->data.picture.height != 32
  102595. )
  102596. )
  102597. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102598. }
  102599. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102600. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102601. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102602. metadata_picture_has_type2 = true;
  102603. }
  102604. }
  102605. }
  102606. encoder->private_->input_capacity = 0;
  102607. for(i = 0; i < encoder->protected_->channels; i++) {
  102608. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102609. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102610. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102611. #endif
  102612. }
  102613. for(i = 0; i < 2; i++) {
  102614. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102615. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102616. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102617. #endif
  102618. }
  102619. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102620. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102621. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102622. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102623. #endif
  102624. for(i = 0; i < encoder->protected_->channels; i++) {
  102625. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102626. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102627. encoder->private_->best_subframe[i] = 0;
  102628. }
  102629. for(i = 0; i < 2; i++) {
  102630. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102631. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102632. encoder->private_->best_subframe_mid_side[i] = 0;
  102633. }
  102634. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102635. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102636. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102637. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102638. #else
  102639. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102640. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102641. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102642. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102643. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102644. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102645. 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);
  102646. #endif
  102647. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102648. encoder->private_->loose_mid_side_stereo_frames = 1;
  102649. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102650. encoder->private_->current_sample_number = 0;
  102651. encoder->private_->current_frame_number = 0;
  102652. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102653. 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? */
  102654. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102655. /*
  102656. * get the CPU info and set the function pointers
  102657. */
  102658. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102659. /* first default to the non-asm routines */
  102660. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102661. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102662. #endif
  102663. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102664. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102665. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102666. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102667. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102668. #endif
  102669. /* now override with asm where appropriate */
  102670. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102671. # ifndef FLAC__NO_ASM
  102672. if(encoder->private_->cpuinfo.use_asm) {
  102673. # ifdef FLAC__CPU_IA32
  102674. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102675. # ifdef FLAC__HAS_NASM
  102676. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102677. if(encoder->protected_->max_lpc_order < 4)
  102678. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102679. else if(encoder->protected_->max_lpc_order < 8)
  102680. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102681. else if(encoder->protected_->max_lpc_order < 12)
  102682. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102683. else
  102684. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102685. }
  102686. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102687. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102688. else
  102689. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102690. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102691. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102692. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102693. }
  102694. else {
  102695. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102696. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102697. }
  102698. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102699. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102700. # endif /* FLAC__HAS_NASM */
  102701. # endif /* FLAC__CPU_IA32 */
  102702. }
  102703. # endif /* !FLAC__NO_ASM */
  102704. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102705. /* finally override based on wide-ness if necessary */
  102706. if(encoder->private_->use_wide_by_block) {
  102707. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102708. }
  102709. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102710. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102711. #if FLAC__HAS_OGG
  102712. encoder->private_->is_ogg = is_ogg;
  102713. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102714. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102715. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102716. }
  102717. #endif
  102718. encoder->private_->read_callback = read_callback;
  102719. encoder->private_->write_callback = write_callback;
  102720. encoder->private_->seek_callback = seek_callback;
  102721. encoder->private_->tell_callback = tell_callback;
  102722. encoder->private_->metadata_callback = metadata_callback;
  102723. encoder->private_->client_data = client_data;
  102724. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102725. /* the above function sets the state for us in case of an error */
  102726. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102727. }
  102728. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102729. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102730. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102731. }
  102732. /*
  102733. * Set up the verify stuff if necessary
  102734. */
  102735. if(encoder->protected_->verify) {
  102736. /*
  102737. * First, set up the fifo which will hold the
  102738. * original signal to compare against
  102739. */
  102740. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102741. for(i = 0; i < encoder->protected_->channels; i++) {
  102742. 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))) {
  102743. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102744. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102745. }
  102746. }
  102747. encoder->private_->verify.input_fifo.tail = 0;
  102748. /*
  102749. * Now set up a stream decoder for verification
  102750. */
  102751. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102752. if(0 == encoder->private_->verify.decoder) {
  102753. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102754. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102755. }
  102756. 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) {
  102757. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102758. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102759. }
  102760. }
  102761. encoder->private_->verify.error_stats.absolute_sample = 0;
  102762. encoder->private_->verify.error_stats.frame_number = 0;
  102763. encoder->private_->verify.error_stats.channel = 0;
  102764. encoder->private_->verify.error_stats.sample = 0;
  102765. encoder->private_->verify.error_stats.expected = 0;
  102766. encoder->private_->verify.error_stats.got = 0;
  102767. /*
  102768. * These must be done before we write any metadata, because that
  102769. * calls the write_callback, which uses these values.
  102770. */
  102771. encoder->private_->first_seekpoint_to_check = 0;
  102772. encoder->private_->samples_written = 0;
  102773. encoder->protected_->streaminfo_offset = 0;
  102774. encoder->protected_->seektable_offset = 0;
  102775. encoder->protected_->audio_offset = 0;
  102776. /*
  102777. * write the stream header
  102778. */
  102779. if(encoder->protected_->verify)
  102780. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102781. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102782. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102783. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102784. }
  102785. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102786. /* the above function sets the state for us in case of an error */
  102787. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102788. }
  102789. /*
  102790. * write the STREAMINFO metadata block
  102791. */
  102792. if(encoder->protected_->verify)
  102793. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102794. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102795. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102796. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102797. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102798. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102799. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102800. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102801. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102802. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102803. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102804. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102805. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102806. if(encoder->protected_->do_md5)
  102807. FLAC__MD5Init(&encoder->private_->md5context);
  102808. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102809. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102810. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102811. }
  102812. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102813. /* the above function sets the state for us in case of an error */
  102814. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102815. }
  102816. /*
  102817. * Now that the STREAMINFO block is written, we can init this to an
  102818. * absurdly-high value...
  102819. */
  102820. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102821. /* ... and clear this to 0 */
  102822. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102823. /*
  102824. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102825. * if not, we will write an empty one (FLAC__add_metadata_block()
  102826. * automatically supplies the vendor string).
  102827. *
  102828. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102829. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102830. * true it will have already insured that the metadata list is properly
  102831. * ordered.)
  102832. */
  102833. if(!metadata_has_vorbis_comment) {
  102834. FLAC__StreamMetadata vorbis_comment;
  102835. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102836. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102837. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102838. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102839. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102840. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102841. vorbis_comment.data.vorbis_comment.comments = 0;
  102842. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102843. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102844. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102845. }
  102846. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102847. /* the above function sets the state for us in case of an error */
  102848. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102849. }
  102850. }
  102851. /*
  102852. * write the user's metadata blocks
  102853. */
  102854. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102855. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102856. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102857. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102858. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102859. }
  102860. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102861. /* the above function sets the state for us in case of an error */
  102862. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102863. }
  102864. }
  102865. /* now that all the metadata is written, we save the stream offset */
  102866. 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 */
  102867. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102868. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102869. }
  102870. if(encoder->protected_->verify)
  102871. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102872. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102873. }
  102874. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102875. FLAC__StreamEncoder *encoder,
  102876. FLAC__StreamEncoderWriteCallback write_callback,
  102877. FLAC__StreamEncoderSeekCallback seek_callback,
  102878. FLAC__StreamEncoderTellCallback tell_callback,
  102879. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102880. void *client_data
  102881. )
  102882. {
  102883. return init_stream_internal_enc(
  102884. encoder,
  102885. /*read_callback=*/0,
  102886. write_callback,
  102887. seek_callback,
  102888. tell_callback,
  102889. metadata_callback,
  102890. client_data,
  102891. /*is_ogg=*/false
  102892. );
  102893. }
  102894. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102895. FLAC__StreamEncoder *encoder,
  102896. FLAC__StreamEncoderReadCallback read_callback,
  102897. FLAC__StreamEncoderWriteCallback write_callback,
  102898. FLAC__StreamEncoderSeekCallback seek_callback,
  102899. FLAC__StreamEncoderTellCallback tell_callback,
  102900. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102901. void *client_data
  102902. )
  102903. {
  102904. return init_stream_internal_enc(
  102905. encoder,
  102906. read_callback,
  102907. write_callback,
  102908. seek_callback,
  102909. tell_callback,
  102910. metadata_callback,
  102911. client_data,
  102912. /*is_ogg=*/true
  102913. );
  102914. }
  102915. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102916. FLAC__StreamEncoder *encoder,
  102917. FILE *file,
  102918. FLAC__StreamEncoderProgressCallback progress_callback,
  102919. void *client_data,
  102920. FLAC__bool is_ogg
  102921. )
  102922. {
  102923. FLAC__StreamEncoderInitStatus init_status;
  102924. FLAC__ASSERT(0 != encoder);
  102925. FLAC__ASSERT(0 != file);
  102926. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102927. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102928. /* double protection */
  102929. if(file == 0) {
  102930. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102931. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102932. }
  102933. /*
  102934. * To make sure that our file does not go unclosed after an error, we
  102935. * must assign the FILE pointer before any further error can occur in
  102936. * this routine.
  102937. */
  102938. if(file == stdout)
  102939. file = get_binary_stdout_(); /* just to be safe */
  102940. encoder->private_->file = file;
  102941. encoder->private_->progress_callback = progress_callback;
  102942. encoder->private_->bytes_written = 0;
  102943. encoder->private_->samples_written = 0;
  102944. encoder->private_->frames_written = 0;
  102945. init_status = init_stream_internal_enc(
  102946. encoder,
  102947. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102948. file_write_callback_,
  102949. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102950. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102951. /*metadata_callback=*/0,
  102952. client_data,
  102953. is_ogg
  102954. );
  102955. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102956. /* the above function sets the state for us in case of an error */
  102957. return init_status;
  102958. }
  102959. {
  102960. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102961. FLAC__ASSERT(blocksize != 0);
  102962. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102963. }
  102964. return init_status;
  102965. }
  102966. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102967. FLAC__StreamEncoder *encoder,
  102968. FILE *file,
  102969. FLAC__StreamEncoderProgressCallback progress_callback,
  102970. void *client_data
  102971. )
  102972. {
  102973. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102974. }
  102975. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102976. FLAC__StreamEncoder *encoder,
  102977. FILE *file,
  102978. FLAC__StreamEncoderProgressCallback progress_callback,
  102979. void *client_data
  102980. )
  102981. {
  102982. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102983. }
  102984. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102985. FLAC__StreamEncoder *encoder,
  102986. const char *filename,
  102987. FLAC__StreamEncoderProgressCallback progress_callback,
  102988. void *client_data,
  102989. FLAC__bool is_ogg
  102990. )
  102991. {
  102992. FILE *file;
  102993. FLAC__ASSERT(0 != encoder);
  102994. /*
  102995. * To make sure that our file does not go unclosed after an error, we
  102996. * have to do the same entrance checks here that are later performed
  102997. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102998. */
  102999. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103000. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103001. file = filename? fopen(filename, "w+b") : stdout;
  103002. if(file == 0) {
  103003. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103004. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103005. }
  103006. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103007. }
  103008. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103009. FLAC__StreamEncoder *encoder,
  103010. const char *filename,
  103011. FLAC__StreamEncoderProgressCallback progress_callback,
  103012. void *client_data
  103013. )
  103014. {
  103015. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103016. }
  103017. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103018. FLAC__StreamEncoder *encoder,
  103019. const char *filename,
  103020. FLAC__StreamEncoderProgressCallback progress_callback,
  103021. void *client_data
  103022. )
  103023. {
  103024. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103025. }
  103026. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103027. {
  103028. FLAC__bool error = false;
  103029. FLAC__ASSERT(0 != encoder);
  103030. FLAC__ASSERT(0 != encoder->private_);
  103031. FLAC__ASSERT(0 != encoder->protected_);
  103032. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103033. return true;
  103034. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103035. if(encoder->private_->current_sample_number != 0) {
  103036. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103037. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103038. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103039. error = true;
  103040. }
  103041. }
  103042. if(encoder->protected_->do_md5)
  103043. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103044. if(!encoder->private_->is_being_deleted) {
  103045. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103046. if(encoder->private_->seek_callback) {
  103047. #if FLAC__HAS_OGG
  103048. if(encoder->private_->is_ogg)
  103049. update_ogg_metadata_(encoder);
  103050. else
  103051. #endif
  103052. update_metadata_(encoder);
  103053. /* check if an error occurred while updating metadata */
  103054. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103055. error = true;
  103056. }
  103057. if(encoder->private_->metadata_callback)
  103058. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103059. }
  103060. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103061. if(!error)
  103062. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103063. error = true;
  103064. }
  103065. }
  103066. if(0 != encoder->private_->file) {
  103067. if(encoder->private_->file != stdout)
  103068. fclose(encoder->private_->file);
  103069. encoder->private_->file = 0;
  103070. }
  103071. #if FLAC__HAS_OGG
  103072. if(encoder->private_->is_ogg)
  103073. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103074. #endif
  103075. free_(encoder);
  103076. set_defaults_enc(encoder);
  103077. if(!error)
  103078. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103079. return !error;
  103080. }
  103081. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103082. {
  103083. FLAC__ASSERT(0 != encoder);
  103084. FLAC__ASSERT(0 != encoder->private_);
  103085. FLAC__ASSERT(0 != encoder->protected_);
  103086. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103087. return false;
  103088. #if FLAC__HAS_OGG
  103089. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103090. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103091. return true;
  103092. #else
  103093. (void)value;
  103094. return false;
  103095. #endif
  103096. }
  103097. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103098. {
  103099. FLAC__ASSERT(0 != encoder);
  103100. FLAC__ASSERT(0 != encoder->private_);
  103101. FLAC__ASSERT(0 != encoder->protected_);
  103102. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103103. return false;
  103104. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103105. encoder->protected_->verify = value;
  103106. #endif
  103107. return true;
  103108. }
  103109. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103110. {
  103111. FLAC__ASSERT(0 != encoder);
  103112. FLAC__ASSERT(0 != encoder->private_);
  103113. FLAC__ASSERT(0 != encoder->protected_);
  103114. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103115. return false;
  103116. encoder->protected_->streamable_subset = value;
  103117. return true;
  103118. }
  103119. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103120. {
  103121. FLAC__ASSERT(0 != encoder);
  103122. FLAC__ASSERT(0 != encoder->private_);
  103123. FLAC__ASSERT(0 != encoder->protected_);
  103124. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103125. return false;
  103126. encoder->protected_->do_md5 = value;
  103127. return true;
  103128. }
  103129. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103130. {
  103131. FLAC__ASSERT(0 != encoder);
  103132. FLAC__ASSERT(0 != encoder->private_);
  103133. FLAC__ASSERT(0 != encoder->protected_);
  103134. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103135. return false;
  103136. encoder->protected_->channels = value;
  103137. return true;
  103138. }
  103139. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103140. {
  103141. FLAC__ASSERT(0 != encoder);
  103142. FLAC__ASSERT(0 != encoder->private_);
  103143. FLAC__ASSERT(0 != encoder->protected_);
  103144. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103145. return false;
  103146. encoder->protected_->bits_per_sample = value;
  103147. return true;
  103148. }
  103149. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103150. {
  103151. FLAC__ASSERT(0 != encoder);
  103152. FLAC__ASSERT(0 != encoder->private_);
  103153. FLAC__ASSERT(0 != encoder->protected_);
  103154. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103155. return false;
  103156. encoder->protected_->sample_rate = value;
  103157. return true;
  103158. }
  103159. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103160. {
  103161. FLAC__bool ok = true;
  103162. FLAC__ASSERT(0 != encoder);
  103163. FLAC__ASSERT(0 != encoder->private_);
  103164. FLAC__ASSERT(0 != encoder->protected_);
  103165. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103166. return false;
  103167. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103168. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103169. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103170. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103171. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103172. #if 0
  103173. /* was: */
  103174. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103175. /* but it's too hard to specify the string in a locale-specific way */
  103176. #else
  103177. encoder->protected_->num_apodizations = 1;
  103178. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103179. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103180. #endif
  103181. #endif
  103182. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103183. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103184. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103185. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103186. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103187. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103188. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103189. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103190. return ok;
  103191. }
  103192. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103193. {
  103194. FLAC__ASSERT(0 != encoder);
  103195. FLAC__ASSERT(0 != encoder->private_);
  103196. FLAC__ASSERT(0 != encoder->protected_);
  103197. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103198. return false;
  103199. encoder->protected_->blocksize = value;
  103200. return true;
  103201. }
  103202. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103203. {
  103204. FLAC__ASSERT(0 != encoder);
  103205. FLAC__ASSERT(0 != encoder->private_);
  103206. FLAC__ASSERT(0 != encoder->protected_);
  103207. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103208. return false;
  103209. encoder->protected_->do_mid_side_stereo = value;
  103210. return true;
  103211. }
  103212. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103213. {
  103214. FLAC__ASSERT(0 != encoder);
  103215. FLAC__ASSERT(0 != encoder->private_);
  103216. FLAC__ASSERT(0 != encoder->protected_);
  103217. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103218. return false;
  103219. encoder->protected_->loose_mid_side_stereo = value;
  103220. return true;
  103221. }
  103222. /*@@@@add to tests*/
  103223. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103224. {
  103225. FLAC__ASSERT(0 != encoder);
  103226. FLAC__ASSERT(0 != encoder->private_);
  103227. FLAC__ASSERT(0 != encoder->protected_);
  103228. FLAC__ASSERT(0 != specification);
  103229. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103230. return false;
  103231. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103232. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103233. #else
  103234. encoder->protected_->num_apodizations = 0;
  103235. while(1) {
  103236. const char *s = strchr(specification, ';');
  103237. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103238. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103239. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103240. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103241. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103242. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103243. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103244. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103245. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103246. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103247. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103248. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103249. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103250. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103251. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103252. if (stddev > 0.0 && stddev <= 0.5) {
  103253. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103254. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103255. }
  103256. }
  103257. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103258. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103259. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103260. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103261. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103262. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103263. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103264. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103265. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103266. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103267. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103268. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103269. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103270. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103271. if (p >= 0.0 && p <= 1.0) {
  103272. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103273. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103274. }
  103275. }
  103276. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103277. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103278. if (encoder->protected_->num_apodizations == 32)
  103279. break;
  103280. if (s)
  103281. specification = s+1;
  103282. else
  103283. break;
  103284. }
  103285. if(encoder->protected_->num_apodizations == 0) {
  103286. encoder->protected_->num_apodizations = 1;
  103287. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103288. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103289. }
  103290. #endif
  103291. return true;
  103292. }
  103293. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103294. {
  103295. FLAC__ASSERT(0 != encoder);
  103296. FLAC__ASSERT(0 != encoder->private_);
  103297. FLAC__ASSERT(0 != encoder->protected_);
  103298. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103299. return false;
  103300. encoder->protected_->max_lpc_order = value;
  103301. return true;
  103302. }
  103303. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103304. {
  103305. FLAC__ASSERT(0 != encoder);
  103306. FLAC__ASSERT(0 != encoder->private_);
  103307. FLAC__ASSERT(0 != encoder->protected_);
  103308. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103309. return false;
  103310. encoder->protected_->qlp_coeff_precision = value;
  103311. return true;
  103312. }
  103313. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103314. {
  103315. FLAC__ASSERT(0 != encoder);
  103316. FLAC__ASSERT(0 != encoder->private_);
  103317. FLAC__ASSERT(0 != encoder->protected_);
  103318. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103319. return false;
  103320. encoder->protected_->do_qlp_coeff_prec_search = value;
  103321. return true;
  103322. }
  103323. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103324. {
  103325. FLAC__ASSERT(0 != encoder);
  103326. FLAC__ASSERT(0 != encoder->private_);
  103327. FLAC__ASSERT(0 != encoder->protected_);
  103328. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103329. return false;
  103330. #if 0
  103331. /*@@@ deprecated: */
  103332. encoder->protected_->do_escape_coding = value;
  103333. #else
  103334. (void)value;
  103335. #endif
  103336. return true;
  103337. }
  103338. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103339. {
  103340. FLAC__ASSERT(0 != encoder);
  103341. FLAC__ASSERT(0 != encoder->private_);
  103342. FLAC__ASSERT(0 != encoder->protected_);
  103343. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103344. return false;
  103345. encoder->protected_->do_exhaustive_model_search = value;
  103346. return true;
  103347. }
  103348. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103349. {
  103350. FLAC__ASSERT(0 != encoder);
  103351. FLAC__ASSERT(0 != encoder->private_);
  103352. FLAC__ASSERT(0 != encoder->protected_);
  103353. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103354. return false;
  103355. encoder->protected_->min_residual_partition_order = value;
  103356. return true;
  103357. }
  103358. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103359. {
  103360. FLAC__ASSERT(0 != encoder);
  103361. FLAC__ASSERT(0 != encoder->private_);
  103362. FLAC__ASSERT(0 != encoder->protected_);
  103363. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103364. return false;
  103365. encoder->protected_->max_residual_partition_order = value;
  103366. return true;
  103367. }
  103368. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103369. {
  103370. FLAC__ASSERT(0 != encoder);
  103371. FLAC__ASSERT(0 != encoder->private_);
  103372. FLAC__ASSERT(0 != encoder->protected_);
  103373. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103374. return false;
  103375. #if 0
  103376. /*@@@ deprecated: */
  103377. encoder->protected_->rice_parameter_search_dist = value;
  103378. #else
  103379. (void)value;
  103380. #endif
  103381. return true;
  103382. }
  103383. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103384. {
  103385. FLAC__ASSERT(0 != encoder);
  103386. FLAC__ASSERT(0 != encoder->private_);
  103387. FLAC__ASSERT(0 != encoder->protected_);
  103388. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103389. return false;
  103390. encoder->protected_->total_samples_estimate = value;
  103391. return true;
  103392. }
  103393. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103394. {
  103395. FLAC__ASSERT(0 != encoder);
  103396. FLAC__ASSERT(0 != encoder->private_);
  103397. FLAC__ASSERT(0 != encoder->protected_);
  103398. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103399. return false;
  103400. if(0 == metadata)
  103401. num_blocks = 0;
  103402. if(0 == num_blocks)
  103403. metadata = 0;
  103404. /* realloc() does not do exactly what we want so... */
  103405. if(encoder->protected_->metadata) {
  103406. free(encoder->protected_->metadata);
  103407. encoder->protected_->metadata = 0;
  103408. encoder->protected_->num_metadata_blocks = 0;
  103409. }
  103410. if(num_blocks) {
  103411. FLAC__StreamMetadata **m;
  103412. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103413. return false;
  103414. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103415. encoder->protected_->metadata = m;
  103416. encoder->protected_->num_metadata_blocks = num_blocks;
  103417. }
  103418. #if FLAC__HAS_OGG
  103419. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103420. return false;
  103421. #endif
  103422. return true;
  103423. }
  103424. /*
  103425. * These three functions are not static, but not publically exposed in
  103426. * include/FLAC/ either. They are used by the test suite.
  103427. */
  103428. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103429. {
  103430. FLAC__ASSERT(0 != encoder);
  103431. FLAC__ASSERT(0 != encoder->private_);
  103432. FLAC__ASSERT(0 != encoder->protected_);
  103433. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103434. return false;
  103435. encoder->private_->disable_constant_subframes = value;
  103436. return true;
  103437. }
  103438. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103439. {
  103440. FLAC__ASSERT(0 != encoder);
  103441. FLAC__ASSERT(0 != encoder->private_);
  103442. FLAC__ASSERT(0 != encoder->protected_);
  103443. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103444. return false;
  103445. encoder->private_->disable_fixed_subframes = value;
  103446. return true;
  103447. }
  103448. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103449. {
  103450. FLAC__ASSERT(0 != encoder);
  103451. FLAC__ASSERT(0 != encoder->private_);
  103452. FLAC__ASSERT(0 != encoder->protected_);
  103453. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103454. return false;
  103455. encoder->private_->disable_verbatim_subframes = value;
  103456. return true;
  103457. }
  103458. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103459. {
  103460. FLAC__ASSERT(0 != encoder);
  103461. FLAC__ASSERT(0 != encoder->private_);
  103462. FLAC__ASSERT(0 != encoder->protected_);
  103463. return encoder->protected_->state;
  103464. }
  103465. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103466. {
  103467. FLAC__ASSERT(0 != encoder);
  103468. FLAC__ASSERT(0 != encoder->private_);
  103469. FLAC__ASSERT(0 != encoder->protected_);
  103470. if(encoder->protected_->verify)
  103471. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103472. else
  103473. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103474. }
  103475. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103476. {
  103477. FLAC__ASSERT(0 != encoder);
  103478. FLAC__ASSERT(0 != encoder->private_);
  103479. FLAC__ASSERT(0 != encoder->protected_);
  103480. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103481. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103482. else
  103483. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103484. }
  103485. 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)
  103486. {
  103487. FLAC__ASSERT(0 != encoder);
  103488. FLAC__ASSERT(0 != encoder->private_);
  103489. FLAC__ASSERT(0 != encoder->protected_);
  103490. if(0 != absolute_sample)
  103491. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103492. if(0 != frame_number)
  103493. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103494. if(0 != channel)
  103495. *channel = encoder->private_->verify.error_stats.channel;
  103496. if(0 != sample)
  103497. *sample = encoder->private_->verify.error_stats.sample;
  103498. if(0 != expected)
  103499. *expected = encoder->private_->verify.error_stats.expected;
  103500. if(0 != got)
  103501. *got = encoder->private_->verify.error_stats.got;
  103502. }
  103503. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103504. {
  103505. FLAC__ASSERT(0 != encoder);
  103506. FLAC__ASSERT(0 != encoder->private_);
  103507. FLAC__ASSERT(0 != encoder->protected_);
  103508. return encoder->protected_->verify;
  103509. }
  103510. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103511. {
  103512. FLAC__ASSERT(0 != encoder);
  103513. FLAC__ASSERT(0 != encoder->private_);
  103514. FLAC__ASSERT(0 != encoder->protected_);
  103515. return encoder->protected_->streamable_subset;
  103516. }
  103517. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103518. {
  103519. FLAC__ASSERT(0 != encoder);
  103520. FLAC__ASSERT(0 != encoder->private_);
  103521. FLAC__ASSERT(0 != encoder->protected_);
  103522. return encoder->protected_->do_md5;
  103523. }
  103524. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103525. {
  103526. FLAC__ASSERT(0 != encoder);
  103527. FLAC__ASSERT(0 != encoder->private_);
  103528. FLAC__ASSERT(0 != encoder->protected_);
  103529. return encoder->protected_->channels;
  103530. }
  103531. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103532. {
  103533. FLAC__ASSERT(0 != encoder);
  103534. FLAC__ASSERT(0 != encoder->private_);
  103535. FLAC__ASSERT(0 != encoder->protected_);
  103536. return encoder->protected_->bits_per_sample;
  103537. }
  103538. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103539. {
  103540. FLAC__ASSERT(0 != encoder);
  103541. FLAC__ASSERT(0 != encoder->private_);
  103542. FLAC__ASSERT(0 != encoder->protected_);
  103543. return encoder->protected_->sample_rate;
  103544. }
  103545. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103546. {
  103547. FLAC__ASSERT(0 != encoder);
  103548. FLAC__ASSERT(0 != encoder->private_);
  103549. FLAC__ASSERT(0 != encoder->protected_);
  103550. return encoder->protected_->blocksize;
  103551. }
  103552. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103553. {
  103554. FLAC__ASSERT(0 != encoder);
  103555. FLAC__ASSERT(0 != encoder->private_);
  103556. FLAC__ASSERT(0 != encoder->protected_);
  103557. return encoder->protected_->do_mid_side_stereo;
  103558. }
  103559. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103560. {
  103561. FLAC__ASSERT(0 != encoder);
  103562. FLAC__ASSERT(0 != encoder->private_);
  103563. FLAC__ASSERT(0 != encoder->protected_);
  103564. return encoder->protected_->loose_mid_side_stereo;
  103565. }
  103566. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103567. {
  103568. FLAC__ASSERT(0 != encoder);
  103569. FLAC__ASSERT(0 != encoder->private_);
  103570. FLAC__ASSERT(0 != encoder->protected_);
  103571. return encoder->protected_->max_lpc_order;
  103572. }
  103573. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103574. {
  103575. FLAC__ASSERT(0 != encoder);
  103576. FLAC__ASSERT(0 != encoder->private_);
  103577. FLAC__ASSERT(0 != encoder->protected_);
  103578. return encoder->protected_->qlp_coeff_precision;
  103579. }
  103580. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103581. {
  103582. FLAC__ASSERT(0 != encoder);
  103583. FLAC__ASSERT(0 != encoder->private_);
  103584. FLAC__ASSERT(0 != encoder->protected_);
  103585. return encoder->protected_->do_qlp_coeff_prec_search;
  103586. }
  103587. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103588. {
  103589. FLAC__ASSERT(0 != encoder);
  103590. FLAC__ASSERT(0 != encoder->private_);
  103591. FLAC__ASSERT(0 != encoder->protected_);
  103592. return encoder->protected_->do_escape_coding;
  103593. }
  103594. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103595. {
  103596. FLAC__ASSERT(0 != encoder);
  103597. FLAC__ASSERT(0 != encoder->private_);
  103598. FLAC__ASSERT(0 != encoder->protected_);
  103599. return encoder->protected_->do_exhaustive_model_search;
  103600. }
  103601. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103602. {
  103603. FLAC__ASSERT(0 != encoder);
  103604. FLAC__ASSERT(0 != encoder->private_);
  103605. FLAC__ASSERT(0 != encoder->protected_);
  103606. return encoder->protected_->min_residual_partition_order;
  103607. }
  103608. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103609. {
  103610. FLAC__ASSERT(0 != encoder);
  103611. FLAC__ASSERT(0 != encoder->private_);
  103612. FLAC__ASSERT(0 != encoder->protected_);
  103613. return encoder->protected_->max_residual_partition_order;
  103614. }
  103615. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103616. {
  103617. FLAC__ASSERT(0 != encoder);
  103618. FLAC__ASSERT(0 != encoder->private_);
  103619. FLAC__ASSERT(0 != encoder->protected_);
  103620. return encoder->protected_->rice_parameter_search_dist;
  103621. }
  103622. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103623. {
  103624. FLAC__ASSERT(0 != encoder);
  103625. FLAC__ASSERT(0 != encoder->private_);
  103626. FLAC__ASSERT(0 != encoder->protected_);
  103627. return encoder->protected_->total_samples_estimate;
  103628. }
  103629. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103630. {
  103631. unsigned i, j = 0, channel;
  103632. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103633. FLAC__ASSERT(0 != encoder);
  103634. FLAC__ASSERT(0 != encoder->private_);
  103635. FLAC__ASSERT(0 != encoder->protected_);
  103636. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103637. do {
  103638. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103639. if(encoder->protected_->verify)
  103640. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103641. for(channel = 0; channel < channels; channel++)
  103642. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103643. if(encoder->protected_->do_mid_side_stereo) {
  103644. FLAC__ASSERT(channels == 2);
  103645. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103646. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103647. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103648. 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' ! */
  103649. }
  103650. }
  103651. else
  103652. j += n;
  103653. encoder->private_->current_sample_number += n;
  103654. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103655. if(encoder->private_->current_sample_number > blocksize) {
  103656. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103657. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103658. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103659. return false;
  103660. /* move unprocessed overread samples to beginnings of arrays */
  103661. for(channel = 0; channel < channels; channel++)
  103662. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103663. if(encoder->protected_->do_mid_side_stereo) {
  103664. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103665. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103666. }
  103667. encoder->private_->current_sample_number = 1;
  103668. }
  103669. } while(j < samples);
  103670. return true;
  103671. }
  103672. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103673. {
  103674. unsigned i, j, k, channel;
  103675. FLAC__int32 x, mid, side;
  103676. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103677. FLAC__ASSERT(0 != encoder);
  103678. FLAC__ASSERT(0 != encoder->private_);
  103679. FLAC__ASSERT(0 != encoder->protected_);
  103680. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103681. j = k = 0;
  103682. /*
  103683. * we have several flavors of the same basic loop, optimized for
  103684. * different conditions:
  103685. */
  103686. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103687. /*
  103688. * stereo coding: unroll channel loop
  103689. */
  103690. do {
  103691. if(encoder->protected_->verify)
  103692. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103693. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103694. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103695. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103696. x = buffer[k++];
  103697. encoder->private_->integer_signal[1][i] = x;
  103698. mid += x;
  103699. side -= x;
  103700. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103701. encoder->private_->integer_signal_mid_side[1][i] = side;
  103702. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103703. }
  103704. encoder->private_->current_sample_number = i;
  103705. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103706. if(i > blocksize) {
  103707. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103708. return false;
  103709. /* move unprocessed overread samples to beginnings of arrays */
  103710. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103711. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103712. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103713. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103714. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103715. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103716. encoder->private_->current_sample_number = 1;
  103717. }
  103718. } while(j < samples);
  103719. }
  103720. else {
  103721. /*
  103722. * independent channel coding: buffer each channel in inner loop
  103723. */
  103724. do {
  103725. if(encoder->protected_->verify)
  103726. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103727. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103728. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103729. for(channel = 0; channel < channels; channel++)
  103730. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103731. }
  103732. encoder->private_->current_sample_number = i;
  103733. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103734. if(i > blocksize) {
  103735. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103736. return false;
  103737. /* move unprocessed overread samples to beginnings of arrays */
  103738. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103739. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103740. for(channel = 0; channel < channels; channel++)
  103741. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103742. encoder->private_->current_sample_number = 1;
  103743. }
  103744. } while(j < samples);
  103745. }
  103746. return true;
  103747. }
  103748. /***********************************************************************
  103749. *
  103750. * Private class methods
  103751. *
  103752. ***********************************************************************/
  103753. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103754. {
  103755. FLAC__ASSERT(0 != encoder);
  103756. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103757. encoder->protected_->verify = true;
  103758. #else
  103759. encoder->protected_->verify = false;
  103760. #endif
  103761. encoder->protected_->streamable_subset = true;
  103762. encoder->protected_->do_md5 = true;
  103763. encoder->protected_->do_mid_side_stereo = false;
  103764. encoder->protected_->loose_mid_side_stereo = false;
  103765. encoder->protected_->channels = 2;
  103766. encoder->protected_->bits_per_sample = 16;
  103767. encoder->protected_->sample_rate = 44100;
  103768. encoder->protected_->blocksize = 0;
  103769. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103770. encoder->protected_->num_apodizations = 1;
  103771. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103772. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103773. #endif
  103774. encoder->protected_->max_lpc_order = 0;
  103775. encoder->protected_->qlp_coeff_precision = 0;
  103776. encoder->protected_->do_qlp_coeff_prec_search = false;
  103777. encoder->protected_->do_exhaustive_model_search = false;
  103778. encoder->protected_->do_escape_coding = false;
  103779. encoder->protected_->min_residual_partition_order = 0;
  103780. encoder->protected_->max_residual_partition_order = 0;
  103781. encoder->protected_->rice_parameter_search_dist = 0;
  103782. encoder->protected_->total_samples_estimate = 0;
  103783. encoder->protected_->metadata = 0;
  103784. encoder->protected_->num_metadata_blocks = 0;
  103785. encoder->private_->seek_table = 0;
  103786. encoder->private_->disable_constant_subframes = false;
  103787. encoder->private_->disable_fixed_subframes = false;
  103788. encoder->private_->disable_verbatim_subframes = false;
  103789. #if FLAC__HAS_OGG
  103790. encoder->private_->is_ogg = false;
  103791. #endif
  103792. encoder->private_->read_callback = 0;
  103793. encoder->private_->write_callback = 0;
  103794. encoder->private_->seek_callback = 0;
  103795. encoder->private_->tell_callback = 0;
  103796. encoder->private_->metadata_callback = 0;
  103797. encoder->private_->progress_callback = 0;
  103798. encoder->private_->client_data = 0;
  103799. #if FLAC__HAS_OGG
  103800. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103801. #endif
  103802. }
  103803. void free_(FLAC__StreamEncoder *encoder)
  103804. {
  103805. unsigned i, channel;
  103806. FLAC__ASSERT(0 != encoder);
  103807. if(encoder->protected_->metadata) {
  103808. free(encoder->protected_->metadata);
  103809. encoder->protected_->metadata = 0;
  103810. encoder->protected_->num_metadata_blocks = 0;
  103811. }
  103812. for(i = 0; i < encoder->protected_->channels; i++) {
  103813. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103814. free(encoder->private_->integer_signal_unaligned[i]);
  103815. encoder->private_->integer_signal_unaligned[i] = 0;
  103816. }
  103817. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103818. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103819. free(encoder->private_->real_signal_unaligned[i]);
  103820. encoder->private_->real_signal_unaligned[i] = 0;
  103821. }
  103822. #endif
  103823. }
  103824. for(i = 0; i < 2; i++) {
  103825. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103826. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103827. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103828. }
  103829. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103830. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103831. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103832. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103833. }
  103834. #endif
  103835. }
  103836. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103837. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103838. if(0 != encoder->private_->window_unaligned[i]) {
  103839. free(encoder->private_->window_unaligned[i]);
  103840. encoder->private_->window_unaligned[i] = 0;
  103841. }
  103842. }
  103843. if(0 != encoder->private_->windowed_signal_unaligned) {
  103844. free(encoder->private_->windowed_signal_unaligned);
  103845. encoder->private_->windowed_signal_unaligned = 0;
  103846. }
  103847. #endif
  103848. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103849. for(i = 0; i < 2; i++) {
  103850. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103851. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103852. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103853. }
  103854. }
  103855. }
  103856. for(channel = 0; channel < 2; channel++) {
  103857. for(i = 0; i < 2; i++) {
  103858. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103859. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103860. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103861. }
  103862. }
  103863. }
  103864. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103865. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103866. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103867. }
  103868. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103869. free(encoder->private_->raw_bits_per_partition_unaligned);
  103870. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103871. }
  103872. if(encoder->protected_->verify) {
  103873. for(i = 0; i < encoder->protected_->channels; i++) {
  103874. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103875. free(encoder->private_->verify.input_fifo.data[i]);
  103876. encoder->private_->verify.input_fifo.data[i] = 0;
  103877. }
  103878. }
  103879. }
  103880. FLAC__bitwriter_free(encoder->private_->frame);
  103881. }
  103882. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103883. {
  103884. FLAC__bool ok;
  103885. unsigned i, channel;
  103886. FLAC__ASSERT(new_blocksize > 0);
  103887. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103888. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103889. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103890. if(new_blocksize <= encoder->private_->input_capacity)
  103891. return true;
  103892. ok = true;
  103893. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103894. * requires that the input arrays (in our case the integer signals)
  103895. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103896. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103897. */
  103898. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103899. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103900. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103901. encoder->private_->integer_signal[i] += 4;
  103902. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103903. #if 0 /* @@@ currently unused */
  103904. if(encoder->protected_->max_lpc_order > 0)
  103905. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103906. #endif
  103907. #endif
  103908. }
  103909. for(i = 0; ok && i < 2; i++) {
  103910. 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]);
  103911. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103912. encoder->private_->integer_signal_mid_side[i] += 4;
  103913. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103914. #if 0 /* @@@ currently unused */
  103915. if(encoder->protected_->max_lpc_order > 0)
  103916. 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]);
  103917. #endif
  103918. #endif
  103919. }
  103920. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103921. if(ok && encoder->protected_->max_lpc_order > 0) {
  103922. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103923. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103924. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103925. }
  103926. #endif
  103927. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103928. for(i = 0; ok && i < 2; i++) {
  103929. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103930. }
  103931. }
  103932. for(channel = 0; ok && channel < 2; channel++) {
  103933. for(i = 0; ok && i < 2; i++) {
  103934. 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]);
  103935. }
  103936. }
  103937. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103938. /*@@@ 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) */
  103939. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103940. if(encoder->protected_->do_escape_coding)
  103941. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103942. /* now adjust the windows if the blocksize has changed */
  103943. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103944. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103945. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103946. switch(encoder->protected_->apodizations[i].type) {
  103947. case FLAC__APODIZATION_BARTLETT:
  103948. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103949. break;
  103950. case FLAC__APODIZATION_BARTLETT_HANN:
  103951. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103952. break;
  103953. case FLAC__APODIZATION_BLACKMAN:
  103954. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103955. break;
  103956. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103957. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103958. break;
  103959. case FLAC__APODIZATION_CONNES:
  103960. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103961. break;
  103962. case FLAC__APODIZATION_FLATTOP:
  103963. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103964. break;
  103965. case FLAC__APODIZATION_GAUSS:
  103966. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103967. break;
  103968. case FLAC__APODIZATION_HAMMING:
  103969. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103970. break;
  103971. case FLAC__APODIZATION_HANN:
  103972. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103973. break;
  103974. case FLAC__APODIZATION_KAISER_BESSEL:
  103975. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103976. break;
  103977. case FLAC__APODIZATION_NUTTALL:
  103978. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103979. break;
  103980. case FLAC__APODIZATION_RECTANGLE:
  103981. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103982. break;
  103983. case FLAC__APODIZATION_TRIANGLE:
  103984. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103985. break;
  103986. case FLAC__APODIZATION_TUKEY:
  103987. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103988. break;
  103989. case FLAC__APODIZATION_WELCH:
  103990. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103991. break;
  103992. default:
  103993. FLAC__ASSERT(0);
  103994. /* double protection */
  103995. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103996. break;
  103997. }
  103998. }
  103999. }
  104000. #endif
  104001. if(ok)
  104002. encoder->private_->input_capacity = new_blocksize;
  104003. else
  104004. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104005. return ok;
  104006. }
  104007. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104008. {
  104009. const FLAC__byte *buffer;
  104010. size_t bytes;
  104011. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104012. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104013. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104014. return false;
  104015. }
  104016. if(encoder->protected_->verify) {
  104017. encoder->private_->verify.output.data = buffer;
  104018. encoder->private_->verify.output.bytes = bytes;
  104019. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104020. encoder->private_->verify.needs_magic_hack = true;
  104021. }
  104022. else {
  104023. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104024. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104025. FLAC__bitwriter_clear(encoder->private_->frame);
  104026. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104027. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104028. return false;
  104029. }
  104030. }
  104031. }
  104032. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104033. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104034. FLAC__bitwriter_clear(encoder->private_->frame);
  104035. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104036. return false;
  104037. }
  104038. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104039. FLAC__bitwriter_clear(encoder->private_->frame);
  104040. if(samples > 0) {
  104041. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104042. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104043. }
  104044. return true;
  104045. }
  104046. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104047. {
  104048. FLAC__StreamEncoderWriteStatus status;
  104049. FLAC__uint64 output_position = 0;
  104050. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104051. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104052. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104053. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104054. }
  104055. /*
  104056. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104057. */
  104058. if(samples == 0) {
  104059. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104060. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104061. encoder->protected_->streaminfo_offset = output_position;
  104062. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104063. encoder->protected_->seektable_offset = output_position;
  104064. }
  104065. /*
  104066. * Mark the current seek point if hit (if audio_offset == 0 that
  104067. * means we're still writing metadata and haven't hit the first
  104068. * frame yet)
  104069. */
  104070. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104071. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104072. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104073. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104074. FLAC__uint64 test_sample;
  104075. unsigned i;
  104076. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104077. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104078. if(test_sample > frame_last_sample) {
  104079. break;
  104080. }
  104081. else if(test_sample >= frame_first_sample) {
  104082. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104083. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104084. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104085. encoder->private_->first_seekpoint_to_check++;
  104086. /* DO NOT: "break;" and here's why:
  104087. * The seektable template may contain more than one target
  104088. * sample for any given frame; we will keep looping, generating
  104089. * duplicate seekpoints for them, and we'll clean it up later,
  104090. * just before writing the seektable back to the metadata.
  104091. */
  104092. }
  104093. else {
  104094. encoder->private_->first_seekpoint_to_check++;
  104095. }
  104096. }
  104097. }
  104098. #if FLAC__HAS_OGG
  104099. if(encoder->private_->is_ogg) {
  104100. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104101. &encoder->protected_->ogg_encoder_aspect,
  104102. buffer,
  104103. bytes,
  104104. samples,
  104105. encoder->private_->current_frame_number,
  104106. is_last_block,
  104107. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104108. encoder,
  104109. encoder->private_->client_data
  104110. );
  104111. }
  104112. else
  104113. #endif
  104114. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104115. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104116. encoder->private_->bytes_written += bytes;
  104117. encoder->private_->samples_written += samples;
  104118. /* we keep a high watermark on the number of frames written because
  104119. * when the encoder goes back to write metadata, 'current_frame'
  104120. * will drop back to 0.
  104121. */
  104122. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104123. }
  104124. else
  104125. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104126. return status;
  104127. }
  104128. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104129. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104130. {
  104131. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104132. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104133. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104134. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104135. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104136. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104137. FLAC__StreamEncoderSeekStatus seek_status;
  104138. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104139. /* All this is based on intimate knowledge of the stream header
  104140. * layout, but a change to the header format that would break this
  104141. * would also break all streams encoded in the previous format.
  104142. */
  104143. /*
  104144. * Write MD5 signature
  104145. */
  104146. {
  104147. const unsigned md5_offset =
  104148. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104149. (
  104150. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104151. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104152. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104153. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104154. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104155. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104156. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104157. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104158. ) / 8;
  104159. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104160. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104161. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104162. return;
  104163. }
  104164. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104165. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104166. return;
  104167. }
  104168. }
  104169. /*
  104170. * Write total samples
  104171. */
  104172. {
  104173. const unsigned total_samples_byte_offset =
  104174. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104175. (
  104176. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104177. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104178. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104179. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104180. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104181. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104182. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104183. - 4
  104184. ) / 8;
  104185. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104186. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104187. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104188. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104189. b[4] = (FLAC__byte)(samples & 0xFF);
  104190. 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) {
  104191. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104192. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104193. return;
  104194. }
  104195. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104196. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104197. return;
  104198. }
  104199. }
  104200. /*
  104201. * Write min/max framesize
  104202. */
  104203. {
  104204. const unsigned min_framesize_offset =
  104205. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104206. (
  104207. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104208. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104209. ) / 8;
  104210. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104211. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104212. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104213. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104214. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104215. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104216. 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) {
  104217. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104218. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104219. return;
  104220. }
  104221. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104222. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104223. return;
  104224. }
  104225. }
  104226. /*
  104227. * Write seektable
  104228. */
  104229. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104230. unsigned i;
  104231. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104232. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104233. 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) {
  104234. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104235. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104236. return;
  104237. }
  104238. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104239. FLAC__uint64 xx;
  104240. unsigned x;
  104241. xx = encoder->private_->seek_table->points[i].sample_number;
  104242. b[7] = (FLAC__byte)xx; xx >>= 8;
  104243. b[6] = (FLAC__byte)xx; xx >>= 8;
  104244. b[5] = (FLAC__byte)xx; xx >>= 8;
  104245. b[4] = (FLAC__byte)xx; xx >>= 8;
  104246. b[3] = (FLAC__byte)xx; xx >>= 8;
  104247. b[2] = (FLAC__byte)xx; xx >>= 8;
  104248. b[1] = (FLAC__byte)xx; xx >>= 8;
  104249. b[0] = (FLAC__byte)xx; xx >>= 8;
  104250. xx = encoder->private_->seek_table->points[i].stream_offset;
  104251. b[15] = (FLAC__byte)xx; xx >>= 8;
  104252. b[14] = (FLAC__byte)xx; xx >>= 8;
  104253. b[13] = (FLAC__byte)xx; xx >>= 8;
  104254. b[12] = (FLAC__byte)xx; xx >>= 8;
  104255. b[11] = (FLAC__byte)xx; xx >>= 8;
  104256. b[10] = (FLAC__byte)xx; xx >>= 8;
  104257. b[9] = (FLAC__byte)xx; xx >>= 8;
  104258. b[8] = (FLAC__byte)xx; xx >>= 8;
  104259. x = encoder->private_->seek_table->points[i].frame_samples;
  104260. b[17] = (FLAC__byte)x; x >>= 8;
  104261. b[16] = (FLAC__byte)x; x >>= 8;
  104262. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104263. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104264. return;
  104265. }
  104266. }
  104267. }
  104268. }
  104269. #if FLAC__HAS_OGG
  104270. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104271. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104272. {
  104273. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104274. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104275. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104276. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104277. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104278. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104279. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104280. FLAC__STREAM_SYNC_LENGTH
  104281. ;
  104282. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104283. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104284. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104285. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104286. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104287. ogg_page page;
  104288. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104289. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104290. /* Pre-check that client supports seeking, since we don't want the
  104291. * ogg_helper code to ever have to deal with this condition.
  104292. */
  104293. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104294. return;
  104295. /* All this is based on intimate knowledge of the stream header
  104296. * layout, but a change to the header format that would break this
  104297. * would also break all streams encoded in the previous format.
  104298. */
  104299. /**
  104300. ** Write STREAMINFO stats
  104301. **/
  104302. simple_ogg_page__init(&page);
  104303. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104304. simple_ogg_page__clear(&page);
  104305. return; /* state already set */
  104306. }
  104307. /*
  104308. * Write MD5 signature
  104309. */
  104310. {
  104311. const unsigned md5_offset =
  104312. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104313. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104314. (
  104315. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104316. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104317. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104318. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104319. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104320. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104321. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104322. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104323. ) / 8;
  104324. if(md5_offset + 16 > (unsigned)page.body_len) {
  104325. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104326. simple_ogg_page__clear(&page);
  104327. return;
  104328. }
  104329. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104330. }
  104331. /*
  104332. * Write total samples
  104333. */
  104334. {
  104335. const unsigned total_samples_byte_offset =
  104336. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104337. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104338. (
  104339. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104340. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104341. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104342. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104343. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104344. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104345. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104346. - 4
  104347. ) / 8;
  104348. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104349. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104350. simple_ogg_page__clear(&page);
  104351. return;
  104352. }
  104353. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104354. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104355. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104356. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104357. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104358. b[4] = (FLAC__byte)(samples & 0xFF);
  104359. memcpy(page.body + total_samples_byte_offset, b, 5);
  104360. }
  104361. /*
  104362. * Write min/max framesize
  104363. */
  104364. {
  104365. const unsigned min_framesize_offset =
  104366. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104367. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104368. (
  104369. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104370. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104371. ) / 8;
  104372. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104373. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104374. simple_ogg_page__clear(&page);
  104375. return;
  104376. }
  104377. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104378. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104379. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104380. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104381. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104382. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104383. memcpy(page.body + min_framesize_offset, b, 6);
  104384. }
  104385. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104386. simple_ogg_page__clear(&page);
  104387. return; /* state already set */
  104388. }
  104389. simple_ogg_page__clear(&page);
  104390. /*
  104391. * Write seektable
  104392. */
  104393. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104394. unsigned i;
  104395. FLAC__byte *p;
  104396. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104397. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104398. simple_ogg_page__init(&page);
  104399. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104400. simple_ogg_page__clear(&page);
  104401. return; /* state already set */
  104402. }
  104403. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104404. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104405. simple_ogg_page__clear(&page);
  104406. return;
  104407. }
  104408. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104409. FLAC__uint64 xx;
  104410. unsigned x;
  104411. xx = encoder->private_->seek_table->points[i].sample_number;
  104412. b[7] = (FLAC__byte)xx; xx >>= 8;
  104413. b[6] = (FLAC__byte)xx; xx >>= 8;
  104414. b[5] = (FLAC__byte)xx; xx >>= 8;
  104415. b[4] = (FLAC__byte)xx; xx >>= 8;
  104416. b[3] = (FLAC__byte)xx; xx >>= 8;
  104417. b[2] = (FLAC__byte)xx; xx >>= 8;
  104418. b[1] = (FLAC__byte)xx; xx >>= 8;
  104419. b[0] = (FLAC__byte)xx; xx >>= 8;
  104420. xx = encoder->private_->seek_table->points[i].stream_offset;
  104421. b[15] = (FLAC__byte)xx; xx >>= 8;
  104422. b[14] = (FLAC__byte)xx; xx >>= 8;
  104423. b[13] = (FLAC__byte)xx; xx >>= 8;
  104424. b[12] = (FLAC__byte)xx; xx >>= 8;
  104425. b[11] = (FLAC__byte)xx; xx >>= 8;
  104426. b[10] = (FLAC__byte)xx; xx >>= 8;
  104427. b[9] = (FLAC__byte)xx; xx >>= 8;
  104428. b[8] = (FLAC__byte)xx; xx >>= 8;
  104429. x = encoder->private_->seek_table->points[i].frame_samples;
  104430. b[17] = (FLAC__byte)x; x >>= 8;
  104431. b[16] = (FLAC__byte)x; x >>= 8;
  104432. memcpy(p, b, 18);
  104433. }
  104434. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104435. simple_ogg_page__clear(&page);
  104436. return; /* state already set */
  104437. }
  104438. simple_ogg_page__clear(&page);
  104439. }
  104440. }
  104441. #endif
  104442. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104443. {
  104444. FLAC__uint16 crc;
  104445. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104446. /*
  104447. * Accumulate raw signal to the MD5 signature
  104448. */
  104449. 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)) {
  104450. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104451. return false;
  104452. }
  104453. /*
  104454. * Process the frame header and subframes into the frame bitbuffer
  104455. */
  104456. if(!process_subframes_(encoder, is_fractional_block)) {
  104457. /* the above function sets the state for us in case of an error */
  104458. return false;
  104459. }
  104460. /*
  104461. * Zero-pad the frame to a byte_boundary
  104462. */
  104463. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104464. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104465. return false;
  104466. }
  104467. /*
  104468. * CRC-16 the whole thing
  104469. */
  104470. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104471. if(
  104472. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104473. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104474. ) {
  104475. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104476. return false;
  104477. }
  104478. /*
  104479. * Write it
  104480. */
  104481. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104482. /* the above function sets the state for us in case of an error */
  104483. return false;
  104484. }
  104485. /*
  104486. * Get ready for the next frame
  104487. */
  104488. encoder->private_->current_sample_number = 0;
  104489. encoder->private_->current_frame_number++;
  104490. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104491. return true;
  104492. }
  104493. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104494. {
  104495. FLAC__FrameHeader frame_header;
  104496. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104497. FLAC__bool do_independent, do_mid_side;
  104498. /*
  104499. * Calculate the min,max Rice partition orders
  104500. */
  104501. if(is_fractional_block) {
  104502. max_partition_order = 0;
  104503. }
  104504. else {
  104505. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104506. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104507. }
  104508. min_partition_order = min(min_partition_order, max_partition_order);
  104509. /*
  104510. * Setup the frame
  104511. */
  104512. frame_header.blocksize = encoder->protected_->blocksize;
  104513. frame_header.sample_rate = encoder->protected_->sample_rate;
  104514. frame_header.channels = encoder->protected_->channels;
  104515. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104516. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104517. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104518. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104519. /*
  104520. * Figure out what channel assignments to try
  104521. */
  104522. if(encoder->protected_->do_mid_side_stereo) {
  104523. if(encoder->protected_->loose_mid_side_stereo) {
  104524. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104525. do_independent = true;
  104526. do_mid_side = true;
  104527. }
  104528. else {
  104529. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104530. do_mid_side = !do_independent;
  104531. }
  104532. }
  104533. else {
  104534. do_independent = true;
  104535. do_mid_side = true;
  104536. }
  104537. }
  104538. else {
  104539. do_independent = true;
  104540. do_mid_side = false;
  104541. }
  104542. FLAC__ASSERT(do_independent || do_mid_side);
  104543. /*
  104544. * Check for wasted bits; set effective bps for each subframe
  104545. */
  104546. if(do_independent) {
  104547. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104548. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104549. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104550. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104551. }
  104552. }
  104553. if(do_mid_side) {
  104554. FLAC__ASSERT(encoder->protected_->channels == 2);
  104555. for(channel = 0; channel < 2; channel++) {
  104556. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104557. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104558. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104559. }
  104560. }
  104561. /*
  104562. * First do a normal encoding pass of each independent channel
  104563. */
  104564. if(do_independent) {
  104565. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104566. if(!
  104567. process_subframe_(
  104568. encoder,
  104569. min_partition_order,
  104570. max_partition_order,
  104571. &frame_header,
  104572. encoder->private_->subframe_bps[channel],
  104573. encoder->private_->integer_signal[channel],
  104574. encoder->private_->subframe_workspace_ptr[channel],
  104575. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104576. encoder->private_->residual_workspace[channel],
  104577. encoder->private_->best_subframe+channel,
  104578. encoder->private_->best_subframe_bits+channel
  104579. )
  104580. )
  104581. return false;
  104582. }
  104583. }
  104584. /*
  104585. * Now do mid and side channels if requested
  104586. */
  104587. if(do_mid_side) {
  104588. FLAC__ASSERT(encoder->protected_->channels == 2);
  104589. for(channel = 0; channel < 2; channel++) {
  104590. if(!
  104591. process_subframe_(
  104592. encoder,
  104593. min_partition_order,
  104594. max_partition_order,
  104595. &frame_header,
  104596. encoder->private_->subframe_bps_mid_side[channel],
  104597. encoder->private_->integer_signal_mid_side[channel],
  104598. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104599. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104600. encoder->private_->residual_workspace_mid_side[channel],
  104601. encoder->private_->best_subframe_mid_side+channel,
  104602. encoder->private_->best_subframe_bits_mid_side+channel
  104603. )
  104604. )
  104605. return false;
  104606. }
  104607. }
  104608. /*
  104609. * Compose the frame bitbuffer
  104610. */
  104611. if(do_mid_side) {
  104612. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104613. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104614. FLAC__ChannelAssignment channel_assignment;
  104615. FLAC__ASSERT(encoder->protected_->channels == 2);
  104616. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104617. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104618. }
  104619. else {
  104620. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104621. unsigned min_bits;
  104622. int ca;
  104623. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104624. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104625. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104626. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104627. FLAC__ASSERT(do_independent && do_mid_side);
  104628. /* We have to figure out which channel assignent results in the smallest frame */
  104629. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104630. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104631. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104632. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104633. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104634. min_bits = bits[channel_assignment];
  104635. for(ca = 1; ca <= 3; ca++) {
  104636. if(bits[ca] < min_bits) {
  104637. min_bits = bits[ca];
  104638. channel_assignment = (FLAC__ChannelAssignment)ca;
  104639. }
  104640. }
  104641. }
  104642. frame_header.channel_assignment = channel_assignment;
  104643. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104644. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104645. return false;
  104646. }
  104647. switch(channel_assignment) {
  104648. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104649. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104650. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104651. break;
  104652. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104653. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104654. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104655. break;
  104656. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104657. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104658. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104659. break;
  104660. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104661. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104662. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104663. break;
  104664. default:
  104665. FLAC__ASSERT(0);
  104666. }
  104667. switch(channel_assignment) {
  104668. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104669. left_bps = encoder->private_->subframe_bps [0];
  104670. right_bps = encoder->private_->subframe_bps [1];
  104671. break;
  104672. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104673. left_bps = encoder->private_->subframe_bps [0];
  104674. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104675. break;
  104676. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104677. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104678. right_bps = encoder->private_->subframe_bps [1];
  104679. break;
  104680. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104681. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104682. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104683. break;
  104684. default:
  104685. FLAC__ASSERT(0);
  104686. }
  104687. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104688. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104689. return false;
  104690. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104691. return false;
  104692. }
  104693. else {
  104694. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104695. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104696. return false;
  104697. }
  104698. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104699. 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)) {
  104700. /* the above function sets the state for us in case of an error */
  104701. return false;
  104702. }
  104703. }
  104704. }
  104705. if(encoder->protected_->loose_mid_side_stereo) {
  104706. encoder->private_->loose_mid_side_stereo_frame_count++;
  104707. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104708. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104709. }
  104710. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104711. return true;
  104712. }
  104713. FLAC__bool process_subframe_(
  104714. FLAC__StreamEncoder *encoder,
  104715. unsigned min_partition_order,
  104716. unsigned max_partition_order,
  104717. const FLAC__FrameHeader *frame_header,
  104718. unsigned subframe_bps,
  104719. const FLAC__int32 integer_signal[],
  104720. FLAC__Subframe *subframe[2],
  104721. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104722. FLAC__int32 *residual[2],
  104723. unsigned *best_subframe,
  104724. unsigned *best_bits
  104725. )
  104726. {
  104727. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104728. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104729. #else
  104730. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104731. #endif
  104732. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104733. FLAC__double lpc_residual_bits_per_sample;
  104734. 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 */
  104735. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104736. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104737. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104738. #endif
  104739. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104740. unsigned rice_parameter;
  104741. unsigned _candidate_bits, _best_bits;
  104742. unsigned _best_subframe;
  104743. /* only use RICE2 partitions if stream bps > 16 */
  104744. 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;
  104745. FLAC__ASSERT(frame_header->blocksize > 0);
  104746. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104747. _best_subframe = 0;
  104748. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104749. _best_bits = UINT_MAX;
  104750. else
  104751. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104752. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104753. unsigned signal_is_constant = false;
  104754. 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);
  104755. /* check for constant subframe */
  104756. if(
  104757. !encoder->private_->disable_constant_subframes &&
  104758. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104759. fixed_residual_bits_per_sample[1] == 0.0
  104760. #else
  104761. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104762. #endif
  104763. ) {
  104764. /* the above means it's possible all samples are the same value; now double-check it: */
  104765. unsigned i;
  104766. signal_is_constant = true;
  104767. for(i = 1; i < frame_header->blocksize; i++) {
  104768. if(integer_signal[0] != integer_signal[i]) {
  104769. signal_is_constant = false;
  104770. break;
  104771. }
  104772. }
  104773. }
  104774. if(signal_is_constant) {
  104775. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104776. if(_candidate_bits < _best_bits) {
  104777. _best_subframe = !_best_subframe;
  104778. _best_bits = _candidate_bits;
  104779. }
  104780. }
  104781. else {
  104782. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104783. /* encode fixed */
  104784. if(encoder->protected_->do_exhaustive_model_search) {
  104785. min_fixed_order = 0;
  104786. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104787. }
  104788. else {
  104789. min_fixed_order = max_fixed_order = guess_fixed_order;
  104790. }
  104791. if(max_fixed_order >= frame_header->blocksize)
  104792. max_fixed_order = frame_header->blocksize - 1;
  104793. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104794. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104795. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104796. continue; /* don't even try */
  104797. 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 */
  104798. #else
  104799. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104800. continue; /* don't even try */
  104801. 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 */
  104802. #endif
  104803. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104804. if(rice_parameter >= rice_parameter_limit) {
  104805. #ifdef DEBUG_VERBOSE
  104806. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104807. #endif
  104808. rice_parameter = rice_parameter_limit - 1;
  104809. }
  104810. _candidate_bits =
  104811. evaluate_fixed_subframe_(
  104812. encoder,
  104813. integer_signal,
  104814. residual[!_best_subframe],
  104815. encoder->private_->abs_residual_partition_sums,
  104816. encoder->private_->raw_bits_per_partition,
  104817. frame_header->blocksize,
  104818. subframe_bps,
  104819. fixed_order,
  104820. rice_parameter,
  104821. rice_parameter_limit,
  104822. min_partition_order,
  104823. max_partition_order,
  104824. encoder->protected_->do_escape_coding,
  104825. encoder->protected_->rice_parameter_search_dist,
  104826. subframe[!_best_subframe],
  104827. partitioned_rice_contents[!_best_subframe]
  104828. );
  104829. if(_candidate_bits < _best_bits) {
  104830. _best_subframe = !_best_subframe;
  104831. _best_bits = _candidate_bits;
  104832. }
  104833. }
  104834. }
  104835. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104836. /* encode lpc */
  104837. if(encoder->protected_->max_lpc_order > 0) {
  104838. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104839. max_lpc_order = frame_header->blocksize-1;
  104840. else
  104841. max_lpc_order = encoder->protected_->max_lpc_order;
  104842. if(max_lpc_order > 0) {
  104843. unsigned a;
  104844. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104845. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104846. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104847. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104848. if(autoc[0] != 0.0) {
  104849. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104850. if(encoder->protected_->do_exhaustive_model_search) {
  104851. min_lpc_order = 1;
  104852. }
  104853. else {
  104854. const unsigned guess_lpc_order =
  104855. FLAC__lpc_compute_best_order(
  104856. lpc_error,
  104857. max_lpc_order,
  104858. frame_header->blocksize,
  104859. subframe_bps + (
  104860. encoder->protected_->do_qlp_coeff_prec_search?
  104861. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104862. encoder->protected_->qlp_coeff_precision
  104863. )
  104864. );
  104865. min_lpc_order = max_lpc_order = guess_lpc_order;
  104866. }
  104867. if(max_lpc_order >= frame_header->blocksize)
  104868. max_lpc_order = frame_header->blocksize - 1;
  104869. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104870. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104871. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104872. continue; /* don't even try */
  104873. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104874. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104875. if(rice_parameter >= rice_parameter_limit) {
  104876. #ifdef DEBUG_VERBOSE
  104877. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104878. #endif
  104879. rice_parameter = rice_parameter_limit - 1;
  104880. }
  104881. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104882. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104883. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104884. if(subframe_bps <= 17) {
  104885. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104886. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104887. }
  104888. else
  104889. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104890. }
  104891. else {
  104892. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104893. }
  104894. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104895. _candidate_bits =
  104896. evaluate_lpc_subframe_(
  104897. encoder,
  104898. integer_signal,
  104899. residual[!_best_subframe],
  104900. encoder->private_->abs_residual_partition_sums,
  104901. encoder->private_->raw_bits_per_partition,
  104902. encoder->private_->lp_coeff[lpc_order-1],
  104903. frame_header->blocksize,
  104904. subframe_bps,
  104905. lpc_order,
  104906. qlp_coeff_precision,
  104907. rice_parameter,
  104908. rice_parameter_limit,
  104909. min_partition_order,
  104910. max_partition_order,
  104911. encoder->protected_->do_escape_coding,
  104912. encoder->protected_->rice_parameter_search_dist,
  104913. subframe[!_best_subframe],
  104914. partitioned_rice_contents[!_best_subframe]
  104915. );
  104916. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104917. if(_candidate_bits < _best_bits) {
  104918. _best_subframe = !_best_subframe;
  104919. _best_bits = _candidate_bits;
  104920. }
  104921. }
  104922. }
  104923. }
  104924. }
  104925. }
  104926. }
  104927. }
  104928. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104929. }
  104930. }
  104931. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104932. if(_best_bits == UINT_MAX) {
  104933. FLAC__ASSERT(_best_subframe == 0);
  104934. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104935. }
  104936. *best_subframe = _best_subframe;
  104937. *best_bits = _best_bits;
  104938. return true;
  104939. }
  104940. FLAC__bool add_subframe_(
  104941. FLAC__StreamEncoder *encoder,
  104942. unsigned blocksize,
  104943. unsigned subframe_bps,
  104944. const FLAC__Subframe *subframe,
  104945. FLAC__BitWriter *frame
  104946. )
  104947. {
  104948. switch(subframe->type) {
  104949. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104950. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104951. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104952. return false;
  104953. }
  104954. break;
  104955. case FLAC__SUBFRAME_TYPE_FIXED:
  104956. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104957. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104958. return false;
  104959. }
  104960. break;
  104961. case FLAC__SUBFRAME_TYPE_LPC:
  104962. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104963. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104964. return false;
  104965. }
  104966. break;
  104967. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104968. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104969. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104970. return false;
  104971. }
  104972. break;
  104973. default:
  104974. FLAC__ASSERT(0);
  104975. }
  104976. return true;
  104977. }
  104978. #define SPOTCHECK_ESTIMATE 0
  104979. #if SPOTCHECK_ESTIMATE
  104980. static void spotcheck_subframe_estimate_(
  104981. FLAC__StreamEncoder *encoder,
  104982. unsigned blocksize,
  104983. unsigned subframe_bps,
  104984. const FLAC__Subframe *subframe,
  104985. unsigned estimate
  104986. )
  104987. {
  104988. FLAC__bool ret;
  104989. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104990. if(frame == 0) {
  104991. fprintf(stderr, "EST: can't allocate frame\n");
  104992. return;
  104993. }
  104994. if(!FLAC__bitwriter_init(frame)) {
  104995. fprintf(stderr, "EST: can't init frame\n");
  104996. return;
  104997. }
  104998. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104999. FLAC__ASSERT(ret);
  105000. {
  105001. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105002. if(estimate != actual)
  105003. 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);
  105004. }
  105005. FLAC__bitwriter_delete(frame);
  105006. }
  105007. #endif
  105008. unsigned evaluate_constant_subframe_(
  105009. FLAC__StreamEncoder *encoder,
  105010. const FLAC__int32 signal,
  105011. unsigned blocksize,
  105012. unsigned subframe_bps,
  105013. FLAC__Subframe *subframe
  105014. )
  105015. {
  105016. unsigned estimate;
  105017. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105018. subframe->data.constant.value = signal;
  105019. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105020. #if SPOTCHECK_ESTIMATE
  105021. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105022. #else
  105023. (void)encoder, (void)blocksize;
  105024. #endif
  105025. return estimate;
  105026. }
  105027. unsigned evaluate_fixed_subframe_(
  105028. FLAC__StreamEncoder *encoder,
  105029. const FLAC__int32 signal[],
  105030. FLAC__int32 residual[],
  105031. FLAC__uint64 abs_residual_partition_sums[],
  105032. unsigned raw_bits_per_partition[],
  105033. unsigned blocksize,
  105034. unsigned subframe_bps,
  105035. unsigned order,
  105036. unsigned rice_parameter,
  105037. unsigned rice_parameter_limit,
  105038. unsigned min_partition_order,
  105039. unsigned max_partition_order,
  105040. FLAC__bool do_escape_coding,
  105041. unsigned rice_parameter_search_dist,
  105042. FLAC__Subframe *subframe,
  105043. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105044. )
  105045. {
  105046. unsigned i, residual_bits, estimate;
  105047. const unsigned residual_samples = blocksize - order;
  105048. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105049. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105050. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105051. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105052. subframe->data.fixed.residual = residual;
  105053. residual_bits =
  105054. find_best_partition_order_(
  105055. encoder->private_,
  105056. residual,
  105057. abs_residual_partition_sums,
  105058. raw_bits_per_partition,
  105059. residual_samples,
  105060. order,
  105061. rice_parameter,
  105062. rice_parameter_limit,
  105063. min_partition_order,
  105064. max_partition_order,
  105065. subframe_bps,
  105066. do_escape_coding,
  105067. rice_parameter_search_dist,
  105068. &subframe->data.fixed.entropy_coding_method
  105069. );
  105070. subframe->data.fixed.order = order;
  105071. for(i = 0; i < order; i++)
  105072. subframe->data.fixed.warmup[i] = signal[i];
  105073. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105074. #if SPOTCHECK_ESTIMATE
  105075. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105076. #endif
  105077. return estimate;
  105078. }
  105079. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105080. unsigned evaluate_lpc_subframe_(
  105081. FLAC__StreamEncoder *encoder,
  105082. const FLAC__int32 signal[],
  105083. FLAC__int32 residual[],
  105084. FLAC__uint64 abs_residual_partition_sums[],
  105085. unsigned raw_bits_per_partition[],
  105086. const FLAC__real lp_coeff[],
  105087. unsigned blocksize,
  105088. unsigned subframe_bps,
  105089. unsigned order,
  105090. unsigned qlp_coeff_precision,
  105091. unsigned rice_parameter,
  105092. unsigned rice_parameter_limit,
  105093. unsigned min_partition_order,
  105094. unsigned max_partition_order,
  105095. FLAC__bool do_escape_coding,
  105096. unsigned rice_parameter_search_dist,
  105097. FLAC__Subframe *subframe,
  105098. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105099. )
  105100. {
  105101. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105102. unsigned i, residual_bits, estimate;
  105103. int quantization, ret;
  105104. const unsigned residual_samples = blocksize - order;
  105105. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105106. if(subframe_bps <= 16) {
  105107. FLAC__ASSERT(order > 0);
  105108. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105109. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105110. }
  105111. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105112. if(ret != 0)
  105113. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105114. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105115. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105116. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105117. else
  105118. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105119. else
  105120. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105121. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105122. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105123. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105124. subframe->data.lpc.residual = residual;
  105125. residual_bits =
  105126. find_best_partition_order_(
  105127. encoder->private_,
  105128. residual,
  105129. abs_residual_partition_sums,
  105130. raw_bits_per_partition,
  105131. residual_samples,
  105132. order,
  105133. rice_parameter,
  105134. rice_parameter_limit,
  105135. min_partition_order,
  105136. max_partition_order,
  105137. subframe_bps,
  105138. do_escape_coding,
  105139. rice_parameter_search_dist,
  105140. &subframe->data.lpc.entropy_coding_method
  105141. );
  105142. subframe->data.lpc.order = order;
  105143. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105144. subframe->data.lpc.quantization_level = quantization;
  105145. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105146. for(i = 0; i < order; i++)
  105147. subframe->data.lpc.warmup[i] = signal[i];
  105148. 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;
  105149. #if SPOTCHECK_ESTIMATE
  105150. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105151. #endif
  105152. return estimate;
  105153. }
  105154. #endif
  105155. unsigned evaluate_verbatim_subframe_(
  105156. FLAC__StreamEncoder *encoder,
  105157. const FLAC__int32 signal[],
  105158. unsigned blocksize,
  105159. unsigned subframe_bps,
  105160. FLAC__Subframe *subframe
  105161. )
  105162. {
  105163. unsigned estimate;
  105164. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105165. subframe->data.verbatim.data = signal;
  105166. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105167. #if SPOTCHECK_ESTIMATE
  105168. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105169. #else
  105170. (void)encoder;
  105171. #endif
  105172. return estimate;
  105173. }
  105174. unsigned find_best_partition_order_(
  105175. FLAC__StreamEncoderPrivate *private_,
  105176. const FLAC__int32 residual[],
  105177. FLAC__uint64 abs_residual_partition_sums[],
  105178. unsigned raw_bits_per_partition[],
  105179. unsigned residual_samples,
  105180. unsigned predictor_order,
  105181. unsigned rice_parameter,
  105182. unsigned rice_parameter_limit,
  105183. unsigned min_partition_order,
  105184. unsigned max_partition_order,
  105185. unsigned bps,
  105186. FLAC__bool do_escape_coding,
  105187. unsigned rice_parameter_search_dist,
  105188. FLAC__EntropyCodingMethod *best_ecm
  105189. )
  105190. {
  105191. unsigned residual_bits, best_residual_bits = 0;
  105192. unsigned best_parameters_index = 0;
  105193. unsigned best_partition_order = 0;
  105194. const unsigned blocksize = residual_samples + predictor_order;
  105195. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105196. min_partition_order = min(min_partition_order, max_partition_order);
  105197. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105198. if(do_escape_coding)
  105199. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105200. {
  105201. int partition_order;
  105202. unsigned sum;
  105203. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105204. if(!
  105205. set_partitioned_rice_(
  105206. #ifdef EXACT_RICE_BITS_CALCULATION
  105207. residual,
  105208. #endif
  105209. abs_residual_partition_sums+sum,
  105210. raw_bits_per_partition+sum,
  105211. residual_samples,
  105212. predictor_order,
  105213. rice_parameter,
  105214. rice_parameter_limit,
  105215. rice_parameter_search_dist,
  105216. (unsigned)partition_order,
  105217. do_escape_coding,
  105218. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105219. &residual_bits
  105220. )
  105221. )
  105222. {
  105223. FLAC__ASSERT(best_residual_bits != 0);
  105224. break;
  105225. }
  105226. sum += 1u << partition_order;
  105227. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105228. best_residual_bits = residual_bits;
  105229. best_parameters_index = !best_parameters_index;
  105230. best_partition_order = partition_order;
  105231. }
  105232. }
  105233. }
  105234. best_ecm->data.partitioned_rice.order = best_partition_order;
  105235. {
  105236. /*
  105237. * We are allowed to de-const the pointer based on our special
  105238. * knowledge; it is const to the outside world.
  105239. */
  105240. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105241. unsigned partition;
  105242. /* save best parameters and raw_bits */
  105243. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105244. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105245. if(do_escape_coding)
  105246. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105247. /*
  105248. * Now need to check if the type should be changed to
  105249. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105250. * size of the rice parameters.
  105251. */
  105252. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105253. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105254. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105255. break;
  105256. }
  105257. }
  105258. }
  105259. return best_residual_bits;
  105260. }
  105261. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105262. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105263. const FLAC__int32 residual[],
  105264. FLAC__uint64 abs_residual_partition_sums[],
  105265. unsigned blocksize,
  105266. unsigned predictor_order,
  105267. unsigned min_partition_order,
  105268. unsigned max_partition_order
  105269. );
  105270. #endif
  105271. void precompute_partition_info_sums_(
  105272. const FLAC__int32 residual[],
  105273. FLAC__uint64 abs_residual_partition_sums[],
  105274. unsigned residual_samples,
  105275. unsigned predictor_order,
  105276. unsigned min_partition_order,
  105277. unsigned max_partition_order,
  105278. unsigned bps
  105279. )
  105280. {
  105281. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105282. unsigned partitions = 1u << max_partition_order;
  105283. FLAC__ASSERT(default_partition_samples > predictor_order);
  105284. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105285. /* slightly pessimistic but still catches all common cases */
  105286. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105287. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105288. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105289. return;
  105290. }
  105291. #endif
  105292. /* first do max_partition_order */
  105293. {
  105294. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105295. /* slightly pessimistic but still catches all common cases */
  105296. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105297. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105298. FLAC__uint32 abs_residual_partition_sum;
  105299. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105300. end += default_partition_samples;
  105301. abs_residual_partition_sum = 0;
  105302. for( ; residual_sample < end; residual_sample++)
  105303. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105304. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105305. }
  105306. }
  105307. else { /* have to pessimistically use 64 bits for accumulator */
  105308. FLAC__uint64 abs_residual_partition_sum;
  105309. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105310. end += default_partition_samples;
  105311. abs_residual_partition_sum = 0;
  105312. for( ; residual_sample < end; residual_sample++)
  105313. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105314. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105315. }
  105316. }
  105317. }
  105318. /* now merge partitions for lower orders */
  105319. {
  105320. unsigned from_partition = 0, to_partition = partitions;
  105321. int partition_order;
  105322. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105323. unsigned i;
  105324. partitions >>= 1;
  105325. for(i = 0; i < partitions; i++) {
  105326. abs_residual_partition_sums[to_partition++] =
  105327. abs_residual_partition_sums[from_partition ] +
  105328. abs_residual_partition_sums[from_partition+1];
  105329. from_partition += 2;
  105330. }
  105331. }
  105332. }
  105333. }
  105334. void precompute_partition_info_escapes_(
  105335. const FLAC__int32 residual[],
  105336. unsigned raw_bits_per_partition[],
  105337. unsigned residual_samples,
  105338. unsigned predictor_order,
  105339. unsigned min_partition_order,
  105340. unsigned max_partition_order
  105341. )
  105342. {
  105343. int partition_order;
  105344. unsigned from_partition, to_partition = 0;
  105345. const unsigned blocksize = residual_samples + predictor_order;
  105346. /* first do max_partition_order */
  105347. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105348. FLAC__int32 r;
  105349. FLAC__uint32 rmax;
  105350. unsigned partition, partition_sample, partition_samples, residual_sample;
  105351. const unsigned partitions = 1u << partition_order;
  105352. const unsigned default_partition_samples = blocksize >> partition_order;
  105353. FLAC__ASSERT(default_partition_samples > predictor_order);
  105354. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105355. partition_samples = default_partition_samples;
  105356. if(partition == 0)
  105357. partition_samples -= predictor_order;
  105358. rmax = 0;
  105359. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105360. r = residual[residual_sample++];
  105361. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105362. if(r < 0)
  105363. rmax |= ~r;
  105364. else
  105365. rmax |= r;
  105366. }
  105367. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105368. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105369. }
  105370. to_partition = partitions;
  105371. break; /*@@@ yuck, should remove the 'for' loop instead */
  105372. }
  105373. /* now merge partitions for lower orders */
  105374. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105375. unsigned m;
  105376. unsigned i;
  105377. const unsigned partitions = 1u << partition_order;
  105378. for(i = 0; i < partitions; i++) {
  105379. m = raw_bits_per_partition[from_partition];
  105380. from_partition++;
  105381. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105382. from_partition++;
  105383. to_partition++;
  105384. }
  105385. }
  105386. }
  105387. #ifdef EXACT_RICE_BITS_CALCULATION
  105388. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105389. const unsigned rice_parameter,
  105390. const unsigned partition_samples,
  105391. const FLAC__int32 *residual
  105392. )
  105393. {
  105394. unsigned i, partition_bits =
  105395. 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 */
  105396. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105397. ;
  105398. for(i = 0; i < partition_samples; i++)
  105399. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105400. return partition_bits;
  105401. }
  105402. #else
  105403. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105404. const unsigned rice_parameter,
  105405. const unsigned partition_samples,
  105406. const FLAC__uint64 abs_residual_partition_sum
  105407. )
  105408. {
  105409. return
  105410. 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 */
  105411. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105412. (
  105413. rice_parameter?
  105414. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105415. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105416. )
  105417. - (partition_samples >> 1)
  105418. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105419. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105420. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105421. * So the subtraction term tries to guess how many extra bits were contributed.
  105422. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105423. */
  105424. ;
  105425. }
  105426. #endif
  105427. FLAC__bool set_partitioned_rice_(
  105428. #ifdef EXACT_RICE_BITS_CALCULATION
  105429. const FLAC__int32 residual[],
  105430. #endif
  105431. const FLAC__uint64 abs_residual_partition_sums[],
  105432. const unsigned raw_bits_per_partition[],
  105433. const unsigned residual_samples,
  105434. const unsigned predictor_order,
  105435. const unsigned suggested_rice_parameter,
  105436. const unsigned rice_parameter_limit,
  105437. const unsigned rice_parameter_search_dist,
  105438. const unsigned partition_order,
  105439. const FLAC__bool search_for_escapes,
  105440. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105441. unsigned *bits
  105442. )
  105443. {
  105444. unsigned rice_parameter, partition_bits;
  105445. unsigned best_partition_bits, best_rice_parameter = 0;
  105446. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105447. unsigned *parameters, *raw_bits;
  105448. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105449. unsigned min_rice_parameter, max_rice_parameter;
  105450. #else
  105451. (void)rice_parameter_search_dist;
  105452. #endif
  105453. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105454. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105455. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105456. parameters = partitioned_rice_contents->parameters;
  105457. raw_bits = partitioned_rice_contents->raw_bits;
  105458. if(partition_order == 0) {
  105459. best_partition_bits = (unsigned)(-1);
  105460. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105461. if(rice_parameter_search_dist) {
  105462. if(suggested_rice_parameter < rice_parameter_search_dist)
  105463. min_rice_parameter = 0;
  105464. else
  105465. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105466. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105467. if(max_rice_parameter >= rice_parameter_limit) {
  105468. #ifdef DEBUG_VERBOSE
  105469. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105470. #endif
  105471. max_rice_parameter = rice_parameter_limit - 1;
  105472. }
  105473. }
  105474. else
  105475. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105476. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105477. #else
  105478. rice_parameter = suggested_rice_parameter;
  105479. #endif
  105480. #ifdef EXACT_RICE_BITS_CALCULATION
  105481. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105482. #else
  105483. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105484. #endif
  105485. if(partition_bits < best_partition_bits) {
  105486. best_rice_parameter = rice_parameter;
  105487. best_partition_bits = partition_bits;
  105488. }
  105489. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105490. }
  105491. #endif
  105492. if(search_for_escapes) {
  105493. 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;
  105494. if(partition_bits <= best_partition_bits) {
  105495. raw_bits[0] = raw_bits_per_partition[0];
  105496. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105497. best_partition_bits = partition_bits;
  105498. }
  105499. else
  105500. raw_bits[0] = 0;
  105501. }
  105502. parameters[0] = best_rice_parameter;
  105503. bits_ += best_partition_bits;
  105504. }
  105505. else {
  105506. unsigned partition, residual_sample;
  105507. unsigned partition_samples;
  105508. FLAC__uint64 mean, k;
  105509. const unsigned partitions = 1u << partition_order;
  105510. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105511. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105512. if(partition == 0) {
  105513. if(partition_samples <= predictor_order)
  105514. return false;
  105515. else
  105516. partition_samples -= predictor_order;
  105517. }
  105518. mean = abs_residual_partition_sums[partition];
  105519. /* we are basically calculating the size in bits of the
  105520. * average residual magnitude in the partition:
  105521. * rice_parameter = floor(log2(mean/partition_samples))
  105522. * 'mean' is not a good name for the variable, it is
  105523. * actually the sum of magnitudes of all residual values
  105524. * in the partition, so the actual mean is
  105525. * mean/partition_samples
  105526. */
  105527. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105528. ;
  105529. if(rice_parameter >= rice_parameter_limit) {
  105530. #ifdef DEBUG_VERBOSE
  105531. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105532. #endif
  105533. rice_parameter = rice_parameter_limit - 1;
  105534. }
  105535. best_partition_bits = (unsigned)(-1);
  105536. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105537. if(rice_parameter_search_dist) {
  105538. if(rice_parameter < rice_parameter_search_dist)
  105539. min_rice_parameter = 0;
  105540. else
  105541. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105542. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105543. if(max_rice_parameter >= rice_parameter_limit) {
  105544. #ifdef DEBUG_VERBOSE
  105545. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105546. #endif
  105547. max_rice_parameter = rice_parameter_limit - 1;
  105548. }
  105549. }
  105550. else
  105551. min_rice_parameter = max_rice_parameter = rice_parameter;
  105552. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105553. #endif
  105554. #ifdef EXACT_RICE_BITS_CALCULATION
  105555. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105556. #else
  105557. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105558. #endif
  105559. if(partition_bits < best_partition_bits) {
  105560. best_rice_parameter = rice_parameter;
  105561. best_partition_bits = partition_bits;
  105562. }
  105563. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105564. }
  105565. #endif
  105566. if(search_for_escapes) {
  105567. 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;
  105568. if(partition_bits <= best_partition_bits) {
  105569. raw_bits[partition] = raw_bits_per_partition[partition];
  105570. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105571. best_partition_bits = partition_bits;
  105572. }
  105573. else
  105574. raw_bits[partition] = 0;
  105575. }
  105576. parameters[partition] = best_rice_parameter;
  105577. bits_ += best_partition_bits;
  105578. residual_sample += partition_samples;
  105579. }
  105580. }
  105581. *bits = bits_;
  105582. return true;
  105583. }
  105584. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105585. {
  105586. unsigned i, shift;
  105587. FLAC__int32 x = 0;
  105588. for(i = 0; i < samples && !(x&1); i++)
  105589. x |= signal[i];
  105590. if(x == 0) {
  105591. shift = 0;
  105592. }
  105593. else {
  105594. for(shift = 0; !(x&1); shift++)
  105595. x >>= 1;
  105596. }
  105597. if(shift > 0) {
  105598. for(i = 0; i < samples; i++)
  105599. signal[i] >>= shift;
  105600. }
  105601. return shift;
  105602. }
  105603. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105604. {
  105605. unsigned channel;
  105606. for(channel = 0; channel < channels; channel++)
  105607. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105608. fifo->tail += wide_samples;
  105609. FLAC__ASSERT(fifo->tail <= fifo->size);
  105610. }
  105611. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105612. {
  105613. unsigned channel;
  105614. unsigned sample, wide_sample;
  105615. unsigned tail = fifo->tail;
  105616. sample = input_offset * channels;
  105617. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105618. for(channel = 0; channel < channels; channel++)
  105619. fifo->data[channel][tail] = input[sample++];
  105620. tail++;
  105621. }
  105622. fifo->tail = tail;
  105623. FLAC__ASSERT(fifo->tail <= fifo->size);
  105624. }
  105625. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105626. {
  105627. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105628. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105629. (void)decoder;
  105630. if(encoder->private_->verify.needs_magic_hack) {
  105631. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105632. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105633. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105634. encoder->private_->verify.needs_magic_hack = false;
  105635. }
  105636. else {
  105637. if(encoded_bytes == 0) {
  105638. /*
  105639. * If we get here, a FIFO underflow has occurred,
  105640. * which means there is a bug somewhere.
  105641. */
  105642. FLAC__ASSERT(0);
  105643. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105644. }
  105645. else if(encoded_bytes < *bytes)
  105646. *bytes = encoded_bytes;
  105647. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105648. encoder->private_->verify.output.data += *bytes;
  105649. encoder->private_->verify.output.bytes -= *bytes;
  105650. }
  105651. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105652. }
  105653. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105654. {
  105655. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105656. unsigned channel;
  105657. const unsigned channels = frame->header.channels;
  105658. const unsigned blocksize = frame->header.blocksize;
  105659. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105660. (void)decoder;
  105661. for(channel = 0; channel < channels; channel++) {
  105662. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105663. unsigned i, sample = 0;
  105664. FLAC__int32 expect = 0, got = 0;
  105665. for(i = 0; i < blocksize; i++) {
  105666. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105667. sample = i;
  105668. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105669. got = (FLAC__int32)buffer[channel][i];
  105670. break;
  105671. }
  105672. }
  105673. FLAC__ASSERT(i < blocksize);
  105674. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105675. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105676. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105677. encoder->private_->verify.error_stats.channel = channel;
  105678. encoder->private_->verify.error_stats.sample = sample;
  105679. encoder->private_->verify.error_stats.expected = expect;
  105680. encoder->private_->verify.error_stats.got = got;
  105681. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105682. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105683. }
  105684. }
  105685. /* dequeue the frame from the fifo */
  105686. encoder->private_->verify.input_fifo.tail -= blocksize;
  105687. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105688. for(channel = 0; channel < channels; channel++)
  105689. 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]));
  105690. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105691. }
  105692. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105693. {
  105694. (void)decoder, (void)metadata, (void)client_data;
  105695. }
  105696. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105697. {
  105698. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105699. (void)decoder, (void)status;
  105700. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105701. }
  105702. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105703. {
  105704. (void)client_data;
  105705. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105706. if (*bytes == 0) {
  105707. if (feof(encoder->private_->file))
  105708. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105709. else if (ferror(encoder->private_->file))
  105710. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105711. }
  105712. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105713. }
  105714. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105715. {
  105716. (void)client_data;
  105717. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105718. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105719. else
  105720. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105721. }
  105722. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105723. {
  105724. off_t offset;
  105725. (void)client_data;
  105726. offset = ftello(encoder->private_->file);
  105727. if(offset < 0) {
  105728. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105729. }
  105730. else {
  105731. *absolute_byte_offset = (FLAC__uint64)offset;
  105732. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105733. }
  105734. }
  105735. #ifdef FLAC__VALGRIND_TESTING
  105736. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105737. {
  105738. size_t ret = fwrite(ptr, size, nmemb, stream);
  105739. if(!ferror(stream))
  105740. fflush(stream);
  105741. return ret;
  105742. }
  105743. #else
  105744. #define local__fwrite fwrite
  105745. #endif
  105746. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105747. {
  105748. (void)client_data, (void)current_frame;
  105749. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105750. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105751. #if FLAC__HAS_OGG
  105752. /* We would like to be able to use 'samples > 0' in the
  105753. * clause here but currently because of the nature of our
  105754. * Ogg writing implementation, 'samples' is always 0 (see
  105755. * ogg_encoder_aspect.c). The downside is extra progress
  105756. * callbacks.
  105757. */
  105758. encoder->private_->is_ogg? true :
  105759. #endif
  105760. samples > 0
  105761. );
  105762. if(call_it) {
  105763. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105764. * because at this point in the callback chain, the stats
  105765. * have not been updated. Only after we return and control
  105766. * gets back to write_frame_() are the stats updated
  105767. */
  105768. 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);
  105769. }
  105770. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105771. }
  105772. else
  105773. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105774. }
  105775. /*
  105776. * This will forcibly set stdout to binary mode (for OSes that require it)
  105777. */
  105778. FILE *get_binary_stdout_(void)
  105779. {
  105780. /* if something breaks here it is probably due to the presence or
  105781. * absence of an underscore before the identifiers 'setmode',
  105782. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105783. */
  105784. #if defined _MSC_VER || defined __MINGW32__
  105785. _setmode(_fileno(stdout), _O_BINARY);
  105786. #elif defined __CYGWIN__
  105787. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105788. setmode(_fileno(stdout), _O_BINARY);
  105789. #elif defined __EMX__
  105790. setmode(fileno(stdout), O_BINARY);
  105791. #endif
  105792. return stdout;
  105793. }
  105794. #endif
  105795. /*** End of inlined file: stream_encoder.c ***/
  105796. /*** Start of inlined file: stream_encoder_framing.c ***/
  105797. /*** Start of inlined file: juce_FlacHeader.h ***/
  105798. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105799. // tasks..
  105800. #define VERSION "1.2.1"
  105801. #define FLAC__NO_DLL 1
  105802. #if JUCE_MSVC
  105803. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105804. #endif
  105805. #if JUCE_MAC
  105806. #define FLAC__SYS_DARWIN 1
  105807. #endif
  105808. /*** End of inlined file: juce_FlacHeader.h ***/
  105809. #if JUCE_USE_FLAC
  105810. #if HAVE_CONFIG_H
  105811. # include <config.h>
  105812. #endif
  105813. #include <stdio.h>
  105814. #include <string.h> /* for strlen() */
  105815. #ifdef max
  105816. #undef max
  105817. #endif
  105818. #define max(x,y) ((x)>(y)?(x):(y))
  105819. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105820. 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);
  105821. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105822. {
  105823. unsigned i, j;
  105824. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105825. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105826. return false;
  105827. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105828. return false;
  105829. /*
  105830. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105831. */
  105832. i = metadata->length;
  105833. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105834. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105835. i -= metadata->data.vorbis_comment.vendor_string.length;
  105836. i += vendor_string_length;
  105837. }
  105838. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105839. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105840. return false;
  105841. switch(metadata->type) {
  105842. case FLAC__METADATA_TYPE_STREAMINFO:
  105843. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105844. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105845. return false;
  105846. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105847. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105848. return false;
  105849. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105850. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105851. return false;
  105852. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105853. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105854. return false;
  105855. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105856. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105857. return false;
  105858. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105859. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105860. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105861. return false;
  105862. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105863. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105864. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105865. return false;
  105866. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105867. return false;
  105868. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105869. return false;
  105870. break;
  105871. case FLAC__METADATA_TYPE_PADDING:
  105872. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105873. return false;
  105874. break;
  105875. case FLAC__METADATA_TYPE_APPLICATION:
  105876. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105877. return false;
  105878. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105879. return false;
  105880. break;
  105881. case FLAC__METADATA_TYPE_SEEKTABLE:
  105882. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105883. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105884. return false;
  105885. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105886. return false;
  105887. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105888. return false;
  105889. }
  105890. break;
  105891. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105892. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105893. return false;
  105894. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105895. return false;
  105896. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105897. return false;
  105898. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105899. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105900. return false;
  105901. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105902. return false;
  105903. }
  105904. break;
  105905. case FLAC__METADATA_TYPE_CUESHEET:
  105906. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105907. 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))
  105908. return false;
  105909. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105910. return false;
  105911. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105912. return false;
  105913. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105914. return false;
  105915. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105916. return false;
  105917. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105918. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105919. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105920. return false;
  105921. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105922. return false;
  105923. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105924. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105925. return false;
  105926. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105927. return false;
  105928. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105929. return false;
  105930. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105931. return false;
  105932. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105933. return false;
  105934. for(j = 0; j < track->num_indices; j++) {
  105935. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105936. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105937. return false;
  105938. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105939. return false;
  105940. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105941. return false;
  105942. }
  105943. }
  105944. break;
  105945. case FLAC__METADATA_TYPE_PICTURE:
  105946. {
  105947. size_t len;
  105948. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105949. return false;
  105950. len = strlen(metadata->data.picture.mime_type);
  105951. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105952. return false;
  105953. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105954. return false;
  105955. len = strlen((const char *)metadata->data.picture.description);
  105956. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105957. return false;
  105958. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105959. return false;
  105960. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105961. return false;
  105962. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105963. return false;
  105964. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105965. return false;
  105966. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105967. return false;
  105968. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105969. return false;
  105970. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105971. return false;
  105972. }
  105973. break;
  105974. default:
  105975. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105976. return false;
  105977. break;
  105978. }
  105979. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105980. return true;
  105981. }
  105982. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105983. {
  105984. unsigned u, blocksize_hint, sample_rate_hint;
  105985. FLAC__byte crc;
  105986. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105987. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105988. return false;
  105989. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105990. return false;
  105991. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105992. return false;
  105993. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105994. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105995. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105996. blocksize_hint = 0;
  105997. switch(header->blocksize) {
  105998. case 192: u = 1; break;
  105999. case 576: u = 2; break;
  106000. case 1152: u = 3; break;
  106001. case 2304: u = 4; break;
  106002. case 4608: u = 5; break;
  106003. case 256: u = 8; break;
  106004. case 512: u = 9; break;
  106005. case 1024: u = 10; break;
  106006. case 2048: u = 11; break;
  106007. case 4096: u = 12; break;
  106008. case 8192: u = 13; break;
  106009. case 16384: u = 14; break;
  106010. case 32768: u = 15; break;
  106011. default:
  106012. if(header->blocksize <= 0x100)
  106013. blocksize_hint = u = 6;
  106014. else
  106015. blocksize_hint = u = 7;
  106016. break;
  106017. }
  106018. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106019. return false;
  106020. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106021. sample_rate_hint = 0;
  106022. switch(header->sample_rate) {
  106023. case 88200: u = 1; break;
  106024. case 176400: u = 2; break;
  106025. case 192000: u = 3; break;
  106026. case 8000: u = 4; break;
  106027. case 16000: u = 5; break;
  106028. case 22050: u = 6; break;
  106029. case 24000: u = 7; break;
  106030. case 32000: u = 8; break;
  106031. case 44100: u = 9; break;
  106032. case 48000: u = 10; break;
  106033. case 96000: u = 11; break;
  106034. default:
  106035. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106036. sample_rate_hint = u = 12;
  106037. else if(header->sample_rate % 10 == 0)
  106038. sample_rate_hint = u = 14;
  106039. else if(header->sample_rate <= 0xffff)
  106040. sample_rate_hint = u = 13;
  106041. else
  106042. u = 0;
  106043. break;
  106044. }
  106045. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106046. return false;
  106047. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106048. switch(header->channel_assignment) {
  106049. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106050. u = header->channels - 1;
  106051. break;
  106052. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106053. FLAC__ASSERT(header->channels == 2);
  106054. u = 8;
  106055. break;
  106056. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106057. FLAC__ASSERT(header->channels == 2);
  106058. u = 9;
  106059. break;
  106060. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106061. FLAC__ASSERT(header->channels == 2);
  106062. u = 10;
  106063. break;
  106064. default:
  106065. FLAC__ASSERT(0);
  106066. }
  106067. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106068. return false;
  106069. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106070. switch(header->bits_per_sample) {
  106071. case 8 : u = 1; break;
  106072. case 12: u = 2; break;
  106073. case 16: u = 4; break;
  106074. case 20: u = 5; break;
  106075. case 24: u = 6; break;
  106076. default: u = 0; break;
  106077. }
  106078. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106079. return false;
  106080. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106081. return false;
  106082. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106083. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106084. return false;
  106085. }
  106086. else {
  106087. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106088. return false;
  106089. }
  106090. if(blocksize_hint)
  106091. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106092. return false;
  106093. switch(sample_rate_hint) {
  106094. case 12:
  106095. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106096. return false;
  106097. break;
  106098. case 13:
  106099. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106100. return false;
  106101. break;
  106102. case 14:
  106103. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106104. return false;
  106105. break;
  106106. }
  106107. /* write the CRC */
  106108. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106109. return false;
  106110. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106111. return false;
  106112. return true;
  106113. }
  106114. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106115. {
  106116. FLAC__bool ok;
  106117. ok =
  106118. 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) &&
  106119. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106120. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106121. ;
  106122. return ok;
  106123. }
  106124. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106125. {
  106126. unsigned i;
  106127. 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))
  106128. return false;
  106129. if(wasted_bits)
  106130. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106131. return false;
  106132. for(i = 0; i < subframe->order; i++)
  106133. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106134. return false;
  106135. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106136. return false;
  106137. switch(subframe->entropy_coding_method.type) {
  106138. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106139. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106140. if(!add_residual_partitioned_rice_(
  106141. bw,
  106142. subframe->residual,
  106143. residual_samples,
  106144. subframe->order,
  106145. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106146. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106147. subframe->entropy_coding_method.data.partitioned_rice.order,
  106148. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106149. ))
  106150. return false;
  106151. break;
  106152. default:
  106153. FLAC__ASSERT(0);
  106154. }
  106155. return true;
  106156. }
  106157. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106158. {
  106159. unsigned i;
  106160. 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))
  106161. return false;
  106162. if(wasted_bits)
  106163. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106164. return false;
  106165. for(i = 0; i < subframe->order; i++)
  106166. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106167. return false;
  106168. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106169. return false;
  106170. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106171. return false;
  106172. for(i = 0; i < subframe->order; i++)
  106173. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106174. return false;
  106175. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106176. return false;
  106177. switch(subframe->entropy_coding_method.type) {
  106178. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106179. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106180. if(!add_residual_partitioned_rice_(
  106181. bw,
  106182. subframe->residual,
  106183. residual_samples,
  106184. subframe->order,
  106185. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106186. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106187. subframe->entropy_coding_method.data.partitioned_rice.order,
  106188. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106189. ))
  106190. return false;
  106191. break;
  106192. default:
  106193. FLAC__ASSERT(0);
  106194. }
  106195. return true;
  106196. }
  106197. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106198. {
  106199. unsigned i;
  106200. const FLAC__int32 *signal = subframe->data;
  106201. 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))
  106202. return false;
  106203. if(wasted_bits)
  106204. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106205. return false;
  106206. for(i = 0; i < samples; i++)
  106207. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106208. return false;
  106209. return true;
  106210. }
  106211. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106212. {
  106213. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106214. return false;
  106215. switch(method->type) {
  106216. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106217. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106218. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106219. return false;
  106220. break;
  106221. default:
  106222. FLAC__ASSERT(0);
  106223. }
  106224. return true;
  106225. }
  106226. 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)
  106227. {
  106228. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106229. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106230. if(partition_order == 0) {
  106231. unsigned i;
  106232. if(raw_bits[0] == 0) {
  106233. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106234. return false;
  106235. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106236. return false;
  106237. }
  106238. else {
  106239. FLAC__ASSERT(rice_parameters[0] == 0);
  106240. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106241. return false;
  106242. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106243. return false;
  106244. for(i = 0; i < residual_samples; i++) {
  106245. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106246. return false;
  106247. }
  106248. }
  106249. return true;
  106250. }
  106251. else {
  106252. unsigned i, j, k = 0, k_last = 0;
  106253. unsigned partition_samples;
  106254. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106255. for(i = 0; i < (1u<<partition_order); i++) {
  106256. partition_samples = default_partition_samples;
  106257. if(i == 0)
  106258. partition_samples -= predictor_order;
  106259. k += partition_samples;
  106260. if(raw_bits[i] == 0) {
  106261. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106262. return false;
  106263. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106264. return false;
  106265. }
  106266. else {
  106267. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106268. return false;
  106269. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106270. return false;
  106271. for(j = k_last; j < k; j++) {
  106272. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106273. return false;
  106274. }
  106275. }
  106276. k_last = k;
  106277. }
  106278. return true;
  106279. }
  106280. }
  106281. #endif
  106282. /*** End of inlined file: stream_encoder_framing.c ***/
  106283. /*** Start of inlined file: window_flac.c ***/
  106284. /*** Start of inlined file: juce_FlacHeader.h ***/
  106285. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106286. // tasks..
  106287. #define VERSION "1.2.1"
  106288. #define FLAC__NO_DLL 1
  106289. #if JUCE_MSVC
  106290. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106291. #endif
  106292. #if JUCE_MAC
  106293. #define FLAC__SYS_DARWIN 1
  106294. #endif
  106295. /*** End of inlined file: juce_FlacHeader.h ***/
  106296. #if JUCE_USE_FLAC
  106297. #if HAVE_CONFIG_H
  106298. # include <config.h>
  106299. #endif
  106300. #include <math.h>
  106301. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106302. #ifndef M_PI
  106303. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106304. #define M_PI 3.14159265358979323846
  106305. #endif
  106306. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106307. {
  106308. const FLAC__int32 N = L - 1;
  106309. FLAC__int32 n;
  106310. if (L & 1) {
  106311. for (n = 0; n <= N/2; n++)
  106312. window[n] = 2.0f * n / (float)N;
  106313. for (; n <= N; n++)
  106314. window[n] = 2.0f - 2.0f * n / (float)N;
  106315. }
  106316. else {
  106317. for (n = 0; n <= L/2-1; n++)
  106318. window[n] = 2.0f * n / (float)N;
  106319. for (; n <= N; n++)
  106320. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106321. }
  106322. }
  106323. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106324. {
  106325. const FLAC__int32 N = L - 1;
  106326. FLAC__int32 n;
  106327. for (n = 0; n < L; n++)
  106328. 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)));
  106329. }
  106330. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106331. {
  106332. const FLAC__int32 N = L - 1;
  106333. FLAC__int32 n;
  106334. for (n = 0; n < L; n++)
  106335. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106336. }
  106337. /* 4-term -92dB side-lobe */
  106338. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106339. {
  106340. const FLAC__int32 N = L - 1;
  106341. FLAC__int32 n;
  106342. for (n = 0; n <= N; n++)
  106343. 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));
  106344. }
  106345. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106346. {
  106347. const FLAC__int32 N = L - 1;
  106348. const double N2 = (double)N / 2.;
  106349. FLAC__int32 n;
  106350. for (n = 0; n <= N; n++) {
  106351. double k = ((double)n - N2) / N2;
  106352. k = 1.0f - k * k;
  106353. window[n] = (FLAC__real)(k * k);
  106354. }
  106355. }
  106356. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106357. {
  106358. const FLAC__int32 N = L - 1;
  106359. FLAC__int32 n;
  106360. for (n = 0; n < L; n++)
  106361. 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));
  106362. }
  106363. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106364. {
  106365. const FLAC__int32 N = L - 1;
  106366. const double N2 = (double)N / 2.;
  106367. FLAC__int32 n;
  106368. for (n = 0; n <= N; n++) {
  106369. const double k = ((double)n - N2) / (stddev * N2);
  106370. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106371. }
  106372. }
  106373. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106374. {
  106375. const FLAC__int32 N = L - 1;
  106376. FLAC__int32 n;
  106377. for (n = 0; n < L; n++)
  106378. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106379. }
  106380. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106381. {
  106382. const FLAC__int32 N = L - 1;
  106383. FLAC__int32 n;
  106384. for (n = 0; n < L; n++)
  106385. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106386. }
  106387. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106388. {
  106389. const FLAC__int32 N = L - 1;
  106390. FLAC__int32 n;
  106391. for (n = 0; n < L; n++)
  106392. 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));
  106393. }
  106394. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106395. {
  106396. const FLAC__int32 N = L - 1;
  106397. FLAC__int32 n;
  106398. for (n = 0; n < L; n++)
  106399. 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));
  106400. }
  106401. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106402. {
  106403. FLAC__int32 n;
  106404. for (n = 0; n < L; n++)
  106405. window[n] = 1.0f;
  106406. }
  106407. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106408. {
  106409. FLAC__int32 n;
  106410. if (L & 1) {
  106411. for (n = 1; n <= L+1/2; n++)
  106412. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106413. for (; n <= L; n++)
  106414. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106415. }
  106416. else {
  106417. for (n = 1; n <= L/2; n++)
  106418. window[n-1] = 2.0f * n / (float)L;
  106419. for (; n <= L; n++)
  106420. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106421. }
  106422. }
  106423. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106424. {
  106425. if (p <= 0.0)
  106426. FLAC__window_rectangle(window, L);
  106427. else if (p >= 1.0)
  106428. FLAC__window_hann(window, L);
  106429. else {
  106430. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106431. FLAC__int32 n;
  106432. /* start with rectangle... */
  106433. FLAC__window_rectangle(window, L);
  106434. /* ...replace ends with hann */
  106435. if (Np > 0) {
  106436. for (n = 0; n <= Np; n++) {
  106437. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106438. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106439. }
  106440. }
  106441. }
  106442. }
  106443. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106444. {
  106445. const FLAC__int32 N = L - 1;
  106446. const double N2 = (double)N / 2.;
  106447. FLAC__int32 n;
  106448. for (n = 0; n <= N; n++) {
  106449. const double k = ((double)n - N2) / N2;
  106450. window[n] = (FLAC__real)(1.0f - k * k);
  106451. }
  106452. }
  106453. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106454. #endif
  106455. /*** End of inlined file: window_flac.c ***/
  106456. #else
  106457. #include <FLAC/all.h>
  106458. #endif
  106459. }
  106460. #undef max
  106461. #undef min
  106462. BEGIN_JUCE_NAMESPACE
  106463. static const char* const flacFormatName = "FLAC file";
  106464. static const char* const flacExtensions[] = { ".flac", 0 };
  106465. class FlacReader : public AudioFormatReader
  106466. {
  106467. public:
  106468. FlacReader (InputStream* const in)
  106469. : AudioFormatReader (in, TRANS (flacFormatName)),
  106470. reservoir (2, 0),
  106471. reservoirStart (0),
  106472. samplesInReservoir (0),
  106473. scanningForLength (false)
  106474. {
  106475. using namespace FlacNamespace;
  106476. lengthInSamples = 0;
  106477. decoder = FLAC__stream_decoder_new();
  106478. ok = FLAC__stream_decoder_init_stream (decoder,
  106479. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106480. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106481. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106482. if (ok)
  106483. {
  106484. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106485. if (lengthInSamples == 0 && sampleRate > 0)
  106486. {
  106487. // the length hasn't been stored in the metadata, so we'll need to
  106488. // work it out the length the hard way, by scanning the whole file..
  106489. scanningForLength = true;
  106490. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106491. scanningForLength = false;
  106492. const int64 tempLength = lengthInSamples;
  106493. FLAC__stream_decoder_reset (decoder);
  106494. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106495. lengthInSamples = tempLength;
  106496. }
  106497. }
  106498. }
  106499. ~FlacReader()
  106500. {
  106501. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106502. }
  106503. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106504. {
  106505. sampleRate = info.sample_rate;
  106506. bitsPerSample = info.bits_per_sample;
  106507. lengthInSamples = (unsigned int) info.total_samples;
  106508. numChannels = info.channels;
  106509. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106510. }
  106511. // returns the number of samples read
  106512. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106513. int64 startSampleInFile, int numSamples)
  106514. {
  106515. using namespace FlacNamespace;
  106516. if (! ok)
  106517. return false;
  106518. while (numSamples > 0)
  106519. {
  106520. if (startSampleInFile >= reservoirStart
  106521. && startSampleInFile < reservoirStart + samplesInReservoir)
  106522. {
  106523. const int num = (int) jmin ((int64) numSamples,
  106524. reservoirStart + samplesInReservoir - startSampleInFile);
  106525. jassert (num > 0);
  106526. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106527. if (destSamples[i] != 0)
  106528. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106529. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106530. sizeof (int) * num);
  106531. startOffsetInDestBuffer += num;
  106532. startSampleInFile += num;
  106533. numSamples -= num;
  106534. }
  106535. else
  106536. {
  106537. if (startSampleInFile >= (int) lengthInSamples)
  106538. {
  106539. samplesInReservoir = 0;
  106540. }
  106541. else if (startSampleInFile < reservoirStart
  106542. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106543. {
  106544. // had some problems with flac crashing if the read pos is aligned more
  106545. // accurately than this. Probably fixed in newer versions of the library, though.
  106546. reservoirStart = (int) (startSampleInFile & ~511);
  106547. samplesInReservoir = 0;
  106548. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106549. }
  106550. else
  106551. {
  106552. reservoirStart += samplesInReservoir;
  106553. samplesInReservoir = 0;
  106554. FLAC__stream_decoder_process_single (decoder);
  106555. }
  106556. if (samplesInReservoir == 0)
  106557. break;
  106558. }
  106559. }
  106560. if (numSamples > 0)
  106561. {
  106562. for (int i = numDestChannels; --i >= 0;)
  106563. if (destSamples[i] != 0)
  106564. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106565. sizeof (int) * numSamples);
  106566. }
  106567. return true;
  106568. }
  106569. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106570. {
  106571. if (scanningForLength)
  106572. {
  106573. lengthInSamples += numSamples;
  106574. }
  106575. else
  106576. {
  106577. if (numSamples > reservoir.getNumSamples())
  106578. reservoir.setSize (numChannels, numSamples, false, false, true);
  106579. const int bitsToShift = 32 - bitsPerSample;
  106580. for (int i = 0; i < (int) numChannels; ++i)
  106581. {
  106582. const FlacNamespace::FLAC__int32* src = buffer[i];
  106583. int n = i;
  106584. while (src == 0 && n > 0)
  106585. src = buffer [--n];
  106586. if (src != 0)
  106587. {
  106588. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106589. for (int j = 0; j < numSamples; ++j)
  106590. dest[j] = src[j] << bitsToShift;
  106591. }
  106592. }
  106593. samplesInReservoir = numSamples;
  106594. }
  106595. }
  106596. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106597. {
  106598. using namespace FlacNamespace;
  106599. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106600. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106601. }
  106602. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106603. {
  106604. using namespace FlacNamespace;
  106605. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106606. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106607. }
  106608. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106609. {
  106610. using namespace FlacNamespace;
  106611. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106612. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106613. }
  106614. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106615. {
  106616. using namespace FlacNamespace;
  106617. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106618. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106619. }
  106620. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106621. {
  106622. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106623. }
  106624. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106625. const FlacNamespace::FLAC__Frame* frame,
  106626. const FlacNamespace::FLAC__int32* const buffer[],
  106627. void* client_data)
  106628. {
  106629. using namespace FlacNamespace;
  106630. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106631. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106632. }
  106633. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106634. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106635. void* client_data)
  106636. {
  106637. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106638. }
  106639. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106640. {
  106641. }
  106642. private:
  106643. FlacNamespace::FLAC__StreamDecoder* decoder;
  106644. AudioSampleBuffer reservoir;
  106645. int reservoirStart, samplesInReservoir;
  106646. bool ok, scanningForLength;
  106647. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106648. };
  106649. class FlacWriter : public AudioFormatWriter
  106650. {
  106651. public:
  106652. FlacWriter (OutputStream* const out, double sampleRate_,
  106653. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106654. : AudioFormatWriter (out, TRANS (flacFormatName),
  106655. sampleRate_, numChannels_, bitsPerSample_)
  106656. {
  106657. using namespace FlacNamespace;
  106658. encoder = FLAC__stream_encoder_new();
  106659. if (qualityOptionIndex > 0)
  106660. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106661. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106662. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106663. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106664. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106665. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106666. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106667. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106668. ok = FLAC__stream_encoder_init_stream (encoder,
  106669. encodeWriteCallback, encodeSeekCallback,
  106670. encodeTellCallback, encodeMetadataCallback,
  106671. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106672. }
  106673. ~FlacWriter()
  106674. {
  106675. if (ok)
  106676. {
  106677. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106678. output->flush();
  106679. }
  106680. else
  106681. {
  106682. output = 0; // to stop the base class deleting this, as it needs to be returned
  106683. // to the caller of createWriter()
  106684. }
  106685. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106686. }
  106687. bool write (const int** samplesToWrite, int numSamples)
  106688. {
  106689. using namespace FlacNamespace;
  106690. if (! ok)
  106691. return false;
  106692. int* buf[3];
  106693. HeapBlock<int> temp;
  106694. const int bitsToShift = 32 - bitsPerSample;
  106695. if (bitsToShift > 0)
  106696. {
  106697. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106698. temp.malloc (numSamples * numChannelsToWrite);
  106699. buf[0] = temp.getData();
  106700. buf[1] = temp.getData() + numSamples;
  106701. buf[2] = 0;
  106702. for (int i = numChannelsToWrite; --i >= 0;)
  106703. if (samplesToWrite[i] != 0)
  106704. for (int j = 0; j < numSamples; ++j)
  106705. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106706. samplesToWrite = const_cast<const int**> (buf);
  106707. }
  106708. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106709. }
  106710. bool writeData (const void* const data, const int size) const
  106711. {
  106712. return output->write (data, size);
  106713. }
  106714. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106715. {
  106716. using namespace FlacNamespace;
  106717. b += bytes;
  106718. for (int i = 0; i < bytes; ++i)
  106719. {
  106720. *(--b) = (FLAC__byte) (val & 0xff);
  106721. val >>= 8;
  106722. }
  106723. }
  106724. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106725. {
  106726. using namespace FlacNamespace;
  106727. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106728. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106729. const unsigned int channelsMinus1 = info.channels - 1;
  106730. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106731. packUint32 (info.min_blocksize, buffer, 2);
  106732. packUint32 (info.max_blocksize, buffer + 2, 2);
  106733. packUint32 (info.min_framesize, buffer + 4, 3);
  106734. packUint32 (info.max_framesize, buffer + 7, 3);
  106735. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106736. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106737. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106738. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106739. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106740. memcpy (buffer + 18, info.md5sum, 16);
  106741. const bool seekOk = output->setPosition (4);
  106742. (void) seekOk;
  106743. // if this fails, you've given it an output stream that can't seek! It needs
  106744. // to be able to seek back to write the header
  106745. jassert (seekOk);
  106746. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106747. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106748. }
  106749. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106750. const FlacNamespace::FLAC__byte buffer[],
  106751. size_t bytes,
  106752. unsigned int /*samples*/,
  106753. unsigned int /*current_frame*/,
  106754. void* client_data)
  106755. {
  106756. using namespace FlacNamespace;
  106757. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106758. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106759. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106760. }
  106761. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106762. {
  106763. using namespace FlacNamespace;
  106764. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106765. }
  106766. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106767. {
  106768. using namespace FlacNamespace;
  106769. if (client_data == 0)
  106770. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106771. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106772. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106773. }
  106774. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106775. {
  106776. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106777. }
  106778. bool ok;
  106779. private:
  106780. FlacNamespace::FLAC__StreamEncoder* encoder;
  106781. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  106782. };
  106783. FlacAudioFormat::FlacAudioFormat()
  106784. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106785. {
  106786. }
  106787. FlacAudioFormat::~FlacAudioFormat()
  106788. {
  106789. }
  106790. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106791. {
  106792. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106793. return Array <int> (rates);
  106794. }
  106795. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106796. {
  106797. const int depths[] = { 16, 24, 0 };
  106798. return Array <int> (depths);
  106799. }
  106800. bool FlacAudioFormat::canDoStereo() { return true; }
  106801. bool FlacAudioFormat::canDoMono() { return true; }
  106802. bool FlacAudioFormat::isCompressed() { return true; }
  106803. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106804. const bool deleteStreamIfOpeningFails)
  106805. {
  106806. ScopedPointer<FlacReader> r (new FlacReader (in));
  106807. if (r->sampleRate != 0)
  106808. return r.release();
  106809. if (! deleteStreamIfOpeningFails)
  106810. r->input = 0;
  106811. return 0;
  106812. }
  106813. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106814. double sampleRate,
  106815. unsigned int numberOfChannels,
  106816. int bitsPerSample,
  106817. const StringPairArray& /*metadataValues*/,
  106818. int qualityOptionIndex)
  106819. {
  106820. if (getPossibleBitDepths().contains (bitsPerSample))
  106821. {
  106822. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  106823. if (w->ok)
  106824. return w.release();
  106825. }
  106826. return 0;
  106827. }
  106828. END_JUCE_NAMESPACE
  106829. #endif
  106830. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106831. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106832. #if JUCE_USE_OGGVORBIS
  106833. #if JUCE_MAC
  106834. #define __MACOSX__ 1
  106835. #endif
  106836. namespace OggVorbisNamespace
  106837. {
  106838. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106839. /*** Start of inlined file: vorbisenc.h ***/
  106840. #ifndef _OV_ENC_H_
  106841. #define _OV_ENC_H_
  106842. #ifdef __cplusplus
  106843. extern "C"
  106844. {
  106845. #endif /* __cplusplus */
  106846. /*** Start of inlined file: codec.h ***/
  106847. #ifndef _vorbis_codec_h_
  106848. #define _vorbis_codec_h_
  106849. #ifdef __cplusplus
  106850. extern "C"
  106851. {
  106852. #endif /* __cplusplus */
  106853. /*** Start of inlined file: ogg.h ***/
  106854. #ifndef _OGG_H
  106855. #define _OGG_H
  106856. #ifdef __cplusplus
  106857. extern "C" {
  106858. #endif
  106859. /*** Start of inlined file: os_types.h ***/
  106860. #ifndef _OS_TYPES_H
  106861. #define _OS_TYPES_H
  106862. /* make it easy on the folks that want to compile the libs with a
  106863. different malloc than stdlib */
  106864. #define _ogg_malloc malloc
  106865. #define _ogg_calloc calloc
  106866. #define _ogg_realloc realloc
  106867. #define _ogg_free free
  106868. #if defined(_WIN32)
  106869. # if defined(__CYGWIN__)
  106870. # include <_G_config.h>
  106871. typedef _G_int64_t ogg_int64_t;
  106872. typedef _G_int32_t ogg_int32_t;
  106873. typedef _G_uint32_t ogg_uint32_t;
  106874. typedef _G_int16_t ogg_int16_t;
  106875. typedef _G_uint16_t ogg_uint16_t;
  106876. # elif defined(__MINGW32__)
  106877. typedef short ogg_int16_t;
  106878. typedef unsigned short ogg_uint16_t;
  106879. typedef int ogg_int32_t;
  106880. typedef unsigned int ogg_uint32_t;
  106881. typedef long long ogg_int64_t;
  106882. typedef unsigned long long ogg_uint64_t;
  106883. # elif defined(__MWERKS__)
  106884. typedef long long ogg_int64_t;
  106885. typedef int ogg_int32_t;
  106886. typedef unsigned int ogg_uint32_t;
  106887. typedef short ogg_int16_t;
  106888. typedef unsigned short ogg_uint16_t;
  106889. # else
  106890. /* MSVC/Borland */
  106891. typedef __int64 ogg_int64_t;
  106892. typedef __int32 ogg_int32_t;
  106893. typedef unsigned __int32 ogg_uint32_t;
  106894. typedef __int16 ogg_int16_t;
  106895. typedef unsigned __int16 ogg_uint16_t;
  106896. # endif
  106897. #elif defined(__MACOS__)
  106898. # include <sys/types.h>
  106899. typedef SInt16 ogg_int16_t;
  106900. typedef UInt16 ogg_uint16_t;
  106901. typedef SInt32 ogg_int32_t;
  106902. typedef UInt32 ogg_uint32_t;
  106903. typedef SInt64 ogg_int64_t;
  106904. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106905. # include <sys/types.h>
  106906. typedef int16_t ogg_int16_t;
  106907. typedef u_int16_t ogg_uint16_t;
  106908. typedef int32_t ogg_int32_t;
  106909. typedef u_int32_t ogg_uint32_t;
  106910. typedef int64_t ogg_int64_t;
  106911. #elif defined(__BEOS__)
  106912. /* Be */
  106913. # include <inttypes.h>
  106914. typedef int16_t ogg_int16_t;
  106915. typedef u_int16_t ogg_uint16_t;
  106916. typedef int32_t ogg_int32_t;
  106917. typedef u_int32_t ogg_uint32_t;
  106918. typedef int64_t ogg_int64_t;
  106919. #elif defined (__EMX__)
  106920. /* OS/2 GCC */
  106921. typedef short ogg_int16_t;
  106922. typedef unsigned short ogg_uint16_t;
  106923. typedef int ogg_int32_t;
  106924. typedef unsigned int ogg_uint32_t;
  106925. typedef long long ogg_int64_t;
  106926. #elif defined (DJGPP)
  106927. /* DJGPP */
  106928. typedef short ogg_int16_t;
  106929. typedef int ogg_int32_t;
  106930. typedef unsigned int ogg_uint32_t;
  106931. typedef long long ogg_int64_t;
  106932. #elif defined(R5900)
  106933. /* PS2 EE */
  106934. typedef long ogg_int64_t;
  106935. typedef int ogg_int32_t;
  106936. typedef unsigned ogg_uint32_t;
  106937. typedef short ogg_int16_t;
  106938. #elif defined(__SYMBIAN32__)
  106939. /* Symbian GCC */
  106940. typedef signed short ogg_int16_t;
  106941. typedef unsigned short ogg_uint16_t;
  106942. typedef signed int ogg_int32_t;
  106943. typedef unsigned int ogg_uint32_t;
  106944. typedef long long int ogg_int64_t;
  106945. #else
  106946. # include <sys/types.h>
  106947. /*** Start of inlined file: config_types.h ***/
  106948. #ifndef __CONFIG_TYPES_H__
  106949. #define __CONFIG_TYPES_H__
  106950. typedef int16_t ogg_int16_t;
  106951. typedef unsigned short ogg_uint16_t;
  106952. typedef int32_t ogg_int32_t;
  106953. typedef unsigned int ogg_uint32_t;
  106954. typedef int64_t ogg_int64_t;
  106955. #endif
  106956. /*** End of inlined file: config_types.h ***/
  106957. #endif
  106958. #endif /* _OS_TYPES_H */
  106959. /*** End of inlined file: os_types.h ***/
  106960. typedef struct {
  106961. long endbyte;
  106962. int endbit;
  106963. unsigned char *buffer;
  106964. unsigned char *ptr;
  106965. long storage;
  106966. } oggpack_buffer;
  106967. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106968. typedef struct {
  106969. unsigned char *header;
  106970. long header_len;
  106971. unsigned char *body;
  106972. long body_len;
  106973. } ogg_page;
  106974. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106975. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106976. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106977. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106978. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106979. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106980. }
  106981. /* ogg_stream_state contains the current encode/decode state of a logical
  106982. Ogg bitstream **********************************************************/
  106983. typedef struct {
  106984. unsigned char *body_data; /* bytes from packet bodies */
  106985. long body_storage; /* storage elements allocated */
  106986. long body_fill; /* elements stored; fill mark */
  106987. long body_returned; /* elements of fill returned */
  106988. int *lacing_vals; /* The values that will go to the segment table */
  106989. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106990. this way, but it is simple coupled to the
  106991. lacing fifo */
  106992. long lacing_storage;
  106993. long lacing_fill;
  106994. long lacing_packet;
  106995. long lacing_returned;
  106996. unsigned char header[282]; /* working space for header encode */
  106997. int header_fill;
  106998. int e_o_s; /* set when we have buffered the last packet in the
  106999. logical bitstream */
  107000. int b_o_s; /* set after we've written the initial page
  107001. of a logical bitstream */
  107002. long serialno;
  107003. long pageno;
  107004. ogg_int64_t packetno; /* sequence number for decode; the framing
  107005. knows where there's a hole in the data,
  107006. but we need coupling so that the codec
  107007. (which is in a seperate abstraction
  107008. layer) also knows about the gap */
  107009. ogg_int64_t granulepos;
  107010. } ogg_stream_state;
  107011. /* ogg_packet is used to encapsulate the data and metadata belonging
  107012. to a single raw Ogg/Vorbis packet *************************************/
  107013. typedef struct {
  107014. unsigned char *packet;
  107015. long bytes;
  107016. long b_o_s;
  107017. long e_o_s;
  107018. ogg_int64_t granulepos;
  107019. ogg_int64_t packetno; /* sequence number for decode; the framing
  107020. knows where there's a hole in the data,
  107021. but we need coupling so that the codec
  107022. (which is in a seperate abstraction
  107023. layer) also knows about the gap */
  107024. } ogg_packet;
  107025. typedef struct {
  107026. unsigned char *data;
  107027. int storage;
  107028. int fill;
  107029. int returned;
  107030. int unsynced;
  107031. int headerbytes;
  107032. int bodybytes;
  107033. } ogg_sync_state;
  107034. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107035. extern void oggpack_writeinit(oggpack_buffer *b);
  107036. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107037. extern void oggpack_writealign(oggpack_buffer *b);
  107038. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107039. extern void oggpack_reset(oggpack_buffer *b);
  107040. extern void oggpack_writeclear(oggpack_buffer *b);
  107041. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107042. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107043. extern long oggpack_look(oggpack_buffer *b,int bits);
  107044. extern long oggpack_look1(oggpack_buffer *b);
  107045. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107046. extern void oggpack_adv1(oggpack_buffer *b);
  107047. extern long oggpack_read(oggpack_buffer *b,int bits);
  107048. extern long oggpack_read1(oggpack_buffer *b);
  107049. extern long oggpack_bytes(oggpack_buffer *b);
  107050. extern long oggpack_bits(oggpack_buffer *b);
  107051. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107052. extern void oggpackB_writeinit(oggpack_buffer *b);
  107053. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107054. extern void oggpackB_writealign(oggpack_buffer *b);
  107055. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107056. extern void oggpackB_reset(oggpack_buffer *b);
  107057. extern void oggpackB_writeclear(oggpack_buffer *b);
  107058. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107059. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107060. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107061. extern long oggpackB_look1(oggpack_buffer *b);
  107062. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107063. extern void oggpackB_adv1(oggpack_buffer *b);
  107064. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107065. extern long oggpackB_read1(oggpack_buffer *b);
  107066. extern long oggpackB_bytes(oggpack_buffer *b);
  107067. extern long oggpackB_bits(oggpack_buffer *b);
  107068. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107069. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107070. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107071. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107072. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107073. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107074. extern int ogg_sync_init(ogg_sync_state *oy);
  107075. extern int ogg_sync_clear(ogg_sync_state *oy);
  107076. extern int ogg_sync_reset(ogg_sync_state *oy);
  107077. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107078. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107079. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107080. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107081. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107082. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107083. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107084. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107085. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107086. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107087. extern int ogg_stream_clear(ogg_stream_state *os);
  107088. extern int ogg_stream_reset(ogg_stream_state *os);
  107089. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107090. extern int ogg_stream_destroy(ogg_stream_state *os);
  107091. extern int ogg_stream_eos(ogg_stream_state *os);
  107092. extern void ogg_page_checksum_set(ogg_page *og);
  107093. extern int ogg_page_version(ogg_page *og);
  107094. extern int ogg_page_continued(ogg_page *og);
  107095. extern int ogg_page_bos(ogg_page *og);
  107096. extern int ogg_page_eos(ogg_page *og);
  107097. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107098. extern int ogg_page_serialno(ogg_page *og);
  107099. extern long ogg_page_pageno(ogg_page *og);
  107100. extern int ogg_page_packets(ogg_page *og);
  107101. extern void ogg_packet_clear(ogg_packet *op);
  107102. #ifdef __cplusplus
  107103. }
  107104. #endif
  107105. #endif /* _OGG_H */
  107106. /*** End of inlined file: ogg.h ***/
  107107. typedef struct vorbis_info{
  107108. int version;
  107109. int channels;
  107110. long rate;
  107111. /* The below bitrate declarations are *hints*.
  107112. Combinations of the three values carry the following implications:
  107113. all three set to the same value:
  107114. implies a fixed rate bitstream
  107115. only nominal set:
  107116. implies a VBR stream that averages the nominal bitrate. No hard
  107117. upper/lower limit
  107118. upper and or lower set:
  107119. implies a VBR bitstream that obeys the bitrate limits. nominal
  107120. may also be set to give a nominal rate.
  107121. none set:
  107122. the coder does not care to speculate.
  107123. */
  107124. long bitrate_upper;
  107125. long bitrate_nominal;
  107126. long bitrate_lower;
  107127. long bitrate_window;
  107128. void *codec_setup;
  107129. } vorbis_info;
  107130. /* vorbis_dsp_state buffers the current vorbis audio
  107131. analysis/synthesis state. The DSP state belongs to a specific
  107132. logical bitstream ****************************************************/
  107133. typedef struct vorbis_dsp_state{
  107134. int analysisp;
  107135. vorbis_info *vi;
  107136. float **pcm;
  107137. float **pcmret;
  107138. int pcm_storage;
  107139. int pcm_current;
  107140. int pcm_returned;
  107141. int preextrapolate;
  107142. int eofflag;
  107143. long lW;
  107144. long W;
  107145. long nW;
  107146. long centerW;
  107147. ogg_int64_t granulepos;
  107148. ogg_int64_t sequence;
  107149. ogg_int64_t glue_bits;
  107150. ogg_int64_t time_bits;
  107151. ogg_int64_t floor_bits;
  107152. ogg_int64_t res_bits;
  107153. void *backend_state;
  107154. } vorbis_dsp_state;
  107155. typedef struct vorbis_block{
  107156. /* necessary stream state for linking to the framing abstraction */
  107157. float **pcm; /* this is a pointer into local storage */
  107158. oggpack_buffer opb;
  107159. long lW;
  107160. long W;
  107161. long nW;
  107162. int pcmend;
  107163. int mode;
  107164. int eofflag;
  107165. ogg_int64_t granulepos;
  107166. ogg_int64_t sequence;
  107167. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107168. /* local storage to avoid remallocing; it's up to the mapping to
  107169. structure it */
  107170. void *localstore;
  107171. long localtop;
  107172. long localalloc;
  107173. long totaluse;
  107174. struct alloc_chain *reap;
  107175. /* bitmetrics for the frame */
  107176. long glue_bits;
  107177. long time_bits;
  107178. long floor_bits;
  107179. long res_bits;
  107180. void *internal;
  107181. } vorbis_block;
  107182. /* vorbis_block is a single block of data to be processed as part of
  107183. the analysis/synthesis stream; it belongs to a specific logical
  107184. bitstream, but is independant from other vorbis_blocks belonging to
  107185. that logical bitstream. *************************************************/
  107186. struct alloc_chain{
  107187. void *ptr;
  107188. struct alloc_chain *next;
  107189. };
  107190. /* vorbis_info contains all the setup information specific to the
  107191. specific compression/decompression mode in progress (eg,
  107192. psychoacoustic settings, channel setup, options, codebook
  107193. etc). vorbis_info and substructures are in backends.h.
  107194. *********************************************************************/
  107195. /* the comments are not part of vorbis_info so that vorbis_info can be
  107196. static storage */
  107197. typedef struct vorbis_comment{
  107198. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107199. whatever vendor is set to in encode */
  107200. char **user_comments;
  107201. int *comment_lengths;
  107202. int comments;
  107203. char *vendor;
  107204. } vorbis_comment;
  107205. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107206. and produce a packet (see docs/analysis.txt). The packet is then
  107207. coded into a framed OggSquish bitstream by the second layer (see
  107208. docs/framing.txt). Decode is the reverse process; we sync/frame
  107209. the bitstream and extract individual packets, then decode the
  107210. packet back into PCM audio.
  107211. The extra framing/packetizing is used in streaming formats, such as
  107212. files. Over the net (such as with UDP), the framing and
  107213. packetization aren't necessary as they're provided by the transport
  107214. and the streaming layer is not used */
  107215. /* Vorbis PRIMITIVES: general ***************************************/
  107216. extern void vorbis_info_init(vorbis_info *vi);
  107217. extern void vorbis_info_clear(vorbis_info *vi);
  107218. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107219. extern void vorbis_comment_init(vorbis_comment *vc);
  107220. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107221. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107222. const char *tag, char *contents);
  107223. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107224. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107225. extern void vorbis_comment_clear(vorbis_comment *vc);
  107226. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107227. extern int vorbis_block_clear(vorbis_block *vb);
  107228. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107229. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107230. ogg_int64_t granulepos);
  107231. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107232. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107233. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107234. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107235. vorbis_comment *vc,
  107236. ogg_packet *op,
  107237. ogg_packet *op_comm,
  107238. ogg_packet *op_code);
  107239. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107240. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107241. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107242. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107243. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107244. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107245. ogg_packet *op);
  107246. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107247. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107248. ogg_packet *op);
  107249. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107250. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107251. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107252. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107253. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107254. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107255. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107256. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107257. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107258. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107259. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107260. /* Vorbis ERRORS and return codes ***********************************/
  107261. #define OV_FALSE -1
  107262. #define OV_EOF -2
  107263. #define OV_HOLE -3
  107264. #define OV_EREAD -128
  107265. #define OV_EFAULT -129
  107266. #define OV_EIMPL -130
  107267. #define OV_EINVAL -131
  107268. #define OV_ENOTVORBIS -132
  107269. #define OV_EBADHEADER -133
  107270. #define OV_EVERSION -134
  107271. #define OV_ENOTAUDIO -135
  107272. #define OV_EBADPACKET -136
  107273. #define OV_EBADLINK -137
  107274. #define OV_ENOSEEK -138
  107275. #ifdef __cplusplus
  107276. }
  107277. #endif /* __cplusplus */
  107278. #endif
  107279. /*** End of inlined file: codec.h ***/
  107280. extern int vorbis_encode_init(vorbis_info *vi,
  107281. long channels,
  107282. long rate,
  107283. long max_bitrate,
  107284. long nominal_bitrate,
  107285. long min_bitrate);
  107286. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107287. long channels,
  107288. long rate,
  107289. long max_bitrate,
  107290. long nominal_bitrate,
  107291. long min_bitrate);
  107292. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107293. long channels,
  107294. long rate,
  107295. float quality /* quality level from 0. (lo) to 1. (hi) */
  107296. );
  107297. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107298. long channels,
  107299. long rate,
  107300. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107301. );
  107302. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107303. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107304. /* deprecated rate management supported only for compatability */
  107305. #define OV_ECTL_RATEMANAGE_GET 0x10
  107306. #define OV_ECTL_RATEMANAGE_SET 0x11
  107307. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107308. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107309. struct ovectl_ratemanage_arg {
  107310. int management_active;
  107311. long bitrate_hard_min;
  107312. long bitrate_hard_max;
  107313. double bitrate_hard_window;
  107314. long bitrate_av_lo;
  107315. long bitrate_av_hi;
  107316. double bitrate_av_window;
  107317. double bitrate_av_window_center;
  107318. };
  107319. /* new rate setup */
  107320. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107321. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107322. struct ovectl_ratemanage2_arg {
  107323. int management_active;
  107324. long bitrate_limit_min_kbps;
  107325. long bitrate_limit_max_kbps;
  107326. long bitrate_limit_reservoir_bits;
  107327. double bitrate_limit_reservoir_bias;
  107328. long bitrate_average_kbps;
  107329. double bitrate_average_damping;
  107330. };
  107331. #define OV_ECTL_LOWPASS_GET 0x20
  107332. #define OV_ECTL_LOWPASS_SET 0x21
  107333. #define OV_ECTL_IBLOCK_GET 0x30
  107334. #define OV_ECTL_IBLOCK_SET 0x31
  107335. #ifdef __cplusplus
  107336. }
  107337. #endif /* __cplusplus */
  107338. #endif
  107339. /*** End of inlined file: vorbisenc.h ***/
  107340. /*** Start of inlined file: vorbisfile.h ***/
  107341. #ifndef _OV_FILE_H_
  107342. #define _OV_FILE_H_
  107343. #ifdef __cplusplus
  107344. extern "C"
  107345. {
  107346. #endif /* __cplusplus */
  107347. #include <stdio.h>
  107348. /* The function prototypes for the callbacks are basically the same as for
  107349. * the stdio functions fread, fseek, fclose, ftell.
  107350. * The one difference is that the FILE * arguments have been replaced with
  107351. * a void * - this is to be used as a pointer to whatever internal data these
  107352. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107353. *
  107354. * If you use other functions, check the docs for these functions and return
  107355. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107356. * unseekable
  107357. */
  107358. typedef struct {
  107359. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107360. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107361. int (*close_func) (void *datasource);
  107362. long (*tell_func) (void *datasource);
  107363. } ov_callbacks;
  107364. #define NOTOPEN 0
  107365. #define PARTOPEN 1
  107366. #define OPENED 2
  107367. #define STREAMSET 3
  107368. #define INITSET 4
  107369. typedef struct OggVorbis_File {
  107370. void *datasource; /* Pointer to a FILE *, etc. */
  107371. int seekable;
  107372. ogg_int64_t offset;
  107373. ogg_int64_t end;
  107374. ogg_sync_state oy;
  107375. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107376. stream appears */
  107377. int links;
  107378. ogg_int64_t *offsets;
  107379. ogg_int64_t *dataoffsets;
  107380. long *serialnos;
  107381. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107382. compatability; x2 size, stores both
  107383. beginning and end values */
  107384. vorbis_info *vi;
  107385. vorbis_comment *vc;
  107386. /* Decoding working state local storage */
  107387. ogg_int64_t pcm_offset;
  107388. int ready_state;
  107389. long current_serialno;
  107390. int current_link;
  107391. double bittrack;
  107392. double samptrack;
  107393. ogg_stream_state os; /* take physical pages, weld into a logical
  107394. stream of packets */
  107395. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107396. vorbis_block vb; /* local working space for packet->PCM decode */
  107397. ov_callbacks callbacks;
  107398. } OggVorbis_File;
  107399. extern int ov_clear(OggVorbis_File *vf);
  107400. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107401. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107402. char *initial, long ibytes, ov_callbacks callbacks);
  107403. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107404. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107405. char *initial, long ibytes, ov_callbacks callbacks);
  107406. extern int ov_test_open(OggVorbis_File *vf);
  107407. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107408. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107409. extern long ov_streams(OggVorbis_File *vf);
  107410. extern long ov_seekable(OggVorbis_File *vf);
  107411. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107412. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107413. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107414. extern double ov_time_total(OggVorbis_File *vf,int i);
  107415. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107416. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107417. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107418. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107419. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107420. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107421. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107422. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107423. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107424. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107425. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107426. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107427. extern double ov_time_tell(OggVorbis_File *vf);
  107428. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107429. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107430. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107431. int *bitstream);
  107432. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107433. int bigendianp,int word,int sgned,int *bitstream);
  107434. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107435. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107436. extern int ov_halfrate_p(OggVorbis_File *vf);
  107437. #ifdef __cplusplus
  107438. }
  107439. #endif /* __cplusplus */
  107440. #endif
  107441. /*** End of inlined file: vorbisfile.h ***/
  107442. /*** Start of inlined file: bitwise.c ***/
  107443. /* We're 'LSb' endian; if we write a word but read individual bits,
  107444. then we'll read the lsb first */
  107445. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107446. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107447. // tasks..
  107448. #if JUCE_MSVC
  107449. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107450. #endif
  107451. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107452. #if JUCE_USE_OGGVORBIS
  107453. #include <string.h>
  107454. #include <stdlib.h>
  107455. #define BUFFER_INCREMENT 256
  107456. static const unsigned long mask[]=
  107457. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107458. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107459. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107460. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107461. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107462. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107463. 0x3fffffff,0x7fffffff,0xffffffff };
  107464. static const unsigned int mask8B[]=
  107465. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107466. void oggpack_writeinit(oggpack_buffer *b){
  107467. memset(b,0,sizeof(*b));
  107468. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107469. b->buffer[0]='\0';
  107470. b->storage=BUFFER_INCREMENT;
  107471. }
  107472. void oggpackB_writeinit(oggpack_buffer *b){
  107473. oggpack_writeinit(b);
  107474. }
  107475. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107476. long bytes=bits>>3;
  107477. bits-=bytes*8;
  107478. b->ptr=b->buffer+bytes;
  107479. b->endbit=bits;
  107480. b->endbyte=bytes;
  107481. *b->ptr&=mask[bits];
  107482. }
  107483. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107484. long bytes=bits>>3;
  107485. bits-=bytes*8;
  107486. b->ptr=b->buffer+bytes;
  107487. b->endbit=bits;
  107488. b->endbyte=bytes;
  107489. *b->ptr&=mask8B[bits];
  107490. }
  107491. /* Takes only up to 32 bits. */
  107492. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107493. if(b->endbyte+4>=b->storage){
  107494. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107495. b->storage+=BUFFER_INCREMENT;
  107496. b->ptr=b->buffer+b->endbyte;
  107497. }
  107498. value&=mask[bits];
  107499. bits+=b->endbit;
  107500. b->ptr[0]|=value<<b->endbit;
  107501. if(bits>=8){
  107502. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107503. if(bits>=16){
  107504. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107505. if(bits>=24){
  107506. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107507. if(bits>=32){
  107508. if(b->endbit)
  107509. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107510. else
  107511. b->ptr[4]=0;
  107512. }
  107513. }
  107514. }
  107515. }
  107516. b->endbyte+=bits/8;
  107517. b->ptr+=bits/8;
  107518. b->endbit=bits&7;
  107519. }
  107520. /* Takes only up to 32 bits. */
  107521. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107522. if(b->endbyte+4>=b->storage){
  107523. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107524. b->storage+=BUFFER_INCREMENT;
  107525. b->ptr=b->buffer+b->endbyte;
  107526. }
  107527. value=(value&mask[bits])<<(32-bits);
  107528. bits+=b->endbit;
  107529. b->ptr[0]|=value>>(24+b->endbit);
  107530. if(bits>=8){
  107531. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107532. if(bits>=16){
  107533. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107534. if(bits>=24){
  107535. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107536. if(bits>=32){
  107537. if(b->endbit)
  107538. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107539. else
  107540. b->ptr[4]=0;
  107541. }
  107542. }
  107543. }
  107544. }
  107545. b->endbyte+=bits/8;
  107546. b->ptr+=bits/8;
  107547. b->endbit=bits&7;
  107548. }
  107549. void oggpack_writealign(oggpack_buffer *b){
  107550. int bits=8-b->endbit;
  107551. if(bits<8)
  107552. oggpack_write(b,0,bits);
  107553. }
  107554. void oggpackB_writealign(oggpack_buffer *b){
  107555. int bits=8-b->endbit;
  107556. if(bits<8)
  107557. oggpackB_write(b,0,bits);
  107558. }
  107559. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107560. void *source,
  107561. long bits,
  107562. void (*w)(oggpack_buffer *,
  107563. unsigned long,
  107564. int),
  107565. int msb){
  107566. unsigned char *ptr=(unsigned char *)source;
  107567. long bytes=bits/8;
  107568. bits-=bytes*8;
  107569. if(b->endbit){
  107570. int i;
  107571. /* unaligned copy. Do it the hard way. */
  107572. for(i=0;i<bytes;i++)
  107573. w(b,(unsigned long)(ptr[i]),8);
  107574. }else{
  107575. /* aligned block copy */
  107576. if(b->endbyte+bytes+1>=b->storage){
  107577. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107578. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107579. b->ptr=b->buffer+b->endbyte;
  107580. }
  107581. memmove(b->ptr,source,bytes);
  107582. b->ptr+=bytes;
  107583. b->endbyte+=bytes;
  107584. *b->ptr=0;
  107585. }
  107586. if(bits){
  107587. if(msb)
  107588. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107589. else
  107590. w(b,(unsigned long)(ptr[bytes]),bits);
  107591. }
  107592. }
  107593. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107594. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107595. }
  107596. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107597. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107598. }
  107599. void oggpack_reset(oggpack_buffer *b){
  107600. b->ptr=b->buffer;
  107601. b->buffer[0]=0;
  107602. b->endbit=b->endbyte=0;
  107603. }
  107604. void oggpackB_reset(oggpack_buffer *b){
  107605. oggpack_reset(b);
  107606. }
  107607. void oggpack_writeclear(oggpack_buffer *b){
  107608. _ogg_free(b->buffer);
  107609. memset(b,0,sizeof(*b));
  107610. }
  107611. void oggpackB_writeclear(oggpack_buffer *b){
  107612. oggpack_writeclear(b);
  107613. }
  107614. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107615. memset(b,0,sizeof(*b));
  107616. b->buffer=b->ptr=buf;
  107617. b->storage=bytes;
  107618. }
  107619. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107620. oggpack_readinit(b,buf,bytes);
  107621. }
  107622. /* Read in bits without advancing the bitptr; bits <= 32 */
  107623. long oggpack_look(oggpack_buffer *b,int bits){
  107624. unsigned long ret;
  107625. unsigned long m=mask[bits];
  107626. bits+=b->endbit;
  107627. if(b->endbyte+4>=b->storage){
  107628. /* not the main path */
  107629. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107630. }
  107631. ret=b->ptr[0]>>b->endbit;
  107632. if(bits>8){
  107633. ret|=b->ptr[1]<<(8-b->endbit);
  107634. if(bits>16){
  107635. ret|=b->ptr[2]<<(16-b->endbit);
  107636. if(bits>24){
  107637. ret|=b->ptr[3]<<(24-b->endbit);
  107638. if(bits>32 && b->endbit)
  107639. ret|=b->ptr[4]<<(32-b->endbit);
  107640. }
  107641. }
  107642. }
  107643. return(m&ret);
  107644. }
  107645. /* Read in bits without advancing the bitptr; bits <= 32 */
  107646. long oggpackB_look(oggpack_buffer *b,int bits){
  107647. unsigned long ret;
  107648. int m=32-bits;
  107649. bits+=b->endbit;
  107650. if(b->endbyte+4>=b->storage){
  107651. /* not the main path */
  107652. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107653. }
  107654. ret=b->ptr[0]<<(24+b->endbit);
  107655. if(bits>8){
  107656. ret|=b->ptr[1]<<(16+b->endbit);
  107657. if(bits>16){
  107658. ret|=b->ptr[2]<<(8+b->endbit);
  107659. if(bits>24){
  107660. ret|=b->ptr[3]<<(b->endbit);
  107661. if(bits>32 && b->endbit)
  107662. ret|=b->ptr[4]>>(8-b->endbit);
  107663. }
  107664. }
  107665. }
  107666. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107667. }
  107668. long oggpack_look1(oggpack_buffer *b){
  107669. if(b->endbyte>=b->storage)return(-1);
  107670. return((b->ptr[0]>>b->endbit)&1);
  107671. }
  107672. long oggpackB_look1(oggpack_buffer *b){
  107673. if(b->endbyte>=b->storage)return(-1);
  107674. return((b->ptr[0]>>(7-b->endbit))&1);
  107675. }
  107676. void oggpack_adv(oggpack_buffer *b,int bits){
  107677. bits+=b->endbit;
  107678. b->ptr+=bits/8;
  107679. b->endbyte+=bits/8;
  107680. b->endbit=bits&7;
  107681. }
  107682. void oggpackB_adv(oggpack_buffer *b,int bits){
  107683. oggpack_adv(b,bits);
  107684. }
  107685. void oggpack_adv1(oggpack_buffer *b){
  107686. if(++(b->endbit)>7){
  107687. b->endbit=0;
  107688. b->ptr++;
  107689. b->endbyte++;
  107690. }
  107691. }
  107692. void oggpackB_adv1(oggpack_buffer *b){
  107693. oggpack_adv1(b);
  107694. }
  107695. /* bits <= 32 */
  107696. long oggpack_read(oggpack_buffer *b,int bits){
  107697. long ret;
  107698. unsigned long m=mask[bits];
  107699. bits+=b->endbit;
  107700. if(b->endbyte+4>=b->storage){
  107701. /* not the main path */
  107702. ret=-1L;
  107703. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107704. }
  107705. ret=b->ptr[0]>>b->endbit;
  107706. if(bits>8){
  107707. ret|=b->ptr[1]<<(8-b->endbit);
  107708. if(bits>16){
  107709. ret|=b->ptr[2]<<(16-b->endbit);
  107710. if(bits>24){
  107711. ret|=b->ptr[3]<<(24-b->endbit);
  107712. if(bits>32 && b->endbit){
  107713. ret|=b->ptr[4]<<(32-b->endbit);
  107714. }
  107715. }
  107716. }
  107717. }
  107718. ret&=m;
  107719. overflow:
  107720. b->ptr+=bits/8;
  107721. b->endbyte+=bits/8;
  107722. b->endbit=bits&7;
  107723. return(ret);
  107724. }
  107725. /* bits <= 32 */
  107726. long oggpackB_read(oggpack_buffer *b,int bits){
  107727. long ret;
  107728. long m=32-bits;
  107729. bits+=b->endbit;
  107730. if(b->endbyte+4>=b->storage){
  107731. /* not the main path */
  107732. ret=-1L;
  107733. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107734. }
  107735. ret=b->ptr[0]<<(24+b->endbit);
  107736. if(bits>8){
  107737. ret|=b->ptr[1]<<(16+b->endbit);
  107738. if(bits>16){
  107739. ret|=b->ptr[2]<<(8+b->endbit);
  107740. if(bits>24){
  107741. ret|=b->ptr[3]<<(b->endbit);
  107742. if(bits>32 && b->endbit)
  107743. ret|=b->ptr[4]>>(8-b->endbit);
  107744. }
  107745. }
  107746. }
  107747. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107748. overflow:
  107749. b->ptr+=bits/8;
  107750. b->endbyte+=bits/8;
  107751. b->endbit=bits&7;
  107752. return(ret);
  107753. }
  107754. long oggpack_read1(oggpack_buffer *b){
  107755. long ret;
  107756. if(b->endbyte>=b->storage){
  107757. /* not the main path */
  107758. ret=-1L;
  107759. goto overflow;
  107760. }
  107761. ret=(b->ptr[0]>>b->endbit)&1;
  107762. overflow:
  107763. b->endbit++;
  107764. if(b->endbit>7){
  107765. b->endbit=0;
  107766. b->ptr++;
  107767. b->endbyte++;
  107768. }
  107769. return(ret);
  107770. }
  107771. long oggpackB_read1(oggpack_buffer *b){
  107772. long ret;
  107773. if(b->endbyte>=b->storage){
  107774. /* not the main path */
  107775. ret=-1L;
  107776. goto overflow;
  107777. }
  107778. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107779. overflow:
  107780. b->endbit++;
  107781. if(b->endbit>7){
  107782. b->endbit=0;
  107783. b->ptr++;
  107784. b->endbyte++;
  107785. }
  107786. return(ret);
  107787. }
  107788. long oggpack_bytes(oggpack_buffer *b){
  107789. return(b->endbyte+(b->endbit+7)/8);
  107790. }
  107791. long oggpack_bits(oggpack_buffer *b){
  107792. return(b->endbyte*8+b->endbit);
  107793. }
  107794. long oggpackB_bytes(oggpack_buffer *b){
  107795. return oggpack_bytes(b);
  107796. }
  107797. long oggpackB_bits(oggpack_buffer *b){
  107798. return oggpack_bits(b);
  107799. }
  107800. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107801. return(b->buffer);
  107802. }
  107803. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107804. return oggpack_get_buffer(b);
  107805. }
  107806. /* Self test of the bitwise routines; everything else is based on
  107807. them, so they damned well better be solid. */
  107808. #ifdef _V_SELFTEST
  107809. #include <stdio.h>
  107810. static int ilog(unsigned int v){
  107811. int ret=0;
  107812. while(v){
  107813. ret++;
  107814. v>>=1;
  107815. }
  107816. return(ret);
  107817. }
  107818. oggpack_buffer o;
  107819. oggpack_buffer r;
  107820. void report(char *in){
  107821. fprintf(stderr,"%s",in);
  107822. exit(1);
  107823. }
  107824. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107825. long bytes,i;
  107826. unsigned char *buffer;
  107827. oggpack_reset(&o);
  107828. for(i=0;i<vals;i++)
  107829. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107830. buffer=oggpack_get_buffer(&o);
  107831. bytes=oggpack_bytes(&o);
  107832. if(bytes!=compsize)report("wrong number of bytes!\n");
  107833. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107834. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107835. report("wrote incorrect value!\n");
  107836. }
  107837. oggpack_readinit(&r,buffer,bytes);
  107838. for(i=0;i<vals;i++){
  107839. int tbit=bits?bits:ilog(b[i]);
  107840. if(oggpack_look(&r,tbit)==-1)
  107841. report("out of data!\n");
  107842. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107843. report("looked at incorrect value!\n");
  107844. if(tbit==1)
  107845. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107846. report("looked at single bit incorrect value!\n");
  107847. if(tbit==1){
  107848. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107849. report("read incorrect single bit value!\n");
  107850. }else{
  107851. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107852. report("read incorrect value!\n");
  107853. }
  107854. }
  107855. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107856. }
  107857. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107858. long bytes,i;
  107859. unsigned char *buffer;
  107860. oggpackB_reset(&o);
  107861. for(i=0;i<vals;i++)
  107862. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107863. buffer=oggpackB_get_buffer(&o);
  107864. bytes=oggpackB_bytes(&o);
  107865. if(bytes!=compsize)report("wrong number of bytes!\n");
  107866. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107867. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107868. report("wrote incorrect value!\n");
  107869. }
  107870. oggpackB_readinit(&r,buffer,bytes);
  107871. for(i=0;i<vals;i++){
  107872. int tbit=bits?bits:ilog(b[i]);
  107873. if(oggpackB_look(&r,tbit)==-1)
  107874. report("out of data!\n");
  107875. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107876. report("looked at incorrect value!\n");
  107877. if(tbit==1)
  107878. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107879. report("looked at single bit incorrect value!\n");
  107880. if(tbit==1){
  107881. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107882. report("read incorrect single bit value!\n");
  107883. }else{
  107884. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107885. report("read incorrect value!\n");
  107886. }
  107887. }
  107888. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107889. }
  107890. int main(void){
  107891. unsigned char *buffer;
  107892. long bytes,i;
  107893. static unsigned long testbuffer1[]=
  107894. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107895. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107896. int test1size=43;
  107897. static unsigned long testbuffer2[]=
  107898. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107899. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107900. 85525151,0,12321,1,349528352};
  107901. int test2size=21;
  107902. static unsigned long testbuffer3[]=
  107903. {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,
  107904. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107905. int test3size=56;
  107906. static unsigned long large[]=
  107907. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107908. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107909. 85525151,0,12321,1,2146528352};
  107910. int onesize=33;
  107911. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107912. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107913. 223,4};
  107914. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107915. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107916. 245,251,128};
  107917. int twosize=6;
  107918. static int two[6]={61,255,255,251,231,29};
  107919. static int twoB[6]={247,63,255,253,249,120};
  107920. int threesize=54;
  107921. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107922. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107923. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107924. 100,52,4,14,18,86,77,1};
  107925. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107926. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107927. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107928. 200,20,254,4,58,106,176,144,0};
  107929. int foursize=38;
  107930. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107931. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107932. 28,2,133,0,1};
  107933. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107934. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107935. 129,10,4,32};
  107936. int fivesize=45;
  107937. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107938. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107939. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107940. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107941. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107942. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107943. int sixsize=7;
  107944. static int six[7]={17,177,170,242,169,19,148};
  107945. static int sixB[7]={136,141,85,79,149,200,41};
  107946. /* Test read/write together */
  107947. /* Later we test against pregenerated bitstreams */
  107948. oggpack_writeinit(&o);
  107949. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107950. cliptest(testbuffer1,test1size,0,one,onesize);
  107951. fprintf(stderr,"ok.");
  107952. fprintf(stderr,"\nNull bit call (LSb): ");
  107953. cliptest(testbuffer3,test3size,0,two,twosize);
  107954. fprintf(stderr,"ok.");
  107955. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107956. cliptest(testbuffer2,test2size,0,three,threesize);
  107957. fprintf(stderr,"ok.");
  107958. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107959. oggpack_reset(&o);
  107960. for(i=0;i<test2size;i++)
  107961. oggpack_write(&o,large[i],32);
  107962. buffer=oggpack_get_buffer(&o);
  107963. bytes=oggpack_bytes(&o);
  107964. oggpack_readinit(&r,buffer,bytes);
  107965. for(i=0;i<test2size;i++){
  107966. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107967. if(oggpack_look(&r,32)!=large[i]){
  107968. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107969. oggpack_look(&r,32),large[i]);
  107970. report("read incorrect value!\n");
  107971. }
  107972. oggpack_adv(&r,32);
  107973. }
  107974. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107975. fprintf(stderr,"ok.");
  107976. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107977. cliptest(testbuffer1,test1size,7,four,foursize);
  107978. fprintf(stderr,"ok.");
  107979. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107980. cliptest(testbuffer2,test2size,17,five,fivesize);
  107981. fprintf(stderr,"ok.");
  107982. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107983. cliptest(testbuffer3,test3size,1,six,sixsize);
  107984. fprintf(stderr,"ok.");
  107985. fprintf(stderr,"\nTesting read past end (LSb): ");
  107986. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107987. for(i=0;i<64;i++){
  107988. if(oggpack_read(&r,1)!=0){
  107989. fprintf(stderr,"failed; got -1 prematurely.\n");
  107990. exit(1);
  107991. }
  107992. }
  107993. if(oggpack_look(&r,1)!=-1 ||
  107994. oggpack_read(&r,1)!=-1){
  107995. fprintf(stderr,"failed; read past end without -1.\n");
  107996. exit(1);
  107997. }
  107998. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107999. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108000. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108001. exit(1);
  108002. }
  108003. if(oggpack_look(&r,18)!=0 ||
  108004. oggpack_look(&r,18)!=0){
  108005. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108006. exit(1);
  108007. }
  108008. if(oggpack_look(&r,19)!=-1 ||
  108009. oggpack_look(&r,19)!=-1){
  108010. fprintf(stderr,"failed; read past end without -1.\n");
  108011. exit(1);
  108012. }
  108013. if(oggpack_look(&r,32)!=-1 ||
  108014. oggpack_look(&r,32)!=-1){
  108015. fprintf(stderr,"failed; read past end without -1.\n");
  108016. exit(1);
  108017. }
  108018. oggpack_writeclear(&o);
  108019. fprintf(stderr,"ok.\n");
  108020. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108021. /* Test read/write together */
  108022. /* Later we test against pregenerated bitstreams */
  108023. oggpackB_writeinit(&o);
  108024. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108025. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108026. fprintf(stderr,"ok.");
  108027. fprintf(stderr,"\nNull bit call (MSb): ");
  108028. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108029. fprintf(stderr,"ok.");
  108030. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108031. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108032. fprintf(stderr,"ok.");
  108033. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108034. oggpackB_reset(&o);
  108035. for(i=0;i<test2size;i++)
  108036. oggpackB_write(&o,large[i],32);
  108037. buffer=oggpackB_get_buffer(&o);
  108038. bytes=oggpackB_bytes(&o);
  108039. oggpackB_readinit(&r,buffer,bytes);
  108040. for(i=0;i<test2size;i++){
  108041. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108042. if(oggpackB_look(&r,32)!=large[i]){
  108043. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108044. oggpackB_look(&r,32),large[i]);
  108045. report("read incorrect value!\n");
  108046. }
  108047. oggpackB_adv(&r,32);
  108048. }
  108049. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108050. fprintf(stderr,"ok.");
  108051. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108052. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108053. fprintf(stderr,"ok.");
  108054. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108055. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108056. fprintf(stderr,"ok.");
  108057. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108058. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108059. fprintf(stderr,"ok.");
  108060. fprintf(stderr,"\nTesting read past end (MSb): ");
  108061. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108062. for(i=0;i<64;i++){
  108063. if(oggpackB_read(&r,1)!=0){
  108064. fprintf(stderr,"failed; got -1 prematurely.\n");
  108065. exit(1);
  108066. }
  108067. }
  108068. if(oggpackB_look(&r,1)!=-1 ||
  108069. oggpackB_read(&r,1)!=-1){
  108070. fprintf(stderr,"failed; read past end without -1.\n");
  108071. exit(1);
  108072. }
  108073. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108074. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108075. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108076. exit(1);
  108077. }
  108078. if(oggpackB_look(&r,18)!=0 ||
  108079. oggpackB_look(&r,18)!=0){
  108080. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108081. exit(1);
  108082. }
  108083. if(oggpackB_look(&r,19)!=-1 ||
  108084. oggpackB_look(&r,19)!=-1){
  108085. fprintf(stderr,"failed; read past end without -1.\n");
  108086. exit(1);
  108087. }
  108088. if(oggpackB_look(&r,32)!=-1 ||
  108089. oggpackB_look(&r,32)!=-1){
  108090. fprintf(stderr,"failed; read past end without -1.\n");
  108091. exit(1);
  108092. }
  108093. oggpackB_writeclear(&o);
  108094. fprintf(stderr,"ok.\n\n");
  108095. return(0);
  108096. }
  108097. #endif /* _V_SELFTEST */
  108098. #undef BUFFER_INCREMENT
  108099. #endif
  108100. /*** End of inlined file: bitwise.c ***/
  108101. /*** Start of inlined file: framing.c ***/
  108102. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108103. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108104. // tasks..
  108105. #if JUCE_MSVC
  108106. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108107. #endif
  108108. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108109. #if JUCE_USE_OGGVORBIS
  108110. #include <stdlib.h>
  108111. #include <string.h>
  108112. /* A complete description of Ogg framing exists in docs/framing.html */
  108113. int ogg_page_version(ogg_page *og){
  108114. return((int)(og->header[4]));
  108115. }
  108116. int ogg_page_continued(ogg_page *og){
  108117. return((int)(og->header[5]&0x01));
  108118. }
  108119. int ogg_page_bos(ogg_page *og){
  108120. return((int)(og->header[5]&0x02));
  108121. }
  108122. int ogg_page_eos(ogg_page *og){
  108123. return((int)(og->header[5]&0x04));
  108124. }
  108125. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108126. unsigned char *page=og->header;
  108127. ogg_int64_t granulepos=page[13]&(0xff);
  108128. granulepos= (granulepos<<8)|(page[12]&0xff);
  108129. granulepos= (granulepos<<8)|(page[11]&0xff);
  108130. granulepos= (granulepos<<8)|(page[10]&0xff);
  108131. granulepos= (granulepos<<8)|(page[9]&0xff);
  108132. granulepos= (granulepos<<8)|(page[8]&0xff);
  108133. granulepos= (granulepos<<8)|(page[7]&0xff);
  108134. granulepos= (granulepos<<8)|(page[6]&0xff);
  108135. return(granulepos);
  108136. }
  108137. int ogg_page_serialno(ogg_page *og){
  108138. return(og->header[14] |
  108139. (og->header[15]<<8) |
  108140. (og->header[16]<<16) |
  108141. (og->header[17]<<24));
  108142. }
  108143. long ogg_page_pageno(ogg_page *og){
  108144. return(og->header[18] |
  108145. (og->header[19]<<8) |
  108146. (og->header[20]<<16) |
  108147. (og->header[21]<<24));
  108148. }
  108149. /* returns the number of packets that are completed on this page (if
  108150. the leading packet is begun on a previous page, but ends on this
  108151. page, it's counted */
  108152. /* NOTE:
  108153. If a page consists of a packet begun on a previous page, and a new
  108154. packet begun (but not completed) on this page, the return will be:
  108155. ogg_page_packets(page) ==1,
  108156. ogg_page_continued(page) !=0
  108157. If a page happens to be a single packet that was begun on a
  108158. previous page, and spans to the next page (in the case of a three or
  108159. more page packet), the return will be:
  108160. ogg_page_packets(page) ==0,
  108161. ogg_page_continued(page) !=0
  108162. */
  108163. int ogg_page_packets(ogg_page *og){
  108164. int i,n=og->header[26],count=0;
  108165. for(i=0;i<n;i++)
  108166. if(og->header[27+i]<255)count++;
  108167. return(count);
  108168. }
  108169. #if 0
  108170. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108171. use the static init below) */
  108172. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108173. int i;
  108174. unsigned long r;
  108175. r = index << 24;
  108176. for (i=0; i<8; i++)
  108177. if (r & 0x80000000UL)
  108178. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108179. polynomial, although we use an
  108180. unreflected alg and an init/final
  108181. of 0, not 0xffffffff */
  108182. else
  108183. r<<=1;
  108184. return (r & 0xffffffffUL);
  108185. }
  108186. #endif
  108187. static const ogg_uint32_t crc_lookup[256]={
  108188. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108189. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108190. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108191. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108192. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108193. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108194. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108195. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108196. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108197. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108198. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108199. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108200. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108201. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108202. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108203. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108204. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108205. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108206. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108207. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108208. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108209. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108210. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108211. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108212. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108213. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108214. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108215. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108216. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108217. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108218. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108219. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108220. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108221. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108222. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108223. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108224. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108225. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108226. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108227. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108228. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108229. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108230. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108231. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108232. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108233. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108234. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108235. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108236. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108237. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108238. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108239. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108240. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108241. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108242. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108243. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108244. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108245. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108246. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108247. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108248. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108249. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108250. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108251. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108252. /* init the encode/decode logical stream state */
  108253. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108254. if(os){
  108255. memset(os,0,sizeof(*os));
  108256. os->body_storage=16*1024;
  108257. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108258. os->lacing_storage=1024;
  108259. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108260. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108261. os->serialno=serialno;
  108262. return(0);
  108263. }
  108264. return(-1);
  108265. }
  108266. /* _clear does not free os, only the non-flat storage within */
  108267. int ogg_stream_clear(ogg_stream_state *os){
  108268. if(os){
  108269. if(os->body_data)_ogg_free(os->body_data);
  108270. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108271. if(os->granule_vals)_ogg_free(os->granule_vals);
  108272. memset(os,0,sizeof(*os));
  108273. }
  108274. return(0);
  108275. }
  108276. int ogg_stream_destroy(ogg_stream_state *os){
  108277. if(os){
  108278. ogg_stream_clear(os);
  108279. _ogg_free(os);
  108280. }
  108281. return(0);
  108282. }
  108283. /* Helpers for ogg_stream_encode; this keeps the structure and
  108284. what's happening fairly clear */
  108285. static void _os_body_expand(ogg_stream_state *os,int needed){
  108286. if(os->body_storage<=os->body_fill+needed){
  108287. os->body_storage+=(needed+1024);
  108288. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108289. }
  108290. }
  108291. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108292. if(os->lacing_storage<=os->lacing_fill+needed){
  108293. os->lacing_storage+=(needed+32);
  108294. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108295. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108296. }
  108297. }
  108298. /* checksum the page */
  108299. /* Direct table CRC; note that this will be faster in the future if we
  108300. perform the checksum silmultaneously with other copies */
  108301. void ogg_page_checksum_set(ogg_page *og){
  108302. if(og){
  108303. ogg_uint32_t crc_reg=0;
  108304. int i;
  108305. /* safety; needed for API behavior, but not framing code */
  108306. og->header[22]=0;
  108307. og->header[23]=0;
  108308. og->header[24]=0;
  108309. og->header[25]=0;
  108310. for(i=0;i<og->header_len;i++)
  108311. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108312. for(i=0;i<og->body_len;i++)
  108313. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108314. og->header[22]=(unsigned char)(crc_reg&0xff);
  108315. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108316. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108317. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108318. }
  108319. }
  108320. /* submit data to the internal buffer of the framing engine */
  108321. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108322. int lacing_vals=op->bytes/255+1,i;
  108323. if(os->body_returned){
  108324. /* advance packet data according to the body_returned pointer. We
  108325. had to keep it around to return a pointer into the buffer last
  108326. call */
  108327. os->body_fill-=os->body_returned;
  108328. if(os->body_fill)
  108329. memmove(os->body_data,os->body_data+os->body_returned,
  108330. os->body_fill);
  108331. os->body_returned=0;
  108332. }
  108333. /* make sure we have the buffer storage */
  108334. _os_body_expand(os,op->bytes);
  108335. _os_lacing_expand(os,lacing_vals);
  108336. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108337. the liability of overly clean abstraction for the time being. It
  108338. will actually be fairly easy to eliminate the extra copy in the
  108339. future */
  108340. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108341. os->body_fill+=op->bytes;
  108342. /* Store lacing vals for this packet */
  108343. for(i=0;i<lacing_vals-1;i++){
  108344. os->lacing_vals[os->lacing_fill+i]=255;
  108345. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108346. }
  108347. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108348. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108349. /* flag the first segment as the beginning of the packet */
  108350. os->lacing_vals[os->lacing_fill]|= 0x100;
  108351. os->lacing_fill+=lacing_vals;
  108352. /* for the sake of completeness */
  108353. os->packetno++;
  108354. if(op->e_o_s)os->e_o_s=1;
  108355. return(0);
  108356. }
  108357. /* This will flush remaining packets into a page (returning nonzero),
  108358. even if there is not enough data to trigger a flush normally
  108359. (undersized page). If there are no packets or partial packets to
  108360. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108361. try to flush a normal sized page like ogg_stream_pageout; a call to
  108362. ogg_stream_flush does not guarantee that all packets have flushed.
  108363. Only a return value of 0 from ogg_stream_flush indicates all packet
  108364. data is flushed into pages.
  108365. since ogg_stream_flush will flush the last page in a stream even if
  108366. it's undersized, you almost certainly want to use ogg_stream_pageout
  108367. (and *not* ogg_stream_flush) unless you specifically need to flush
  108368. an page regardless of size in the middle of a stream. */
  108369. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108370. int i;
  108371. int vals=0;
  108372. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108373. int bytes=0;
  108374. long acc=0;
  108375. ogg_int64_t granule_pos=-1;
  108376. if(maxvals==0)return(0);
  108377. /* construct a page */
  108378. /* decide how many segments to include */
  108379. /* If this is the initial header case, the first page must only include
  108380. the initial header packet */
  108381. if(os->b_o_s==0){ /* 'initial header page' case */
  108382. granule_pos=0;
  108383. for(vals=0;vals<maxvals;vals++){
  108384. if((os->lacing_vals[vals]&0x0ff)<255){
  108385. vals++;
  108386. break;
  108387. }
  108388. }
  108389. }else{
  108390. for(vals=0;vals<maxvals;vals++){
  108391. if(acc>4096)break;
  108392. acc+=os->lacing_vals[vals]&0x0ff;
  108393. if((os->lacing_vals[vals]&0xff)<255)
  108394. granule_pos=os->granule_vals[vals];
  108395. }
  108396. }
  108397. /* construct the header in temp storage */
  108398. memcpy(os->header,"OggS",4);
  108399. /* stream structure version */
  108400. os->header[4]=0x00;
  108401. /* continued packet flag? */
  108402. os->header[5]=0x00;
  108403. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108404. /* first page flag? */
  108405. if(os->b_o_s==0)os->header[5]|=0x02;
  108406. /* last page flag? */
  108407. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108408. os->b_o_s=1;
  108409. /* 64 bits of PCM position */
  108410. for(i=6;i<14;i++){
  108411. os->header[i]=(unsigned char)(granule_pos&0xff);
  108412. granule_pos>>=8;
  108413. }
  108414. /* 32 bits of stream serial number */
  108415. {
  108416. long serialno=os->serialno;
  108417. for(i=14;i<18;i++){
  108418. os->header[i]=(unsigned char)(serialno&0xff);
  108419. serialno>>=8;
  108420. }
  108421. }
  108422. /* 32 bits of page counter (we have both counter and page header
  108423. because this val can roll over) */
  108424. if(os->pageno==-1)os->pageno=0; /* because someone called
  108425. stream_reset; this would be a
  108426. strange thing to do in an
  108427. encode stream, but it has
  108428. plausible uses */
  108429. {
  108430. long pageno=os->pageno++;
  108431. for(i=18;i<22;i++){
  108432. os->header[i]=(unsigned char)(pageno&0xff);
  108433. pageno>>=8;
  108434. }
  108435. }
  108436. /* zero for computation; filled in later */
  108437. os->header[22]=0;
  108438. os->header[23]=0;
  108439. os->header[24]=0;
  108440. os->header[25]=0;
  108441. /* segment table */
  108442. os->header[26]=(unsigned char)(vals&0xff);
  108443. for(i=0;i<vals;i++)
  108444. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108445. /* set pointers in the ogg_page struct */
  108446. og->header=os->header;
  108447. og->header_len=os->header_fill=vals+27;
  108448. og->body=os->body_data+os->body_returned;
  108449. og->body_len=bytes;
  108450. /* advance the lacing data and set the body_returned pointer */
  108451. os->lacing_fill-=vals;
  108452. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108453. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108454. os->body_returned+=bytes;
  108455. /* calculate the checksum */
  108456. ogg_page_checksum_set(og);
  108457. /* done */
  108458. return(1);
  108459. }
  108460. /* This constructs pages from buffered packet segments. The pointers
  108461. returned are to static buffers; do not free. The returned buffers are
  108462. good only until the next call (using the same ogg_stream_state) */
  108463. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108464. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108465. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108466. os->lacing_fill>=255 || /* 'segment table full' case */
  108467. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108468. return(ogg_stream_flush(os,og));
  108469. }
  108470. /* not enough data to construct a page and not end of stream */
  108471. return(0);
  108472. }
  108473. int ogg_stream_eos(ogg_stream_state *os){
  108474. return os->e_o_s;
  108475. }
  108476. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108477. /* This has two layers to place more of the multi-serialno and paging
  108478. control in the application's hands. First, we expose a data buffer
  108479. using ogg_sync_buffer(). The app either copies into the
  108480. buffer, or passes it directly to read(), etc. We then call
  108481. ogg_sync_wrote() to tell how many bytes we just added.
  108482. Pages are returned (pointers into the buffer in ogg_sync_state)
  108483. by ogg_sync_pageout(). The page is then submitted to
  108484. ogg_stream_pagein() along with the appropriate
  108485. ogg_stream_state* (ie, matching serialno). We then get raw
  108486. packets out calling ogg_stream_packetout() with a
  108487. ogg_stream_state. */
  108488. /* initialize the struct to a known state */
  108489. int ogg_sync_init(ogg_sync_state *oy){
  108490. if(oy){
  108491. memset(oy,0,sizeof(*oy));
  108492. }
  108493. return(0);
  108494. }
  108495. /* clear non-flat storage within */
  108496. int ogg_sync_clear(ogg_sync_state *oy){
  108497. if(oy){
  108498. if(oy->data)_ogg_free(oy->data);
  108499. ogg_sync_init(oy);
  108500. }
  108501. return(0);
  108502. }
  108503. int ogg_sync_destroy(ogg_sync_state *oy){
  108504. if(oy){
  108505. ogg_sync_clear(oy);
  108506. _ogg_free(oy);
  108507. }
  108508. return(0);
  108509. }
  108510. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108511. /* first, clear out any space that has been previously returned */
  108512. if(oy->returned){
  108513. oy->fill-=oy->returned;
  108514. if(oy->fill>0)
  108515. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108516. oy->returned=0;
  108517. }
  108518. if(size>oy->storage-oy->fill){
  108519. /* We need to extend the internal buffer */
  108520. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108521. if(oy->data)
  108522. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108523. else
  108524. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108525. oy->storage=newsize;
  108526. }
  108527. /* expose a segment at least as large as requested at the fill mark */
  108528. return((char *)oy->data+oy->fill);
  108529. }
  108530. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108531. if(oy->fill+bytes>oy->storage)return(-1);
  108532. oy->fill+=bytes;
  108533. return(0);
  108534. }
  108535. /* sync the stream. This is meant to be useful for finding page
  108536. boundaries.
  108537. return values for this:
  108538. -n) skipped n bytes
  108539. 0) page not ready; more data (no bytes skipped)
  108540. n) page synced at current location; page length n bytes
  108541. */
  108542. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108543. unsigned char *page=oy->data+oy->returned;
  108544. unsigned char *next;
  108545. long bytes=oy->fill-oy->returned;
  108546. if(oy->headerbytes==0){
  108547. int headerbytes,i;
  108548. if(bytes<27)return(0); /* not enough for a header */
  108549. /* verify capture pattern */
  108550. if(memcmp(page,"OggS",4))goto sync_fail;
  108551. headerbytes=page[26]+27;
  108552. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108553. /* count up body length in the segment table */
  108554. for(i=0;i<page[26];i++)
  108555. oy->bodybytes+=page[27+i];
  108556. oy->headerbytes=headerbytes;
  108557. }
  108558. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108559. /* The whole test page is buffered. Verify the checksum */
  108560. {
  108561. /* Grab the checksum bytes, set the header field to zero */
  108562. char chksum[4];
  108563. ogg_page log;
  108564. memcpy(chksum,page+22,4);
  108565. memset(page+22,0,4);
  108566. /* set up a temp page struct and recompute the checksum */
  108567. log.header=page;
  108568. log.header_len=oy->headerbytes;
  108569. log.body=page+oy->headerbytes;
  108570. log.body_len=oy->bodybytes;
  108571. ogg_page_checksum_set(&log);
  108572. /* Compare */
  108573. if(memcmp(chksum,page+22,4)){
  108574. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108575. at all) */
  108576. /* replace the computed checksum with the one actually read in */
  108577. memcpy(page+22,chksum,4);
  108578. /* Bad checksum. Lose sync */
  108579. goto sync_fail;
  108580. }
  108581. }
  108582. /* yes, have a whole page all ready to go */
  108583. {
  108584. unsigned char *page=oy->data+oy->returned;
  108585. long bytes;
  108586. if(og){
  108587. og->header=page;
  108588. og->header_len=oy->headerbytes;
  108589. og->body=page+oy->headerbytes;
  108590. og->body_len=oy->bodybytes;
  108591. }
  108592. oy->unsynced=0;
  108593. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108594. oy->headerbytes=0;
  108595. oy->bodybytes=0;
  108596. return(bytes);
  108597. }
  108598. sync_fail:
  108599. oy->headerbytes=0;
  108600. oy->bodybytes=0;
  108601. /* search for possible capture */
  108602. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108603. if(!next)
  108604. next=oy->data+oy->fill;
  108605. oy->returned=next-oy->data;
  108606. return(-(next-page));
  108607. }
  108608. /* sync the stream and get a page. Keep trying until we find a page.
  108609. Supress 'sync errors' after reporting the first.
  108610. return values:
  108611. -1) recapture (hole in data)
  108612. 0) need more data
  108613. 1) page returned
  108614. Returns pointers into buffered data; invalidated by next call to
  108615. _stream, _clear, _init, or _buffer */
  108616. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108617. /* all we need to do is verify a page at the head of the stream
  108618. buffer. If it doesn't verify, we look for the next potential
  108619. frame */
  108620. for(;;){
  108621. long ret=ogg_sync_pageseek(oy,og);
  108622. if(ret>0){
  108623. /* have a page */
  108624. return(1);
  108625. }
  108626. if(ret==0){
  108627. /* need more data */
  108628. return(0);
  108629. }
  108630. /* head did not start a synced page... skipped some bytes */
  108631. if(!oy->unsynced){
  108632. oy->unsynced=1;
  108633. return(-1);
  108634. }
  108635. /* loop. keep looking */
  108636. }
  108637. }
  108638. /* add the incoming page to the stream state; we decompose the page
  108639. into packet segments here as well. */
  108640. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108641. unsigned char *header=og->header;
  108642. unsigned char *body=og->body;
  108643. long bodysize=og->body_len;
  108644. int segptr=0;
  108645. int version=ogg_page_version(og);
  108646. int continued=ogg_page_continued(og);
  108647. int bos=ogg_page_bos(og);
  108648. int eos=ogg_page_eos(og);
  108649. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108650. int serialno=ogg_page_serialno(og);
  108651. long pageno=ogg_page_pageno(og);
  108652. int segments=header[26];
  108653. /* clean up 'returned data' */
  108654. {
  108655. long lr=os->lacing_returned;
  108656. long br=os->body_returned;
  108657. /* body data */
  108658. if(br){
  108659. os->body_fill-=br;
  108660. if(os->body_fill)
  108661. memmove(os->body_data,os->body_data+br,os->body_fill);
  108662. os->body_returned=0;
  108663. }
  108664. if(lr){
  108665. /* segment table */
  108666. if(os->lacing_fill-lr){
  108667. memmove(os->lacing_vals,os->lacing_vals+lr,
  108668. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108669. memmove(os->granule_vals,os->granule_vals+lr,
  108670. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108671. }
  108672. os->lacing_fill-=lr;
  108673. os->lacing_packet-=lr;
  108674. os->lacing_returned=0;
  108675. }
  108676. }
  108677. /* check the serial number */
  108678. if(serialno!=os->serialno)return(-1);
  108679. if(version>0)return(-1);
  108680. _os_lacing_expand(os,segments+1);
  108681. /* are we in sequence? */
  108682. if(pageno!=os->pageno){
  108683. int i;
  108684. /* unroll previous partial packet (if any) */
  108685. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108686. os->body_fill-=os->lacing_vals[i]&0xff;
  108687. os->lacing_fill=os->lacing_packet;
  108688. /* make a note of dropped data in segment table */
  108689. if(os->pageno!=-1){
  108690. os->lacing_vals[os->lacing_fill++]=0x400;
  108691. os->lacing_packet++;
  108692. }
  108693. }
  108694. /* are we a 'continued packet' page? If so, we may need to skip
  108695. some segments */
  108696. if(continued){
  108697. if(os->lacing_fill<1 ||
  108698. os->lacing_vals[os->lacing_fill-1]==0x400){
  108699. bos=0;
  108700. for(;segptr<segments;segptr++){
  108701. int val=header[27+segptr];
  108702. body+=val;
  108703. bodysize-=val;
  108704. if(val<255){
  108705. segptr++;
  108706. break;
  108707. }
  108708. }
  108709. }
  108710. }
  108711. if(bodysize){
  108712. _os_body_expand(os,bodysize);
  108713. memcpy(os->body_data+os->body_fill,body,bodysize);
  108714. os->body_fill+=bodysize;
  108715. }
  108716. {
  108717. int saved=-1;
  108718. while(segptr<segments){
  108719. int val=header[27+segptr];
  108720. os->lacing_vals[os->lacing_fill]=val;
  108721. os->granule_vals[os->lacing_fill]=-1;
  108722. if(bos){
  108723. os->lacing_vals[os->lacing_fill]|=0x100;
  108724. bos=0;
  108725. }
  108726. if(val<255)saved=os->lacing_fill;
  108727. os->lacing_fill++;
  108728. segptr++;
  108729. if(val<255)os->lacing_packet=os->lacing_fill;
  108730. }
  108731. /* set the granulepos on the last granuleval of the last full packet */
  108732. if(saved!=-1){
  108733. os->granule_vals[saved]=granulepos;
  108734. }
  108735. }
  108736. if(eos){
  108737. os->e_o_s=1;
  108738. if(os->lacing_fill>0)
  108739. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108740. }
  108741. os->pageno=pageno+1;
  108742. return(0);
  108743. }
  108744. /* clear things to an initial state. Good to call, eg, before seeking */
  108745. int ogg_sync_reset(ogg_sync_state *oy){
  108746. oy->fill=0;
  108747. oy->returned=0;
  108748. oy->unsynced=0;
  108749. oy->headerbytes=0;
  108750. oy->bodybytes=0;
  108751. return(0);
  108752. }
  108753. int ogg_stream_reset(ogg_stream_state *os){
  108754. os->body_fill=0;
  108755. os->body_returned=0;
  108756. os->lacing_fill=0;
  108757. os->lacing_packet=0;
  108758. os->lacing_returned=0;
  108759. os->header_fill=0;
  108760. os->e_o_s=0;
  108761. os->b_o_s=0;
  108762. os->pageno=-1;
  108763. os->packetno=0;
  108764. os->granulepos=0;
  108765. return(0);
  108766. }
  108767. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108768. ogg_stream_reset(os);
  108769. os->serialno=serialno;
  108770. return(0);
  108771. }
  108772. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108773. /* The last part of decode. We have the stream broken into packet
  108774. segments. Now we need to group them into packets (or return the
  108775. out of sync markers) */
  108776. int ptr=os->lacing_returned;
  108777. if(os->lacing_packet<=ptr)return(0);
  108778. if(os->lacing_vals[ptr]&0x400){
  108779. /* we need to tell the codec there's a gap; it might need to
  108780. handle previous packet dependencies. */
  108781. os->lacing_returned++;
  108782. os->packetno++;
  108783. return(-1);
  108784. }
  108785. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108786. to ask if there's a whole packet
  108787. waiting */
  108788. /* Gather the whole packet. We'll have no holes or a partial packet */
  108789. {
  108790. int size=os->lacing_vals[ptr]&0xff;
  108791. int bytes=size;
  108792. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108793. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108794. while(size==255){
  108795. int val=os->lacing_vals[++ptr];
  108796. size=val&0xff;
  108797. if(val&0x200)eos=0x200;
  108798. bytes+=size;
  108799. }
  108800. if(op){
  108801. op->e_o_s=eos;
  108802. op->b_o_s=bos;
  108803. op->packet=os->body_data+os->body_returned;
  108804. op->packetno=os->packetno;
  108805. op->granulepos=os->granule_vals[ptr];
  108806. op->bytes=bytes;
  108807. }
  108808. if(adv){
  108809. os->body_returned+=bytes;
  108810. os->lacing_returned=ptr+1;
  108811. os->packetno++;
  108812. }
  108813. }
  108814. return(1);
  108815. }
  108816. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108817. return _packetout(os,op,1);
  108818. }
  108819. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108820. return _packetout(os,op,0);
  108821. }
  108822. void ogg_packet_clear(ogg_packet *op) {
  108823. _ogg_free(op->packet);
  108824. memset(op, 0, sizeof(*op));
  108825. }
  108826. #ifdef _V_SELFTEST
  108827. #include <stdio.h>
  108828. ogg_stream_state os_en, os_de;
  108829. ogg_sync_state oy;
  108830. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108831. long j;
  108832. static int sequence=0;
  108833. static int lastno=0;
  108834. if(op->bytes!=len){
  108835. fprintf(stderr,"incorrect packet length!\n");
  108836. exit(1);
  108837. }
  108838. if(op->granulepos!=pos){
  108839. fprintf(stderr,"incorrect packet position!\n");
  108840. exit(1);
  108841. }
  108842. /* packet number just follows sequence/gap; adjust the input number
  108843. for that */
  108844. if(no==0){
  108845. sequence=0;
  108846. }else{
  108847. sequence++;
  108848. if(no>lastno+1)
  108849. sequence++;
  108850. }
  108851. lastno=no;
  108852. if(op->packetno!=sequence){
  108853. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108854. (long)(op->packetno),sequence);
  108855. exit(1);
  108856. }
  108857. /* Test data */
  108858. for(j=0;j<op->bytes;j++)
  108859. if(op->packet[j]!=((j+no)&0xff)){
  108860. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108861. j,op->packet[j],(j+no)&0xff);
  108862. exit(1);
  108863. }
  108864. }
  108865. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108866. long j;
  108867. /* Test data */
  108868. for(j=0;j<og->body_len;j++)
  108869. if(og->body[j]!=data[j]){
  108870. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108871. j,data[j],og->body[j]);
  108872. exit(1);
  108873. }
  108874. /* Test header */
  108875. for(j=0;j<og->header_len;j++){
  108876. if(og->header[j]!=header[j]){
  108877. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108878. for(j=0;j<header[26]+27;j++)
  108879. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108880. fprintf(stderr,"\n");
  108881. exit(1);
  108882. }
  108883. }
  108884. if(og->header_len!=header[26]+27){
  108885. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108886. og->header_len,header[26]+27);
  108887. exit(1);
  108888. }
  108889. }
  108890. void print_header(ogg_page *og){
  108891. int j;
  108892. fprintf(stderr,"\nHEADER:\n");
  108893. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108894. og->header[0],og->header[1],og->header[2],og->header[3],
  108895. (int)og->header[4],(int)og->header[5]);
  108896. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108897. (og->header[9]<<24)|(og->header[8]<<16)|
  108898. (og->header[7]<<8)|og->header[6],
  108899. (og->header[17]<<24)|(og->header[16]<<16)|
  108900. (og->header[15]<<8)|og->header[14],
  108901. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108902. (og->header[19]<<8)|og->header[18]);
  108903. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108904. (int)og->header[22],(int)og->header[23],
  108905. (int)og->header[24],(int)og->header[25],
  108906. (int)og->header[26]);
  108907. for(j=27;j<og->header_len;j++)
  108908. fprintf(stderr,"%d ",(int)og->header[j]);
  108909. fprintf(stderr,")\n\n");
  108910. }
  108911. void copy_page(ogg_page *og){
  108912. unsigned char *temp=_ogg_malloc(og->header_len);
  108913. memcpy(temp,og->header,og->header_len);
  108914. og->header=temp;
  108915. temp=_ogg_malloc(og->body_len);
  108916. memcpy(temp,og->body,og->body_len);
  108917. og->body=temp;
  108918. }
  108919. void free_page(ogg_page *og){
  108920. _ogg_free (og->header);
  108921. _ogg_free (og->body);
  108922. }
  108923. void error(void){
  108924. fprintf(stderr,"error!\n");
  108925. exit(1);
  108926. }
  108927. /* 17 only */
  108928. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108929. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108930. 0x01,0x02,0x03,0x04,0,0,0,0,
  108931. 0x15,0xed,0xec,0x91,
  108932. 1,
  108933. 17};
  108934. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108935. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108936. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108937. 0x01,0x02,0x03,0x04,0,0,0,0,
  108938. 0x59,0x10,0x6c,0x2c,
  108939. 1,
  108940. 17};
  108941. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108942. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108943. 0x01,0x02,0x03,0x04,1,0,0,0,
  108944. 0x89,0x33,0x85,0xce,
  108945. 13,
  108946. 254,255,0,255,1,255,245,255,255,0,
  108947. 255,255,90};
  108948. /* nil packets; beginning,middle,end */
  108949. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108950. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108951. 0x01,0x02,0x03,0x04,0,0,0,0,
  108952. 0xff,0x7b,0x23,0x17,
  108953. 1,
  108954. 0};
  108955. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108956. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108957. 0x01,0x02,0x03,0x04,1,0,0,0,
  108958. 0x5c,0x3f,0x66,0xcb,
  108959. 17,
  108960. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108961. 255,255,90,0};
  108962. /* large initial packet */
  108963. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108964. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108965. 0x01,0x02,0x03,0x04,0,0,0,0,
  108966. 0x01,0x27,0x31,0xaa,
  108967. 18,
  108968. 255,255,255,255,255,255,255,255,
  108969. 255,255,255,255,255,255,255,255,255,10};
  108970. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108971. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108972. 0x01,0x02,0x03,0x04,1,0,0,0,
  108973. 0x7f,0x4e,0x8a,0xd2,
  108974. 4,
  108975. 255,4,255,0};
  108976. /* continuing packet test */
  108977. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108978. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108979. 0x01,0x02,0x03,0x04,0,0,0,0,
  108980. 0xff,0x7b,0x23,0x17,
  108981. 1,
  108982. 0};
  108983. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108984. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108985. 0x01,0x02,0x03,0x04,1,0,0,0,
  108986. 0x54,0x05,0x51,0xc8,
  108987. 17,
  108988. 255,255,255,255,255,255,255,255,
  108989. 255,255,255,255,255,255,255,255,255};
  108990. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108991. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108992. 0x01,0x02,0x03,0x04,2,0,0,0,
  108993. 0xc8,0xc3,0xcb,0xed,
  108994. 5,
  108995. 10,255,4,255,0};
  108996. /* page with the 255 segment limit */
  108997. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108998. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108999. 0x01,0x02,0x03,0x04,0,0,0,0,
  109000. 0xff,0x7b,0x23,0x17,
  109001. 1,
  109002. 0};
  109003. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109004. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109005. 0x01,0x02,0x03,0x04,1,0,0,0,
  109006. 0xed,0x2a,0x2e,0xa7,
  109007. 255,
  109008. 10,10,10,10,10,10,10,10,
  109009. 10,10,10,10,10,10,10,10,
  109010. 10,10,10,10,10,10,10,10,
  109011. 10,10,10,10,10,10,10,10,
  109012. 10,10,10,10,10,10,10,10,
  109013. 10,10,10,10,10,10,10,10,
  109014. 10,10,10,10,10,10,10,10,
  109015. 10,10,10,10,10,10,10,10,
  109016. 10,10,10,10,10,10,10,10,
  109017. 10,10,10,10,10,10,10,10,
  109018. 10,10,10,10,10,10,10,10,
  109019. 10,10,10,10,10,10,10,10,
  109020. 10,10,10,10,10,10,10,10,
  109021. 10,10,10,10,10,10,10,10,
  109022. 10,10,10,10,10,10,10,10,
  109023. 10,10,10,10,10,10,10,10,
  109024. 10,10,10,10,10,10,10,10,
  109025. 10,10,10,10,10,10,10,10,
  109026. 10,10,10,10,10,10,10,10,
  109027. 10,10,10,10,10,10,10,10,
  109028. 10,10,10,10,10,10,10,10,
  109029. 10,10,10,10,10,10,10,10,
  109030. 10,10,10,10,10,10,10,10,
  109031. 10,10,10,10,10,10,10,10,
  109032. 10,10,10,10,10,10,10,10,
  109033. 10,10,10,10,10,10,10,10,
  109034. 10,10,10,10,10,10,10,10,
  109035. 10,10,10,10,10,10,10,10,
  109036. 10,10,10,10,10,10,10,10,
  109037. 10,10,10,10,10,10,10,10,
  109038. 10,10,10,10,10,10,10,10,
  109039. 10,10,10,10,10,10,10};
  109040. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109041. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109042. 0x01,0x02,0x03,0x04,2,0,0,0,
  109043. 0x6c,0x3b,0x82,0x3d,
  109044. 1,
  109045. 50};
  109046. /* packet that overspans over an entire page */
  109047. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109048. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109049. 0x01,0x02,0x03,0x04,0,0,0,0,
  109050. 0xff,0x7b,0x23,0x17,
  109051. 1,
  109052. 0};
  109053. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109054. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109055. 0x01,0x02,0x03,0x04,1,0,0,0,
  109056. 0x3c,0xd9,0x4d,0x3f,
  109057. 17,
  109058. 100,255,255,255,255,255,255,255,255,
  109059. 255,255,255,255,255,255,255,255};
  109060. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109061. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109062. 0x01,0x02,0x03,0x04,2,0,0,0,
  109063. 0x01,0xd2,0xe5,0xe5,
  109064. 17,
  109065. 255,255,255,255,255,255,255,255,
  109066. 255,255,255,255,255,255,255,255,255};
  109067. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109068. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109069. 0x01,0x02,0x03,0x04,3,0,0,0,
  109070. 0xef,0xdd,0x88,0xde,
  109071. 7,
  109072. 255,255,75,255,4,255,0};
  109073. /* packet that overspans over an entire page */
  109074. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109075. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109076. 0x01,0x02,0x03,0x04,0,0,0,0,
  109077. 0xff,0x7b,0x23,0x17,
  109078. 1,
  109079. 0};
  109080. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109081. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109082. 0x01,0x02,0x03,0x04,1,0,0,0,
  109083. 0x3c,0xd9,0x4d,0x3f,
  109084. 17,
  109085. 100,255,255,255,255,255,255,255,255,
  109086. 255,255,255,255,255,255,255,255};
  109087. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109088. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109089. 0x01,0x02,0x03,0x04,2,0,0,0,
  109090. 0xd4,0xe0,0x60,0xe5,
  109091. 1,0};
  109092. void test_pack(const int *pl, const int **headers, int byteskip,
  109093. int pageskip, int packetskip){
  109094. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109095. long inptr=0;
  109096. long outptr=0;
  109097. long deptr=0;
  109098. long depacket=0;
  109099. long granule_pos=7,pageno=0;
  109100. int i,j,packets,pageout=pageskip;
  109101. int eosflag=0;
  109102. int bosflag=0;
  109103. int byteskipcount=0;
  109104. ogg_stream_reset(&os_en);
  109105. ogg_stream_reset(&os_de);
  109106. ogg_sync_reset(&oy);
  109107. for(packets=0;packets<packetskip;packets++)
  109108. depacket+=pl[packets];
  109109. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109110. for(i=0;i<packets;i++){
  109111. /* construct a test packet */
  109112. ogg_packet op;
  109113. int len=pl[i];
  109114. op.packet=data+inptr;
  109115. op.bytes=len;
  109116. op.e_o_s=(pl[i+1]<0?1:0);
  109117. op.granulepos=granule_pos;
  109118. granule_pos+=1024;
  109119. for(j=0;j<len;j++)data[inptr++]=i+j;
  109120. /* submit the test packet */
  109121. ogg_stream_packetin(&os_en,&op);
  109122. /* retrieve any finished pages */
  109123. {
  109124. ogg_page og;
  109125. while(ogg_stream_pageout(&os_en,&og)){
  109126. /* We have a page. Check it carefully */
  109127. fprintf(stderr,"%ld, ",pageno);
  109128. if(headers[pageno]==NULL){
  109129. fprintf(stderr,"coded too many pages!\n");
  109130. exit(1);
  109131. }
  109132. check_page(data+outptr,headers[pageno],&og);
  109133. outptr+=og.body_len;
  109134. pageno++;
  109135. if(pageskip){
  109136. bosflag=1;
  109137. pageskip--;
  109138. deptr+=og.body_len;
  109139. }
  109140. /* have a complete page; submit it to sync/decode */
  109141. {
  109142. ogg_page og_de;
  109143. ogg_packet op_de,op_de2;
  109144. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109145. char *next=buf;
  109146. byteskipcount+=og.header_len;
  109147. if(byteskipcount>byteskip){
  109148. memcpy(next,og.header,byteskipcount-byteskip);
  109149. next+=byteskipcount-byteskip;
  109150. byteskipcount=byteskip;
  109151. }
  109152. byteskipcount+=og.body_len;
  109153. if(byteskipcount>byteskip){
  109154. memcpy(next,og.body,byteskipcount-byteskip);
  109155. next+=byteskipcount-byteskip;
  109156. byteskipcount=byteskip;
  109157. }
  109158. ogg_sync_wrote(&oy,next-buf);
  109159. while(1){
  109160. int ret=ogg_sync_pageout(&oy,&og_de);
  109161. if(ret==0)break;
  109162. if(ret<0)continue;
  109163. /* got a page. Happy happy. Verify that it's good. */
  109164. fprintf(stderr,"(%ld), ",pageout);
  109165. check_page(data+deptr,headers[pageout],&og_de);
  109166. deptr+=og_de.body_len;
  109167. pageout++;
  109168. /* submit it to deconstitution */
  109169. ogg_stream_pagein(&os_de,&og_de);
  109170. /* packets out? */
  109171. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109172. ogg_stream_packetpeek(&os_de,NULL);
  109173. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109174. /* verify peek and out match */
  109175. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109176. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109177. depacket);
  109178. exit(1);
  109179. }
  109180. /* verify the packet! */
  109181. /* check data */
  109182. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109183. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109184. depacket);
  109185. exit(1);
  109186. }
  109187. /* check bos flag */
  109188. if(bosflag==0 && op_de.b_o_s==0){
  109189. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109190. exit(1);
  109191. }
  109192. if(bosflag && op_de.b_o_s){
  109193. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109194. exit(1);
  109195. }
  109196. bosflag=1;
  109197. depacket+=op_de.bytes;
  109198. /* check eos flag */
  109199. if(eosflag){
  109200. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109201. exit(1);
  109202. }
  109203. if(op_de.e_o_s)eosflag=1;
  109204. /* check granulepos flag */
  109205. if(op_de.granulepos!=-1){
  109206. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109207. }
  109208. }
  109209. }
  109210. }
  109211. }
  109212. }
  109213. }
  109214. _ogg_free(data);
  109215. if(headers[pageno]!=NULL){
  109216. fprintf(stderr,"did not write last page!\n");
  109217. exit(1);
  109218. }
  109219. if(headers[pageout]!=NULL){
  109220. fprintf(stderr,"did not decode last page!\n");
  109221. exit(1);
  109222. }
  109223. if(inptr!=outptr){
  109224. fprintf(stderr,"encoded page data incomplete!\n");
  109225. exit(1);
  109226. }
  109227. if(inptr!=deptr){
  109228. fprintf(stderr,"decoded page data incomplete!\n");
  109229. exit(1);
  109230. }
  109231. if(inptr!=depacket){
  109232. fprintf(stderr,"decoded packet data incomplete!\n");
  109233. exit(1);
  109234. }
  109235. if(!eosflag){
  109236. fprintf(stderr,"Never got a packet with EOS set!\n");
  109237. exit(1);
  109238. }
  109239. fprintf(stderr,"ok.\n");
  109240. }
  109241. int main(void){
  109242. ogg_stream_init(&os_en,0x04030201);
  109243. ogg_stream_init(&os_de,0x04030201);
  109244. ogg_sync_init(&oy);
  109245. /* Exercise each code path in the framing code. Also verify that
  109246. the checksums are working. */
  109247. {
  109248. /* 17 only */
  109249. const int packets[]={17, -1};
  109250. const int *headret[]={head1_0,NULL};
  109251. fprintf(stderr,"testing single page encoding... ");
  109252. test_pack(packets,headret,0,0,0);
  109253. }
  109254. {
  109255. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109256. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109257. const int *headret[]={head1_1,head2_1,NULL};
  109258. fprintf(stderr,"testing basic page encoding... ");
  109259. test_pack(packets,headret,0,0,0);
  109260. }
  109261. {
  109262. /* nil packets; beginning,middle,end */
  109263. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109264. const int *headret[]={head1_2,head2_2,NULL};
  109265. fprintf(stderr,"testing basic nil packets... ");
  109266. test_pack(packets,headret,0,0,0);
  109267. }
  109268. {
  109269. /* large initial packet */
  109270. const int packets[]={4345,259,255,-1};
  109271. const int *headret[]={head1_3,head2_3,NULL};
  109272. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109273. test_pack(packets,headret,0,0,0);
  109274. }
  109275. {
  109276. /* continuing packet test */
  109277. const int packets[]={0,4345,259,255,-1};
  109278. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109279. fprintf(stderr,"testing single packet page span... ");
  109280. test_pack(packets,headret,0,0,0);
  109281. }
  109282. /* page with the 255 segment limit */
  109283. {
  109284. const int packets[]={0,10,10,10,10,10,10,10,10,
  109285. 10,10,10,10,10,10,10,10,
  109286. 10,10,10,10,10,10,10,10,
  109287. 10,10,10,10,10,10,10,10,
  109288. 10,10,10,10,10,10,10,10,
  109289. 10,10,10,10,10,10,10,10,
  109290. 10,10,10,10,10,10,10,10,
  109291. 10,10,10,10,10,10,10,10,
  109292. 10,10,10,10,10,10,10,10,
  109293. 10,10,10,10,10,10,10,10,
  109294. 10,10,10,10,10,10,10,10,
  109295. 10,10,10,10,10,10,10,10,
  109296. 10,10,10,10,10,10,10,10,
  109297. 10,10,10,10,10,10,10,10,
  109298. 10,10,10,10,10,10,10,10,
  109299. 10,10,10,10,10,10,10,10,
  109300. 10,10,10,10,10,10,10,10,
  109301. 10,10,10,10,10,10,10,10,
  109302. 10,10,10,10,10,10,10,10,
  109303. 10,10,10,10,10,10,10,10,
  109304. 10,10,10,10,10,10,10,10,
  109305. 10,10,10,10,10,10,10,10,
  109306. 10,10,10,10,10,10,10,10,
  109307. 10,10,10,10,10,10,10,10,
  109308. 10,10,10,10,10,10,10,10,
  109309. 10,10,10,10,10,10,10,10,
  109310. 10,10,10,10,10,10,10,10,
  109311. 10,10,10,10,10,10,10,10,
  109312. 10,10,10,10,10,10,10,10,
  109313. 10,10,10,10,10,10,10,10,
  109314. 10,10,10,10,10,10,10,10,
  109315. 10,10,10,10,10,10,10,50,-1};
  109316. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109317. fprintf(stderr,"testing max packet segments... ");
  109318. test_pack(packets,headret,0,0,0);
  109319. }
  109320. {
  109321. /* packet that overspans over an entire page */
  109322. const int packets[]={0,100,9000,259,255,-1};
  109323. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109324. fprintf(stderr,"testing very large packets... ");
  109325. test_pack(packets,headret,0,0,0);
  109326. }
  109327. {
  109328. /* test for the libogg 1.1.1 resync in large continuation bug
  109329. found by Josh Coalson) */
  109330. const int packets[]={0,100,9000,259,255,-1};
  109331. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109332. fprintf(stderr,"testing continuation resync in very large packets... ");
  109333. test_pack(packets,headret,100,2,3);
  109334. }
  109335. {
  109336. /* term only page. why not? */
  109337. const int packets[]={0,100,4080,-1};
  109338. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109339. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109340. test_pack(packets,headret,0,0,0);
  109341. }
  109342. {
  109343. /* build a bunch of pages for testing */
  109344. unsigned char *data=_ogg_malloc(1024*1024);
  109345. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109346. int inptr=0,i,j;
  109347. ogg_page og[5];
  109348. ogg_stream_reset(&os_en);
  109349. for(i=0;pl[i]!=-1;i++){
  109350. ogg_packet op;
  109351. int len=pl[i];
  109352. op.packet=data+inptr;
  109353. op.bytes=len;
  109354. op.e_o_s=(pl[i+1]<0?1:0);
  109355. op.granulepos=(i+1)*1000;
  109356. for(j=0;j<len;j++)data[inptr++]=i+j;
  109357. ogg_stream_packetin(&os_en,&op);
  109358. }
  109359. _ogg_free(data);
  109360. /* retrieve finished pages */
  109361. for(i=0;i<5;i++){
  109362. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109363. fprintf(stderr,"Too few pages output building sync tests!\n");
  109364. exit(1);
  109365. }
  109366. copy_page(&og[i]);
  109367. }
  109368. /* Test lost pages on pagein/packetout: no rollback */
  109369. {
  109370. ogg_page temp;
  109371. ogg_packet test;
  109372. fprintf(stderr,"Testing loss of pages... ");
  109373. ogg_sync_reset(&oy);
  109374. ogg_stream_reset(&os_de);
  109375. for(i=0;i<5;i++){
  109376. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109377. og[i].header_len);
  109378. ogg_sync_wrote(&oy,og[i].header_len);
  109379. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109380. ogg_sync_wrote(&oy,og[i].body_len);
  109381. }
  109382. ogg_sync_pageout(&oy,&temp);
  109383. ogg_stream_pagein(&os_de,&temp);
  109384. ogg_sync_pageout(&oy,&temp);
  109385. ogg_stream_pagein(&os_de,&temp);
  109386. ogg_sync_pageout(&oy,&temp);
  109387. /* skip */
  109388. ogg_sync_pageout(&oy,&temp);
  109389. ogg_stream_pagein(&os_de,&temp);
  109390. /* do we get the expected results/packets? */
  109391. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109392. checkpacket(&test,0,0,0);
  109393. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109394. checkpacket(&test,100,1,-1);
  109395. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109396. checkpacket(&test,4079,2,3000);
  109397. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109398. fprintf(stderr,"Error: loss of page did not return error\n");
  109399. exit(1);
  109400. }
  109401. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109402. checkpacket(&test,76,5,-1);
  109403. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109404. checkpacket(&test,34,6,-1);
  109405. fprintf(stderr,"ok.\n");
  109406. }
  109407. /* Test lost pages on pagein/packetout: rollback with continuation */
  109408. {
  109409. ogg_page temp;
  109410. ogg_packet test;
  109411. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109412. ogg_sync_reset(&oy);
  109413. ogg_stream_reset(&os_de);
  109414. for(i=0;i<5;i++){
  109415. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109416. og[i].header_len);
  109417. ogg_sync_wrote(&oy,og[i].header_len);
  109418. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109419. ogg_sync_wrote(&oy,og[i].body_len);
  109420. }
  109421. ogg_sync_pageout(&oy,&temp);
  109422. ogg_stream_pagein(&os_de,&temp);
  109423. ogg_sync_pageout(&oy,&temp);
  109424. ogg_stream_pagein(&os_de,&temp);
  109425. ogg_sync_pageout(&oy,&temp);
  109426. ogg_stream_pagein(&os_de,&temp);
  109427. ogg_sync_pageout(&oy,&temp);
  109428. /* skip */
  109429. ogg_sync_pageout(&oy,&temp);
  109430. ogg_stream_pagein(&os_de,&temp);
  109431. /* do we get the expected results/packets? */
  109432. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109433. checkpacket(&test,0,0,0);
  109434. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109435. checkpacket(&test,100,1,-1);
  109436. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109437. checkpacket(&test,4079,2,3000);
  109438. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109439. checkpacket(&test,2956,3,4000);
  109440. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109441. fprintf(stderr,"Error: loss of page did not return error\n");
  109442. exit(1);
  109443. }
  109444. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109445. checkpacket(&test,300,13,14000);
  109446. fprintf(stderr,"ok.\n");
  109447. }
  109448. /* the rest only test sync */
  109449. {
  109450. ogg_page og_de;
  109451. /* Test fractional page inputs: incomplete capture */
  109452. fprintf(stderr,"Testing sync on partial inputs... ");
  109453. ogg_sync_reset(&oy);
  109454. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109455. 3);
  109456. ogg_sync_wrote(&oy,3);
  109457. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109458. /* Test fractional page inputs: incomplete fixed header */
  109459. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109460. 20);
  109461. ogg_sync_wrote(&oy,20);
  109462. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109463. /* Test fractional page inputs: incomplete header */
  109464. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109465. 5);
  109466. ogg_sync_wrote(&oy,5);
  109467. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109468. /* Test fractional page inputs: incomplete body */
  109469. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109470. og[1].header_len-28);
  109471. ogg_sync_wrote(&oy,og[1].header_len-28);
  109472. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109473. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109474. ogg_sync_wrote(&oy,1000);
  109475. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109476. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109477. og[1].body_len-1000);
  109478. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109479. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109480. fprintf(stderr,"ok.\n");
  109481. }
  109482. /* Test fractional page inputs: page + incomplete capture */
  109483. {
  109484. ogg_page og_de;
  109485. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109486. ogg_sync_reset(&oy);
  109487. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109488. og[1].header_len);
  109489. ogg_sync_wrote(&oy,og[1].header_len);
  109490. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109491. og[1].body_len);
  109492. ogg_sync_wrote(&oy,og[1].body_len);
  109493. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109494. 20);
  109495. ogg_sync_wrote(&oy,20);
  109496. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109497. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109498. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109499. og[1].header_len-20);
  109500. ogg_sync_wrote(&oy,og[1].header_len-20);
  109501. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109502. og[1].body_len);
  109503. ogg_sync_wrote(&oy,og[1].body_len);
  109504. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109505. fprintf(stderr,"ok.\n");
  109506. }
  109507. /* Test recapture: garbage + page */
  109508. {
  109509. ogg_page og_de;
  109510. fprintf(stderr,"Testing search for capture... ");
  109511. ogg_sync_reset(&oy);
  109512. /* 'garbage' */
  109513. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109514. og[1].body_len);
  109515. ogg_sync_wrote(&oy,og[1].body_len);
  109516. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109517. og[1].header_len);
  109518. ogg_sync_wrote(&oy,og[1].header_len);
  109519. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109520. og[1].body_len);
  109521. ogg_sync_wrote(&oy,og[1].body_len);
  109522. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109523. 20);
  109524. ogg_sync_wrote(&oy,20);
  109525. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109526. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109527. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109528. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109529. og[2].header_len-20);
  109530. ogg_sync_wrote(&oy,og[2].header_len-20);
  109531. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109532. og[2].body_len);
  109533. ogg_sync_wrote(&oy,og[2].body_len);
  109534. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109535. fprintf(stderr,"ok.\n");
  109536. }
  109537. /* Test recapture: page + garbage + page */
  109538. {
  109539. ogg_page og_de;
  109540. fprintf(stderr,"Testing recapture... ");
  109541. ogg_sync_reset(&oy);
  109542. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109543. og[1].header_len);
  109544. ogg_sync_wrote(&oy,og[1].header_len);
  109545. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109546. og[1].body_len);
  109547. ogg_sync_wrote(&oy,og[1].body_len);
  109548. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109549. og[2].header_len);
  109550. ogg_sync_wrote(&oy,og[2].header_len);
  109551. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109552. og[2].header_len);
  109553. ogg_sync_wrote(&oy,og[2].header_len);
  109554. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109555. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109556. og[2].body_len-5);
  109557. ogg_sync_wrote(&oy,og[2].body_len-5);
  109558. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109559. og[3].header_len);
  109560. ogg_sync_wrote(&oy,og[3].header_len);
  109561. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109562. og[3].body_len);
  109563. ogg_sync_wrote(&oy,og[3].body_len);
  109564. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109565. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109566. fprintf(stderr,"ok.\n");
  109567. }
  109568. /* Free page data that was previously copied */
  109569. {
  109570. for(i=0;i<5;i++){
  109571. free_page(&og[i]);
  109572. }
  109573. }
  109574. }
  109575. return(0);
  109576. }
  109577. #endif
  109578. #endif
  109579. /*** End of inlined file: framing.c ***/
  109580. /*** Start of inlined file: analysis.c ***/
  109581. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109582. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109583. // tasks..
  109584. #if JUCE_MSVC
  109585. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109586. #endif
  109587. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109588. #if JUCE_USE_OGGVORBIS
  109589. #include <stdio.h>
  109590. #include <string.h>
  109591. #include <math.h>
  109592. /*** Start of inlined file: codec_internal.h ***/
  109593. #ifndef _V_CODECI_H_
  109594. #define _V_CODECI_H_
  109595. /*** Start of inlined file: envelope.h ***/
  109596. #ifndef _V_ENVELOPE_
  109597. #define _V_ENVELOPE_
  109598. /*** Start of inlined file: mdct.h ***/
  109599. #ifndef _OGG_mdct_H_
  109600. #define _OGG_mdct_H_
  109601. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109602. #ifdef MDCT_INTEGERIZED
  109603. #define DATA_TYPE int
  109604. #define REG_TYPE register int
  109605. #define TRIGBITS 14
  109606. #define cPI3_8 6270
  109607. #define cPI2_8 11585
  109608. #define cPI1_8 15137
  109609. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109610. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109611. #define HALVE(x) ((x)>>1)
  109612. #else
  109613. #define DATA_TYPE float
  109614. #define REG_TYPE float
  109615. #define cPI3_8 .38268343236508977175F
  109616. #define cPI2_8 .70710678118654752441F
  109617. #define cPI1_8 .92387953251128675613F
  109618. #define FLOAT_CONV(x) (x)
  109619. #define MULT_NORM(x) (x)
  109620. #define HALVE(x) ((x)*.5f)
  109621. #endif
  109622. typedef struct {
  109623. int n;
  109624. int log2n;
  109625. DATA_TYPE *trig;
  109626. int *bitrev;
  109627. DATA_TYPE scale;
  109628. } mdct_lookup;
  109629. extern void mdct_init(mdct_lookup *lookup,int n);
  109630. extern void mdct_clear(mdct_lookup *l);
  109631. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109632. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109633. #endif
  109634. /*** End of inlined file: mdct.h ***/
  109635. #define VE_PRE 16
  109636. #define VE_WIN 4
  109637. #define VE_POST 2
  109638. #define VE_AMP (VE_PRE+VE_POST-1)
  109639. #define VE_BANDS 7
  109640. #define VE_NEARDC 15
  109641. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109642. #define VE_MAXSTRETCH 12 /* one-third full block */
  109643. typedef struct {
  109644. float ampbuf[VE_AMP];
  109645. int ampptr;
  109646. float nearDC[VE_NEARDC];
  109647. float nearDC_acc;
  109648. float nearDC_partialacc;
  109649. int nearptr;
  109650. } envelope_filter_state;
  109651. typedef struct {
  109652. int begin;
  109653. int end;
  109654. float *window;
  109655. float total;
  109656. } envelope_band;
  109657. typedef struct {
  109658. int ch;
  109659. int winlength;
  109660. int searchstep;
  109661. float minenergy;
  109662. mdct_lookup mdct;
  109663. float *mdct_win;
  109664. envelope_band band[VE_BANDS];
  109665. envelope_filter_state *filter;
  109666. int stretch;
  109667. int *mark;
  109668. long storage;
  109669. long current;
  109670. long curmark;
  109671. long cursor;
  109672. } envelope_lookup;
  109673. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109674. extern void _ve_envelope_clear(envelope_lookup *e);
  109675. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109676. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109677. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109678. #endif
  109679. /*** End of inlined file: envelope.h ***/
  109680. /*** Start of inlined file: codebook.h ***/
  109681. #ifndef _V_CODEBOOK_H_
  109682. #define _V_CODEBOOK_H_
  109683. /* This structure encapsulates huffman and VQ style encoding books; it
  109684. doesn't do anything specific to either.
  109685. valuelist/quantlist are nonNULL (and q_* significant) only if
  109686. there's entry->value mapping to be done.
  109687. If encode-side mapping must be done (and thus the entry needs to be
  109688. hunted), the auxiliary encode pointer will point to a decision
  109689. tree. This is true of both VQ and huffman, but is mostly useful
  109690. with VQ.
  109691. */
  109692. typedef struct static_codebook{
  109693. long dim; /* codebook dimensions (elements per vector) */
  109694. long entries; /* codebook entries */
  109695. long *lengthlist; /* codeword lengths in bits */
  109696. /* mapping ***************************************************************/
  109697. int maptype; /* 0=none
  109698. 1=implicitly populated values from map column
  109699. 2=listed arbitrary values */
  109700. /* The below does a linear, single monotonic sequence mapping. */
  109701. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109702. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109703. int q_quant; /* bits: 0 < quant <= 16 */
  109704. int q_sequencep; /* bitflag */
  109705. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109706. map == 2: list of dim*entries quantized entry vals
  109707. */
  109708. /* encode helpers ********************************************************/
  109709. struct encode_aux_nearestmatch *nearest_tree;
  109710. struct encode_aux_threshmatch *thresh_tree;
  109711. struct encode_aux_pigeonhole *pigeon_tree;
  109712. int allocedp;
  109713. } static_codebook;
  109714. /* this structures an arbitrary trained book to quickly find the
  109715. nearest cell match */
  109716. typedef struct encode_aux_nearestmatch{
  109717. /* pre-calculated partitioning tree */
  109718. long *ptr0;
  109719. long *ptr1;
  109720. long *p; /* decision points (each is an entry) */
  109721. long *q; /* decision points (each is an entry) */
  109722. long aux; /* number of tree entries */
  109723. long alloc;
  109724. } encode_aux_nearestmatch;
  109725. /* assumes a maptype of 1; encode side only, so that's OK */
  109726. typedef struct encode_aux_threshmatch{
  109727. float *quantthresh;
  109728. long *quantmap;
  109729. int quantvals;
  109730. int threshvals;
  109731. } encode_aux_threshmatch;
  109732. typedef struct encode_aux_pigeonhole{
  109733. float min;
  109734. float del;
  109735. int mapentries;
  109736. int quantvals;
  109737. long *pigeonmap;
  109738. long fittotal;
  109739. long *fitlist;
  109740. long *fitmap;
  109741. long *fitlength;
  109742. } encode_aux_pigeonhole;
  109743. typedef struct codebook{
  109744. long dim; /* codebook dimensions (elements per vector) */
  109745. long entries; /* codebook entries */
  109746. long used_entries; /* populated codebook entries */
  109747. const static_codebook *c;
  109748. /* for encode, the below are entry-ordered, fully populated */
  109749. /* for decode, the below are ordered by bitreversed codeword and only
  109750. used entries are populated */
  109751. float *valuelist; /* list of dim*entries actual entry values */
  109752. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109753. int *dec_index; /* only used if sparseness collapsed */
  109754. char *dec_codelengths;
  109755. ogg_uint32_t *dec_firsttable;
  109756. int dec_firsttablen;
  109757. int dec_maxlength;
  109758. } codebook;
  109759. extern void vorbis_staticbook_clear(static_codebook *b);
  109760. extern void vorbis_staticbook_destroy(static_codebook *b);
  109761. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109762. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109763. extern void vorbis_book_clear(codebook *b);
  109764. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109765. extern float *_book_logdist(const static_codebook *b,float *vals);
  109766. extern float _float32_unpack(long val);
  109767. extern long _float32_pack(float val);
  109768. extern int _best(codebook *book, float *a, int step);
  109769. extern int _ilog(unsigned int v);
  109770. extern long _book_maptype1_quantvals(const static_codebook *b);
  109771. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109772. extern long vorbis_book_codeword(codebook *book,int entry);
  109773. extern long vorbis_book_codelen(codebook *book,int entry);
  109774. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109775. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109776. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109777. extern int vorbis_book_errorv(codebook *book, float *a);
  109778. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109779. oggpack_buffer *b);
  109780. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109781. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109782. oggpack_buffer *b,int n);
  109783. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109784. oggpack_buffer *b,int n);
  109785. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109786. oggpack_buffer *b,int n);
  109787. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109788. long off,int ch,
  109789. oggpack_buffer *b,int n);
  109790. #endif
  109791. /*** End of inlined file: codebook.h ***/
  109792. #define BLOCKTYPE_IMPULSE 0
  109793. #define BLOCKTYPE_PADDING 1
  109794. #define BLOCKTYPE_TRANSITION 0
  109795. #define BLOCKTYPE_LONG 1
  109796. #define PACKETBLOBS 15
  109797. typedef struct vorbis_block_internal{
  109798. float **pcmdelay; /* this is a pointer into local storage */
  109799. float ampmax;
  109800. int blocktype;
  109801. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109802. blob [PACKETBLOBS/2] points to
  109803. the oggpack_buffer in the
  109804. main vorbis_block */
  109805. } vorbis_block_internal;
  109806. typedef void vorbis_look_floor;
  109807. typedef void vorbis_look_residue;
  109808. typedef void vorbis_look_transform;
  109809. /* mode ************************************************************/
  109810. typedef struct {
  109811. int blockflag;
  109812. int windowtype;
  109813. int transformtype;
  109814. int mapping;
  109815. } vorbis_info_mode;
  109816. typedef void vorbis_info_floor;
  109817. typedef void vorbis_info_residue;
  109818. typedef void vorbis_info_mapping;
  109819. /*** Start of inlined file: psy.h ***/
  109820. #ifndef _V_PSY_H_
  109821. #define _V_PSY_H_
  109822. /*** Start of inlined file: smallft.h ***/
  109823. #ifndef _V_SMFT_H_
  109824. #define _V_SMFT_H_
  109825. typedef struct {
  109826. int n;
  109827. float *trigcache;
  109828. int *splitcache;
  109829. } drft_lookup;
  109830. extern void drft_forward(drft_lookup *l,float *data);
  109831. extern void drft_backward(drft_lookup *l,float *data);
  109832. extern void drft_init(drft_lookup *l,int n);
  109833. extern void drft_clear(drft_lookup *l);
  109834. #endif
  109835. /*** End of inlined file: smallft.h ***/
  109836. /*** Start of inlined file: backends.h ***/
  109837. /* this is exposed up here because we need it for static modes.
  109838. Lookups for each backend aren't exposed because there's no reason
  109839. to do so */
  109840. #ifndef _vorbis_backend_h_
  109841. #define _vorbis_backend_h_
  109842. /* this would all be simpler/shorter with templates, but.... */
  109843. /* Floor backend generic *****************************************/
  109844. typedef struct{
  109845. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109846. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109847. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109848. void (*free_info) (vorbis_info_floor *);
  109849. void (*free_look) (vorbis_look_floor *);
  109850. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109851. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109852. void *buffer,float *);
  109853. } vorbis_func_floor;
  109854. typedef struct{
  109855. int order;
  109856. long rate;
  109857. long barkmap;
  109858. int ampbits;
  109859. int ampdB;
  109860. int numbooks; /* <= 16 */
  109861. int books[16];
  109862. float lessthan; /* encode-only config setting hacks for libvorbis */
  109863. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109864. } vorbis_info_floor0;
  109865. #define VIF_POSIT 63
  109866. #define VIF_CLASS 16
  109867. #define VIF_PARTS 31
  109868. typedef struct{
  109869. int partitions; /* 0 to 31 */
  109870. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109871. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109872. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109873. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109874. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109875. int mult; /* 1 2 3 or 4 */
  109876. int postlist[VIF_POSIT+2]; /* first two implicit */
  109877. /* encode side analysis parameters */
  109878. float maxover;
  109879. float maxunder;
  109880. float maxerr;
  109881. float twofitweight;
  109882. float twofitatten;
  109883. int n;
  109884. } vorbis_info_floor1;
  109885. /* Residue backend generic *****************************************/
  109886. typedef struct{
  109887. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109888. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109889. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109890. vorbis_info_residue *);
  109891. void (*free_info) (vorbis_info_residue *);
  109892. void (*free_look) (vorbis_look_residue *);
  109893. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109894. float **,int *,int);
  109895. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109896. vorbis_look_residue *,
  109897. float **,float **,int *,int,long **);
  109898. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109899. float **,int *,int);
  109900. } vorbis_func_residue;
  109901. typedef struct vorbis_info_residue0{
  109902. /* block-partitioned VQ coded straight residue */
  109903. long begin;
  109904. long end;
  109905. /* first stage (lossless partitioning) */
  109906. int grouping; /* group n vectors per partition */
  109907. int partitions; /* possible codebooks for a partition */
  109908. int groupbook; /* huffbook for partitioning */
  109909. int secondstages[64]; /* expanded out to pointers in lookup */
  109910. int booklist[256]; /* list of second stage books */
  109911. float classmetric1[64];
  109912. float classmetric2[64];
  109913. } vorbis_info_residue0;
  109914. /* Mapping backend generic *****************************************/
  109915. typedef struct{
  109916. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109917. oggpack_buffer *);
  109918. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109919. void (*free_info) (vorbis_info_mapping *);
  109920. int (*forward) (struct vorbis_block *vb);
  109921. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109922. } vorbis_func_mapping;
  109923. typedef struct vorbis_info_mapping0{
  109924. int submaps; /* <= 16 */
  109925. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109926. int floorsubmap[16]; /* [mux] submap to floors */
  109927. int residuesubmap[16]; /* [mux] submap to residue */
  109928. int coupling_steps;
  109929. int coupling_mag[256];
  109930. int coupling_ang[256];
  109931. } vorbis_info_mapping0;
  109932. #endif
  109933. /*** End of inlined file: backends.h ***/
  109934. #ifndef EHMER_MAX
  109935. #define EHMER_MAX 56
  109936. #endif
  109937. /* psychoacoustic setup ********************************************/
  109938. #define P_BANDS 17 /* 62Hz to 16kHz */
  109939. #define P_LEVELS 8 /* 30dB to 100dB */
  109940. #define P_LEVEL_0 30. /* 30 dB */
  109941. #define P_NOISECURVES 3
  109942. #define NOISE_COMPAND_LEVELS 40
  109943. typedef struct vorbis_info_psy{
  109944. int blockflag;
  109945. float ath_adjatt;
  109946. float ath_maxatt;
  109947. float tone_masteratt[P_NOISECURVES];
  109948. float tone_centerboost;
  109949. float tone_decay;
  109950. float tone_abs_limit;
  109951. float toneatt[P_BANDS];
  109952. int noisemaskp;
  109953. float noisemaxsupp;
  109954. float noisewindowlo;
  109955. float noisewindowhi;
  109956. int noisewindowlomin;
  109957. int noisewindowhimin;
  109958. int noisewindowfixed;
  109959. float noiseoff[P_NOISECURVES][P_BANDS];
  109960. float noisecompand[NOISE_COMPAND_LEVELS];
  109961. float max_curve_dB;
  109962. int normal_channel_p;
  109963. int normal_point_p;
  109964. int normal_start;
  109965. int normal_partition;
  109966. double normal_thresh;
  109967. } vorbis_info_psy;
  109968. typedef struct{
  109969. int eighth_octave_lines;
  109970. /* for block long/short tuning; encode only */
  109971. float preecho_thresh[VE_BANDS];
  109972. float postecho_thresh[VE_BANDS];
  109973. float stretch_penalty;
  109974. float preecho_minenergy;
  109975. float ampmax_att_per_sec;
  109976. /* channel coupling config */
  109977. int coupling_pkHz[PACKETBLOBS];
  109978. int coupling_pointlimit[2][PACKETBLOBS];
  109979. int coupling_prepointamp[PACKETBLOBS];
  109980. int coupling_postpointamp[PACKETBLOBS];
  109981. int sliding_lowpass[2][PACKETBLOBS];
  109982. } vorbis_info_psy_global;
  109983. typedef struct {
  109984. float ampmax;
  109985. int channels;
  109986. vorbis_info_psy_global *gi;
  109987. int coupling_pointlimit[2][P_NOISECURVES];
  109988. } vorbis_look_psy_global;
  109989. typedef struct {
  109990. int n;
  109991. struct vorbis_info_psy *vi;
  109992. float ***tonecurves;
  109993. float **noiseoffset;
  109994. float *ath;
  109995. long *octave; /* in n.ocshift format */
  109996. long *bark;
  109997. long firstoc;
  109998. long shiftoc;
  109999. int eighth_octave_lines; /* power of two, please */
  110000. int total_octave_lines;
  110001. long rate; /* cache it */
  110002. float m_val; /* Masking compensation value */
  110003. } vorbis_look_psy;
  110004. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110005. vorbis_info_psy_global *gi,int n,long rate);
  110006. extern void _vp_psy_clear(vorbis_look_psy *p);
  110007. extern void *_vi_psy_dup(void *source);
  110008. extern void _vi_psy_free(vorbis_info_psy *i);
  110009. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110010. extern void _vp_remove_floor(vorbis_look_psy *p,
  110011. float *mdct,
  110012. int *icodedflr,
  110013. float *residue,
  110014. int sliding_lowpass);
  110015. extern void _vp_noisemask(vorbis_look_psy *p,
  110016. float *logmdct,
  110017. float *logmask);
  110018. extern void _vp_tonemask(vorbis_look_psy *p,
  110019. float *logfft,
  110020. float *logmask,
  110021. float global_specmax,
  110022. float local_specmax);
  110023. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110024. float *noise,
  110025. float *tone,
  110026. int offset_select,
  110027. float *logmask,
  110028. float *mdct,
  110029. float *logmdct);
  110030. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110031. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110032. vorbis_info_psy_global *g,
  110033. vorbis_look_psy *p,
  110034. vorbis_info_mapping0 *vi,
  110035. float **mdct);
  110036. extern void _vp_couple(int blobno,
  110037. vorbis_info_psy_global *g,
  110038. vorbis_look_psy *p,
  110039. vorbis_info_mapping0 *vi,
  110040. float **res,
  110041. float **mag_memo,
  110042. int **mag_sort,
  110043. int **ifloor,
  110044. int *nonzero,
  110045. int sliding_lowpass);
  110046. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110047. float *in,float *out,int *sortedindex);
  110048. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110049. float *magnitudes,int *sortedindex);
  110050. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110051. vorbis_look_psy *p,
  110052. vorbis_info_mapping0 *vi,
  110053. float **mags);
  110054. extern void hf_reduction(vorbis_info_psy_global *g,
  110055. vorbis_look_psy *p,
  110056. vorbis_info_mapping0 *vi,
  110057. float **mdct);
  110058. #endif
  110059. /*** End of inlined file: psy.h ***/
  110060. /*** Start of inlined file: bitrate.h ***/
  110061. #ifndef _V_BITRATE_H_
  110062. #define _V_BITRATE_H_
  110063. /*** Start of inlined file: os.h ***/
  110064. #ifndef _OS_H
  110065. #define _OS_H
  110066. /********************************************************************
  110067. * *
  110068. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110069. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110070. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110071. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110072. * *
  110073. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110074. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110075. * *
  110076. ********************************************************************
  110077. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110078. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110079. ********************************************************************/
  110080. #ifdef HAVE_CONFIG_H
  110081. #include "config.h"
  110082. #endif
  110083. #include <math.h>
  110084. /*** Start of inlined file: misc.h ***/
  110085. #ifndef _V_RANDOM_H_
  110086. #define _V_RANDOM_H_
  110087. extern int analysis_noisy;
  110088. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110089. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110090. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110091. ogg_int64_t off);
  110092. #ifdef DEBUG_MALLOC
  110093. #define _VDBG_GRAPHFILE "malloc.m"
  110094. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110095. extern void _VDBG_free(void *ptr,char *file,long line);
  110096. #ifndef MISC_C
  110097. #undef _ogg_malloc
  110098. #undef _ogg_calloc
  110099. #undef _ogg_realloc
  110100. #undef _ogg_free
  110101. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110102. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110103. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110104. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110105. #endif
  110106. #endif
  110107. #endif
  110108. /*** End of inlined file: misc.h ***/
  110109. #ifndef _V_IFDEFJAIL_H_
  110110. # define _V_IFDEFJAIL_H_
  110111. # ifdef __GNUC__
  110112. # define STIN static __inline__
  110113. # elif _WIN32
  110114. # define STIN static __inline
  110115. # else
  110116. # define STIN static
  110117. # endif
  110118. #ifdef DJGPP
  110119. # define rint(x) (floor((x)+0.5f))
  110120. #endif
  110121. #ifndef M_PI
  110122. # define M_PI (3.1415926536f)
  110123. #endif
  110124. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110125. # include <malloc.h>
  110126. # define rint(x) (floor((x)+0.5f))
  110127. # define NO_FLOAT_MATH_LIB
  110128. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110129. #endif
  110130. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110131. void *_alloca(size_t size);
  110132. # define alloca _alloca
  110133. #endif
  110134. #ifndef FAST_HYPOT
  110135. # define FAST_HYPOT hypot
  110136. #endif
  110137. #endif
  110138. #ifdef HAVE_ALLOCA_H
  110139. # include <alloca.h>
  110140. #endif
  110141. #ifdef USE_MEMORY_H
  110142. # include <memory.h>
  110143. #endif
  110144. #ifndef min
  110145. # define min(x,y) ((x)>(y)?(y):(x))
  110146. #endif
  110147. #ifndef max
  110148. # define max(x,y) ((x)<(y)?(y):(x))
  110149. #endif
  110150. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110151. # define VORBIS_FPU_CONTROL
  110152. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110153. Because of encapsulation constraints (GCC can't see inside the asm
  110154. block and so we end up doing stupid things like a store/load that
  110155. is collectively a noop), we do it this way */
  110156. /* we must set up the fpu before this works!! */
  110157. typedef ogg_int16_t vorbis_fpu_control;
  110158. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110159. ogg_int16_t ret;
  110160. ogg_int16_t temp;
  110161. __asm__ __volatile__("fnstcw %0\n\t"
  110162. "movw %0,%%dx\n\t"
  110163. "orw $62463,%%dx\n\t"
  110164. "movw %%dx,%1\n\t"
  110165. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110166. *fpu=ret;
  110167. }
  110168. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110169. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110170. }
  110171. /* assumes the FPU is in round mode! */
  110172. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110173. we get extra fst/fld to
  110174. truncate precision */
  110175. int i;
  110176. __asm__("fistl %0": "=m"(i) : "t"(f));
  110177. return(i);
  110178. }
  110179. #endif
  110180. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110181. # define VORBIS_FPU_CONTROL
  110182. typedef ogg_int16_t vorbis_fpu_control;
  110183. static __inline int vorbis_ftoi(double f){
  110184. int i;
  110185. __asm{
  110186. fld f
  110187. fistp i
  110188. }
  110189. return i;
  110190. }
  110191. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110192. }
  110193. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110194. }
  110195. #endif
  110196. #ifndef VORBIS_FPU_CONTROL
  110197. typedef int vorbis_fpu_control;
  110198. static int vorbis_ftoi(double f){
  110199. return (int)(f+.5);
  110200. }
  110201. /* We don't have special code for this compiler/arch, so do it the slow way */
  110202. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110203. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110204. #endif
  110205. #endif /* _OS_H */
  110206. /*** End of inlined file: os.h ***/
  110207. /* encode side bitrate tracking */
  110208. typedef struct bitrate_manager_state {
  110209. int managed;
  110210. long avg_reservoir;
  110211. long minmax_reservoir;
  110212. long avg_bitsper;
  110213. long min_bitsper;
  110214. long max_bitsper;
  110215. long short_per_long;
  110216. double avgfloat;
  110217. vorbis_block *vb;
  110218. int choice;
  110219. } bitrate_manager_state;
  110220. typedef struct bitrate_manager_info{
  110221. long avg_rate;
  110222. long min_rate;
  110223. long max_rate;
  110224. long reservoir_bits;
  110225. double reservoir_bias;
  110226. double slew_damp;
  110227. } bitrate_manager_info;
  110228. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110229. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110230. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110231. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110232. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110233. #endif
  110234. /*** End of inlined file: bitrate.h ***/
  110235. static int ilog(unsigned int v){
  110236. int ret=0;
  110237. while(v){
  110238. ret++;
  110239. v>>=1;
  110240. }
  110241. return(ret);
  110242. }
  110243. static int ilog2(unsigned int v){
  110244. int ret=0;
  110245. if(v)--v;
  110246. while(v){
  110247. ret++;
  110248. v>>=1;
  110249. }
  110250. return(ret);
  110251. }
  110252. typedef struct private_state {
  110253. /* local lookup storage */
  110254. envelope_lookup *ve; /* envelope lookup */
  110255. int window[2];
  110256. vorbis_look_transform **transform[2]; /* block, type */
  110257. drft_lookup fft_look[2];
  110258. int modebits;
  110259. vorbis_look_floor **flr;
  110260. vorbis_look_residue **residue;
  110261. vorbis_look_psy *psy;
  110262. vorbis_look_psy_global *psy_g_look;
  110263. /* local storage, only used on the encoding side. This way the
  110264. application does not need to worry about freeing some packets'
  110265. memory and not others'; packet storage is always tracked.
  110266. Cleared next call to a _dsp_ function */
  110267. unsigned char *header;
  110268. unsigned char *header1;
  110269. unsigned char *header2;
  110270. bitrate_manager_state bms;
  110271. ogg_int64_t sample_count;
  110272. } private_state;
  110273. /* codec_setup_info contains all the setup information specific to the
  110274. specific compression/decompression mode in progress (eg,
  110275. psychoacoustic settings, channel setup, options, codebook
  110276. etc).
  110277. *********************************************************************/
  110278. /*** Start of inlined file: highlevel.h ***/
  110279. typedef struct highlevel_byblocktype {
  110280. double tone_mask_setting;
  110281. double tone_peaklimit_setting;
  110282. double noise_bias_setting;
  110283. double noise_compand_setting;
  110284. } highlevel_byblocktype;
  110285. typedef struct highlevel_encode_setup {
  110286. void *setup;
  110287. int set_in_stone;
  110288. double base_setting;
  110289. double long_setting;
  110290. double short_setting;
  110291. double impulse_noisetune;
  110292. int managed;
  110293. long bitrate_min;
  110294. long bitrate_av;
  110295. double bitrate_av_damp;
  110296. long bitrate_max;
  110297. long bitrate_reservoir;
  110298. double bitrate_reservoir_bias;
  110299. int impulse_block_p;
  110300. int noise_normalize_p;
  110301. double stereo_point_setting;
  110302. double lowpass_kHz;
  110303. double ath_floating_dB;
  110304. double ath_absolute_dB;
  110305. double amplitude_track_dBpersec;
  110306. double trigger_setting;
  110307. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110308. } highlevel_encode_setup;
  110309. /*** End of inlined file: highlevel.h ***/
  110310. typedef struct codec_setup_info {
  110311. /* Vorbis supports only short and long blocks, but allows the
  110312. encoder to choose the sizes */
  110313. long blocksizes[2];
  110314. /* modes are the primary means of supporting on-the-fly different
  110315. blocksizes, different channel mappings (LR or M/A),
  110316. different residue backends, etc. Each mode consists of a
  110317. blocksize flag and a mapping (along with the mapping setup */
  110318. int modes;
  110319. int maps;
  110320. int floors;
  110321. int residues;
  110322. int books;
  110323. int psys; /* encode only */
  110324. vorbis_info_mode *mode_param[64];
  110325. int map_type[64];
  110326. vorbis_info_mapping *map_param[64];
  110327. int floor_type[64];
  110328. vorbis_info_floor *floor_param[64];
  110329. int residue_type[64];
  110330. vorbis_info_residue *residue_param[64];
  110331. static_codebook *book_param[256];
  110332. codebook *fullbooks;
  110333. vorbis_info_psy *psy_param[4]; /* encode only */
  110334. vorbis_info_psy_global psy_g_param;
  110335. bitrate_manager_info bi;
  110336. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110337. highly redundant structure, but
  110338. improves clarity of program flow. */
  110339. int halfrate_flag; /* painless downsample for decode */
  110340. } codec_setup_info;
  110341. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110342. extern void _vp_global_free(vorbis_look_psy_global *look);
  110343. #endif
  110344. /*** End of inlined file: codec_internal.h ***/
  110345. /*** Start of inlined file: registry.h ***/
  110346. #ifndef _V_REG_H_
  110347. #define _V_REG_H_
  110348. #define VI_TRANSFORMB 1
  110349. #define VI_WINDOWB 1
  110350. #define VI_TIMEB 1
  110351. #define VI_FLOORB 2
  110352. #define VI_RESB 3
  110353. #define VI_MAPB 1
  110354. extern vorbis_func_floor *_floor_P[];
  110355. extern vorbis_func_residue *_residue_P[];
  110356. extern vorbis_func_mapping *_mapping_P[];
  110357. #endif
  110358. /*** End of inlined file: registry.h ***/
  110359. /*** Start of inlined file: scales.h ***/
  110360. #ifndef _V_SCALES_H_
  110361. #define _V_SCALES_H_
  110362. #include <math.h>
  110363. /* 20log10(x) */
  110364. #define VORBIS_IEEE_FLOAT32 1
  110365. #ifdef VORBIS_IEEE_FLOAT32
  110366. static float unitnorm(float x){
  110367. union {
  110368. ogg_uint32_t i;
  110369. float f;
  110370. } ix;
  110371. ix.f = x;
  110372. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110373. return ix.f;
  110374. }
  110375. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110376. static float todB(const float *x){
  110377. union {
  110378. ogg_uint32_t i;
  110379. float f;
  110380. } ix;
  110381. ix.f = *x;
  110382. ix.i = ix.i&0x7fffffff;
  110383. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110384. }
  110385. #define todB_nn(x) todB(x)
  110386. #else
  110387. static float unitnorm(float x){
  110388. if(x<0)return(-1.f);
  110389. return(1.f);
  110390. }
  110391. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110392. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110393. #endif
  110394. #define fromdB(x) (exp((x)*.11512925f))
  110395. /* The bark scale equations are approximations, since the original
  110396. table was somewhat hand rolled. The below are chosen to have the
  110397. best possible fit to the rolled tables, thus their somewhat odd
  110398. appearance (these are more accurate and over a longer range than
  110399. the oft-quoted bark equations found in the texts I have). The
  110400. approximations are valid from 0 - 30kHz (nyquist) or so.
  110401. all f in Hz, z in Bark */
  110402. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110403. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110404. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110405. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110406. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110407. 0.0 */
  110408. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110409. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110410. #endif
  110411. /*** End of inlined file: scales.h ***/
  110412. int analysis_noisy=1;
  110413. /* decides between modes, dispatches to the appropriate mapping. */
  110414. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110415. int ret,i;
  110416. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110417. vb->glue_bits=0;
  110418. vb->time_bits=0;
  110419. vb->floor_bits=0;
  110420. vb->res_bits=0;
  110421. /* first things first. Make sure encode is ready */
  110422. for(i=0;i<PACKETBLOBS;i++)
  110423. oggpack_reset(vbi->packetblob[i]);
  110424. /* we only have one mapping type (0), and we let the mapping code
  110425. itself figure out what soft mode to use. This allows easier
  110426. bitrate management */
  110427. if((ret=_mapping_P[0]->forward(vb)))
  110428. return(ret);
  110429. if(op){
  110430. if(vorbis_bitrate_managed(vb))
  110431. /* The app is using a bitmanaged mode... but not using the
  110432. bitrate management interface. */
  110433. return(OV_EINVAL);
  110434. op->packet=oggpack_get_buffer(&vb->opb);
  110435. op->bytes=oggpack_bytes(&vb->opb);
  110436. op->b_o_s=0;
  110437. op->e_o_s=vb->eofflag;
  110438. op->granulepos=vb->granulepos;
  110439. op->packetno=vb->sequence; /* for sake of completeness */
  110440. }
  110441. return(0);
  110442. }
  110443. /* there was no great place to put this.... */
  110444. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110445. int j;
  110446. FILE *of;
  110447. char buffer[80];
  110448. /* if(i==5870){*/
  110449. sprintf(buffer,"%s_%d.m",base,i);
  110450. of=fopen(buffer,"w");
  110451. if(!of)perror("failed to open data dump file");
  110452. for(j=0;j<n;j++){
  110453. if(bark){
  110454. float b=toBARK((4000.f*j/n)+.25);
  110455. fprintf(of,"%f ",b);
  110456. }else
  110457. if(off!=0)
  110458. fprintf(of,"%f ",(double)(j+off)/8000.);
  110459. else
  110460. fprintf(of,"%f ",(double)j);
  110461. if(dB){
  110462. float val;
  110463. if(v[j]==0.)
  110464. val=-140.;
  110465. else
  110466. val=todB(v+j);
  110467. fprintf(of,"%f\n",val);
  110468. }else{
  110469. fprintf(of,"%f\n",v[j]);
  110470. }
  110471. }
  110472. fclose(of);
  110473. /* } */
  110474. }
  110475. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110476. ogg_int64_t off){
  110477. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110478. }
  110479. #endif
  110480. /*** End of inlined file: analysis.c ***/
  110481. /*** Start of inlined file: bitrate.c ***/
  110482. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110483. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110484. // tasks..
  110485. #if JUCE_MSVC
  110486. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110487. #endif
  110488. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110489. #if JUCE_USE_OGGVORBIS
  110490. #include <stdlib.h>
  110491. #include <string.h>
  110492. #include <math.h>
  110493. /* compute bitrate tracking setup */
  110494. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110495. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110496. bitrate_manager_info *bi=&ci->bi;
  110497. memset(bm,0,sizeof(*bm));
  110498. if(bi && (bi->reservoir_bits>0)){
  110499. long ratesamples=vi->rate;
  110500. int halfsamples=ci->blocksizes[0]>>1;
  110501. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110502. bm->managed=1;
  110503. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110504. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110505. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110506. bm->avgfloat=PACKETBLOBS/2;
  110507. /* not a necessary fix, but one that leads to a more balanced
  110508. typical initialization */
  110509. {
  110510. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110511. bm->minmax_reservoir=desired_fill;
  110512. bm->avg_reservoir=desired_fill;
  110513. }
  110514. }
  110515. }
  110516. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110517. memset(bm,0,sizeof(*bm));
  110518. return;
  110519. }
  110520. int vorbis_bitrate_managed(vorbis_block *vb){
  110521. vorbis_dsp_state *vd=vb->vd;
  110522. private_state *b=(private_state*)vd->backend_state;
  110523. bitrate_manager_state *bm=&b->bms;
  110524. if(bm && bm->managed)return(1);
  110525. return(0);
  110526. }
  110527. /* finish taking in the block we just processed */
  110528. int vorbis_bitrate_addblock(vorbis_block *vb){
  110529. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110530. vorbis_dsp_state *vd=vb->vd;
  110531. private_state *b=(private_state*)vd->backend_state;
  110532. bitrate_manager_state *bm=&b->bms;
  110533. vorbis_info *vi=vd->vi;
  110534. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110535. bitrate_manager_info *bi=&ci->bi;
  110536. int choice=rint(bm->avgfloat);
  110537. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110538. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110539. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110540. int samples=ci->blocksizes[vb->W]>>1;
  110541. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110542. if(!bm->managed){
  110543. /* not a bitrate managed stream, but for API simplicity, we'll
  110544. buffer the packet to keep the code path clean */
  110545. if(bm->vb)return(-1); /* one has been submitted without
  110546. being claimed */
  110547. bm->vb=vb;
  110548. return(0);
  110549. }
  110550. bm->vb=vb;
  110551. /* look ahead for avg floater */
  110552. if(bm->avg_bitsper>0){
  110553. double slew=0.;
  110554. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110555. double slewlimit= 15./bi->slew_damp;
  110556. /* choosing a new floater:
  110557. if we're over target, we slew down
  110558. if we're under target, we slew up
  110559. choose slew as follows: look through packetblobs of this frame
  110560. and set slew as the first in the appropriate direction that
  110561. gives us the slew we want. This may mean no slew if delta is
  110562. already favorable.
  110563. Then limit slew to slew max */
  110564. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110565. while(choice>0 && this_bits>avg_target_bits &&
  110566. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110567. choice--;
  110568. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110569. }
  110570. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110571. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110572. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110573. choice++;
  110574. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110575. }
  110576. }
  110577. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110578. if(slew<-slewlimit)slew=-slewlimit;
  110579. if(slew>slewlimit)slew=slewlimit;
  110580. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110581. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110582. }
  110583. /* enforce min(if used) on the current floater (if used) */
  110584. if(bm->min_bitsper>0){
  110585. /* do we need to force the bitrate up? */
  110586. if(this_bits<min_target_bits){
  110587. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110588. choice++;
  110589. if(choice>=PACKETBLOBS)break;
  110590. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110591. }
  110592. }
  110593. }
  110594. /* enforce max (if used) on the current floater (if used) */
  110595. if(bm->max_bitsper>0){
  110596. /* do we need to force the bitrate down? */
  110597. if(this_bits>max_target_bits){
  110598. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110599. choice--;
  110600. if(choice<0)break;
  110601. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110602. }
  110603. }
  110604. }
  110605. /* Choice of packetblobs now made based on floater, and min/max
  110606. requirements. Now boundary check extreme choices */
  110607. if(choice<0){
  110608. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110609. frame will need to be truncated */
  110610. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110611. bm->choice=choice=0;
  110612. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110613. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110614. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110615. }
  110616. }else{
  110617. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110618. if(choice>=PACKETBLOBS)
  110619. choice=PACKETBLOBS-1;
  110620. bm->choice=choice;
  110621. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110622. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110623. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110624. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110625. }
  110626. /* now we have the final packet and the final packet size. Update statistics */
  110627. /* min and max reservoir */
  110628. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110629. if(max_target_bits>0 && this_bits>max_target_bits){
  110630. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110631. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110632. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110633. }else{
  110634. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110635. if(bm->minmax_reservoir>desired_fill){
  110636. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110637. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110638. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110639. }else{
  110640. bm->minmax_reservoir=desired_fill;
  110641. }
  110642. }else{
  110643. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110644. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110645. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110646. }else{
  110647. bm->minmax_reservoir=desired_fill;
  110648. }
  110649. }
  110650. }
  110651. }
  110652. /* avg reservoir */
  110653. if(bm->avg_bitsper>0){
  110654. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110655. bm->avg_reservoir+=this_bits-avg_target_bits;
  110656. }
  110657. return(0);
  110658. }
  110659. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110660. private_state *b=(private_state*)vd->backend_state;
  110661. bitrate_manager_state *bm=&b->bms;
  110662. vorbis_block *vb=bm->vb;
  110663. int choice=PACKETBLOBS/2;
  110664. if(!vb)return 0;
  110665. if(op){
  110666. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110667. if(vorbis_bitrate_managed(vb))
  110668. choice=bm->choice;
  110669. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110670. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110671. op->b_o_s=0;
  110672. op->e_o_s=vb->eofflag;
  110673. op->granulepos=vb->granulepos;
  110674. op->packetno=vb->sequence; /* for sake of completeness */
  110675. }
  110676. bm->vb=0;
  110677. return(1);
  110678. }
  110679. #endif
  110680. /*** End of inlined file: bitrate.c ***/
  110681. /*** Start of inlined file: block.c ***/
  110682. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110683. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110684. // tasks..
  110685. #if JUCE_MSVC
  110686. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110687. #endif
  110688. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110689. #if JUCE_USE_OGGVORBIS
  110690. #include <stdio.h>
  110691. #include <stdlib.h>
  110692. #include <string.h>
  110693. /*** Start of inlined file: window.h ***/
  110694. #ifndef _V_WINDOW_
  110695. #define _V_WINDOW_
  110696. extern float *_vorbis_window_get(int n);
  110697. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110698. int lW,int W,int nW);
  110699. #endif
  110700. /*** End of inlined file: window.h ***/
  110701. /*** Start of inlined file: lpc.h ***/
  110702. #ifndef _V_LPC_H_
  110703. #define _V_LPC_H_
  110704. /* simple linear scale LPC code */
  110705. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110706. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110707. float *data,long n);
  110708. #endif
  110709. /*** End of inlined file: lpc.h ***/
  110710. /* pcm accumulator examples (not exhaustive):
  110711. <-------------- lW ---------------->
  110712. <--------------- W ---------------->
  110713. : .....|..... _______________ |
  110714. : .''' | '''_--- | |\ |
  110715. :.....''' |_____--- '''......| | \_______|
  110716. :.................|__________________|_______|__|______|
  110717. |<------ Sl ------>| > Sr < |endW
  110718. |beginSl |endSl | |endSr
  110719. |beginW |endlW |beginSr
  110720. |< lW >|
  110721. <--------------- W ---------------->
  110722. | | .. ______________ |
  110723. | | ' `/ | ---_ |
  110724. |___.'___/`. | ---_____|
  110725. |_______|__|_______|_________________|
  110726. | >|Sl|< |<------ Sr ----->|endW
  110727. | | |endSl |beginSr |endSr
  110728. |beginW | |endlW
  110729. mult[0] |beginSl mult[n]
  110730. <-------------- lW ----------------->
  110731. |<--W-->|
  110732. : .............. ___ | |
  110733. : .''' |`/ \ | |
  110734. :.....''' |/`....\|...|
  110735. :.........................|___|___|___|
  110736. |Sl |Sr |endW
  110737. | | |endSr
  110738. | |beginSr
  110739. | |endSl
  110740. |beginSl
  110741. |beginW
  110742. */
  110743. /* block abstraction setup *********************************************/
  110744. #ifndef WORD_ALIGN
  110745. #define WORD_ALIGN 8
  110746. #endif
  110747. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110748. int i;
  110749. memset(vb,0,sizeof(*vb));
  110750. vb->vd=v;
  110751. vb->localalloc=0;
  110752. vb->localstore=NULL;
  110753. if(v->analysisp){
  110754. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110755. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110756. vbi->ampmax=-9999;
  110757. for(i=0;i<PACKETBLOBS;i++){
  110758. if(i==PACKETBLOBS/2){
  110759. vbi->packetblob[i]=&vb->opb;
  110760. }else{
  110761. vbi->packetblob[i]=
  110762. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110763. }
  110764. oggpack_writeinit(vbi->packetblob[i]);
  110765. }
  110766. }
  110767. return(0);
  110768. }
  110769. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110770. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110771. if(bytes+vb->localtop>vb->localalloc){
  110772. /* can't just _ogg_realloc... there are outstanding pointers */
  110773. if(vb->localstore){
  110774. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110775. vb->totaluse+=vb->localtop;
  110776. link->next=vb->reap;
  110777. link->ptr=vb->localstore;
  110778. vb->reap=link;
  110779. }
  110780. /* highly conservative */
  110781. vb->localalloc=bytes;
  110782. vb->localstore=_ogg_malloc(vb->localalloc);
  110783. vb->localtop=0;
  110784. }
  110785. {
  110786. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110787. vb->localtop+=bytes;
  110788. return ret;
  110789. }
  110790. }
  110791. /* reap the chain, pull the ripcord */
  110792. void _vorbis_block_ripcord(vorbis_block *vb){
  110793. /* reap the chain */
  110794. struct alloc_chain *reap=vb->reap;
  110795. while(reap){
  110796. struct alloc_chain *next=reap->next;
  110797. _ogg_free(reap->ptr);
  110798. memset(reap,0,sizeof(*reap));
  110799. _ogg_free(reap);
  110800. reap=next;
  110801. }
  110802. /* consolidate storage */
  110803. if(vb->totaluse){
  110804. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110805. vb->localalloc+=vb->totaluse;
  110806. vb->totaluse=0;
  110807. }
  110808. /* pull the ripcord */
  110809. vb->localtop=0;
  110810. vb->reap=NULL;
  110811. }
  110812. int vorbis_block_clear(vorbis_block *vb){
  110813. int i;
  110814. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110815. _vorbis_block_ripcord(vb);
  110816. if(vb->localstore)_ogg_free(vb->localstore);
  110817. if(vbi){
  110818. for(i=0;i<PACKETBLOBS;i++){
  110819. oggpack_writeclear(vbi->packetblob[i]);
  110820. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110821. }
  110822. _ogg_free(vbi);
  110823. }
  110824. memset(vb,0,sizeof(*vb));
  110825. return(0);
  110826. }
  110827. /* Analysis side code, but directly related to blocking. Thus it's
  110828. here and not in analysis.c (which is for analysis transforms only).
  110829. The init is here because some of it is shared */
  110830. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110831. int i;
  110832. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110833. private_state *b=NULL;
  110834. int hs;
  110835. if(ci==NULL) return 1;
  110836. hs=ci->halfrate_flag;
  110837. memset(v,0,sizeof(*v));
  110838. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110839. v->vi=vi;
  110840. b->modebits=ilog2(ci->modes);
  110841. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110842. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110843. /* MDCT is tranform 0 */
  110844. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110845. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110846. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110847. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110848. /* Vorbis I uses only window type 0 */
  110849. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110850. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110851. if(encp){ /* encode/decode differ here */
  110852. /* analysis always needs an fft */
  110853. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110854. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110855. /* finish the codebooks */
  110856. if(!ci->fullbooks){
  110857. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110858. for(i=0;i<ci->books;i++)
  110859. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110860. }
  110861. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110862. for(i=0;i<ci->psys;i++){
  110863. _vp_psy_init(b->psy+i,
  110864. ci->psy_param[i],
  110865. &ci->psy_g_param,
  110866. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110867. vi->rate);
  110868. }
  110869. v->analysisp=1;
  110870. }else{
  110871. /* finish the codebooks */
  110872. if(!ci->fullbooks){
  110873. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110874. for(i=0;i<ci->books;i++){
  110875. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110876. /* decode codebooks are now standalone after init */
  110877. vorbis_staticbook_destroy(ci->book_param[i]);
  110878. ci->book_param[i]=NULL;
  110879. }
  110880. }
  110881. }
  110882. /* initialize the storage vectors. blocksize[1] is small for encode,
  110883. but the correct size for decode */
  110884. v->pcm_storage=ci->blocksizes[1];
  110885. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110886. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110887. {
  110888. int i;
  110889. for(i=0;i<vi->channels;i++)
  110890. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110891. }
  110892. /* all 1 (large block) or 0 (small block) */
  110893. /* explicitly set for the sake of clarity */
  110894. v->lW=0; /* previous window size */
  110895. v->W=0; /* current window size */
  110896. /* all vector indexes */
  110897. v->centerW=ci->blocksizes[1]/2;
  110898. v->pcm_current=v->centerW;
  110899. /* initialize all the backend lookups */
  110900. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110901. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110902. for(i=0;i<ci->floors;i++)
  110903. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110904. look(v,ci->floor_param[i]);
  110905. for(i=0;i<ci->residues;i++)
  110906. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110907. look(v,ci->residue_param[i]);
  110908. return 0;
  110909. }
  110910. /* arbitrary settings and spec-mandated numbers get filled in here */
  110911. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110912. private_state *b=NULL;
  110913. if(_vds_shared_init(v,vi,1))return 1;
  110914. b=(private_state*)v->backend_state;
  110915. b->psy_g_look=_vp_global_look(vi);
  110916. /* Initialize the envelope state storage */
  110917. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110918. _ve_envelope_init(b->ve,vi);
  110919. vorbis_bitrate_init(vi,&b->bms);
  110920. /* compressed audio packets start after the headers
  110921. with sequence number 3 */
  110922. v->sequence=3;
  110923. return(0);
  110924. }
  110925. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110926. int i;
  110927. if(v){
  110928. vorbis_info *vi=v->vi;
  110929. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110930. private_state *b=(private_state*)v->backend_state;
  110931. if(b){
  110932. if(b->ve){
  110933. _ve_envelope_clear(b->ve);
  110934. _ogg_free(b->ve);
  110935. }
  110936. if(b->transform[0]){
  110937. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110938. _ogg_free(b->transform[0][0]);
  110939. _ogg_free(b->transform[0]);
  110940. }
  110941. if(b->transform[1]){
  110942. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110943. _ogg_free(b->transform[1][0]);
  110944. _ogg_free(b->transform[1]);
  110945. }
  110946. if(b->flr){
  110947. for(i=0;i<ci->floors;i++)
  110948. _floor_P[ci->floor_type[i]]->
  110949. free_look(b->flr[i]);
  110950. _ogg_free(b->flr);
  110951. }
  110952. if(b->residue){
  110953. for(i=0;i<ci->residues;i++)
  110954. _residue_P[ci->residue_type[i]]->
  110955. free_look(b->residue[i]);
  110956. _ogg_free(b->residue);
  110957. }
  110958. if(b->psy){
  110959. for(i=0;i<ci->psys;i++)
  110960. _vp_psy_clear(b->psy+i);
  110961. _ogg_free(b->psy);
  110962. }
  110963. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110964. vorbis_bitrate_clear(&b->bms);
  110965. drft_clear(&b->fft_look[0]);
  110966. drft_clear(&b->fft_look[1]);
  110967. }
  110968. if(v->pcm){
  110969. for(i=0;i<vi->channels;i++)
  110970. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110971. _ogg_free(v->pcm);
  110972. if(v->pcmret)_ogg_free(v->pcmret);
  110973. }
  110974. if(b){
  110975. /* free header, header1, header2 */
  110976. if(b->header)_ogg_free(b->header);
  110977. if(b->header1)_ogg_free(b->header1);
  110978. if(b->header2)_ogg_free(b->header2);
  110979. _ogg_free(b);
  110980. }
  110981. memset(v,0,sizeof(*v));
  110982. }
  110983. }
  110984. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110985. int i;
  110986. vorbis_info *vi=v->vi;
  110987. private_state *b=(private_state*)v->backend_state;
  110988. /* free header, header1, header2 */
  110989. if(b->header)_ogg_free(b->header);b->header=NULL;
  110990. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110991. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110992. /* Do we have enough storage space for the requested buffer? If not,
  110993. expand the PCM (and envelope) storage */
  110994. if(v->pcm_current+vals>=v->pcm_storage){
  110995. v->pcm_storage=v->pcm_current+vals*2;
  110996. for(i=0;i<vi->channels;i++){
  110997. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110998. }
  110999. }
  111000. for(i=0;i<vi->channels;i++)
  111001. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111002. return(v->pcmret);
  111003. }
  111004. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111005. int i;
  111006. int order=32;
  111007. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111008. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111009. long j;
  111010. v->preextrapolate=1;
  111011. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111012. for(i=0;i<v->vi->channels;i++){
  111013. /* need to run the extrapolation in reverse! */
  111014. for(j=0;j<v->pcm_current;j++)
  111015. work[j]=v->pcm[i][v->pcm_current-j-1];
  111016. /* prime as above */
  111017. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111018. /* run the predictor filter */
  111019. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111020. order,
  111021. work+v->pcm_current-v->centerW,
  111022. v->centerW);
  111023. for(j=0;j<v->pcm_current;j++)
  111024. v->pcm[i][v->pcm_current-j-1]=work[j];
  111025. }
  111026. }
  111027. }
  111028. /* call with val<=0 to set eof */
  111029. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111030. vorbis_info *vi=v->vi;
  111031. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111032. if(vals<=0){
  111033. int order=32;
  111034. int i;
  111035. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111036. /* if it wasn't done earlier (very short sample) */
  111037. if(!v->preextrapolate)
  111038. _preextrapolate_helper(v);
  111039. /* We're encoding the end of the stream. Just make sure we have
  111040. [at least] a few full blocks of zeroes at the end. */
  111041. /* actually, we don't want zeroes; that could drop a large
  111042. amplitude off a cliff, creating spread spectrum noise that will
  111043. suck to encode. Extrapolate for the sake of cleanliness. */
  111044. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111045. v->eofflag=v->pcm_current;
  111046. v->pcm_current+=ci->blocksizes[1]*3;
  111047. for(i=0;i<vi->channels;i++){
  111048. if(v->eofflag>order*2){
  111049. /* extrapolate with LPC to fill in */
  111050. long n;
  111051. /* make a predictor filter */
  111052. n=v->eofflag;
  111053. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111054. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111055. /* run the predictor filter */
  111056. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111057. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111058. }else{
  111059. /* not enough data to extrapolate (unlikely to happen due to
  111060. guarding the overlap, but bulletproof in case that
  111061. assumtion goes away). zeroes will do. */
  111062. memset(v->pcm[i]+v->eofflag,0,
  111063. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111064. }
  111065. }
  111066. }else{
  111067. if(v->pcm_current+vals>v->pcm_storage)
  111068. return(OV_EINVAL);
  111069. v->pcm_current+=vals;
  111070. /* we may want to reverse extrapolate the beginning of a stream
  111071. too... in case we're beginning on a cliff! */
  111072. /* clumsy, but simple. It only runs once, so simple is good. */
  111073. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111074. _preextrapolate_helper(v);
  111075. }
  111076. return(0);
  111077. }
  111078. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111079. the next block on which to continue analysis */
  111080. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111081. int i;
  111082. vorbis_info *vi=v->vi;
  111083. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111084. private_state *b=(private_state*)v->backend_state;
  111085. vorbis_look_psy_global *g=b->psy_g_look;
  111086. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111087. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111088. /* check to see if we're started... */
  111089. if(!v->preextrapolate)return(0);
  111090. /* check to see if we're done... */
  111091. if(v->eofflag==-1)return(0);
  111092. /* By our invariant, we have lW, W and centerW set. Search for
  111093. the next boundary so we can determine nW (the next window size)
  111094. which lets us compute the shape of the current block's window */
  111095. /* we do an envelope search even on a single blocksize; we may still
  111096. be throwing more bits at impulses, and envelope search handles
  111097. marking impulses too. */
  111098. {
  111099. long bp=_ve_envelope_search(v);
  111100. if(bp==-1){
  111101. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111102. full long block */
  111103. v->nW=0;
  111104. }else{
  111105. if(ci->blocksizes[0]==ci->blocksizes[1])
  111106. v->nW=0;
  111107. else
  111108. v->nW=bp;
  111109. }
  111110. }
  111111. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111112. {
  111113. /* center of next block + next block maximum right side. */
  111114. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111115. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111116. although this check is
  111117. less strict that the
  111118. _ve_envelope_search,
  111119. the search is not run
  111120. if we only use one
  111121. block size */
  111122. }
  111123. /* fill in the block. Note that for a short window, lW and nW are *short*
  111124. regardless of actual settings in the stream */
  111125. _vorbis_block_ripcord(vb);
  111126. vb->lW=v->lW;
  111127. vb->W=v->W;
  111128. vb->nW=v->nW;
  111129. if(v->W){
  111130. if(!v->lW || !v->nW){
  111131. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111132. /*fprintf(stderr,"-");*/
  111133. }else{
  111134. vbi->blocktype=BLOCKTYPE_LONG;
  111135. /*fprintf(stderr,"_");*/
  111136. }
  111137. }else{
  111138. if(_ve_envelope_mark(v)){
  111139. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111140. /*fprintf(stderr,"|");*/
  111141. }else{
  111142. vbi->blocktype=BLOCKTYPE_PADDING;
  111143. /*fprintf(stderr,".");*/
  111144. }
  111145. }
  111146. vb->vd=v;
  111147. vb->sequence=v->sequence++;
  111148. vb->granulepos=v->granulepos;
  111149. vb->pcmend=ci->blocksizes[v->W];
  111150. /* copy the vectors; this uses the local storage in vb */
  111151. /* this tracks 'strongest peak' for later psychoacoustics */
  111152. /* moved to the global psy state; clean this mess up */
  111153. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111154. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111155. vbi->ampmax=g->ampmax;
  111156. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111157. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111158. for(i=0;i<vi->channels;i++){
  111159. vbi->pcmdelay[i]=
  111160. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111161. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111162. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111163. /* before we added the delay
  111164. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111165. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111166. */
  111167. }
  111168. /* handle eof detection: eof==0 means that we've not yet received EOF
  111169. eof>0 marks the last 'real' sample in pcm[]
  111170. eof<0 'no more to do'; doesn't get here */
  111171. if(v->eofflag){
  111172. if(v->centerW>=v->eofflag){
  111173. v->eofflag=-1;
  111174. vb->eofflag=1;
  111175. return(1);
  111176. }
  111177. }
  111178. /* advance storage vectors and clean up */
  111179. {
  111180. int new_centerNext=ci->blocksizes[1]/2;
  111181. int movementW=centerNext-new_centerNext;
  111182. if(movementW>0){
  111183. _ve_envelope_shift(b->ve,movementW);
  111184. v->pcm_current-=movementW;
  111185. for(i=0;i<vi->channels;i++)
  111186. memmove(v->pcm[i],v->pcm[i]+movementW,
  111187. v->pcm_current*sizeof(*v->pcm[i]));
  111188. v->lW=v->W;
  111189. v->W=v->nW;
  111190. v->centerW=new_centerNext;
  111191. if(v->eofflag){
  111192. v->eofflag-=movementW;
  111193. if(v->eofflag<=0)v->eofflag=-1;
  111194. /* do not add padding to end of stream! */
  111195. if(v->centerW>=v->eofflag){
  111196. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111197. }else{
  111198. v->granulepos+=movementW;
  111199. }
  111200. }else{
  111201. v->granulepos+=movementW;
  111202. }
  111203. }
  111204. }
  111205. /* done */
  111206. return(1);
  111207. }
  111208. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111209. vorbis_info *vi=v->vi;
  111210. codec_setup_info *ci;
  111211. int hs;
  111212. if(!v->backend_state)return -1;
  111213. if(!vi)return -1;
  111214. ci=(codec_setup_info*) vi->codec_setup;
  111215. if(!ci)return -1;
  111216. hs=ci->halfrate_flag;
  111217. v->centerW=ci->blocksizes[1]>>(hs+1);
  111218. v->pcm_current=v->centerW>>hs;
  111219. v->pcm_returned=-1;
  111220. v->granulepos=-1;
  111221. v->sequence=-1;
  111222. v->eofflag=0;
  111223. ((private_state *)(v->backend_state))->sample_count=-1;
  111224. return(0);
  111225. }
  111226. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111227. if(_vds_shared_init(v,vi,0)) return 1;
  111228. vorbis_synthesis_restart(v);
  111229. return 0;
  111230. }
  111231. /* Unlike in analysis, the window is only partially applied for each
  111232. block. The time domain envelope is not yet handled at the point of
  111233. calling (as it relies on the previous block). */
  111234. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111235. vorbis_info *vi=v->vi;
  111236. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111237. private_state *b=(private_state*)v->backend_state;
  111238. int hs=ci->halfrate_flag;
  111239. int i,j;
  111240. if(!vb)return(OV_EINVAL);
  111241. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111242. v->lW=v->W;
  111243. v->W=vb->W;
  111244. v->nW=-1;
  111245. if((v->sequence==-1)||
  111246. (v->sequence+1 != vb->sequence)){
  111247. v->granulepos=-1; /* out of sequence; lose count */
  111248. b->sample_count=-1;
  111249. }
  111250. v->sequence=vb->sequence;
  111251. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111252. was called on block */
  111253. int n=ci->blocksizes[v->W]>>(hs+1);
  111254. int n0=ci->blocksizes[0]>>(hs+1);
  111255. int n1=ci->blocksizes[1]>>(hs+1);
  111256. int thisCenter;
  111257. int prevCenter;
  111258. v->glue_bits+=vb->glue_bits;
  111259. v->time_bits+=vb->time_bits;
  111260. v->floor_bits+=vb->floor_bits;
  111261. v->res_bits+=vb->res_bits;
  111262. if(v->centerW){
  111263. thisCenter=n1;
  111264. prevCenter=0;
  111265. }else{
  111266. thisCenter=0;
  111267. prevCenter=n1;
  111268. }
  111269. /* v->pcm is now used like a two-stage double buffer. We don't want
  111270. to have to constantly shift *or* adjust memory usage. Don't
  111271. accept a new block until the old is shifted out */
  111272. for(j=0;j<vi->channels;j++){
  111273. /* the overlap/add section */
  111274. if(v->lW){
  111275. if(v->W){
  111276. /* large/large */
  111277. float *w=_vorbis_window_get(b->window[1]-hs);
  111278. float *pcm=v->pcm[j]+prevCenter;
  111279. float *p=vb->pcm[j];
  111280. for(i=0;i<n1;i++)
  111281. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111282. }else{
  111283. /* large/small */
  111284. float *w=_vorbis_window_get(b->window[0]-hs);
  111285. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111286. float *p=vb->pcm[j];
  111287. for(i=0;i<n0;i++)
  111288. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111289. }
  111290. }else{
  111291. if(v->W){
  111292. /* small/large */
  111293. float *w=_vorbis_window_get(b->window[0]-hs);
  111294. float *pcm=v->pcm[j]+prevCenter;
  111295. float *p=vb->pcm[j]+n1/2-n0/2;
  111296. for(i=0;i<n0;i++)
  111297. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111298. for(;i<n1/2+n0/2;i++)
  111299. pcm[i]=p[i];
  111300. }else{
  111301. /* small/small */
  111302. float *w=_vorbis_window_get(b->window[0]-hs);
  111303. float *pcm=v->pcm[j]+prevCenter;
  111304. float *p=vb->pcm[j];
  111305. for(i=0;i<n0;i++)
  111306. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111307. }
  111308. }
  111309. /* the copy section */
  111310. {
  111311. float *pcm=v->pcm[j]+thisCenter;
  111312. float *p=vb->pcm[j]+n;
  111313. for(i=0;i<n;i++)
  111314. pcm[i]=p[i];
  111315. }
  111316. }
  111317. if(v->centerW)
  111318. v->centerW=0;
  111319. else
  111320. v->centerW=n1;
  111321. /* deal with initial packet state; we do this using the explicit
  111322. pcm_returned==-1 flag otherwise we're sensitive to first block
  111323. being short or long */
  111324. if(v->pcm_returned==-1){
  111325. v->pcm_returned=thisCenter;
  111326. v->pcm_current=thisCenter;
  111327. }else{
  111328. v->pcm_returned=prevCenter;
  111329. v->pcm_current=prevCenter+
  111330. ((ci->blocksizes[v->lW]/4+
  111331. ci->blocksizes[v->W]/4)>>hs);
  111332. }
  111333. }
  111334. /* track the frame number... This is for convenience, but also
  111335. making sure our last packet doesn't end with added padding. If
  111336. the last packet is partial, the number of samples we'll have to
  111337. return will be past the vb->granulepos.
  111338. This is not foolproof! It will be confused if we begin
  111339. decoding at the last page after a seek or hole. In that case,
  111340. we don't have a starting point to judge where the last frame
  111341. is. For this reason, vorbisfile will always try to make sure
  111342. it reads the last two marked pages in proper sequence */
  111343. if(b->sample_count==-1){
  111344. b->sample_count=0;
  111345. }else{
  111346. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111347. }
  111348. if(v->granulepos==-1){
  111349. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111350. v->granulepos=vb->granulepos;
  111351. /* is this a short page? */
  111352. if(b->sample_count>v->granulepos){
  111353. /* corner case; if this is both the first and last audio page,
  111354. then spec says the end is cut, not beginning */
  111355. if(vb->eofflag){
  111356. /* trim the end */
  111357. /* no preceeding granulepos; assume we started at zero (we'd
  111358. have to in a short single-page stream) */
  111359. /* granulepos could be -1 due to a seek, but that would result
  111360. in a long count, not short count */
  111361. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111362. }else{
  111363. /* trim the beginning */
  111364. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111365. if(v->pcm_returned>v->pcm_current)
  111366. v->pcm_returned=v->pcm_current;
  111367. }
  111368. }
  111369. }
  111370. }else{
  111371. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111372. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111373. if(v->granulepos>vb->granulepos){
  111374. long extra=v->granulepos-vb->granulepos;
  111375. if(extra)
  111376. if(vb->eofflag){
  111377. /* partial last frame. Strip the extra samples off */
  111378. v->pcm_current-=extra>>hs;
  111379. } /* else {Shouldn't happen *unless* the bitstream is out of
  111380. spec. Either way, believe the bitstream } */
  111381. } /* else {Shouldn't happen *unless* the bitstream is out of
  111382. spec. Either way, believe the bitstream } */
  111383. v->granulepos=vb->granulepos;
  111384. }
  111385. }
  111386. /* Update, cleanup */
  111387. if(vb->eofflag)v->eofflag=1;
  111388. return(0);
  111389. }
  111390. /* pcm==NULL indicates we just want the pending samples, no more */
  111391. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111392. vorbis_info *vi=v->vi;
  111393. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111394. if(pcm){
  111395. int i;
  111396. for(i=0;i<vi->channels;i++)
  111397. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111398. *pcm=v->pcmret;
  111399. }
  111400. return(v->pcm_current-v->pcm_returned);
  111401. }
  111402. return(0);
  111403. }
  111404. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111405. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111406. v->pcm_returned+=n;
  111407. return(0);
  111408. }
  111409. /* intended for use with a specific vorbisfile feature; we want access
  111410. to the [usually synthetic/postextrapolated] buffer and lapping at
  111411. the end of a decode cycle, specifically, a half-short-block worth.
  111412. This funtion works like pcmout above, except it will also expose
  111413. this implicit buffer data not normally decoded. */
  111414. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111415. vorbis_info *vi=v->vi;
  111416. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111417. int hs=ci->halfrate_flag;
  111418. int n=ci->blocksizes[v->W]>>(hs+1);
  111419. int n0=ci->blocksizes[0]>>(hs+1);
  111420. int n1=ci->blocksizes[1]>>(hs+1);
  111421. int i,j;
  111422. if(v->pcm_returned<0)return 0;
  111423. /* our returned data ends at pcm_returned; because the synthesis pcm
  111424. buffer is a two-fragment ring, that means our data block may be
  111425. fragmented by buffering, wrapping or a short block not filling
  111426. out a buffer. To simplify things, we unfragment if it's at all
  111427. possibly needed. Otherwise, we'd need to call lapout more than
  111428. once as well as hold additional dsp state. Opt for
  111429. simplicity. */
  111430. /* centerW was advanced by blockin; it would be the center of the
  111431. *next* block */
  111432. if(v->centerW==n1){
  111433. /* the data buffer wraps; swap the halves */
  111434. /* slow, sure, small */
  111435. for(j=0;j<vi->channels;j++){
  111436. float *p=v->pcm[j];
  111437. for(i=0;i<n1;i++){
  111438. float temp=p[i];
  111439. p[i]=p[i+n1];
  111440. p[i+n1]=temp;
  111441. }
  111442. }
  111443. v->pcm_current-=n1;
  111444. v->pcm_returned-=n1;
  111445. v->centerW=0;
  111446. }
  111447. /* solidify buffer into contiguous space */
  111448. if((v->lW^v->W)==1){
  111449. /* long/short or short/long */
  111450. for(j=0;j<vi->channels;j++){
  111451. float *s=v->pcm[j];
  111452. float *d=v->pcm[j]+(n1-n0)/2;
  111453. for(i=(n1+n0)/2-1;i>=0;--i)
  111454. d[i]=s[i];
  111455. }
  111456. v->pcm_returned+=(n1-n0)/2;
  111457. v->pcm_current+=(n1-n0)/2;
  111458. }else{
  111459. if(v->lW==0){
  111460. /* short/short */
  111461. for(j=0;j<vi->channels;j++){
  111462. float *s=v->pcm[j];
  111463. float *d=v->pcm[j]+n1-n0;
  111464. for(i=n0-1;i>=0;--i)
  111465. d[i]=s[i];
  111466. }
  111467. v->pcm_returned+=n1-n0;
  111468. v->pcm_current+=n1-n0;
  111469. }
  111470. }
  111471. if(pcm){
  111472. int i;
  111473. for(i=0;i<vi->channels;i++)
  111474. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111475. *pcm=v->pcmret;
  111476. }
  111477. return(n1+n-v->pcm_returned);
  111478. }
  111479. float *vorbis_window(vorbis_dsp_state *v,int W){
  111480. vorbis_info *vi=v->vi;
  111481. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111482. int hs=ci->halfrate_flag;
  111483. private_state *b=(private_state*)v->backend_state;
  111484. if(b->window[W]-1<0)return NULL;
  111485. return _vorbis_window_get(b->window[W]-hs);
  111486. }
  111487. #endif
  111488. /*** End of inlined file: block.c ***/
  111489. /*** Start of inlined file: codebook.c ***/
  111490. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111491. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111492. // tasks..
  111493. #if JUCE_MSVC
  111494. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111495. #endif
  111496. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111497. #if JUCE_USE_OGGVORBIS
  111498. #include <stdlib.h>
  111499. #include <string.h>
  111500. #include <math.h>
  111501. /* packs the given codebook into the bitstream **************************/
  111502. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111503. long i,j;
  111504. int ordered=0;
  111505. /* first the basic parameters */
  111506. oggpack_write(opb,0x564342,24);
  111507. oggpack_write(opb,c->dim,16);
  111508. oggpack_write(opb,c->entries,24);
  111509. /* pack the codewords. There are two packings; length ordered and
  111510. length random. Decide between the two now. */
  111511. for(i=1;i<c->entries;i++)
  111512. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111513. if(i==c->entries)ordered=1;
  111514. if(ordered){
  111515. /* length ordered. We only need to say how many codewords of
  111516. each length. The actual codewords are generated
  111517. deterministically */
  111518. long count=0;
  111519. oggpack_write(opb,1,1); /* ordered */
  111520. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111521. for(i=1;i<c->entries;i++){
  111522. long thisx=c->lengthlist[i];
  111523. long last=c->lengthlist[i-1];
  111524. if(thisx>last){
  111525. for(j=last;j<thisx;j++){
  111526. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111527. count=i;
  111528. }
  111529. }
  111530. }
  111531. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111532. }else{
  111533. /* length random. Again, we don't code the codeword itself, just
  111534. the length. This time, though, we have to encode each length */
  111535. oggpack_write(opb,0,1); /* unordered */
  111536. /* algortihmic mapping has use for 'unused entries', which we tag
  111537. here. The algorithmic mapping happens as usual, but the unused
  111538. entry has no codeword. */
  111539. for(i=0;i<c->entries;i++)
  111540. if(c->lengthlist[i]==0)break;
  111541. if(i==c->entries){
  111542. oggpack_write(opb,0,1); /* no unused entries */
  111543. for(i=0;i<c->entries;i++)
  111544. oggpack_write(opb,c->lengthlist[i]-1,5);
  111545. }else{
  111546. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111547. for(i=0;i<c->entries;i++){
  111548. if(c->lengthlist[i]==0){
  111549. oggpack_write(opb,0,1);
  111550. }else{
  111551. oggpack_write(opb,1,1);
  111552. oggpack_write(opb,c->lengthlist[i]-1,5);
  111553. }
  111554. }
  111555. }
  111556. }
  111557. /* is the entry number the desired return value, or do we have a
  111558. mapping? If we have a mapping, what type? */
  111559. oggpack_write(opb,c->maptype,4);
  111560. switch(c->maptype){
  111561. case 0:
  111562. /* no mapping */
  111563. break;
  111564. case 1:case 2:
  111565. /* implicitly populated value mapping */
  111566. /* explicitly populated value mapping */
  111567. if(!c->quantlist){
  111568. /* no quantlist? error */
  111569. return(-1);
  111570. }
  111571. /* values that define the dequantization */
  111572. oggpack_write(opb,c->q_min,32);
  111573. oggpack_write(opb,c->q_delta,32);
  111574. oggpack_write(opb,c->q_quant-1,4);
  111575. oggpack_write(opb,c->q_sequencep,1);
  111576. {
  111577. int quantvals;
  111578. switch(c->maptype){
  111579. case 1:
  111580. /* a single column of (c->entries/c->dim) quantized values for
  111581. building a full value list algorithmically (square lattice) */
  111582. quantvals=_book_maptype1_quantvals(c);
  111583. break;
  111584. case 2:
  111585. /* every value (c->entries*c->dim total) specified explicitly */
  111586. quantvals=c->entries*c->dim;
  111587. break;
  111588. default: /* NOT_REACHABLE */
  111589. quantvals=-1;
  111590. }
  111591. /* quantized values */
  111592. for(i=0;i<quantvals;i++)
  111593. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111594. }
  111595. break;
  111596. default:
  111597. /* error case; we don't have any other map types now */
  111598. return(-1);
  111599. }
  111600. return(0);
  111601. }
  111602. /* unpacks a codebook from the packet buffer into the codebook struct,
  111603. readies the codebook auxiliary structures for decode *************/
  111604. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111605. long i,j;
  111606. memset(s,0,sizeof(*s));
  111607. s->allocedp=1;
  111608. /* make sure alignment is correct */
  111609. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111610. /* first the basic parameters */
  111611. s->dim=oggpack_read(opb,16);
  111612. s->entries=oggpack_read(opb,24);
  111613. if(s->entries==-1)goto _eofout;
  111614. /* codeword ordering.... length ordered or unordered? */
  111615. switch((int)oggpack_read(opb,1)){
  111616. case 0:
  111617. /* unordered */
  111618. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111619. /* allocated but unused entries? */
  111620. if(oggpack_read(opb,1)){
  111621. /* yes, unused entries */
  111622. for(i=0;i<s->entries;i++){
  111623. if(oggpack_read(opb,1)){
  111624. long num=oggpack_read(opb,5);
  111625. if(num==-1)goto _eofout;
  111626. s->lengthlist[i]=num+1;
  111627. }else
  111628. s->lengthlist[i]=0;
  111629. }
  111630. }else{
  111631. /* all entries used; no tagging */
  111632. for(i=0;i<s->entries;i++){
  111633. long num=oggpack_read(opb,5);
  111634. if(num==-1)goto _eofout;
  111635. s->lengthlist[i]=num+1;
  111636. }
  111637. }
  111638. break;
  111639. case 1:
  111640. /* ordered */
  111641. {
  111642. long length=oggpack_read(opb,5)+1;
  111643. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111644. for(i=0;i<s->entries;){
  111645. long num=oggpack_read(opb,_ilog(s->entries-i));
  111646. if(num==-1)goto _eofout;
  111647. for(j=0;j<num && i<s->entries;j++,i++)
  111648. s->lengthlist[i]=length;
  111649. length++;
  111650. }
  111651. }
  111652. break;
  111653. default:
  111654. /* EOF */
  111655. return(-1);
  111656. }
  111657. /* Do we have a mapping to unpack? */
  111658. switch((s->maptype=oggpack_read(opb,4))){
  111659. case 0:
  111660. /* no mapping */
  111661. break;
  111662. case 1: case 2:
  111663. /* implicitly populated value mapping */
  111664. /* explicitly populated value mapping */
  111665. s->q_min=oggpack_read(opb,32);
  111666. s->q_delta=oggpack_read(opb,32);
  111667. s->q_quant=oggpack_read(opb,4)+1;
  111668. s->q_sequencep=oggpack_read(opb,1);
  111669. {
  111670. int quantvals=0;
  111671. switch(s->maptype){
  111672. case 1:
  111673. quantvals=_book_maptype1_quantvals(s);
  111674. break;
  111675. case 2:
  111676. quantvals=s->entries*s->dim;
  111677. break;
  111678. }
  111679. /* quantized values */
  111680. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111681. for(i=0;i<quantvals;i++)
  111682. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111683. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111684. }
  111685. break;
  111686. default:
  111687. goto _errout;
  111688. }
  111689. /* all set */
  111690. return(0);
  111691. _errout:
  111692. _eofout:
  111693. vorbis_staticbook_clear(s);
  111694. return(-1);
  111695. }
  111696. /* returns the number of bits ************************************************/
  111697. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111698. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111699. return(book->c->lengthlist[a]);
  111700. }
  111701. /* One the encode side, our vector writers are each designed for a
  111702. specific purpose, and the encoder is not flexible without modification:
  111703. The LSP vector coder uses a single stage nearest-match with no
  111704. interleave, so no step and no error return. This is specced by floor0
  111705. and doesn't change.
  111706. Residue0 encoding interleaves, uses multiple stages, and each stage
  111707. peels of a specific amount of resolution from a lattice (thus we want
  111708. to match by threshold, not nearest match). Residue doesn't *have* to
  111709. be encoded that way, but to change it, one will need to add more
  111710. infrastructure on the encode side (decode side is specced and simpler) */
  111711. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111712. /* returns entry number and *modifies a* to the quantization value *****/
  111713. int vorbis_book_errorv(codebook *book,float *a){
  111714. int dim=book->dim,k;
  111715. int best=_best(book,a,1);
  111716. for(k=0;k<dim;k++)
  111717. a[k]=(book->valuelist+best*dim)[k];
  111718. return(best);
  111719. }
  111720. /* returns the number of bits and *modifies a* to the quantization value *****/
  111721. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111722. int k,dim=book->dim;
  111723. for(k=0;k<dim;k++)
  111724. a[k]=(book->valuelist+best*dim)[k];
  111725. return(vorbis_book_encode(book,best,b));
  111726. }
  111727. /* the 'eliminate the decode tree' optimization actually requires the
  111728. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111729. (and one of the first places where carefully thought out design
  111730. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111731. to an MSb bitpacker), but not actually the huge hit it appears to
  111732. be. The first-stage decode table catches most words so that
  111733. bitreverse is not in the main execution path. */
  111734. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111735. int read=book->dec_maxlength;
  111736. long lo,hi;
  111737. long lok = oggpack_look(b,book->dec_firsttablen);
  111738. if (lok >= 0) {
  111739. long entry = book->dec_firsttable[lok];
  111740. if(entry&0x80000000UL){
  111741. lo=(entry>>15)&0x7fff;
  111742. hi=book->used_entries-(entry&0x7fff);
  111743. }else{
  111744. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111745. return(entry-1);
  111746. }
  111747. }else{
  111748. lo=0;
  111749. hi=book->used_entries;
  111750. }
  111751. lok = oggpack_look(b, read);
  111752. while(lok<0 && read>1)
  111753. lok = oggpack_look(b, --read);
  111754. if(lok<0)return -1;
  111755. /* bisect search for the codeword in the ordered list */
  111756. {
  111757. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111758. while(hi-lo>1){
  111759. long p=(hi-lo)>>1;
  111760. long test=book->codelist[lo+p]>testword;
  111761. lo+=p&(test-1);
  111762. hi-=p&(-test);
  111763. }
  111764. if(book->dec_codelengths[lo]<=read){
  111765. oggpack_adv(b, book->dec_codelengths[lo]);
  111766. return(lo);
  111767. }
  111768. }
  111769. oggpack_adv(b, read);
  111770. return(-1);
  111771. }
  111772. /* Decode side is specced and easier, because we don't need to find
  111773. matches using different criteria; we simply read and map. There are
  111774. two things we need to do 'depending':
  111775. We may need to support interleave. We don't really, but it's
  111776. convenient to do it here rather than rebuild the vector later.
  111777. Cascades may be additive or multiplicitive; this is not inherent in
  111778. the codebook, but set in the code using the codebook. Like
  111779. interleaving, it's easiest to do it here.
  111780. addmul==0 -> declarative (set the value)
  111781. addmul==1 -> additive
  111782. addmul==2 -> multiplicitive */
  111783. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111784. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111785. long packed_entry=decode_packed_entry_number(book,b);
  111786. if(packed_entry>=0)
  111787. return(book->dec_index[packed_entry]);
  111788. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111789. return(packed_entry);
  111790. }
  111791. /* returns 0 on OK or -1 on eof *************************************/
  111792. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111793. int step=n/book->dim;
  111794. long *entry = (long*)alloca(sizeof(*entry)*step);
  111795. float **t = (float**)alloca(sizeof(*t)*step);
  111796. int i,j,o;
  111797. for (i = 0; i < step; i++) {
  111798. entry[i]=decode_packed_entry_number(book,b);
  111799. if(entry[i]==-1)return(-1);
  111800. t[i] = book->valuelist+entry[i]*book->dim;
  111801. }
  111802. for(i=0,o=0;i<book->dim;i++,o+=step)
  111803. for (j=0;j<step;j++)
  111804. a[o+j]+=t[j][i];
  111805. return(0);
  111806. }
  111807. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111808. int i,j,entry;
  111809. float *t;
  111810. if(book->dim>8){
  111811. for(i=0;i<n;){
  111812. entry = decode_packed_entry_number(book,b);
  111813. if(entry==-1)return(-1);
  111814. t = book->valuelist+entry*book->dim;
  111815. for (j=0;j<book->dim;)
  111816. a[i++]+=t[j++];
  111817. }
  111818. }else{
  111819. for(i=0;i<n;){
  111820. entry = decode_packed_entry_number(book,b);
  111821. if(entry==-1)return(-1);
  111822. t = book->valuelist+entry*book->dim;
  111823. j=0;
  111824. switch((int)book->dim){
  111825. case 8:
  111826. a[i++]+=t[j++];
  111827. case 7:
  111828. a[i++]+=t[j++];
  111829. case 6:
  111830. a[i++]+=t[j++];
  111831. case 5:
  111832. a[i++]+=t[j++];
  111833. case 4:
  111834. a[i++]+=t[j++];
  111835. case 3:
  111836. a[i++]+=t[j++];
  111837. case 2:
  111838. a[i++]+=t[j++];
  111839. case 1:
  111840. a[i++]+=t[j++];
  111841. case 0:
  111842. break;
  111843. }
  111844. }
  111845. }
  111846. return(0);
  111847. }
  111848. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111849. int i,j,entry;
  111850. float *t;
  111851. for(i=0;i<n;){
  111852. entry = decode_packed_entry_number(book,b);
  111853. if(entry==-1)return(-1);
  111854. t = book->valuelist+entry*book->dim;
  111855. for (j=0;j<book->dim;)
  111856. a[i++]=t[j++];
  111857. }
  111858. return(0);
  111859. }
  111860. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111861. oggpack_buffer *b,int n){
  111862. long i,j,entry;
  111863. int chptr=0;
  111864. for(i=offset/ch;i<(offset+n)/ch;){
  111865. entry = decode_packed_entry_number(book,b);
  111866. if(entry==-1)return(-1);
  111867. {
  111868. const float *t = book->valuelist+entry*book->dim;
  111869. for (j=0;j<book->dim;j++){
  111870. a[chptr++][i]+=t[j];
  111871. if(chptr==ch){
  111872. chptr=0;
  111873. i++;
  111874. }
  111875. }
  111876. }
  111877. }
  111878. return(0);
  111879. }
  111880. #ifdef _V_SELFTEST
  111881. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111882. number of vectors through (keeping track of the quantized values),
  111883. and decode using the unpacked book. quantized version of in should
  111884. exactly equal out */
  111885. #include <stdio.h>
  111886. #include "vorbis/book/lsp20_0.vqh"
  111887. #include "vorbis/book/res0a_13.vqh"
  111888. #define TESTSIZE 40
  111889. float test1[TESTSIZE]={
  111890. 0.105939f,
  111891. 0.215373f,
  111892. 0.429117f,
  111893. 0.587974f,
  111894. 0.181173f,
  111895. 0.296583f,
  111896. 0.515707f,
  111897. 0.715261f,
  111898. 0.162327f,
  111899. 0.263834f,
  111900. 0.342876f,
  111901. 0.406025f,
  111902. 0.103571f,
  111903. 0.223561f,
  111904. 0.368513f,
  111905. 0.540313f,
  111906. 0.136672f,
  111907. 0.395882f,
  111908. 0.587183f,
  111909. 0.652476f,
  111910. 0.114338f,
  111911. 0.417300f,
  111912. 0.525486f,
  111913. 0.698679f,
  111914. 0.147492f,
  111915. 0.324481f,
  111916. 0.643089f,
  111917. 0.757582f,
  111918. 0.139556f,
  111919. 0.215795f,
  111920. 0.324559f,
  111921. 0.399387f,
  111922. 0.120236f,
  111923. 0.267420f,
  111924. 0.446940f,
  111925. 0.608760f,
  111926. 0.115587f,
  111927. 0.287234f,
  111928. 0.571081f,
  111929. 0.708603f,
  111930. };
  111931. float test3[TESTSIZE]={
  111932. 0,1,-2,3,4,-5,6,7,8,9,
  111933. 8,-2,7,-1,4,6,8,3,1,-9,
  111934. 10,11,12,13,14,15,26,17,18,19,
  111935. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111936. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111937. &_vq_book_res0a_13,NULL};
  111938. float *testvec[]={test1,test3};
  111939. int main(){
  111940. oggpack_buffer write;
  111941. oggpack_buffer read;
  111942. long ptr=0,i;
  111943. oggpack_writeinit(&write);
  111944. fprintf(stderr,"Testing codebook abstraction...:\n");
  111945. while(testlist[ptr]){
  111946. codebook c;
  111947. static_codebook s;
  111948. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111949. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111950. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111951. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111952. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111953. /* pack the codebook, write the testvector */
  111954. oggpack_reset(&write);
  111955. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111956. we can write */
  111957. vorbis_staticbook_pack(testlist[ptr],&write);
  111958. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111959. for(i=0;i<TESTSIZE;i+=c.dim){
  111960. int best=_best(&c,qv+i,1);
  111961. vorbis_book_encodev(&c,best,qv+i,&write);
  111962. }
  111963. vorbis_book_clear(&c);
  111964. fprintf(stderr,"OK.\n");
  111965. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111966. /* transfer the write data to a read buffer and unpack/read */
  111967. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111968. if(vorbis_staticbook_unpack(&read,&s)){
  111969. fprintf(stderr,"Error unpacking codebook.\n");
  111970. exit(1);
  111971. }
  111972. if(vorbis_book_init_decode(&c,&s)){
  111973. fprintf(stderr,"Error initializing codebook.\n");
  111974. exit(1);
  111975. }
  111976. for(i=0;i<TESTSIZE;i+=c.dim)
  111977. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111978. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111979. exit(1);
  111980. }
  111981. for(i=0;i<TESTSIZE;i++)
  111982. if(fabs(qv[i]-iv[i])>.000001){
  111983. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111984. iv[i],qv[i],i);
  111985. exit(1);
  111986. }
  111987. fprintf(stderr,"OK\n");
  111988. ptr++;
  111989. }
  111990. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111991. exit(0);
  111992. }
  111993. #endif
  111994. #endif
  111995. /*** End of inlined file: codebook.c ***/
  111996. /*** Start of inlined file: envelope.c ***/
  111997. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111998. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111999. // tasks..
  112000. #if JUCE_MSVC
  112001. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112002. #endif
  112003. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112004. #if JUCE_USE_OGGVORBIS
  112005. #include <stdlib.h>
  112006. #include <string.h>
  112007. #include <stdio.h>
  112008. #include <math.h>
  112009. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112010. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112011. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112012. int ch=vi->channels;
  112013. int i,j;
  112014. int n=e->winlength=128;
  112015. e->searchstep=64; /* not random */
  112016. e->minenergy=gi->preecho_minenergy;
  112017. e->ch=ch;
  112018. e->storage=128;
  112019. e->cursor=ci->blocksizes[1]/2;
  112020. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112021. mdct_init(&e->mdct,n);
  112022. for(i=0;i<n;i++){
  112023. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112024. e->mdct_win[i]*=e->mdct_win[i];
  112025. }
  112026. /* magic follows */
  112027. e->band[0].begin=2; e->band[0].end=4;
  112028. e->band[1].begin=4; e->band[1].end=5;
  112029. e->band[2].begin=6; e->band[2].end=6;
  112030. e->band[3].begin=9; e->band[3].end=8;
  112031. e->band[4].begin=13; e->band[4].end=8;
  112032. e->band[5].begin=17; e->band[5].end=8;
  112033. e->band[6].begin=22; e->band[6].end=8;
  112034. for(j=0;j<VE_BANDS;j++){
  112035. n=e->band[j].end;
  112036. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112037. for(i=0;i<n;i++){
  112038. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112039. e->band[j].total+=e->band[j].window[i];
  112040. }
  112041. e->band[j].total=1./e->band[j].total;
  112042. }
  112043. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112044. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112045. }
  112046. void _ve_envelope_clear(envelope_lookup *e){
  112047. int i;
  112048. mdct_clear(&e->mdct);
  112049. for(i=0;i<VE_BANDS;i++)
  112050. _ogg_free(e->band[i].window);
  112051. _ogg_free(e->mdct_win);
  112052. _ogg_free(e->filter);
  112053. _ogg_free(e->mark);
  112054. memset(e,0,sizeof(*e));
  112055. }
  112056. /* fairly straight threshhold-by-band based until we find something
  112057. that works better and isn't patented. */
  112058. static int _ve_amp(envelope_lookup *ve,
  112059. vorbis_info_psy_global *gi,
  112060. float *data,
  112061. envelope_band *bands,
  112062. envelope_filter_state *filters,
  112063. long pos){
  112064. long n=ve->winlength;
  112065. int ret=0;
  112066. long i,j;
  112067. float decay;
  112068. /* we want to have a 'minimum bar' for energy, else we're just
  112069. basing blocks on quantization noise that outweighs the signal
  112070. itself (for low power signals) */
  112071. float minV=ve->minenergy;
  112072. float *vec=(float*) alloca(n*sizeof(*vec));
  112073. /* stretch is used to gradually lengthen the number of windows
  112074. considered prevoius-to-potential-trigger */
  112075. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112076. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112077. if(penalty<0.f)penalty=0.f;
  112078. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112079. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112080. totalshift+pos*ve->searchstep);*/
  112081. /* window and transform */
  112082. for(i=0;i<n;i++)
  112083. vec[i]=data[i]*ve->mdct_win[i];
  112084. mdct_forward(&ve->mdct,vec,vec);
  112085. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112086. /* near-DC spreading function; this has nothing to do with
  112087. psychoacoustics, just sidelobe leakage and window size */
  112088. {
  112089. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112090. int ptr=filters->nearptr;
  112091. /* the accumulation is regularly refreshed from scratch to avoid
  112092. floating point creep */
  112093. if(ptr==0){
  112094. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112095. filters->nearDC_partialacc=temp;
  112096. }else{
  112097. decay=filters->nearDC_acc+=temp;
  112098. filters->nearDC_partialacc+=temp;
  112099. }
  112100. filters->nearDC_acc-=filters->nearDC[ptr];
  112101. filters->nearDC[ptr]=temp;
  112102. decay*=(1./(VE_NEARDC+1));
  112103. filters->nearptr++;
  112104. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112105. decay=todB(&decay)*.5-15.f;
  112106. }
  112107. /* perform spreading and limiting, also smooth the spectrum. yes,
  112108. the MDCT results in all real coefficients, but it still *behaves*
  112109. like real/imaginary pairs */
  112110. for(i=0;i<n/2;i+=2){
  112111. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112112. val=todB(&val)*.5f;
  112113. if(val<decay)val=decay;
  112114. if(val<minV)val=minV;
  112115. vec[i>>1]=val;
  112116. decay-=8.;
  112117. }
  112118. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112119. /* perform preecho/postecho triggering by band */
  112120. for(j=0;j<VE_BANDS;j++){
  112121. float acc=0.;
  112122. float valmax,valmin;
  112123. /* accumulate amplitude */
  112124. for(i=0;i<bands[j].end;i++)
  112125. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112126. acc*=bands[j].total;
  112127. /* convert amplitude to delta */
  112128. {
  112129. int p,thisx=filters[j].ampptr;
  112130. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112131. p=thisx;
  112132. p--;
  112133. if(p<0)p+=VE_AMP;
  112134. postmax=max(acc,filters[j].ampbuf[p]);
  112135. postmin=min(acc,filters[j].ampbuf[p]);
  112136. for(i=0;i<stretch;i++){
  112137. p--;
  112138. if(p<0)p+=VE_AMP;
  112139. premax=max(premax,filters[j].ampbuf[p]);
  112140. premin=min(premin,filters[j].ampbuf[p]);
  112141. }
  112142. valmin=postmin-premin;
  112143. valmax=postmax-premax;
  112144. /*filters[j].markers[pos]=valmax;*/
  112145. filters[j].ampbuf[thisx]=acc;
  112146. filters[j].ampptr++;
  112147. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112148. }
  112149. /* look at min/max, decide trigger */
  112150. if(valmax>gi->preecho_thresh[j]+penalty){
  112151. ret|=1;
  112152. ret|=4;
  112153. }
  112154. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112155. }
  112156. return(ret);
  112157. }
  112158. #if 0
  112159. static int seq=0;
  112160. static ogg_int64_t totalshift=-1024;
  112161. #endif
  112162. long _ve_envelope_search(vorbis_dsp_state *v){
  112163. vorbis_info *vi=v->vi;
  112164. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112165. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112166. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112167. long i,j;
  112168. int first=ve->current/ve->searchstep;
  112169. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112170. if(first<0)first=0;
  112171. /* make sure we have enough storage to match the PCM */
  112172. if(last+VE_WIN+VE_POST>ve->storage){
  112173. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112174. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112175. }
  112176. for(j=first;j<last;j++){
  112177. int ret=0;
  112178. ve->stretch++;
  112179. if(ve->stretch>VE_MAXSTRETCH*2)
  112180. ve->stretch=VE_MAXSTRETCH*2;
  112181. for(i=0;i<ve->ch;i++){
  112182. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112183. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112184. }
  112185. ve->mark[j+VE_POST]=0;
  112186. if(ret&1){
  112187. ve->mark[j]=1;
  112188. ve->mark[j+1]=1;
  112189. }
  112190. if(ret&2){
  112191. ve->mark[j]=1;
  112192. if(j>0)ve->mark[j-1]=1;
  112193. }
  112194. if(ret&4)ve->stretch=-1;
  112195. }
  112196. ve->current=last*ve->searchstep;
  112197. {
  112198. long centerW=v->centerW;
  112199. long testW=
  112200. centerW+
  112201. ci->blocksizes[v->W]/4+
  112202. ci->blocksizes[1]/2+
  112203. ci->blocksizes[0]/4;
  112204. j=ve->cursor;
  112205. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112206. working back one window */
  112207. if(j>=testW)return(1);
  112208. ve->cursor=j;
  112209. if(ve->mark[j/ve->searchstep]){
  112210. if(j>centerW){
  112211. #if 0
  112212. if(j>ve->curmark){
  112213. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112214. int l,m;
  112215. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112216. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112217. seq,
  112218. (totalshift+ve->cursor)/44100.,
  112219. (totalshift+j)/44100.);
  112220. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112221. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112222. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112223. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112224. for(m=0;m<VE_BANDS;m++){
  112225. char buf[80];
  112226. sprintf(buf,"delL%d",m);
  112227. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112228. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112229. }
  112230. for(m=0;m<VE_BANDS;m++){
  112231. char buf[80];
  112232. sprintf(buf,"delR%d",m);
  112233. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112234. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112235. }
  112236. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112237. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112238. seq++;
  112239. }
  112240. #endif
  112241. ve->curmark=j;
  112242. if(j>=testW)return(1);
  112243. return(0);
  112244. }
  112245. }
  112246. j+=ve->searchstep;
  112247. }
  112248. }
  112249. return(-1);
  112250. }
  112251. int _ve_envelope_mark(vorbis_dsp_state *v){
  112252. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112253. vorbis_info *vi=v->vi;
  112254. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112255. long centerW=v->centerW;
  112256. long beginW=centerW-ci->blocksizes[v->W]/4;
  112257. long endW=centerW+ci->blocksizes[v->W]/4;
  112258. if(v->W){
  112259. beginW-=ci->blocksizes[v->lW]/4;
  112260. endW+=ci->blocksizes[v->nW]/4;
  112261. }else{
  112262. beginW-=ci->blocksizes[0]/4;
  112263. endW+=ci->blocksizes[0]/4;
  112264. }
  112265. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112266. {
  112267. long first=beginW/ve->searchstep;
  112268. long last=endW/ve->searchstep;
  112269. long i;
  112270. for(i=first;i<last;i++)
  112271. if(ve->mark[i])return(1);
  112272. }
  112273. return(0);
  112274. }
  112275. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112276. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112277. ahead of ve->current */
  112278. int smallshift=shift/e->searchstep;
  112279. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112280. #if 0
  112281. for(i=0;i<VE_BANDS*e->ch;i++)
  112282. memmove(e->filter[i].markers,
  112283. e->filter[i].markers+smallshift,
  112284. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112285. totalshift+=shift;
  112286. #endif
  112287. e->current-=shift;
  112288. if(e->curmark>=0)
  112289. e->curmark-=shift;
  112290. e->cursor-=shift;
  112291. }
  112292. #endif
  112293. /*** End of inlined file: envelope.c ***/
  112294. /*** Start of inlined file: floor0.c ***/
  112295. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112296. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112297. // tasks..
  112298. #if JUCE_MSVC
  112299. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112300. #endif
  112301. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112302. #if JUCE_USE_OGGVORBIS
  112303. #include <stdlib.h>
  112304. #include <string.h>
  112305. #include <math.h>
  112306. /*** Start of inlined file: lsp.h ***/
  112307. #ifndef _V_LSP_H_
  112308. #define _V_LSP_H_
  112309. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112310. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112311. float *lsp,int m,
  112312. float amp,float ampoffset);
  112313. #endif
  112314. /*** End of inlined file: lsp.h ***/
  112315. #include <stdio.h>
  112316. typedef struct {
  112317. int ln;
  112318. int m;
  112319. int **linearmap;
  112320. int n[2];
  112321. vorbis_info_floor0 *vi;
  112322. long bits;
  112323. long frames;
  112324. } vorbis_look_floor0;
  112325. /***********************************************/
  112326. static void floor0_free_info(vorbis_info_floor *i){
  112327. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112328. if(info){
  112329. memset(info,0,sizeof(*info));
  112330. _ogg_free(info);
  112331. }
  112332. }
  112333. static void floor0_free_look(vorbis_look_floor *i){
  112334. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112335. if(look){
  112336. if(look->linearmap){
  112337. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112338. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112339. _ogg_free(look->linearmap);
  112340. }
  112341. memset(look,0,sizeof(*look));
  112342. _ogg_free(look);
  112343. }
  112344. }
  112345. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112346. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112347. int j;
  112348. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112349. info->order=oggpack_read(opb,8);
  112350. info->rate=oggpack_read(opb,16);
  112351. info->barkmap=oggpack_read(opb,16);
  112352. info->ampbits=oggpack_read(opb,6);
  112353. info->ampdB=oggpack_read(opb,8);
  112354. info->numbooks=oggpack_read(opb,4)+1;
  112355. if(info->order<1)goto err_out;
  112356. if(info->rate<1)goto err_out;
  112357. if(info->barkmap<1)goto err_out;
  112358. if(info->numbooks<1)goto err_out;
  112359. for(j=0;j<info->numbooks;j++){
  112360. info->books[j]=oggpack_read(opb,8);
  112361. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112362. }
  112363. return(info);
  112364. err_out:
  112365. floor0_free_info(info);
  112366. return(NULL);
  112367. }
  112368. /* initialize Bark scale and normalization lookups. We could do this
  112369. with static tables, but Vorbis allows a number of possible
  112370. combinations, so it's best to do it computationally.
  112371. The below is authoritative in terms of defining scale mapping.
  112372. Note that the scale depends on the sampling rate as well as the
  112373. linear block and mapping sizes */
  112374. static void floor0_map_lazy_init(vorbis_block *vb,
  112375. vorbis_info_floor *infoX,
  112376. vorbis_look_floor0 *look){
  112377. if(!look->linearmap[vb->W]){
  112378. vorbis_dsp_state *vd=vb->vd;
  112379. vorbis_info *vi=vd->vi;
  112380. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112381. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112382. int W=vb->W;
  112383. int n=ci->blocksizes[W]/2,j;
  112384. /* we choose a scaling constant so that:
  112385. floor(bark(rate/2-1)*C)=mapped-1
  112386. floor(bark(rate/2)*C)=mapped */
  112387. float scale=look->ln/toBARK(info->rate/2.f);
  112388. /* the mapping from a linear scale to a smaller bark scale is
  112389. straightforward. We do *not* make sure that the linear mapping
  112390. does not skip bark-scale bins; the decoder simply skips them and
  112391. the encoder may do what it wishes in filling them. They're
  112392. necessary in some mapping combinations to keep the scale spacing
  112393. accurate */
  112394. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112395. for(j=0;j<n;j++){
  112396. int val=floor( toBARK((info->rate/2.f)/n*j)
  112397. *scale); /* bark numbers represent band edges */
  112398. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112399. look->linearmap[W][j]=val;
  112400. }
  112401. look->linearmap[W][j]=-1;
  112402. look->n[W]=n;
  112403. }
  112404. }
  112405. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112406. vorbis_info_floor *i){
  112407. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112408. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112409. look->m=info->order;
  112410. look->ln=info->barkmap;
  112411. look->vi=info;
  112412. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112413. return look;
  112414. }
  112415. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112416. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112417. vorbis_info_floor0 *info=look->vi;
  112418. int j,k;
  112419. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112420. if(ampraw>0){ /* also handles the -1 out of data case */
  112421. long maxval=(1<<info->ampbits)-1;
  112422. float amp=(float)ampraw/maxval*info->ampdB;
  112423. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112424. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112425. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112426. codebook *b=ci->fullbooks+info->books[booknum];
  112427. float last=0.f;
  112428. /* the additional b->dim is a guard against any possible stack
  112429. smash; b->dim is provably more than we can overflow the
  112430. vector */
  112431. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112432. for(j=0;j<look->m;j+=b->dim)
  112433. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112434. for(j=0;j<look->m;){
  112435. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112436. last=lsp[j-1];
  112437. }
  112438. lsp[look->m]=amp;
  112439. return(lsp);
  112440. }
  112441. }
  112442. eop:
  112443. return(NULL);
  112444. }
  112445. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112446. void *memo,float *out){
  112447. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112448. vorbis_info_floor0 *info=look->vi;
  112449. floor0_map_lazy_init(vb,info,look);
  112450. if(memo){
  112451. float *lsp=(float *)memo;
  112452. float amp=lsp[look->m];
  112453. /* take the coefficients back to a spectral envelope curve */
  112454. vorbis_lsp_to_curve(out,
  112455. look->linearmap[vb->W],
  112456. look->n[vb->W],
  112457. look->ln,
  112458. lsp,look->m,amp,(float)info->ampdB);
  112459. return(1);
  112460. }
  112461. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112462. return(0);
  112463. }
  112464. /* export hooks */
  112465. vorbis_func_floor floor0_exportbundle={
  112466. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112467. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112468. };
  112469. #endif
  112470. /*** End of inlined file: floor0.c ***/
  112471. /*** Start of inlined file: floor1.c ***/
  112472. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112473. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112474. // tasks..
  112475. #if JUCE_MSVC
  112476. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112477. #endif
  112478. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112479. #if JUCE_USE_OGGVORBIS
  112480. #include <stdlib.h>
  112481. #include <string.h>
  112482. #include <math.h>
  112483. #include <stdio.h>
  112484. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112485. typedef struct {
  112486. int sorted_index[VIF_POSIT+2];
  112487. int forward_index[VIF_POSIT+2];
  112488. int reverse_index[VIF_POSIT+2];
  112489. int hineighbor[VIF_POSIT];
  112490. int loneighbor[VIF_POSIT];
  112491. int posts;
  112492. int n;
  112493. int quant_q;
  112494. vorbis_info_floor1 *vi;
  112495. long phrasebits;
  112496. long postbits;
  112497. long frames;
  112498. } vorbis_look_floor1;
  112499. typedef struct lsfit_acc{
  112500. long x0;
  112501. long x1;
  112502. long xa;
  112503. long ya;
  112504. long x2a;
  112505. long y2a;
  112506. long xya;
  112507. long an;
  112508. } lsfit_acc;
  112509. /***********************************************/
  112510. static void floor1_free_info(vorbis_info_floor *i){
  112511. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112512. if(info){
  112513. memset(info,0,sizeof(*info));
  112514. _ogg_free(info);
  112515. }
  112516. }
  112517. static void floor1_free_look(vorbis_look_floor *i){
  112518. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112519. if(look){
  112520. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112521. (float)look->phrasebits/look->frames,
  112522. (float)look->postbits/look->frames,
  112523. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112524. memset(look,0,sizeof(*look));
  112525. _ogg_free(look);
  112526. }
  112527. }
  112528. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112529. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112530. int j,k;
  112531. int count=0;
  112532. int rangebits;
  112533. int maxposit=info->postlist[1];
  112534. int maxclass=-1;
  112535. /* save out partitions */
  112536. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112537. for(j=0;j<info->partitions;j++){
  112538. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112539. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112540. }
  112541. /* save out partition classes */
  112542. for(j=0;j<maxclass+1;j++){
  112543. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112544. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112545. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112546. for(k=0;k<(1<<info->class_subs[j]);k++)
  112547. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112548. }
  112549. /* save out the post list */
  112550. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112551. oggpack_write(opb,ilog2(maxposit),4);
  112552. rangebits=ilog2(maxposit);
  112553. for(j=0,k=0;j<info->partitions;j++){
  112554. count+=info->class_dim[info->partitionclass[j]];
  112555. for(;k<count;k++)
  112556. oggpack_write(opb,info->postlist[k+2],rangebits);
  112557. }
  112558. }
  112559. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112560. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112561. int j,k,count=0,maxclass=-1,rangebits;
  112562. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112563. /* read partitions */
  112564. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112565. for(j=0;j<info->partitions;j++){
  112566. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112567. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112568. }
  112569. /* read partition classes */
  112570. for(j=0;j<maxclass+1;j++){
  112571. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112572. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112573. if(info->class_subs[j]<0)
  112574. goto err_out;
  112575. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112576. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112577. goto err_out;
  112578. for(k=0;k<(1<<info->class_subs[j]);k++){
  112579. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112580. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112581. goto err_out;
  112582. }
  112583. }
  112584. /* read the post list */
  112585. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112586. rangebits=oggpack_read(opb,4);
  112587. for(j=0,k=0;j<info->partitions;j++){
  112588. count+=info->class_dim[info->partitionclass[j]];
  112589. for(;k<count;k++){
  112590. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112591. if(t<0 || t>=(1<<rangebits))
  112592. goto err_out;
  112593. }
  112594. }
  112595. info->postlist[0]=0;
  112596. info->postlist[1]=1<<rangebits;
  112597. return(info);
  112598. err_out:
  112599. floor1_free_info(info);
  112600. return(NULL);
  112601. }
  112602. static int JUCE_CDECL icomp(const void *a,const void *b){
  112603. return(**(int **)a-**(int **)b);
  112604. }
  112605. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112606. vorbis_info_floor *in){
  112607. int *sortpointer[VIF_POSIT+2];
  112608. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112609. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112610. int i,j,n=0;
  112611. look->vi=info;
  112612. look->n=info->postlist[1];
  112613. /* we drop each position value in-between already decoded values,
  112614. and use linear interpolation to predict each new value past the
  112615. edges. The positions are read in the order of the position
  112616. list... we precompute the bounding positions in the lookup. Of
  112617. course, the neighbors can change (if a position is declined), but
  112618. this is an initial mapping */
  112619. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112620. n+=2;
  112621. look->posts=n;
  112622. /* also store a sorted position index */
  112623. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112624. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112625. /* points from sort order back to range number */
  112626. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112627. /* points from range order to sorted position */
  112628. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112629. /* we actually need the post values too */
  112630. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112631. /* quantize values to multiplier spec */
  112632. switch(info->mult){
  112633. case 1: /* 1024 -> 256 */
  112634. look->quant_q=256;
  112635. break;
  112636. case 2: /* 1024 -> 128 */
  112637. look->quant_q=128;
  112638. break;
  112639. case 3: /* 1024 -> 86 */
  112640. look->quant_q=86;
  112641. break;
  112642. case 4: /* 1024 -> 64 */
  112643. look->quant_q=64;
  112644. break;
  112645. }
  112646. /* discover our neighbors for decode where we don't use fit flags
  112647. (that would push the neighbors outward) */
  112648. for(i=0;i<n-2;i++){
  112649. int lo=0;
  112650. int hi=1;
  112651. int lx=0;
  112652. int hx=look->n;
  112653. int currentx=info->postlist[i+2];
  112654. for(j=0;j<i+2;j++){
  112655. int x=info->postlist[j];
  112656. if(x>lx && x<currentx){
  112657. lo=j;
  112658. lx=x;
  112659. }
  112660. if(x<hx && x>currentx){
  112661. hi=j;
  112662. hx=x;
  112663. }
  112664. }
  112665. look->loneighbor[i]=lo;
  112666. look->hineighbor[i]=hi;
  112667. }
  112668. return(look);
  112669. }
  112670. static int render_point(int x0,int x1,int y0,int y1,int x){
  112671. y0&=0x7fff; /* mask off flag */
  112672. y1&=0x7fff;
  112673. {
  112674. int dy=y1-y0;
  112675. int adx=x1-x0;
  112676. int ady=abs(dy);
  112677. int err=ady*(x-x0);
  112678. int off=err/adx;
  112679. if(dy<0)return(y0-off);
  112680. return(y0+off);
  112681. }
  112682. }
  112683. static int vorbis_dBquant(const float *x){
  112684. int i= *x*7.3142857f+1023.5f;
  112685. if(i>1023)return(1023);
  112686. if(i<0)return(0);
  112687. return i;
  112688. }
  112689. static float FLOOR1_fromdB_LOOKUP[256]={
  112690. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112691. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112692. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112693. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112694. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112695. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112696. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112697. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112698. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112699. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112700. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112701. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112702. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112703. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112704. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112705. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112706. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112707. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112708. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112709. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112710. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112711. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112712. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112713. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112714. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112715. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112716. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112717. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112718. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112719. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112720. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112721. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112722. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112723. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112724. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112725. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112726. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112727. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112728. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112729. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112730. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112731. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112732. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112733. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112734. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112735. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112736. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112737. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112738. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112739. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112740. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112741. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112742. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112743. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112744. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112745. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112746. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112747. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112748. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112749. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112750. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112751. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112752. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112753. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112754. };
  112755. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112756. int dy=y1-y0;
  112757. int adx=x1-x0;
  112758. int ady=abs(dy);
  112759. int base=dy/adx;
  112760. int sy=(dy<0?base-1:base+1);
  112761. int x=x0;
  112762. int y=y0;
  112763. int err=0;
  112764. ady-=abs(base*adx);
  112765. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112766. while(++x<x1){
  112767. err=err+ady;
  112768. if(err>=adx){
  112769. err-=adx;
  112770. y+=sy;
  112771. }else{
  112772. y+=base;
  112773. }
  112774. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112775. }
  112776. }
  112777. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112778. int dy=y1-y0;
  112779. int adx=x1-x0;
  112780. int ady=abs(dy);
  112781. int base=dy/adx;
  112782. int sy=(dy<0?base-1:base+1);
  112783. int x=x0;
  112784. int y=y0;
  112785. int err=0;
  112786. ady-=abs(base*adx);
  112787. d[x]=y;
  112788. while(++x<x1){
  112789. err=err+ady;
  112790. if(err>=adx){
  112791. err-=adx;
  112792. y+=sy;
  112793. }else{
  112794. y+=base;
  112795. }
  112796. d[x]=y;
  112797. }
  112798. }
  112799. /* the floor has already been filtered to only include relevant sections */
  112800. static int accumulate_fit(const float *flr,const float *mdct,
  112801. int x0, int x1,lsfit_acc *a,
  112802. int n,vorbis_info_floor1 *info){
  112803. long i;
  112804. 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;
  112805. memset(a,0,sizeof(*a));
  112806. a->x0=x0;
  112807. a->x1=x1;
  112808. if(x1>=n)x1=n-1;
  112809. for(i=x0;i<=x1;i++){
  112810. int quantized=vorbis_dBquant(flr+i);
  112811. if(quantized){
  112812. if(mdct[i]+info->twofitatten>=flr[i]){
  112813. xa += i;
  112814. ya += quantized;
  112815. x2a += i*i;
  112816. y2a += quantized*quantized;
  112817. xya += i*quantized;
  112818. na++;
  112819. }else{
  112820. xb += i;
  112821. yb += quantized;
  112822. x2b += i*i;
  112823. y2b += quantized*quantized;
  112824. xyb += i*quantized;
  112825. nb++;
  112826. }
  112827. }
  112828. }
  112829. xb+=xa;
  112830. yb+=ya;
  112831. x2b+=x2a;
  112832. y2b+=y2a;
  112833. xyb+=xya;
  112834. nb+=na;
  112835. /* weight toward the actually used frequencies if we meet the threshhold */
  112836. {
  112837. int weight=nb*info->twofitweight/(na+1);
  112838. a->xa=xa*weight+xb;
  112839. a->ya=ya*weight+yb;
  112840. a->x2a=x2a*weight+x2b;
  112841. a->y2a=y2a*weight+y2b;
  112842. a->xya=xya*weight+xyb;
  112843. a->an=na*weight+nb;
  112844. }
  112845. return(na);
  112846. }
  112847. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112848. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112849. long x0=a[0].x0;
  112850. long x1=a[fits-1].x1;
  112851. for(i=0;i<fits;i++){
  112852. x+=a[i].xa;
  112853. y+=a[i].ya;
  112854. x2+=a[i].x2a;
  112855. y2+=a[i].y2a;
  112856. xy+=a[i].xya;
  112857. an+=a[i].an;
  112858. }
  112859. if(*y0>=0){
  112860. x+= x0;
  112861. y+= *y0;
  112862. x2+= x0 * x0;
  112863. y2+= *y0 * *y0;
  112864. xy+= *y0 * x0;
  112865. an++;
  112866. }
  112867. if(*y1>=0){
  112868. x+= x1;
  112869. y+= *y1;
  112870. x2+= x1 * x1;
  112871. y2+= *y1 * *y1;
  112872. xy+= *y1 * x1;
  112873. an++;
  112874. }
  112875. if(an){
  112876. /* need 64 bit multiplies, which C doesn't give portably as int */
  112877. double fx=x;
  112878. double fy=y;
  112879. double fx2=x2;
  112880. double fxy=xy;
  112881. double denom=1./(an*fx2-fx*fx);
  112882. double a=(fy*fx2-fxy*fx)*denom;
  112883. double b=(an*fxy-fx*fy)*denom;
  112884. *y0=rint(a+b*x0);
  112885. *y1=rint(a+b*x1);
  112886. /* limit to our range! */
  112887. if(*y0>1023)*y0=1023;
  112888. if(*y1>1023)*y1=1023;
  112889. if(*y0<0)*y0=0;
  112890. if(*y1<0)*y1=0;
  112891. }else{
  112892. *y0=0;
  112893. *y1=0;
  112894. }
  112895. }
  112896. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112897. long y=0;
  112898. int i;
  112899. for(i=0;i<fits && y==0;i++)
  112900. y+=a[i].ya;
  112901. *y0=*y1=y;
  112902. }*/
  112903. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112904. const float *mdct,
  112905. vorbis_info_floor1 *info){
  112906. int dy=y1-y0;
  112907. int adx=x1-x0;
  112908. int ady=abs(dy);
  112909. int base=dy/adx;
  112910. int sy=(dy<0?base-1:base+1);
  112911. int x=x0;
  112912. int y=y0;
  112913. int err=0;
  112914. int val=vorbis_dBquant(mask+x);
  112915. int mse=0;
  112916. int n=0;
  112917. ady-=abs(base*adx);
  112918. mse=(y-val);
  112919. mse*=mse;
  112920. n++;
  112921. if(mdct[x]+info->twofitatten>=mask[x]){
  112922. if(y+info->maxover<val)return(1);
  112923. if(y-info->maxunder>val)return(1);
  112924. }
  112925. while(++x<x1){
  112926. err=err+ady;
  112927. if(err>=adx){
  112928. err-=adx;
  112929. y+=sy;
  112930. }else{
  112931. y+=base;
  112932. }
  112933. val=vorbis_dBquant(mask+x);
  112934. mse+=((y-val)*(y-val));
  112935. n++;
  112936. if(mdct[x]+info->twofitatten>=mask[x]){
  112937. if(val){
  112938. if(y+info->maxover<val)return(1);
  112939. if(y-info->maxunder>val)return(1);
  112940. }
  112941. }
  112942. }
  112943. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112944. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112945. if(mse/n>info->maxerr)return(1);
  112946. return(0);
  112947. }
  112948. static int post_Y(int *A,int *B,int pos){
  112949. if(A[pos]<0)
  112950. return B[pos];
  112951. if(B[pos]<0)
  112952. return A[pos];
  112953. return (A[pos]+B[pos])>>1;
  112954. }
  112955. int *floor1_fit(vorbis_block *vb,void *look_,
  112956. const float *logmdct, /* in */
  112957. const float *logmask){
  112958. long i,j;
  112959. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112960. vorbis_info_floor1 *info=look->vi;
  112961. long n=look->n;
  112962. long posts=look->posts;
  112963. long nonzero=0;
  112964. lsfit_acc fits[VIF_POSIT+1];
  112965. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112966. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112967. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112968. int hineighbor[VIF_POSIT+2];
  112969. int *output=NULL;
  112970. int memo[VIF_POSIT+2];
  112971. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112972. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112973. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112974. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112975. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112976. /* quantize the relevant floor points and collect them into line fit
  112977. structures (one per minimal division) at the same time */
  112978. if(posts==0){
  112979. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112980. }else{
  112981. for(i=0;i<posts-1;i++)
  112982. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112983. look->sorted_index[i+1],fits+i,
  112984. n,info);
  112985. }
  112986. if(nonzero){
  112987. /* start by fitting the implicit base case.... */
  112988. int y0=-200;
  112989. int y1=-200;
  112990. fit_line(fits,posts-1,&y0,&y1);
  112991. fit_valueA[0]=y0;
  112992. fit_valueB[0]=y0;
  112993. fit_valueB[1]=y1;
  112994. fit_valueA[1]=y1;
  112995. /* Non degenerate case */
  112996. /* start progressive splitting. This is a greedy, non-optimal
  112997. algorithm, but simple and close enough to the best
  112998. answer. */
  112999. for(i=2;i<posts;i++){
  113000. int sortpos=look->reverse_index[i];
  113001. int ln=loneighbor[sortpos];
  113002. int hn=hineighbor[sortpos];
  113003. /* eliminate repeat searches of a particular range with a memo */
  113004. if(memo[ln]!=hn){
  113005. /* haven't performed this error search yet */
  113006. int lsortpos=look->reverse_index[ln];
  113007. int hsortpos=look->reverse_index[hn];
  113008. memo[ln]=hn;
  113009. {
  113010. /* A note: we want to bound/minimize *local*, not global, error */
  113011. int lx=info->postlist[ln];
  113012. int hx=info->postlist[hn];
  113013. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113014. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113015. if(ly==-1 || hy==-1){
  113016. exit(1);
  113017. }
  113018. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113019. /* outside error bounds/begin search area. Split it. */
  113020. int ly0=-200;
  113021. int ly1=-200;
  113022. int hy0=-200;
  113023. int hy1=-200;
  113024. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113025. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113026. /* store new edge values */
  113027. fit_valueB[ln]=ly0;
  113028. if(ln==0)fit_valueA[ln]=ly0;
  113029. fit_valueA[i]=ly1;
  113030. fit_valueB[i]=hy0;
  113031. fit_valueA[hn]=hy1;
  113032. if(hn==1)fit_valueB[hn]=hy1;
  113033. if(ly1>=0 || hy0>=0){
  113034. /* store new neighbor values */
  113035. for(j=sortpos-1;j>=0;j--)
  113036. if(hineighbor[j]==hn)
  113037. hineighbor[j]=i;
  113038. else
  113039. break;
  113040. for(j=sortpos+1;j<posts;j++)
  113041. if(loneighbor[j]==ln)
  113042. loneighbor[j]=i;
  113043. else
  113044. break;
  113045. }
  113046. }else{
  113047. fit_valueA[i]=-200;
  113048. fit_valueB[i]=-200;
  113049. }
  113050. }
  113051. }
  113052. }
  113053. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113054. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113055. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113056. /* fill in posts marked as not using a fit; we will zero
  113057. back out to 'unused' when encoding them so long as curve
  113058. interpolation doesn't force them into use */
  113059. for(i=2;i<posts;i++){
  113060. int ln=look->loneighbor[i-2];
  113061. int hn=look->hineighbor[i-2];
  113062. int x0=info->postlist[ln];
  113063. int x1=info->postlist[hn];
  113064. int y0=output[ln];
  113065. int y1=output[hn];
  113066. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113067. int vx=post_Y(fit_valueA,fit_valueB,i);
  113068. if(vx>=0 && predicted!=vx){
  113069. output[i]=vx;
  113070. }else{
  113071. output[i]= predicted|0x8000;
  113072. }
  113073. }
  113074. }
  113075. return(output);
  113076. }
  113077. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113078. int *A,int *B,
  113079. int del){
  113080. long i;
  113081. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113082. long posts=look->posts;
  113083. int *output=NULL;
  113084. if(A && B){
  113085. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113086. for(i=0;i<posts;i++){
  113087. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113088. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113089. }
  113090. }
  113091. return(output);
  113092. }
  113093. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113094. void*look_,
  113095. int *post,int *ilogmask){
  113096. long i,j;
  113097. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113098. vorbis_info_floor1 *info=look->vi;
  113099. long posts=look->posts;
  113100. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113101. int out[VIF_POSIT+2];
  113102. static_codebook **sbooks=ci->book_param;
  113103. codebook *books=ci->fullbooks;
  113104. static long seq=0;
  113105. /* quantize values to multiplier spec */
  113106. if(post){
  113107. for(i=0;i<posts;i++){
  113108. int val=post[i]&0x7fff;
  113109. switch(info->mult){
  113110. case 1: /* 1024 -> 256 */
  113111. val>>=2;
  113112. break;
  113113. case 2: /* 1024 -> 128 */
  113114. val>>=3;
  113115. break;
  113116. case 3: /* 1024 -> 86 */
  113117. val/=12;
  113118. break;
  113119. case 4: /* 1024 -> 64 */
  113120. val>>=4;
  113121. break;
  113122. }
  113123. post[i]=val | (post[i]&0x8000);
  113124. }
  113125. out[0]=post[0];
  113126. out[1]=post[1];
  113127. /* find prediction values for each post and subtract them */
  113128. for(i=2;i<posts;i++){
  113129. int ln=look->loneighbor[i-2];
  113130. int hn=look->hineighbor[i-2];
  113131. int x0=info->postlist[ln];
  113132. int x1=info->postlist[hn];
  113133. int y0=post[ln];
  113134. int y1=post[hn];
  113135. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113136. if((post[i]&0x8000) || (predicted==post[i])){
  113137. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113138. in interpolation */
  113139. out[i]=0;
  113140. }else{
  113141. int headroom=(look->quant_q-predicted<predicted?
  113142. look->quant_q-predicted:predicted);
  113143. int val=post[i]-predicted;
  113144. /* at this point the 'deviation' value is in the range +/- max
  113145. range, but the real, unique range can always be mapped to
  113146. only [0-maxrange). So we want to wrap the deviation into
  113147. this limited range, but do it in the way that least screws
  113148. an essentially gaussian probability distribution. */
  113149. if(val<0)
  113150. if(val<-headroom)
  113151. val=headroom-val-1;
  113152. else
  113153. val=-1-(val<<1);
  113154. else
  113155. if(val>=headroom)
  113156. val= val+headroom;
  113157. else
  113158. val<<=1;
  113159. out[i]=val;
  113160. post[ln]&=0x7fff;
  113161. post[hn]&=0x7fff;
  113162. }
  113163. }
  113164. /* we have everything we need. pack it out */
  113165. /* mark nontrivial floor */
  113166. oggpack_write(opb,1,1);
  113167. /* beginning/end post */
  113168. look->frames++;
  113169. look->postbits+=ilog(look->quant_q-1)*2;
  113170. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113171. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113172. /* partition by partition */
  113173. for(i=0,j=2;i<info->partitions;i++){
  113174. int classx=info->partitionclass[i];
  113175. int cdim=info->class_dim[classx];
  113176. int csubbits=info->class_subs[classx];
  113177. int csub=1<<csubbits;
  113178. int bookas[8]={0,0,0,0,0,0,0,0};
  113179. int cval=0;
  113180. int cshift=0;
  113181. int k,l;
  113182. /* generate the partition's first stage cascade value */
  113183. if(csubbits){
  113184. int maxval[8];
  113185. for(k=0;k<csub;k++){
  113186. int booknum=info->class_subbook[classx][k];
  113187. if(booknum<0){
  113188. maxval[k]=1;
  113189. }else{
  113190. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113191. }
  113192. }
  113193. for(k=0;k<cdim;k++){
  113194. for(l=0;l<csub;l++){
  113195. int val=out[j+k];
  113196. if(val<maxval[l]){
  113197. bookas[k]=l;
  113198. break;
  113199. }
  113200. }
  113201. cval|= bookas[k]<<cshift;
  113202. cshift+=csubbits;
  113203. }
  113204. /* write it */
  113205. look->phrasebits+=
  113206. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113207. #ifdef TRAIN_FLOOR1
  113208. {
  113209. FILE *of;
  113210. char buffer[80];
  113211. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113212. vb->pcmend/2,posts-2,class);
  113213. of=fopen(buffer,"a");
  113214. fprintf(of,"%d\n",cval);
  113215. fclose(of);
  113216. }
  113217. #endif
  113218. }
  113219. /* write post values */
  113220. for(k=0;k<cdim;k++){
  113221. int book=info->class_subbook[classx][bookas[k]];
  113222. if(book>=0){
  113223. /* hack to allow training with 'bad' books */
  113224. if(out[j+k]<(books+book)->entries)
  113225. look->postbits+=vorbis_book_encode(books+book,
  113226. out[j+k],opb);
  113227. /*else
  113228. fprintf(stderr,"+!");*/
  113229. #ifdef TRAIN_FLOOR1
  113230. {
  113231. FILE *of;
  113232. char buffer[80];
  113233. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113234. vb->pcmend/2,posts-2,class,bookas[k]);
  113235. of=fopen(buffer,"a");
  113236. fprintf(of,"%d\n",out[j+k]);
  113237. fclose(of);
  113238. }
  113239. #endif
  113240. }
  113241. }
  113242. j+=cdim;
  113243. }
  113244. {
  113245. /* generate quantized floor equivalent to what we'd unpack in decode */
  113246. /* render the lines */
  113247. int hx=0;
  113248. int lx=0;
  113249. int ly=post[0]*info->mult;
  113250. for(j=1;j<look->posts;j++){
  113251. int current=look->forward_index[j];
  113252. int hy=post[current]&0x7fff;
  113253. if(hy==post[current]){
  113254. hy*=info->mult;
  113255. hx=info->postlist[current];
  113256. render_line0(lx,hx,ly,hy,ilogmask);
  113257. lx=hx;
  113258. ly=hy;
  113259. }
  113260. }
  113261. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113262. seq++;
  113263. return(1);
  113264. }
  113265. }else{
  113266. oggpack_write(opb,0,1);
  113267. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113268. seq++;
  113269. return(0);
  113270. }
  113271. }
  113272. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113273. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113274. vorbis_info_floor1 *info=look->vi;
  113275. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113276. int i,j,k;
  113277. codebook *books=ci->fullbooks;
  113278. /* unpack wrapped/predicted values from stream */
  113279. if(oggpack_read(&vb->opb,1)==1){
  113280. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113281. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113282. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113283. /* partition by partition */
  113284. for(i=0,j=2;i<info->partitions;i++){
  113285. int classx=info->partitionclass[i];
  113286. int cdim=info->class_dim[classx];
  113287. int csubbits=info->class_subs[classx];
  113288. int csub=1<<csubbits;
  113289. int cval=0;
  113290. /* decode the partition's first stage cascade value */
  113291. if(csubbits){
  113292. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113293. if(cval==-1)goto eop;
  113294. }
  113295. for(k=0;k<cdim;k++){
  113296. int book=info->class_subbook[classx][cval&(csub-1)];
  113297. cval>>=csubbits;
  113298. if(book>=0){
  113299. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113300. goto eop;
  113301. }else{
  113302. fit_value[j+k]=0;
  113303. }
  113304. }
  113305. j+=cdim;
  113306. }
  113307. /* unwrap positive values and reconsitute via linear interpolation */
  113308. for(i=2;i<look->posts;i++){
  113309. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113310. info->postlist[look->hineighbor[i-2]],
  113311. fit_value[look->loneighbor[i-2]],
  113312. fit_value[look->hineighbor[i-2]],
  113313. info->postlist[i]);
  113314. int hiroom=look->quant_q-predicted;
  113315. int loroom=predicted;
  113316. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113317. int val=fit_value[i];
  113318. if(val){
  113319. if(val>=room){
  113320. if(hiroom>loroom){
  113321. val = val-loroom;
  113322. }else{
  113323. val = -1-(val-hiroom);
  113324. }
  113325. }else{
  113326. if(val&1){
  113327. val= -((val+1)>>1);
  113328. }else{
  113329. val>>=1;
  113330. }
  113331. }
  113332. fit_value[i]=val+predicted;
  113333. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113334. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113335. }else{
  113336. fit_value[i]=predicted|0x8000;
  113337. }
  113338. }
  113339. return(fit_value);
  113340. }
  113341. eop:
  113342. return(NULL);
  113343. }
  113344. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113345. float *out){
  113346. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113347. vorbis_info_floor1 *info=look->vi;
  113348. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113349. int n=ci->blocksizes[vb->W]/2;
  113350. int j;
  113351. if(memo){
  113352. /* render the lines */
  113353. int *fit_value=(int *)memo;
  113354. int hx=0;
  113355. int lx=0;
  113356. int ly=fit_value[0]*info->mult;
  113357. for(j=1;j<look->posts;j++){
  113358. int current=look->forward_index[j];
  113359. int hy=fit_value[current]&0x7fff;
  113360. if(hy==fit_value[current]){
  113361. hy*=info->mult;
  113362. hx=info->postlist[current];
  113363. render_line(lx,hx,ly,hy,out);
  113364. lx=hx;
  113365. ly=hy;
  113366. }
  113367. }
  113368. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113369. return(1);
  113370. }
  113371. memset(out,0,sizeof(*out)*n);
  113372. return(0);
  113373. }
  113374. /* export hooks */
  113375. vorbis_func_floor floor1_exportbundle={
  113376. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113377. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113378. };
  113379. #endif
  113380. /*** End of inlined file: floor1.c ***/
  113381. /*** Start of inlined file: info.c ***/
  113382. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113383. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113384. // tasks..
  113385. #if JUCE_MSVC
  113386. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113387. #endif
  113388. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113389. #if JUCE_USE_OGGVORBIS
  113390. /* general handling of the header and the vorbis_info structure (and
  113391. substructures) */
  113392. #include <stdlib.h>
  113393. #include <string.h>
  113394. #include <ctype.h>
  113395. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113396. while(bytes--){
  113397. oggpack_write(o,*s++,8);
  113398. }
  113399. }
  113400. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113401. while(bytes--){
  113402. *buf++=oggpack_read(o,8);
  113403. }
  113404. }
  113405. void vorbis_comment_init(vorbis_comment *vc){
  113406. memset(vc,0,sizeof(*vc));
  113407. }
  113408. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113409. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113410. (vc->comments+2)*sizeof(*vc->user_comments));
  113411. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113412. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113413. vc->comment_lengths[vc->comments]=strlen(comment);
  113414. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113415. strcpy(vc->user_comments[vc->comments], comment);
  113416. vc->comments++;
  113417. vc->user_comments[vc->comments]=NULL;
  113418. }
  113419. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113420. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113421. strcpy(comment, tag);
  113422. strcat(comment, "=");
  113423. strcat(comment, contents);
  113424. vorbis_comment_add(vc, comment);
  113425. }
  113426. /* This is more or less the same as strncasecmp - but that doesn't exist
  113427. * everywhere, and this is a fairly trivial function, so we include it */
  113428. static int tagcompare(const char *s1, const char *s2, int n){
  113429. int c=0;
  113430. while(c < n){
  113431. if(toupper(s1[c]) != toupper(s2[c]))
  113432. return !0;
  113433. c++;
  113434. }
  113435. return 0;
  113436. }
  113437. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113438. long i;
  113439. int found = 0;
  113440. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113441. char *fulltag = (char*)alloca(taglen+ 1);
  113442. strcpy(fulltag, tag);
  113443. strcat(fulltag, "=");
  113444. for(i=0;i<vc->comments;i++){
  113445. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113446. if(count == found)
  113447. /* We return a pointer to the data, not a copy */
  113448. return vc->user_comments[i] + taglen;
  113449. else
  113450. found++;
  113451. }
  113452. }
  113453. return NULL; /* didn't find anything */
  113454. }
  113455. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113456. int i,count=0;
  113457. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113458. char *fulltag = (char*)alloca(taglen+1);
  113459. strcpy(fulltag,tag);
  113460. strcat(fulltag, "=");
  113461. for(i=0;i<vc->comments;i++){
  113462. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113463. count++;
  113464. }
  113465. return count;
  113466. }
  113467. void vorbis_comment_clear(vorbis_comment *vc){
  113468. if(vc){
  113469. long i;
  113470. for(i=0;i<vc->comments;i++)
  113471. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113472. if(vc->user_comments)_ogg_free(vc->user_comments);
  113473. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113474. if(vc->vendor)_ogg_free(vc->vendor);
  113475. }
  113476. memset(vc,0,sizeof(*vc));
  113477. }
  113478. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113479. They may be equal, but short will never ge greater than long */
  113480. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113481. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113482. return ci ? ci->blocksizes[zo] : -1;
  113483. }
  113484. /* used by synthesis, which has a full, alloced vi */
  113485. void vorbis_info_init(vorbis_info *vi){
  113486. memset(vi,0,sizeof(*vi));
  113487. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113488. }
  113489. void vorbis_info_clear(vorbis_info *vi){
  113490. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113491. int i;
  113492. if(ci){
  113493. for(i=0;i<ci->modes;i++)
  113494. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113495. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113496. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113497. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113498. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113499. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113500. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113501. for(i=0;i<ci->books;i++){
  113502. if(ci->book_param[i]){
  113503. /* knows if the book was not alloced */
  113504. vorbis_staticbook_destroy(ci->book_param[i]);
  113505. }
  113506. if(ci->fullbooks)
  113507. vorbis_book_clear(ci->fullbooks+i);
  113508. }
  113509. if(ci->fullbooks)
  113510. _ogg_free(ci->fullbooks);
  113511. for(i=0;i<ci->psys;i++)
  113512. _vi_psy_free(ci->psy_param[i]);
  113513. _ogg_free(ci);
  113514. }
  113515. memset(vi,0,sizeof(*vi));
  113516. }
  113517. /* Header packing/unpacking ********************************************/
  113518. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113519. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113520. if(!ci)return(OV_EFAULT);
  113521. vi->version=oggpack_read(opb,32);
  113522. if(vi->version!=0)return(OV_EVERSION);
  113523. vi->channels=oggpack_read(opb,8);
  113524. vi->rate=oggpack_read(opb,32);
  113525. vi->bitrate_upper=oggpack_read(opb,32);
  113526. vi->bitrate_nominal=oggpack_read(opb,32);
  113527. vi->bitrate_lower=oggpack_read(opb,32);
  113528. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113529. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113530. if(vi->rate<1)goto err_out;
  113531. if(vi->channels<1)goto err_out;
  113532. if(ci->blocksizes[0]<8)goto err_out;
  113533. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113534. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113535. return(0);
  113536. err_out:
  113537. vorbis_info_clear(vi);
  113538. return(OV_EBADHEADER);
  113539. }
  113540. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113541. int i;
  113542. int vendorlen=oggpack_read(opb,32);
  113543. if(vendorlen<0)goto err_out;
  113544. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113545. _v_readstring(opb,vc->vendor,vendorlen);
  113546. vc->comments=oggpack_read(opb,32);
  113547. if(vc->comments<0)goto err_out;
  113548. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113549. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113550. for(i=0;i<vc->comments;i++){
  113551. int len=oggpack_read(opb,32);
  113552. if(len<0)goto err_out;
  113553. vc->comment_lengths[i]=len;
  113554. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113555. _v_readstring(opb,vc->user_comments[i],len);
  113556. }
  113557. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113558. return(0);
  113559. err_out:
  113560. vorbis_comment_clear(vc);
  113561. return(OV_EBADHEADER);
  113562. }
  113563. /* all of the real encoding details are here. The modes, books,
  113564. everything */
  113565. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113566. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113567. int i;
  113568. if(!ci)return(OV_EFAULT);
  113569. /* codebooks */
  113570. ci->books=oggpack_read(opb,8)+1;
  113571. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113572. for(i=0;i<ci->books;i++){
  113573. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113574. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113575. }
  113576. /* time backend settings; hooks are unused */
  113577. {
  113578. int times=oggpack_read(opb,6)+1;
  113579. for(i=0;i<times;i++){
  113580. int test=oggpack_read(opb,16);
  113581. if(test<0 || test>=VI_TIMEB)goto err_out;
  113582. }
  113583. }
  113584. /* floor backend settings */
  113585. ci->floors=oggpack_read(opb,6)+1;
  113586. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113587. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113588. for(i=0;i<ci->floors;i++){
  113589. ci->floor_type[i]=oggpack_read(opb,16);
  113590. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113591. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113592. if(!ci->floor_param[i])goto err_out;
  113593. }
  113594. /* residue backend settings */
  113595. ci->residues=oggpack_read(opb,6)+1;
  113596. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113597. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113598. for(i=0;i<ci->residues;i++){
  113599. ci->residue_type[i]=oggpack_read(opb,16);
  113600. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113601. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113602. if(!ci->residue_param[i])goto err_out;
  113603. }
  113604. /* map backend settings */
  113605. ci->maps=oggpack_read(opb,6)+1;
  113606. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113607. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113608. for(i=0;i<ci->maps;i++){
  113609. ci->map_type[i]=oggpack_read(opb,16);
  113610. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113611. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113612. if(!ci->map_param[i])goto err_out;
  113613. }
  113614. /* mode settings */
  113615. ci->modes=oggpack_read(opb,6)+1;
  113616. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113617. for(i=0;i<ci->modes;i++){
  113618. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113619. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113620. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113621. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113622. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113623. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113624. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113625. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113626. }
  113627. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113628. return(0);
  113629. err_out:
  113630. vorbis_info_clear(vi);
  113631. return(OV_EBADHEADER);
  113632. }
  113633. /* The Vorbis header is in three packets; the initial small packet in
  113634. the first page that identifies basic parameters, a second packet
  113635. with bitstream comments and a third packet that holds the
  113636. codebook. */
  113637. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113638. oggpack_buffer opb;
  113639. if(op){
  113640. oggpack_readinit(&opb,op->packet,op->bytes);
  113641. /* Which of the three types of header is this? */
  113642. /* Also verify header-ness, vorbis */
  113643. {
  113644. char buffer[6];
  113645. int packtype=oggpack_read(&opb,8);
  113646. memset(buffer,0,6);
  113647. _v_readstring(&opb,buffer,6);
  113648. if(memcmp(buffer,"vorbis",6)){
  113649. /* not a vorbis header */
  113650. return(OV_ENOTVORBIS);
  113651. }
  113652. switch(packtype){
  113653. case 0x01: /* least significant *bit* is read first */
  113654. if(!op->b_o_s){
  113655. /* Not the initial packet */
  113656. return(OV_EBADHEADER);
  113657. }
  113658. if(vi->rate!=0){
  113659. /* previously initialized info header */
  113660. return(OV_EBADHEADER);
  113661. }
  113662. return(_vorbis_unpack_info(vi,&opb));
  113663. case 0x03: /* least significant *bit* is read first */
  113664. if(vi->rate==0){
  113665. /* um... we didn't get the initial header */
  113666. return(OV_EBADHEADER);
  113667. }
  113668. return(_vorbis_unpack_comment(vc,&opb));
  113669. case 0x05: /* least significant *bit* is read first */
  113670. if(vi->rate==0 || vc->vendor==NULL){
  113671. /* um... we didn;t get the initial header or comments yet */
  113672. return(OV_EBADHEADER);
  113673. }
  113674. return(_vorbis_unpack_books(vi,&opb));
  113675. default:
  113676. /* Not a valid vorbis header type */
  113677. return(OV_EBADHEADER);
  113678. break;
  113679. }
  113680. }
  113681. }
  113682. return(OV_EBADHEADER);
  113683. }
  113684. /* pack side **********************************************************/
  113685. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113686. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113687. if(!ci)return(OV_EFAULT);
  113688. /* preamble */
  113689. oggpack_write(opb,0x01,8);
  113690. _v_writestring(opb,"vorbis", 6);
  113691. /* basic information about the stream */
  113692. oggpack_write(opb,0x00,32);
  113693. oggpack_write(opb,vi->channels,8);
  113694. oggpack_write(opb,vi->rate,32);
  113695. oggpack_write(opb,vi->bitrate_upper,32);
  113696. oggpack_write(opb,vi->bitrate_nominal,32);
  113697. oggpack_write(opb,vi->bitrate_lower,32);
  113698. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113699. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113700. oggpack_write(opb,1,1);
  113701. return(0);
  113702. }
  113703. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113704. char temp[]="Xiph.Org libVorbis I 20050304";
  113705. int bytes = strlen(temp);
  113706. /* preamble */
  113707. oggpack_write(opb,0x03,8);
  113708. _v_writestring(opb,"vorbis", 6);
  113709. /* vendor */
  113710. oggpack_write(opb,bytes,32);
  113711. _v_writestring(opb,temp, bytes);
  113712. /* comments */
  113713. oggpack_write(opb,vc->comments,32);
  113714. if(vc->comments){
  113715. int i;
  113716. for(i=0;i<vc->comments;i++){
  113717. if(vc->user_comments[i]){
  113718. oggpack_write(opb,vc->comment_lengths[i],32);
  113719. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113720. }else{
  113721. oggpack_write(opb,0,32);
  113722. }
  113723. }
  113724. }
  113725. oggpack_write(opb,1,1);
  113726. return(0);
  113727. }
  113728. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113729. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113730. int i;
  113731. if(!ci)return(OV_EFAULT);
  113732. oggpack_write(opb,0x05,8);
  113733. _v_writestring(opb,"vorbis", 6);
  113734. /* books */
  113735. oggpack_write(opb,ci->books-1,8);
  113736. for(i=0;i<ci->books;i++)
  113737. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113738. /* times; hook placeholders */
  113739. oggpack_write(opb,0,6);
  113740. oggpack_write(opb,0,16);
  113741. /* floors */
  113742. oggpack_write(opb,ci->floors-1,6);
  113743. for(i=0;i<ci->floors;i++){
  113744. oggpack_write(opb,ci->floor_type[i],16);
  113745. if(_floor_P[ci->floor_type[i]]->pack)
  113746. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113747. else
  113748. goto err_out;
  113749. }
  113750. /* residues */
  113751. oggpack_write(opb,ci->residues-1,6);
  113752. for(i=0;i<ci->residues;i++){
  113753. oggpack_write(opb,ci->residue_type[i],16);
  113754. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113755. }
  113756. /* maps */
  113757. oggpack_write(opb,ci->maps-1,6);
  113758. for(i=0;i<ci->maps;i++){
  113759. oggpack_write(opb,ci->map_type[i],16);
  113760. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113761. }
  113762. /* modes */
  113763. oggpack_write(opb,ci->modes-1,6);
  113764. for(i=0;i<ci->modes;i++){
  113765. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113766. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113767. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113768. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113769. }
  113770. oggpack_write(opb,1,1);
  113771. return(0);
  113772. err_out:
  113773. return(-1);
  113774. }
  113775. int vorbis_commentheader_out(vorbis_comment *vc,
  113776. ogg_packet *op){
  113777. oggpack_buffer opb;
  113778. oggpack_writeinit(&opb);
  113779. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113780. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113781. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113782. op->bytes=oggpack_bytes(&opb);
  113783. op->b_o_s=0;
  113784. op->e_o_s=0;
  113785. op->granulepos=0;
  113786. op->packetno=1;
  113787. return 0;
  113788. }
  113789. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113790. vorbis_comment *vc,
  113791. ogg_packet *op,
  113792. ogg_packet *op_comm,
  113793. ogg_packet *op_code){
  113794. int ret=OV_EIMPL;
  113795. vorbis_info *vi=v->vi;
  113796. oggpack_buffer opb;
  113797. private_state *b=(private_state*)v->backend_state;
  113798. if(!b){
  113799. ret=OV_EFAULT;
  113800. goto err_out;
  113801. }
  113802. /* first header packet **********************************************/
  113803. oggpack_writeinit(&opb);
  113804. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113805. /* build the packet */
  113806. if(b->header)_ogg_free(b->header);
  113807. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113808. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113809. op->packet=b->header;
  113810. op->bytes=oggpack_bytes(&opb);
  113811. op->b_o_s=1;
  113812. op->e_o_s=0;
  113813. op->granulepos=0;
  113814. op->packetno=0;
  113815. /* second header packet (comments) **********************************/
  113816. oggpack_reset(&opb);
  113817. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113818. if(b->header1)_ogg_free(b->header1);
  113819. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113820. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113821. op_comm->packet=b->header1;
  113822. op_comm->bytes=oggpack_bytes(&opb);
  113823. op_comm->b_o_s=0;
  113824. op_comm->e_o_s=0;
  113825. op_comm->granulepos=0;
  113826. op_comm->packetno=1;
  113827. /* third header packet (modes/codebooks) ****************************/
  113828. oggpack_reset(&opb);
  113829. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113830. if(b->header2)_ogg_free(b->header2);
  113831. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113832. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113833. op_code->packet=b->header2;
  113834. op_code->bytes=oggpack_bytes(&opb);
  113835. op_code->b_o_s=0;
  113836. op_code->e_o_s=0;
  113837. op_code->granulepos=0;
  113838. op_code->packetno=2;
  113839. oggpack_writeclear(&opb);
  113840. return(0);
  113841. err_out:
  113842. oggpack_writeclear(&opb);
  113843. memset(op,0,sizeof(*op));
  113844. memset(op_comm,0,sizeof(*op_comm));
  113845. memset(op_code,0,sizeof(*op_code));
  113846. if(b->header)_ogg_free(b->header);
  113847. if(b->header1)_ogg_free(b->header1);
  113848. if(b->header2)_ogg_free(b->header2);
  113849. b->header=NULL;
  113850. b->header1=NULL;
  113851. b->header2=NULL;
  113852. return(ret);
  113853. }
  113854. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113855. if(granulepos>=0)
  113856. return((double)granulepos/v->vi->rate);
  113857. return(-1);
  113858. }
  113859. #endif
  113860. /*** End of inlined file: info.c ***/
  113861. /*** Start of inlined file: lpc.c ***/
  113862. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113863. are derived from code written by Jutta Degener and Carsten Bormann;
  113864. thus we include their copyright below. The entirety of this file
  113865. is freely redistributable on the condition that both of these
  113866. copyright notices are preserved without modification. */
  113867. /* Preserved Copyright: *********************************************/
  113868. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113869. Technische Universita"t Berlin
  113870. Any use of this software is permitted provided that this notice is not
  113871. removed and that neither the authors nor the Technische Universita"t
  113872. Berlin are deemed to have made any representations as to the
  113873. suitability of this software for any purpose nor are held responsible
  113874. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113875. THIS SOFTWARE.
  113876. As a matter of courtesy, the authors request to be informed about uses
  113877. this software has found, about bugs in this software, and about any
  113878. improvements that may be of general interest.
  113879. Berlin, 28.11.1994
  113880. Jutta Degener
  113881. Carsten Bormann
  113882. *********************************************************************/
  113883. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113884. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113885. // tasks..
  113886. #if JUCE_MSVC
  113887. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113888. #endif
  113889. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113890. #if JUCE_USE_OGGVORBIS
  113891. #include <stdlib.h>
  113892. #include <string.h>
  113893. #include <math.h>
  113894. /* Autocorrelation LPC coeff generation algorithm invented by
  113895. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113896. /* Input : n elements of time doamin data
  113897. Output: m lpc coefficients, excitation energy */
  113898. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113899. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113900. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113901. double error;
  113902. int i,j;
  113903. /* autocorrelation, p+1 lag coefficients */
  113904. j=m+1;
  113905. while(j--){
  113906. double d=0; /* double needed for accumulator depth */
  113907. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113908. aut[j]=d;
  113909. }
  113910. /* Generate lpc coefficients from autocorr values */
  113911. error=aut[0];
  113912. for(i=0;i<m;i++){
  113913. double r= -aut[i+1];
  113914. if(error==0){
  113915. memset(lpci,0,m*sizeof(*lpci));
  113916. return 0;
  113917. }
  113918. /* Sum up this iteration's reflection coefficient; note that in
  113919. Vorbis we don't save it. If anyone wants to recycle this code
  113920. and needs reflection coefficients, save the results of 'r' from
  113921. each iteration. */
  113922. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113923. r/=error;
  113924. /* Update LPC coefficients and total error */
  113925. lpc[i]=r;
  113926. for(j=0;j<i/2;j++){
  113927. double tmp=lpc[j];
  113928. lpc[j]+=r*lpc[i-1-j];
  113929. lpc[i-1-j]+=r*tmp;
  113930. }
  113931. if(i%2)lpc[j]+=lpc[j]*r;
  113932. error*=1.f-r*r;
  113933. }
  113934. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113935. /* we need the error value to know how big an impulse to hit the
  113936. filter with later */
  113937. return error;
  113938. }
  113939. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113940. float *data,long n){
  113941. /* in: coeff[0...m-1] LPC coefficients
  113942. prime[0...m-1] initial values (allocated size of n+m-1)
  113943. out: data[0...n-1] data samples */
  113944. long i,j,o,p;
  113945. float y;
  113946. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113947. if(!prime)
  113948. for(i=0;i<m;i++)
  113949. work[i]=0.f;
  113950. else
  113951. for(i=0;i<m;i++)
  113952. work[i]=prime[i];
  113953. for(i=0;i<n;i++){
  113954. y=0;
  113955. o=i;
  113956. p=m;
  113957. for(j=0;j<m;j++)
  113958. y-=work[o++]*coeff[--p];
  113959. data[i]=work[o]=y;
  113960. }
  113961. }
  113962. #endif
  113963. /*** End of inlined file: lpc.c ***/
  113964. /*** Start of inlined file: lsp.c ***/
  113965. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113966. an iterative root polisher (CACM algorithm 283). It *is* possible
  113967. to confuse this algorithm into not converging; that should only
  113968. happen with absurdly closely spaced roots (very sharp peaks in the
  113969. LPC f response) which in turn should be impossible in our use of
  113970. the code. If this *does* happen anyway, it's a bug in the floor
  113971. finder; find the cause of the confusion (probably a single bin
  113972. spike or accidental near-float-limit resolution problems) and
  113973. correct it. */
  113974. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113975. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113976. // tasks..
  113977. #if JUCE_MSVC
  113978. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113979. #endif
  113980. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113981. #if JUCE_USE_OGGVORBIS
  113982. #include <math.h>
  113983. #include <string.h>
  113984. #include <stdlib.h>
  113985. /*** Start of inlined file: lookup.h ***/
  113986. #ifndef _V_LOOKUP_H_
  113987. #ifdef FLOAT_LOOKUP
  113988. extern float vorbis_coslook(float a);
  113989. extern float vorbis_invsqlook(float a);
  113990. extern float vorbis_invsq2explook(int a);
  113991. extern float vorbis_fromdBlook(float a);
  113992. #endif
  113993. #ifdef INT_LOOKUP
  113994. extern long vorbis_invsqlook_i(long a,long e);
  113995. extern long vorbis_coslook_i(long a);
  113996. extern float vorbis_fromdBlook_i(long a);
  113997. #endif
  113998. #endif
  113999. /*** End of inlined file: lookup.h ***/
  114000. /* three possible LSP to f curve functions; the exact computation
  114001. (float), a lookup based float implementation, and an integer
  114002. implementation. The float lookup is likely the optimal choice on
  114003. any machine with an FPU. The integer implementation is *not* fixed
  114004. point (due to the need for a large dynamic range and thus a
  114005. seperately tracked exponent) and thus much more complex than the
  114006. relatively simple float implementations. It's mostly for future
  114007. work on a fully fixed point implementation for processors like the
  114008. ARM family. */
  114009. /* undefine both for the 'old' but more precise implementation */
  114010. #define FLOAT_LOOKUP
  114011. #undef INT_LOOKUP
  114012. #ifdef FLOAT_LOOKUP
  114013. /*** Start of inlined file: lookup.c ***/
  114014. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114015. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114016. // tasks..
  114017. #if JUCE_MSVC
  114018. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114019. #endif
  114020. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114021. #if JUCE_USE_OGGVORBIS
  114022. #include <math.h>
  114023. /*** Start of inlined file: lookup.h ***/
  114024. #ifndef _V_LOOKUP_H_
  114025. #ifdef FLOAT_LOOKUP
  114026. extern float vorbis_coslook(float a);
  114027. extern float vorbis_invsqlook(float a);
  114028. extern float vorbis_invsq2explook(int a);
  114029. extern float vorbis_fromdBlook(float a);
  114030. #endif
  114031. #ifdef INT_LOOKUP
  114032. extern long vorbis_invsqlook_i(long a,long e);
  114033. extern long vorbis_coslook_i(long a);
  114034. extern float vorbis_fromdBlook_i(long a);
  114035. #endif
  114036. #endif
  114037. /*** End of inlined file: lookup.h ***/
  114038. /*** Start of inlined file: lookup_data.h ***/
  114039. #ifndef _V_LOOKUP_DATA_H_
  114040. #ifdef FLOAT_LOOKUP
  114041. #define COS_LOOKUP_SZ 128
  114042. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114043. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114044. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114045. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114046. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114047. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114048. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114049. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114050. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114051. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114052. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114053. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114054. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114055. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114056. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114057. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114058. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114059. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114060. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114061. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114062. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114063. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114064. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114065. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114066. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114067. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114068. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114069. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114070. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114071. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114072. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114073. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114074. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114075. -1.0000000000000f,
  114076. };
  114077. #define INVSQ_LOOKUP_SZ 32
  114078. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114079. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114080. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114081. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114082. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114083. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114084. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114085. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114086. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114087. 1.000000000000f,
  114088. };
  114089. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114090. #define INVSQ2EXP_LOOKUP_MAX 32
  114091. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114092. INVSQ2EXP_LOOKUP_MIN+1]={
  114093. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114094. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114095. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114096. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114097. 256.f, 181.019336f, 128.f, 90.50966799f,
  114098. 64.f, 45.254834f, 32.f, 22.627417f,
  114099. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114100. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114101. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114102. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114103. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114104. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114105. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114106. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114107. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114108. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114109. 1.525878906e-05f,
  114110. };
  114111. #endif
  114112. #define FROMdB_LOOKUP_SZ 35
  114113. #define FROMdB2_LOOKUP_SZ 32
  114114. #define FROMdB_SHIFT 5
  114115. #define FROMdB2_SHIFT 3
  114116. #define FROMdB2_MASK 31
  114117. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114118. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114119. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114120. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114121. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114122. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114123. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114124. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114125. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114126. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114127. };
  114128. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114129. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114130. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114131. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114132. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114133. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114134. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114135. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114136. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114137. };
  114138. #ifdef INT_LOOKUP
  114139. #define INVSQ_LOOKUP_I_SHIFT 10
  114140. #define INVSQ_LOOKUP_I_MASK 1023
  114141. static long INVSQ_LOOKUP_I[64+1]={
  114142. 92682l, 91966l, 91267l, 90583l,
  114143. 89915l, 89261l, 88621l, 87995l,
  114144. 87381l, 86781l, 86192l, 85616l,
  114145. 85051l, 84497l, 83953l, 83420l,
  114146. 82897l, 82384l, 81880l, 81385l,
  114147. 80899l, 80422l, 79953l, 79492l,
  114148. 79039l, 78594l, 78156l, 77726l,
  114149. 77302l, 76885l, 76475l, 76072l,
  114150. 75674l, 75283l, 74898l, 74519l,
  114151. 74146l, 73778l, 73415l, 73058l,
  114152. 72706l, 72359l, 72016l, 71679l,
  114153. 71347l, 71019l, 70695l, 70376l,
  114154. 70061l, 69750l, 69444l, 69141l,
  114155. 68842l, 68548l, 68256l, 67969l,
  114156. 67685l, 67405l, 67128l, 66855l,
  114157. 66585l, 66318l, 66054l, 65794l,
  114158. 65536l,
  114159. };
  114160. #define COS_LOOKUP_I_SHIFT 9
  114161. #define COS_LOOKUP_I_MASK 511
  114162. #define COS_LOOKUP_I_SZ 128
  114163. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114164. 16384l, 16379l, 16364l, 16340l,
  114165. 16305l, 16261l, 16207l, 16143l,
  114166. 16069l, 15986l, 15893l, 15791l,
  114167. 15679l, 15557l, 15426l, 15286l,
  114168. 15137l, 14978l, 14811l, 14635l,
  114169. 14449l, 14256l, 14053l, 13842l,
  114170. 13623l, 13395l, 13160l, 12916l,
  114171. 12665l, 12406l, 12140l, 11866l,
  114172. 11585l, 11297l, 11003l, 10702l,
  114173. 10394l, 10080l, 9760l, 9434l,
  114174. 9102l, 8765l, 8423l, 8076l,
  114175. 7723l, 7366l, 7005l, 6639l,
  114176. 6270l, 5897l, 5520l, 5139l,
  114177. 4756l, 4370l, 3981l, 3590l,
  114178. 3196l, 2801l, 2404l, 2006l,
  114179. 1606l, 1205l, 804l, 402l,
  114180. 0l, -401l, -803l, -1204l,
  114181. -1605l, -2005l, -2403l, -2800l,
  114182. -3195l, -3589l, -3980l, -4369l,
  114183. -4755l, -5138l, -5519l, -5896l,
  114184. -6269l, -6638l, -7004l, -7365l,
  114185. -7722l, -8075l, -8422l, -8764l,
  114186. -9101l, -9433l, -9759l, -10079l,
  114187. -10393l, -10701l, -11002l, -11296l,
  114188. -11584l, -11865l, -12139l, -12405l,
  114189. -12664l, -12915l, -13159l, -13394l,
  114190. -13622l, -13841l, -14052l, -14255l,
  114191. -14448l, -14634l, -14810l, -14977l,
  114192. -15136l, -15285l, -15425l, -15556l,
  114193. -15678l, -15790l, -15892l, -15985l,
  114194. -16068l, -16142l, -16206l, -16260l,
  114195. -16304l, -16339l, -16363l, -16378l,
  114196. -16383l,
  114197. };
  114198. #endif
  114199. #endif
  114200. /*** End of inlined file: lookup_data.h ***/
  114201. #ifdef FLOAT_LOOKUP
  114202. /* interpolated lookup based cos function, domain 0 to PI only */
  114203. float vorbis_coslook(float a){
  114204. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114205. int i=vorbis_ftoi(d-.5);
  114206. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114207. }
  114208. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114209. float vorbis_invsqlook(float a){
  114210. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114211. int i=vorbis_ftoi(d-.5f);
  114212. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114213. }
  114214. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114215. float vorbis_invsq2explook(int a){
  114216. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114217. }
  114218. #include <stdio.h>
  114219. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114220. float vorbis_fromdBlook(float a){
  114221. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114222. return (i<0)?1.f:
  114223. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114224. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114225. }
  114226. #endif
  114227. #ifdef INT_LOOKUP
  114228. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114229. 16.16 format
  114230. returns in m.8 format */
  114231. long vorbis_invsqlook_i(long a,long e){
  114232. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114233. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114234. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114235. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114236. d)>>16); /* result 1.16 */
  114237. e+=32;
  114238. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114239. e=(e>>1)-8;
  114240. return(val>>e);
  114241. }
  114242. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114243. /* a is in n.12 format */
  114244. float vorbis_fromdBlook_i(long a){
  114245. int i=(-a)>>(12-FROMdB2_SHIFT);
  114246. return (i<0)?1.f:
  114247. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114248. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114249. }
  114250. /* interpolated lookup based cos function, domain 0 to PI only */
  114251. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114252. long vorbis_coslook_i(long a){
  114253. int i=a>>COS_LOOKUP_I_SHIFT;
  114254. int d=a&COS_LOOKUP_I_MASK;
  114255. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114256. COS_LOOKUP_I_SHIFT);
  114257. }
  114258. #endif
  114259. #endif
  114260. /*** End of inlined file: lookup.c ***/
  114261. /* catch this in the build system; we #include for
  114262. compilers (like gcc) that can't inline across
  114263. modules */
  114264. /* side effect: changes *lsp to cosines of lsp */
  114265. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114266. float amp,float ampoffset){
  114267. int i;
  114268. float wdel=M_PI/ln;
  114269. vorbis_fpu_control fpu;
  114270. (void) fpu; // to avoid an unused variable warning
  114271. vorbis_fpu_setround(&fpu);
  114272. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114273. i=0;
  114274. while(i<n){
  114275. int k=map[i];
  114276. int qexp;
  114277. float p=.7071067812f;
  114278. float q=.7071067812f;
  114279. float w=vorbis_coslook(wdel*k);
  114280. float *ftmp=lsp;
  114281. int c=m>>1;
  114282. do{
  114283. q*=ftmp[0]-w;
  114284. p*=ftmp[1]-w;
  114285. ftmp+=2;
  114286. }while(--c);
  114287. if(m&1){
  114288. /* odd order filter; slightly assymetric */
  114289. /* the last coefficient */
  114290. q*=ftmp[0]-w;
  114291. q*=q;
  114292. p*=p*(1.f-w*w);
  114293. }else{
  114294. /* even order filter; still symmetric */
  114295. q*=q*(1.f+w);
  114296. p*=p*(1.f-w);
  114297. }
  114298. q=frexp(p+q,&qexp);
  114299. q=vorbis_fromdBlook(amp*
  114300. vorbis_invsqlook(q)*
  114301. vorbis_invsq2explook(qexp+m)-
  114302. ampoffset);
  114303. do{
  114304. curve[i++]*=q;
  114305. }while(map[i]==k);
  114306. }
  114307. vorbis_fpu_restore(fpu);
  114308. }
  114309. #else
  114310. #ifdef INT_LOOKUP
  114311. /*** Start of inlined file: lookup.c ***/
  114312. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114313. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114314. // tasks..
  114315. #if JUCE_MSVC
  114316. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114317. #endif
  114318. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114319. #if JUCE_USE_OGGVORBIS
  114320. #include <math.h>
  114321. /*** Start of inlined file: lookup.h ***/
  114322. #ifndef _V_LOOKUP_H_
  114323. #ifdef FLOAT_LOOKUP
  114324. extern float vorbis_coslook(float a);
  114325. extern float vorbis_invsqlook(float a);
  114326. extern float vorbis_invsq2explook(int a);
  114327. extern float vorbis_fromdBlook(float a);
  114328. #endif
  114329. #ifdef INT_LOOKUP
  114330. extern long vorbis_invsqlook_i(long a,long e);
  114331. extern long vorbis_coslook_i(long a);
  114332. extern float vorbis_fromdBlook_i(long a);
  114333. #endif
  114334. #endif
  114335. /*** End of inlined file: lookup.h ***/
  114336. /*** Start of inlined file: lookup_data.h ***/
  114337. #ifndef _V_LOOKUP_DATA_H_
  114338. #ifdef FLOAT_LOOKUP
  114339. #define COS_LOOKUP_SZ 128
  114340. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114341. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114342. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114343. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114344. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114345. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114346. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114347. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114348. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114349. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114350. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114351. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114352. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114353. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114354. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114355. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114356. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114357. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114358. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114359. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114360. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114361. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114362. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114363. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114364. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114365. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114366. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114367. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114368. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114369. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114370. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114371. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114372. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114373. -1.0000000000000f,
  114374. };
  114375. #define INVSQ_LOOKUP_SZ 32
  114376. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114377. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114378. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114379. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114380. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114381. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114382. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114383. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114384. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114385. 1.000000000000f,
  114386. };
  114387. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114388. #define INVSQ2EXP_LOOKUP_MAX 32
  114389. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114390. INVSQ2EXP_LOOKUP_MIN+1]={
  114391. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114392. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114393. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114394. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114395. 256.f, 181.019336f, 128.f, 90.50966799f,
  114396. 64.f, 45.254834f, 32.f, 22.627417f,
  114397. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114398. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114399. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114400. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114401. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114402. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114403. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114404. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114405. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114406. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114407. 1.525878906e-05f,
  114408. };
  114409. #endif
  114410. #define FROMdB_LOOKUP_SZ 35
  114411. #define FROMdB2_LOOKUP_SZ 32
  114412. #define FROMdB_SHIFT 5
  114413. #define FROMdB2_SHIFT 3
  114414. #define FROMdB2_MASK 31
  114415. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114416. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114417. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114418. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114419. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114420. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114421. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114422. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114423. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114424. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114425. };
  114426. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114427. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114428. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114429. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114430. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114431. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114432. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114433. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114434. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114435. };
  114436. #ifdef INT_LOOKUP
  114437. #define INVSQ_LOOKUP_I_SHIFT 10
  114438. #define INVSQ_LOOKUP_I_MASK 1023
  114439. static long INVSQ_LOOKUP_I[64+1]={
  114440. 92682l, 91966l, 91267l, 90583l,
  114441. 89915l, 89261l, 88621l, 87995l,
  114442. 87381l, 86781l, 86192l, 85616l,
  114443. 85051l, 84497l, 83953l, 83420l,
  114444. 82897l, 82384l, 81880l, 81385l,
  114445. 80899l, 80422l, 79953l, 79492l,
  114446. 79039l, 78594l, 78156l, 77726l,
  114447. 77302l, 76885l, 76475l, 76072l,
  114448. 75674l, 75283l, 74898l, 74519l,
  114449. 74146l, 73778l, 73415l, 73058l,
  114450. 72706l, 72359l, 72016l, 71679l,
  114451. 71347l, 71019l, 70695l, 70376l,
  114452. 70061l, 69750l, 69444l, 69141l,
  114453. 68842l, 68548l, 68256l, 67969l,
  114454. 67685l, 67405l, 67128l, 66855l,
  114455. 66585l, 66318l, 66054l, 65794l,
  114456. 65536l,
  114457. };
  114458. #define COS_LOOKUP_I_SHIFT 9
  114459. #define COS_LOOKUP_I_MASK 511
  114460. #define COS_LOOKUP_I_SZ 128
  114461. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114462. 16384l, 16379l, 16364l, 16340l,
  114463. 16305l, 16261l, 16207l, 16143l,
  114464. 16069l, 15986l, 15893l, 15791l,
  114465. 15679l, 15557l, 15426l, 15286l,
  114466. 15137l, 14978l, 14811l, 14635l,
  114467. 14449l, 14256l, 14053l, 13842l,
  114468. 13623l, 13395l, 13160l, 12916l,
  114469. 12665l, 12406l, 12140l, 11866l,
  114470. 11585l, 11297l, 11003l, 10702l,
  114471. 10394l, 10080l, 9760l, 9434l,
  114472. 9102l, 8765l, 8423l, 8076l,
  114473. 7723l, 7366l, 7005l, 6639l,
  114474. 6270l, 5897l, 5520l, 5139l,
  114475. 4756l, 4370l, 3981l, 3590l,
  114476. 3196l, 2801l, 2404l, 2006l,
  114477. 1606l, 1205l, 804l, 402l,
  114478. 0l, -401l, -803l, -1204l,
  114479. -1605l, -2005l, -2403l, -2800l,
  114480. -3195l, -3589l, -3980l, -4369l,
  114481. -4755l, -5138l, -5519l, -5896l,
  114482. -6269l, -6638l, -7004l, -7365l,
  114483. -7722l, -8075l, -8422l, -8764l,
  114484. -9101l, -9433l, -9759l, -10079l,
  114485. -10393l, -10701l, -11002l, -11296l,
  114486. -11584l, -11865l, -12139l, -12405l,
  114487. -12664l, -12915l, -13159l, -13394l,
  114488. -13622l, -13841l, -14052l, -14255l,
  114489. -14448l, -14634l, -14810l, -14977l,
  114490. -15136l, -15285l, -15425l, -15556l,
  114491. -15678l, -15790l, -15892l, -15985l,
  114492. -16068l, -16142l, -16206l, -16260l,
  114493. -16304l, -16339l, -16363l, -16378l,
  114494. -16383l,
  114495. };
  114496. #endif
  114497. #endif
  114498. /*** End of inlined file: lookup_data.h ***/
  114499. #ifdef FLOAT_LOOKUP
  114500. /* interpolated lookup based cos function, domain 0 to PI only */
  114501. float vorbis_coslook(float a){
  114502. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114503. int i=vorbis_ftoi(d-.5);
  114504. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114505. }
  114506. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114507. float vorbis_invsqlook(float a){
  114508. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114509. int i=vorbis_ftoi(d-.5f);
  114510. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114511. }
  114512. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114513. float vorbis_invsq2explook(int a){
  114514. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114515. }
  114516. #include <stdio.h>
  114517. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114518. float vorbis_fromdBlook(float a){
  114519. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114520. return (i<0)?1.f:
  114521. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114522. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114523. }
  114524. #endif
  114525. #ifdef INT_LOOKUP
  114526. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114527. 16.16 format
  114528. returns in m.8 format */
  114529. long vorbis_invsqlook_i(long a,long e){
  114530. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114531. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114532. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114533. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114534. d)>>16); /* result 1.16 */
  114535. e+=32;
  114536. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114537. e=(e>>1)-8;
  114538. return(val>>e);
  114539. }
  114540. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114541. /* a is in n.12 format */
  114542. float vorbis_fromdBlook_i(long a){
  114543. int i=(-a)>>(12-FROMdB2_SHIFT);
  114544. return (i<0)?1.f:
  114545. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114546. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114547. }
  114548. /* interpolated lookup based cos function, domain 0 to PI only */
  114549. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114550. long vorbis_coslook_i(long a){
  114551. int i=a>>COS_LOOKUP_I_SHIFT;
  114552. int d=a&COS_LOOKUP_I_MASK;
  114553. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114554. COS_LOOKUP_I_SHIFT);
  114555. }
  114556. #endif
  114557. #endif
  114558. /*** End of inlined file: lookup.c ***/
  114559. /* catch this in the build system; we #include for
  114560. compilers (like gcc) that can't inline across
  114561. modules */
  114562. static int MLOOP_1[64]={
  114563. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114564. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114565. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114566. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114567. };
  114568. static int MLOOP_2[64]={
  114569. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114570. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114571. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114572. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114573. };
  114574. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114575. /* side effect: changes *lsp to cosines of lsp */
  114576. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114577. float amp,float ampoffset){
  114578. /* 0 <= m < 256 */
  114579. /* set up for using all int later */
  114580. int i;
  114581. int ampoffseti=rint(ampoffset*4096.f);
  114582. int ampi=rint(amp*16.f);
  114583. long *ilsp=alloca(m*sizeof(*ilsp));
  114584. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114585. i=0;
  114586. while(i<n){
  114587. int j,k=map[i];
  114588. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114589. unsigned long qi=46341;
  114590. int qexp=0,shift;
  114591. long wi=vorbis_coslook_i(k*65536/ln);
  114592. qi*=labs(ilsp[0]-wi);
  114593. pi*=labs(ilsp[1]-wi);
  114594. for(j=3;j<m;j+=2){
  114595. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114596. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114597. shift=MLOOP_3[(pi|qi)>>16];
  114598. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114599. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114600. qexp+=shift;
  114601. }
  114602. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114603. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114604. shift=MLOOP_3[(pi|qi)>>16];
  114605. /* pi,qi normalized collectively, both tracked using qexp */
  114606. if(m&1){
  114607. /* odd order filter; slightly assymetric */
  114608. /* the last coefficient */
  114609. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114610. pi=(pi>>shift)<<14;
  114611. qexp+=shift;
  114612. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114613. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114614. shift=MLOOP_3[(pi|qi)>>16];
  114615. pi>>=shift;
  114616. qi>>=shift;
  114617. qexp+=shift-14*((m+1)>>1);
  114618. pi=((pi*pi)>>16);
  114619. qi=((qi*qi)>>16);
  114620. qexp=qexp*2+m;
  114621. pi*=(1<<14)-((wi*wi)>>14);
  114622. qi+=pi>>14;
  114623. }else{
  114624. /* even order filter; still symmetric */
  114625. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114626. worth tracking step by step */
  114627. pi>>=shift;
  114628. qi>>=shift;
  114629. qexp+=shift-7*m;
  114630. pi=((pi*pi)>>16);
  114631. qi=((qi*qi)>>16);
  114632. qexp=qexp*2+m;
  114633. pi*=(1<<14)-wi;
  114634. qi*=(1<<14)+wi;
  114635. qi=(qi+pi)>>14;
  114636. }
  114637. /* we've let the normalization drift because it wasn't important;
  114638. however, for the lookup, things must be normalized again. We
  114639. need at most one right shift or a number of left shifts */
  114640. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114641. qi>>=1; qexp++;
  114642. }else
  114643. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114644. qi<<=1; qexp--;
  114645. }
  114646. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114647. vorbis_invsqlook_i(qi,qexp)-
  114648. /* m.8, m+n<=8 */
  114649. ampoffseti); /* 8.12[0] */
  114650. curve[i]*=amp;
  114651. while(map[++i]==k)curve[i]*=amp;
  114652. }
  114653. }
  114654. #else
  114655. /* old, nonoptimized but simple version for any poor sap who needs to
  114656. figure out what the hell this code does, or wants the other
  114657. fraction of a dB precision */
  114658. /* side effect: changes *lsp to cosines of lsp */
  114659. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114660. float amp,float ampoffset){
  114661. int i;
  114662. float wdel=M_PI/ln;
  114663. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114664. i=0;
  114665. while(i<n){
  114666. int j,k=map[i];
  114667. float p=.5f;
  114668. float q=.5f;
  114669. float w=2.f*cos(wdel*k);
  114670. for(j=1;j<m;j+=2){
  114671. q *= w-lsp[j-1];
  114672. p *= w-lsp[j];
  114673. }
  114674. if(j==m){
  114675. /* odd order filter; slightly assymetric */
  114676. /* the last coefficient */
  114677. q*=w-lsp[j-1];
  114678. p*=p*(4.f-w*w);
  114679. q*=q;
  114680. }else{
  114681. /* even order filter; still symmetric */
  114682. p*=p*(2.f-w);
  114683. q*=q*(2.f+w);
  114684. }
  114685. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114686. curve[i]*=q;
  114687. while(map[++i]==k)curve[i]*=q;
  114688. }
  114689. }
  114690. #endif
  114691. #endif
  114692. static void cheby(float *g, int ord) {
  114693. int i, j;
  114694. g[0] *= .5f;
  114695. for(i=2; i<= ord; i++) {
  114696. for(j=ord; j >= i; j--) {
  114697. g[j-2] -= g[j];
  114698. g[j] += g[j];
  114699. }
  114700. }
  114701. }
  114702. static int JUCE_CDECL comp(const void *a,const void *b){
  114703. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114704. }
  114705. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114706. but there are root sets for which it gets into limit cycles
  114707. (exacerbated by zero suppression) and fails. We can't afford to
  114708. fail, even if the failure is 1 in 100,000,000, so we now use
  114709. Laguerre and later polish with Newton-Raphson (which can then
  114710. afford to fail) */
  114711. #define EPSILON 10e-7
  114712. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114713. int i,m;
  114714. double lastdelta=0.f;
  114715. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114716. for(i=0;i<=ord;i++)defl[i]=a[i];
  114717. for(m=ord;m>0;m--){
  114718. double newx=0.f,delta;
  114719. /* iterate a root */
  114720. while(1){
  114721. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114722. /* eval the polynomial and its first two derivatives */
  114723. for(i=m;i>0;i--){
  114724. ppp = newx*ppp + pp;
  114725. pp = newx*pp + p;
  114726. p = newx*p + defl[i-1];
  114727. }
  114728. /* Laguerre's method */
  114729. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114730. if(denom<0)
  114731. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114732. if(pp>0){
  114733. denom = pp + sqrt(denom);
  114734. if(denom<EPSILON)denom=EPSILON;
  114735. }else{
  114736. denom = pp - sqrt(denom);
  114737. if(denom>-(EPSILON))denom=-(EPSILON);
  114738. }
  114739. delta = m*p/denom;
  114740. newx -= delta;
  114741. if(delta<0.f)delta*=-1;
  114742. if(fabs(delta/newx)<10e-12)break;
  114743. lastdelta=delta;
  114744. }
  114745. r[m-1]=newx;
  114746. /* forward deflation */
  114747. for(i=m;i>0;i--)
  114748. defl[i-1]+=newx*defl[i];
  114749. defl++;
  114750. }
  114751. return(0);
  114752. }
  114753. /* for spit-and-polish only */
  114754. static int Newton_Raphson(float *a,int ord,float *r){
  114755. int i, k, count=0;
  114756. double error=1.f;
  114757. double *root=(double*)alloca(ord*sizeof(*root));
  114758. for(i=0; i<ord;i++) root[i] = r[i];
  114759. while(error>1e-20){
  114760. error=0;
  114761. for(i=0; i<ord; i++) { /* Update each point. */
  114762. double pp=0.,delta;
  114763. double rooti=root[i];
  114764. double p=a[ord];
  114765. for(k=ord-1; k>= 0; k--) {
  114766. pp= pp* rooti + p;
  114767. p = p * rooti + a[k];
  114768. }
  114769. delta = p/pp;
  114770. root[i] -= delta;
  114771. error+= delta*delta;
  114772. }
  114773. if(count>40)return(-1);
  114774. count++;
  114775. }
  114776. /* Replaced the original bubble sort with a real sort. With your
  114777. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114778. for(i=0; i<ord;i++) r[i] = root[i];
  114779. return(0);
  114780. }
  114781. /* Convert lpc coefficients to lsp coefficients */
  114782. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114783. int order2=(m+1)>>1;
  114784. int g1_order,g2_order;
  114785. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114786. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114787. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114788. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114789. int i;
  114790. /* even and odd are slightly different base cases */
  114791. g1_order=(m+1)>>1;
  114792. g2_order=(m) >>1;
  114793. /* Compute the lengths of the x polynomials. */
  114794. /* Compute the first half of K & R F1 & F2 polynomials. */
  114795. /* Compute half of the symmetric and antisymmetric polynomials. */
  114796. /* Remove the roots at +1 and -1. */
  114797. g1[g1_order] = 1.f;
  114798. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114799. g2[g2_order] = 1.f;
  114800. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114801. if(g1_order>g2_order){
  114802. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114803. }else{
  114804. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114805. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114806. }
  114807. /* Convert into polynomials in cos(alpha) */
  114808. cheby(g1,g1_order);
  114809. cheby(g2,g2_order);
  114810. /* Find the roots of the 2 even polynomials.*/
  114811. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114812. Laguerre_With_Deflation(g2,g2_order,g2r))
  114813. return(-1);
  114814. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114815. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114816. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114817. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114818. for(i=0;i<g1_order;i++)
  114819. lsp[i*2] = acos(g1r[i]);
  114820. for(i=0;i<g2_order;i++)
  114821. lsp[i*2+1] = acos(g2r[i]);
  114822. return(0);
  114823. }
  114824. #endif
  114825. /*** End of inlined file: lsp.c ***/
  114826. /*** Start of inlined file: mapping0.c ***/
  114827. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114828. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114829. // tasks..
  114830. #if JUCE_MSVC
  114831. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114832. #endif
  114833. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114834. #if JUCE_USE_OGGVORBIS
  114835. #include <stdlib.h>
  114836. #include <stdio.h>
  114837. #include <string.h>
  114838. #include <math.h>
  114839. /* simplistic, wasteful way of doing this (unique lookup for each
  114840. mode/submapping); there should be a central repository for
  114841. identical lookups. That will require minor work, so I'm putting it
  114842. off as low priority.
  114843. Why a lookup for each backend in a given mode? Because the
  114844. blocksize is set by the mode, and low backend lookups may require
  114845. parameters from other areas of the mode/mapping */
  114846. static void mapping0_free_info(vorbis_info_mapping *i){
  114847. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114848. if(info){
  114849. memset(info,0,sizeof(*info));
  114850. _ogg_free(info);
  114851. }
  114852. }
  114853. static int ilog3(unsigned int v){
  114854. int ret=0;
  114855. if(v)--v;
  114856. while(v){
  114857. ret++;
  114858. v>>=1;
  114859. }
  114860. return(ret);
  114861. }
  114862. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114863. oggpack_buffer *opb){
  114864. int i;
  114865. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114866. /* another 'we meant to do it this way' hack... up to beta 4, we
  114867. packed 4 binary zeros here to signify one submapping in use. We
  114868. now redefine that to mean four bitflags that indicate use of
  114869. deeper features; bit0:submappings, bit1:coupling,
  114870. bit2,3:reserved. This is backward compatable with all actual uses
  114871. of the beta code. */
  114872. if(info->submaps>1){
  114873. oggpack_write(opb,1,1);
  114874. oggpack_write(opb,info->submaps-1,4);
  114875. }else
  114876. oggpack_write(opb,0,1);
  114877. if(info->coupling_steps>0){
  114878. oggpack_write(opb,1,1);
  114879. oggpack_write(opb,info->coupling_steps-1,8);
  114880. for(i=0;i<info->coupling_steps;i++){
  114881. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114882. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114883. }
  114884. }else
  114885. oggpack_write(opb,0,1);
  114886. oggpack_write(opb,0,2); /* 2,3:reserved */
  114887. /* we don't write the channel submappings if we only have one... */
  114888. if(info->submaps>1){
  114889. for(i=0;i<vi->channels;i++)
  114890. oggpack_write(opb,info->chmuxlist[i],4);
  114891. }
  114892. for(i=0;i<info->submaps;i++){
  114893. oggpack_write(opb,0,8); /* time submap unused */
  114894. oggpack_write(opb,info->floorsubmap[i],8);
  114895. oggpack_write(opb,info->residuesubmap[i],8);
  114896. }
  114897. }
  114898. /* also responsible for range checking */
  114899. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114900. int i;
  114901. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114902. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114903. memset(info,0,sizeof(*info));
  114904. if(oggpack_read(opb,1))
  114905. info->submaps=oggpack_read(opb,4)+1;
  114906. else
  114907. info->submaps=1;
  114908. if(oggpack_read(opb,1)){
  114909. info->coupling_steps=oggpack_read(opb,8)+1;
  114910. for(i=0;i<info->coupling_steps;i++){
  114911. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114912. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114913. if(testM<0 ||
  114914. testA<0 ||
  114915. testM==testA ||
  114916. testM>=vi->channels ||
  114917. testA>=vi->channels) goto err_out;
  114918. }
  114919. }
  114920. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114921. if(info->submaps>1){
  114922. for(i=0;i<vi->channels;i++){
  114923. info->chmuxlist[i]=oggpack_read(opb,4);
  114924. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114925. }
  114926. }
  114927. for(i=0;i<info->submaps;i++){
  114928. oggpack_read(opb,8); /* time submap unused */
  114929. info->floorsubmap[i]=oggpack_read(opb,8);
  114930. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114931. info->residuesubmap[i]=oggpack_read(opb,8);
  114932. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114933. }
  114934. return info;
  114935. err_out:
  114936. mapping0_free_info(info);
  114937. return(NULL);
  114938. }
  114939. #if 0
  114940. static long seq=0;
  114941. static ogg_int64_t total=0;
  114942. static float FLOOR1_fromdB_LOOKUP[256]={
  114943. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114944. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114945. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114946. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114947. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114948. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114949. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114950. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114951. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114952. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114953. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114954. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114955. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114956. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114957. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114958. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114959. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114960. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114961. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114962. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114963. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114964. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114965. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114966. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114967. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114968. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114969. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114970. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114971. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114972. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114973. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114974. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114975. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114976. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114977. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114978. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114979. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114980. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114981. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114982. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114983. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114984. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114985. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114986. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114987. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114988. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114989. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114990. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114991. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114992. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114993. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114994. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114995. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114996. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114997. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114998. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114999. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115000. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115001. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115002. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115003. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115004. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115005. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115006. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115007. };
  115008. #endif
  115009. extern int *floor1_fit(vorbis_block *vb,void *look,
  115010. const float *logmdct, /* in */
  115011. const float *logmask);
  115012. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115013. int *A,int *B,
  115014. int del);
  115015. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115016. void*look,
  115017. int *post,int *ilogmask);
  115018. static int mapping0_forward(vorbis_block *vb){
  115019. vorbis_dsp_state *vd=vb->vd;
  115020. vorbis_info *vi=vd->vi;
  115021. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115022. private_state *b=(private_state*)vb->vd->backend_state;
  115023. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115024. int n=vb->pcmend;
  115025. int i,j,k;
  115026. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115027. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115028. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115029. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115030. float global_ampmax=vbi->ampmax;
  115031. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115032. int blocktype=vbi->blocktype;
  115033. int modenumber=vb->W;
  115034. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115035. vorbis_look_psy *psy_look=
  115036. b->psy+blocktype+(vb->W?2:0);
  115037. vb->mode=modenumber;
  115038. for(i=0;i<vi->channels;i++){
  115039. float scale=4.f/n;
  115040. float scale_dB;
  115041. float *pcm =vb->pcm[i];
  115042. float *logfft =pcm;
  115043. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115044. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115045. todB estimation used on IEEE 754
  115046. compliant machines had a bug that
  115047. returned dB values about a third
  115048. of a decibel too high. The bug
  115049. was harmless because tunings
  115050. implicitly took that into
  115051. account. However, fixing the bug
  115052. in the estimator requires
  115053. changing all the tunings as well.
  115054. For now, it's easier to sync
  115055. things back up here, and
  115056. recalibrate the tunings in the
  115057. next major model upgrade. */
  115058. #if 0
  115059. if(vi->channels==2)
  115060. if(i==0)
  115061. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115062. else
  115063. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115064. #endif
  115065. /* window the PCM data */
  115066. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115067. #if 0
  115068. if(vi->channels==2)
  115069. if(i==0)
  115070. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115071. else
  115072. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115073. #endif
  115074. /* transform the PCM data */
  115075. /* only MDCT right now.... */
  115076. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115077. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115078. drft_forward(&b->fft_look[vb->W],pcm);
  115079. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115080. original todB estimation used on
  115081. IEEE 754 compliant machines had a
  115082. bug that returned dB values about
  115083. a third of a decibel too high.
  115084. The bug was harmless because
  115085. tunings implicitly took that into
  115086. account. However, fixing the bug
  115087. in the estimator requires
  115088. changing all the tunings as well.
  115089. For now, it's easier to sync
  115090. things back up here, and
  115091. recalibrate the tunings in the
  115092. next major model upgrade. */
  115093. local_ampmax[i]=logfft[0];
  115094. for(j=1;j<n-1;j+=2){
  115095. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115096. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115097. .345 is a hack; the original todB
  115098. estimation used on IEEE 754
  115099. compliant machines had a bug that
  115100. returned dB values about a third
  115101. of a decibel too high. The bug
  115102. was harmless because tunings
  115103. implicitly took that into
  115104. account. However, fixing the bug
  115105. in the estimator requires
  115106. changing all the tunings as well.
  115107. For now, it's easier to sync
  115108. things back up here, and
  115109. recalibrate the tunings in the
  115110. next major model upgrade. */
  115111. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115112. }
  115113. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115114. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115115. #if 0
  115116. if(vi->channels==2){
  115117. if(i==0){
  115118. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115119. }else{
  115120. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115121. }
  115122. }
  115123. #endif
  115124. }
  115125. {
  115126. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115127. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115128. for(i=0;i<vi->channels;i++){
  115129. /* the encoder setup assumes that all the modes used by any
  115130. specific bitrate tweaking use the same floor */
  115131. int submap=info->chmuxlist[i];
  115132. /* the following makes things clearer to *me* anyway */
  115133. float *mdct =gmdct[i];
  115134. float *logfft =vb->pcm[i];
  115135. float *logmdct =logfft+n/2;
  115136. float *logmask =logfft;
  115137. vb->mode=modenumber;
  115138. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115139. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115140. for(j=0;j<n/2;j++)
  115141. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115142. todB estimation used on IEEE 754
  115143. compliant machines had a bug that
  115144. returned dB values about a third
  115145. of a decibel too high. The bug
  115146. was harmless because tunings
  115147. implicitly took that into
  115148. account. However, fixing the bug
  115149. in the estimator requires
  115150. changing all the tunings as well.
  115151. For now, it's easier to sync
  115152. things back up here, and
  115153. recalibrate the tunings in the
  115154. next major model upgrade. */
  115155. #if 0
  115156. if(vi->channels==2){
  115157. if(i==0)
  115158. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115159. else
  115160. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115161. }else{
  115162. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115163. }
  115164. #endif
  115165. /* first step; noise masking. Not only does 'noise masking'
  115166. give us curves from which we can decide how much resolution
  115167. to give noise parts of the spectrum, it also implicitly hands
  115168. us a tonality estimate (the larger the value in the
  115169. 'noise_depth' vector, the more tonal that area is) */
  115170. _vp_noisemask(psy_look,
  115171. logmdct,
  115172. noise); /* noise does not have by-frequency offset
  115173. bias applied yet */
  115174. #if 0
  115175. if(vi->channels==2){
  115176. if(i==0)
  115177. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115178. else
  115179. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115180. }
  115181. #endif
  115182. /* second step: 'all the other crap'; all the stuff that isn't
  115183. computed/fit for bitrate management goes in the second psy
  115184. vector. This includes tone masking, peak limiting and ATH */
  115185. _vp_tonemask(psy_look,
  115186. logfft,
  115187. tone,
  115188. global_ampmax,
  115189. local_ampmax[i]);
  115190. #if 0
  115191. if(vi->channels==2){
  115192. if(i==0)
  115193. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115194. else
  115195. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115196. }
  115197. #endif
  115198. /* third step; we offset the noise vectors, overlay tone
  115199. masking. We then do a floor1-specific line fit. If we're
  115200. performing bitrate management, the line fit is performed
  115201. multiple times for up/down tweakage on demand. */
  115202. #if 0
  115203. {
  115204. float aotuv[psy_look->n];
  115205. #endif
  115206. _vp_offset_and_mix(psy_look,
  115207. noise,
  115208. tone,
  115209. 1,
  115210. logmask,
  115211. mdct,
  115212. logmdct);
  115213. #if 0
  115214. if(vi->channels==2){
  115215. if(i==0)
  115216. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115217. else
  115218. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115219. }
  115220. }
  115221. #endif
  115222. #if 0
  115223. if(vi->channels==2){
  115224. if(i==0)
  115225. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115226. else
  115227. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115228. }
  115229. #endif
  115230. /* this algorithm is hardwired to floor 1 for now; abort out if
  115231. we're *not* floor1. This won't happen unless someone has
  115232. broken the encode setup lib. Guard it anyway. */
  115233. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115234. floor_posts[i][PACKETBLOBS/2]=
  115235. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115236. logmdct,
  115237. logmask);
  115238. /* are we managing bitrate? If so, perform two more fits for
  115239. later rate tweaking (fits represent hi/lo) */
  115240. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115241. /* higher rate by way of lower noise curve */
  115242. _vp_offset_and_mix(psy_look,
  115243. noise,
  115244. tone,
  115245. 2,
  115246. logmask,
  115247. mdct,
  115248. logmdct);
  115249. #if 0
  115250. if(vi->channels==2){
  115251. if(i==0)
  115252. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115253. else
  115254. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115255. }
  115256. #endif
  115257. floor_posts[i][PACKETBLOBS-1]=
  115258. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115259. logmdct,
  115260. logmask);
  115261. /* lower rate by way of higher noise curve */
  115262. _vp_offset_and_mix(psy_look,
  115263. noise,
  115264. tone,
  115265. 0,
  115266. logmask,
  115267. mdct,
  115268. logmdct);
  115269. #if 0
  115270. if(vi->channels==2)
  115271. if(i==0)
  115272. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115273. else
  115274. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115275. #endif
  115276. floor_posts[i][0]=
  115277. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115278. logmdct,
  115279. logmask);
  115280. /* we also interpolate a range of intermediate curves for
  115281. intermediate rates */
  115282. for(k=1;k<PACKETBLOBS/2;k++)
  115283. floor_posts[i][k]=
  115284. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115285. floor_posts[i][0],
  115286. floor_posts[i][PACKETBLOBS/2],
  115287. k*65536/(PACKETBLOBS/2));
  115288. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115289. floor_posts[i][k]=
  115290. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115291. floor_posts[i][PACKETBLOBS/2],
  115292. floor_posts[i][PACKETBLOBS-1],
  115293. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115294. }
  115295. }
  115296. }
  115297. vbi->ampmax=global_ampmax;
  115298. /*
  115299. the next phases are performed once for vbr-only and PACKETBLOB
  115300. times for bitrate managed modes.
  115301. 1) encode actual mode being used
  115302. 2) encode the floor for each channel, compute coded mask curve/res
  115303. 3) normalize and couple.
  115304. 4) encode residue
  115305. 5) save packet bytes to the packetblob vector
  115306. */
  115307. /* iterate over the many masking curve fits we've created */
  115308. {
  115309. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115310. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115311. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115312. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115313. float **mag_memo;
  115314. int **mag_sort;
  115315. if(info->coupling_steps){
  115316. mag_memo=_vp_quantize_couple_memo(vb,
  115317. &ci->psy_g_param,
  115318. psy_look,
  115319. info,
  115320. gmdct);
  115321. mag_sort=_vp_quantize_couple_sort(vb,
  115322. psy_look,
  115323. info,
  115324. mag_memo);
  115325. hf_reduction(&ci->psy_g_param,
  115326. psy_look,
  115327. info,
  115328. mag_memo);
  115329. }
  115330. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115331. if(psy_look->vi->normal_channel_p){
  115332. for(i=0;i<vi->channels;i++){
  115333. float *mdct =gmdct[i];
  115334. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115335. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115336. }
  115337. }
  115338. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115339. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115340. k++){
  115341. oggpack_buffer *opb=vbi->packetblob[k];
  115342. /* start out our new packet blob with packet type and mode */
  115343. /* Encode the packet type */
  115344. oggpack_write(opb,0,1);
  115345. /* Encode the modenumber */
  115346. /* Encode frame mode, pre,post windowsize, then dispatch */
  115347. oggpack_write(opb,modenumber,b->modebits);
  115348. if(vb->W){
  115349. oggpack_write(opb,vb->lW,1);
  115350. oggpack_write(opb,vb->nW,1);
  115351. }
  115352. /* encode floor, compute masking curve, sep out residue */
  115353. for(i=0;i<vi->channels;i++){
  115354. int submap=info->chmuxlist[i];
  115355. float *mdct =gmdct[i];
  115356. float *res =vb->pcm[i];
  115357. int *ilogmask=ilogmaskch[i]=
  115358. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115359. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115360. floor_posts[i][k],
  115361. ilogmask);
  115362. #if 0
  115363. {
  115364. char buf[80];
  115365. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115366. float work[n/2];
  115367. for(j=0;j<n/2;j++)
  115368. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115369. _analysis_output(buf,seq,work,n/2,1,1,0);
  115370. }
  115371. #endif
  115372. _vp_remove_floor(psy_look,
  115373. mdct,
  115374. ilogmask,
  115375. res,
  115376. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115377. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115378. #if 0
  115379. {
  115380. char buf[80];
  115381. float work[n/2];
  115382. for(j=0;j<n/2;j++)
  115383. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115384. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115385. _analysis_output(buf,seq,work,n/2,1,1,0);
  115386. }
  115387. #endif
  115388. }
  115389. /* our iteration is now based on masking curve, not prequant and
  115390. coupling. Only one prequant/coupling step */
  115391. /* quantize/couple */
  115392. /* incomplete implementation that assumes the tree is all depth
  115393. one, or no tree at all */
  115394. if(info->coupling_steps){
  115395. _vp_couple(k,
  115396. &ci->psy_g_param,
  115397. psy_look,
  115398. info,
  115399. vb->pcm,
  115400. mag_memo,
  115401. mag_sort,
  115402. ilogmaskch,
  115403. nonzero,
  115404. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115405. }
  115406. /* classify and encode by submap */
  115407. for(i=0;i<info->submaps;i++){
  115408. int ch_in_bundle=0;
  115409. long **classifications;
  115410. int resnum=info->residuesubmap[i];
  115411. for(j=0;j<vi->channels;j++){
  115412. if(info->chmuxlist[j]==i){
  115413. zerobundle[ch_in_bundle]=0;
  115414. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115415. res_bundle[ch_in_bundle]=vb->pcm[j];
  115416. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115417. }
  115418. }
  115419. classifications=_residue_P[ci->residue_type[resnum]]->
  115420. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115421. _residue_P[ci->residue_type[resnum]]->
  115422. forward(opb,vb,b->residue[resnum],
  115423. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115424. }
  115425. /* ok, done encoding. Next protopacket. */
  115426. }
  115427. }
  115428. #if 0
  115429. seq++;
  115430. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115431. #endif
  115432. return(0);
  115433. }
  115434. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115435. vorbis_dsp_state *vd=vb->vd;
  115436. vorbis_info *vi=vd->vi;
  115437. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115438. private_state *b=(private_state*)vd->backend_state;
  115439. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115440. int i,j;
  115441. long n=vb->pcmend=ci->blocksizes[vb->W];
  115442. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115443. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115444. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115445. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115446. /* recover the spectral envelope; store it in the PCM vector for now */
  115447. for(i=0;i<vi->channels;i++){
  115448. int submap=info->chmuxlist[i];
  115449. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115450. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115451. if(floormemo[i])
  115452. nonzero[i]=1;
  115453. else
  115454. nonzero[i]=0;
  115455. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115456. }
  115457. /* channel coupling can 'dirty' the nonzero listing */
  115458. for(i=0;i<info->coupling_steps;i++){
  115459. if(nonzero[info->coupling_mag[i]] ||
  115460. nonzero[info->coupling_ang[i]]){
  115461. nonzero[info->coupling_mag[i]]=1;
  115462. nonzero[info->coupling_ang[i]]=1;
  115463. }
  115464. }
  115465. /* recover the residue into our working vectors */
  115466. for(i=0;i<info->submaps;i++){
  115467. int ch_in_bundle=0;
  115468. for(j=0;j<vi->channels;j++){
  115469. if(info->chmuxlist[j]==i){
  115470. if(nonzero[j])
  115471. zerobundle[ch_in_bundle]=1;
  115472. else
  115473. zerobundle[ch_in_bundle]=0;
  115474. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115475. }
  115476. }
  115477. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115478. inverse(vb,b->residue[info->residuesubmap[i]],
  115479. pcmbundle,zerobundle,ch_in_bundle);
  115480. }
  115481. /* channel coupling */
  115482. for(i=info->coupling_steps-1;i>=0;i--){
  115483. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115484. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115485. for(j=0;j<n/2;j++){
  115486. float mag=pcmM[j];
  115487. float ang=pcmA[j];
  115488. if(mag>0)
  115489. if(ang>0){
  115490. pcmM[j]=mag;
  115491. pcmA[j]=mag-ang;
  115492. }else{
  115493. pcmA[j]=mag;
  115494. pcmM[j]=mag+ang;
  115495. }
  115496. else
  115497. if(ang>0){
  115498. pcmM[j]=mag;
  115499. pcmA[j]=mag+ang;
  115500. }else{
  115501. pcmA[j]=mag;
  115502. pcmM[j]=mag-ang;
  115503. }
  115504. }
  115505. }
  115506. /* compute and apply spectral envelope */
  115507. for(i=0;i<vi->channels;i++){
  115508. float *pcm=vb->pcm[i];
  115509. int submap=info->chmuxlist[i];
  115510. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115511. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115512. floormemo[i],pcm);
  115513. }
  115514. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115515. /* only MDCT right now.... */
  115516. for(i=0;i<vi->channels;i++){
  115517. float *pcm=vb->pcm[i];
  115518. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115519. }
  115520. /* all done! */
  115521. return(0);
  115522. }
  115523. /* export hooks */
  115524. vorbis_func_mapping mapping0_exportbundle={
  115525. &mapping0_pack,
  115526. &mapping0_unpack,
  115527. &mapping0_free_info,
  115528. &mapping0_forward,
  115529. &mapping0_inverse
  115530. };
  115531. #endif
  115532. /*** End of inlined file: mapping0.c ***/
  115533. /*** Start of inlined file: mdct.c ***/
  115534. /* this can also be run as an integer transform by uncommenting a
  115535. define in mdct.h; the integerization is a first pass and although
  115536. it's likely stable for Vorbis, the dynamic range is constrained and
  115537. roundoff isn't done (so it's noisy). Consider it functional, but
  115538. only a starting point. There's no point on a machine with an FPU */
  115539. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115540. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115541. // tasks..
  115542. #if JUCE_MSVC
  115543. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115544. #endif
  115545. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115546. #if JUCE_USE_OGGVORBIS
  115547. #include <stdio.h>
  115548. #include <stdlib.h>
  115549. #include <string.h>
  115550. #include <math.h>
  115551. /* build lookups for trig functions; also pre-figure scaling and
  115552. some window function algebra. */
  115553. void mdct_init(mdct_lookup *lookup,int n){
  115554. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115555. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115556. int i;
  115557. int n2=n>>1;
  115558. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115559. lookup->n=n;
  115560. lookup->trig=T;
  115561. lookup->bitrev=bitrev;
  115562. /* trig lookups... */
  115563. for(i=0;i<n/4;i++){
  115564. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115565. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115566. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115567. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115568. }
  115569. for(i=0;i<n/8;i++){
  115570. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115571. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115572. }
  115573. /* bitreverse lookup... */
  115574. {
  115575. int mask=(1<<(log2n-1))-1,i,j;
  115576. int msb=1<<(log2n-2);
  115577. for(i=0;i<n/8;i++){
  115578. int acc=0;
  115579. for(j=0;msb>>j;j++)
  115580. if((msb>>j)&i)acc|=1<<j;
  115581. bitrev[i*2]=((~acc)&mask)-1;
  115582. bitrev[i*2+1]=acc;
  115583. }
  115584. }
  115585. lookup->scale=FLOAT_CONV(4.f/n);
  115586. }
  115587. /* 8 point butterfly (in place, 4 register) */
  115588. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115589. REG_TYPE r0 = x[6] + x[2];
  115590. REG_TYPE r1 = x[6] - x[2];
  115591. REG_TYPE r2 = x[4] + x[0];
  115592. REG_TYPE r3 = x[4] - x[0];
  115593. x[6] = r0 + r2;
  115594. x[4] = r0 - r2;
  115595. r0 = x[5] - x[1];
  115596. r2 = x[7] - x[3];
  115597. x[0] = r1 + r0;
  115598. x[2] = r1 - r0;
  115599. r0 = x[5] + x[1];
  115600. r1 = x[7] + x[3];
  115601. x[3] = r2 + r3;
  115602. x[1] = r2 - r3;
  115603. x[7] = r1 + r0;
  115604. x[5] = r1 - r0;
  115605. }
  115606. /* 16 point butterfly (in place, 4 register) */
  115607. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115608. REG_TYPE r0 = x[1] - x[9];
  115609. REG_TYPE r1 = x[0] - x[8];
  115610. x[8] += x[0];
  115611. x[9] += x[1];
  115612. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115613. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115614. r0 = x[3] - x[11];
  115615. r1 = x[10] - x[2];
  115616. x[10] += x[2];
  115617. x[11] += x[3];
  115618. x[2] = r0;
  115619. x[3] = r1;
  115620. r0 = x[12] - x[4];
  115621. r1 = x[13] - x[5];
  115622. x[12] += x[4];
  115623. x[13] += x[5];
  115624. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115625. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115626. r0 = x[14] - x[6];
  115627. r1 = x[15] - x[7];
  115628. x[14] += x[6];
  115629. x[15] += x[7];
  115630. x[6] = r0;
  115631. x[7] = r1;
  115632. mdct_butterfly_8(x);
  115633. mdct_butterfly_8(x+8);
  115634. }
  115635. /* 32 point butterfly (in place, 4 register) */
  115636. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115637. REG_TYPE r0 = x[30] - x[14];
  115638. REG_TYPE r1 = x[31] - x[15];
  115639. x[30] += x[14];
  115640. x[31] += x[15];
  115641. x[14] = r0;
  115642. x[15] = r1;
  115643. r0 = x[28] - x[12];
  115644. r1 = x[29] - x[13];
  115645. x[28] += x[12];
  115646. x[29] += x[13];
  115647. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115648. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115649. r0 = x[26] - x[10];
  115650. r1 = x[27] - x[11];
  115651. x[26] += x[10];
  115652. x[27] += x[11];
  115653. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115654. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115655. r0 = x[24] - x[8];
  115656. r1 = x[25] - x[9];
  115657. x[24] += x[8];
  115658. x[25] += x[9];
  115659. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115660. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115661. r0 = x[22] - x[6];
  115662. r1 = x[7] - x[23];
  115663. x[22] += x[6];
  115664. x[23] += x[7];
  115665. x[6] = r1;
  115666. x[7] = r0;
  115667. r0 = x[4] - x[20];
  115668. r1 = x[5] - x[21];
  115669. x[20] += x[4];
  115670. x[21] += x[5];
  115671. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115672. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115673. r0 = x[2] - x[18];
  115674. r1 = x[3] - x[19];
  115675. x[18] += x[2];
  115676. x[19] += x[3];
  115677. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115678. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115679. r0 = x[0] - x[16];
  115680. r1 = x[1] - x[17];
  115681. x[16] += x[0];
  115682. x[17] += x[1];
  115683. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115684. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115685. mdct_butterfly_16(x);
  115686. mdct_butterfly_16(x+16);
  115687. }
  115688. /* N point first stage butterfly (in place, 2 register) */
  115689. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115690. DATA_TYPE *x,
  115691. int points){
  115692. DATA_TYPE *x1 = x + points - 8;
  115693. DATA_TYPE *x2 = x + (points>>1) - 8;
  115694. REG_TYPE r0;
  115695. REG_TYPE r1;
  115696. do{
  115697. r0 = x1[6] - x2[6];
  115698. r1 = x1[7] - x2[7];
  115699. x1[6] += x2[6];
  115700. x1[7] += x2[7];
  115701. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115702. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115703. r0 = x1[4] - x2[4];
  115704. r1 = x1[5] - x2[5];
  115705. x1[4] += x2[4];
  115706. x1[5] += x2[5];
  115707. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115708. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115709. r0 = x1[2] - x2[2];
  115710. r1 = x1[3] - x2[3];
  115711. x1[2] += x2[2];
  115712. x1[3] += x2[3];
  115713. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115714. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115715. r0 = x1[0] - x2[0];
  115716. r1 = x1[1] - x2[1];
  115717. x1[0] += x2[0];
  115718. x1[1] += x2[1];
  115719. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115720. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115721. x1-=8;
  115722. x2-=8;
  115723. T+=16;
  115724. }while(x2>=x);
  115725. }
  115726. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115727. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115728. DATA_TYPE *x,
  115729. int points,
  115730. int trigint){
  115731. DATA_TYPE *x1 = x + points - 8;
  115732. DATA_TYPE *x2 = x + (points>>1) - 8;
  115733. REG_TYPE r0;
  115734. REG_TYPE r1;
  115735. do{
  115736. r0 = x1[6] - x2[6];
  115737. r1 = x1[7] - x2[7];
  115738. x1[6] += x2[6];
  115739. x1[7] += x2[7];
  115740. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115741. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115742. T+=trigint;
  115743. r0 = x1[4] - x2[4];
  115744. r1 = x1[5] - x2[5];
  115745. x1[4] += x2[4];
  115746. x1[5] += x2[5];
  115747. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115748. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115749. T+=trigint;
  115750. r0 = x1[2] - x2[2];
  115751. r1 = x1[3] - x2[3];
  115752. x1[2] += x2[2];
  115753. x1[3] += x2[3];
  115754. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115755. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115756. T+=trigint;
  115757. r0 = x1[0] - x2[0];
  115758. r1 = x1[1] - x2[1];
  115759. x1[0] += x2[0];
  115760. x1[1] += x2[1];
  115761. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115762. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115763. T+=trigint;
  115764. x1-=8;
  115765. x2-=8;
  115766. }while(x2>=x);
  115767. }
  115768. STIN void mdct_butterflies(mdct_lookup *init,
  115769. DATA_TYPE *x,
  115770. int points){
  115771. DATA_TYPE *T=init->trig;
  115772. int stages=init->log2n-5;
  115773. int i,j;
  115774. if(--stages>0){
  115775. mdct_butterfly_first(T,x,points);
  115776. }
  115777. for(i=1;--stages>0;i++){
  115778. for(j=0;j<(1<<i);j++)
  115779. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115780. }
  115781. for(j=0;j<points;j+=32)
  115782. mdct_butterfly_32(x+j);
  115783. }
  115784. void mdct_clear(mdct_lookup *l){
  115785. if(l){
  115786. if(l->trig)_ogg_free(l->trig);
  115787. if(l->bitrev)_ogg_free(l->bitrev);
  115788. memset(l,0,sizeof(*l));
  115789. }
  115790. }
  115791. STIN void mdct_bitreverse(mdct_lookup *init,
  115792. DATA_TYPE *x){
  115793. int n = init->n;
  115794. int *bit = init->bitrev;
  115795. DATA_TYPE *w0 = x;
  115796. DATA_TYPE *w1 = x = w0+(n>>1);
  115797. DATA_TYPE *T = init->trig+n;
  115798. do{
  115799. DATA_TYPE *x0 = x+bit[0];
  115800. DATA_TYPE *x1 = x+bit[1];
  115801. REG_TYPE r0 = x0[1] - x1[1];
  115802. REG_TYPE r1 = x0[0] + x1[0];
  115803. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115804. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115805. w1 -= 4;
  115806. r0 = HALVE(x0[1] + x1[1]);
  115807. r1 = HALVE(x0[0] - x1[0]);
  115808. w0[0] = r0 + r2;
  115809. w1[2] = r0 - r2;
  115810. w0[1] = r1 + r3;
  115811. w1[3] = r3 - r1;
  115812. x0 = x+bit[2];
  115813. x1 = x+bit[3];
  115814. r0 = x0[1] - x1[1];
  115815. r1 = x0[0] + x1[0];
  115816. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115817. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115818. r0 = HALVE(x0[1] + x1[1]);
  115819. r1 = HALVE(x0[0] - x1[0]);
  115820. w0[2] = r0 + r2;
  115821. w1[0] = r0 - r2;
  115822. w0[3] = r1 + r3;
  115823. w1[1] = r3 - r1;
  115824. T += 4;
  115825. bit += 4;
  115826. w0 += 4;
  115827. }while(w0<w1);
  115828. }
  115829. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115830. int n=init->n;
  115831. int n2=n>>1;
  115832. int n4=n>>2;
  115833. /* rotate */
  115834. DATA_TYPE *iX = in+n2-7;
  115835. DATA_TYPE *oX = out+n2+n4;
  115836. DATA_TYPE *T = init->trig+n4;
  115837. do{
  115838. oX -= 4;
  115839. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115840. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115841. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115842. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115843. iX -= 8;
  115844. T += 4;
  115845. }while(iX>=in);
  115846. iX = in+n2-8;
  115847. oX = out+n2+n4;
  115848. T = init->trig+n4;
  115849. do{
  115850. T -= 4;
  115851. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115852. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115853. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115854. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115855. iX -= 8;
  115856. oX += 4;
  115857. }while(iX>=in);
  115858. mdct_butterflies(init,out+n2,n2);
  115859. mdct_bitreverse(init,out);
  115860. /* roatate + window */
  115861. {
  115862. DATA_TYPE *oX1=out+n2+n4;
  115863. DATA_TYPE *oX2=out+n2+n4;
  115864. DATA_TYPE *iX =out;
  115865. T =init->trig+n2;
  115866. do{
  115867. oX1-=4;
  115868. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115869. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115870. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115871. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115872. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115873. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115874. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115875. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115876. oX2+=4;
  115877. iX += 8;
  115878. T += 8;
  115879. }while(iX<oX1);
  115880. iX=out+n2+n4;
  115881. oX1=out+n4;
  115882. oX2=oX1;
  115883. do{
  115884. oX1-=4;
  115885. iX-=4;
  115886. oX2[0] = -(oX1[3] = iX[3]);
  115887. oX2[1] = -(oX1[2] = iX[2]);
  115888. oX2[2] = -(oX1[1] = iX[1]);
  115889. oX2[3] = -(oX1[0] = iX[0]);
  115890. oX2+=4;
  115891. }while(oX2<iX);
  115892. iX=out+n2+n4;
  115893. oX1=out+n2+n4;
  115894. oX2=out+n2;
  115895. do{
  115896. oX1-=4;
  115897. oX1[0]= iX[3];
  115898. oX1[1]= iX[2];
  115899. oX1[2]= iX[1];
  115900. oX1[3]= iX[0];
  115901. iX+=4;
  115902. }while(oX1>oX2);
  115903. }
  115904. }
  115905. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115906. int n=init->n;
  115907. int n2=n>>1;
  115908. int n4=n>>2;
  115909. int n8=n>>3;
  115910. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115911. DATA_TYPE *w2=w+n2;
  115912. /* rotate */
  115913. /* window + rotate + step 1 */
  115914. REG_TYPE r0;
  115915. REG_TYPE r1;
  115916. DATA_TYPE *x0=in+n2+n4;
  115917. DATA_TYPE *x1=x0+1;
  115918. DATA_TYPE *T=init->trig+n2;
  115919. int i=0;
  115920. for(i=0;i<n8;i+=2){
  115921. x0 -=4;
  115922. T-=2;
  115923. r0= x0[2] + x1[0];
  115924. r1= x0[0] + x1[2];
  115925. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115926. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115927. x1 +=4;
  115928. }
  115929. x1=in+1;
  115930. for(;i<n2-n8;i+=2){
  115931. T-=2;
  115932. x0 -=4;
  115933. r0= x0[2] - x1[0];
  115934. r1= x0[0] - x1[2];
  115935. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115936. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115937. x1 +=4;
  115938. }
  115939. x0=in+n;
  115940. for(;i<n2;i+=2){
  115941. T-=2;
  115942. x0 -=4;
  115943. r0= -x0[2] - x1[0];
  115944. r1= -x0[0] - x1[2];
  115945. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115946. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115947. x1 +=4;
  115948. }
  115949. mdct_butterflies(init,w+n2,n2);
  115950. mdct_bitreverse(init,w);
  115951. /* roatate + window */
  115952. T=init->trig+n2;
  115953. x0=out+n2;
  115954. for(i=0;i<n4;i++){
  115955. x0--;
  115956. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115957. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115958. w+=2;
  115959. T+=2;
  115960. }
  115961. }
  115962. #endif
  115963. /*** End of inlined file: mdct.c ***/
  115964. /*** Start of inlined file: psy.c ***/
  115965. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115966. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115967. // tasks..
  115968. #if JUCE_MSVC
  115969. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115970. #endif
  115971. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115972. #if JUCE_USE_OGGVORBIS
  115973. #include <stdlib.h>
  115974. #include <math.h>
  115975. #include <string.h>
  115976. /*** Start of inlined file: masking.h ***/
  115977. #ifndef _V_MASKING_H_
  115978. #define _V_MASKING_H_
  115979. /* more detailed ATH; the bass if flat to save stressing the floor
  115980. overly for only a bin or two of savings. */
  115981. #define MAX_ATH 88
  115982. static float ATH[]={
  115983. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115984. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115985. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115986. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115987. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115988. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115989. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115990. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115991. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115992. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115993. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115994. };
  115995. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115996. replaced by an empirically collected data set. The previously
  115997. published values were, far too often, simply on crack. */
  115998. #define EHMER_OFFSET 16
  115999. #define EHMER_MAX 56
  116000. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116001. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116002. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116003. for collection of these curves) */
  116004. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116005. /* 62.5 Hz */
  116006. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116007. -60, -60, -60, -60, -62, -62, -65, -73,
  116008. -69, -68, -68, -67, -70, -70, -72, -74,
  116009. -75, -79, -79, -80, -83, -88, -93, -100,
  116010. -110, -999, -999, -999, -999, -999, -999, -999,
  116011. -999, -999, -999, -999, -999, -999, -999, -999,
  116012. -999, -999, -999, -999, -999, -999, -999, -999},
  116013. { -48, -48, -48, -48, -48, -48, -48, -48,
  116014. -48, -48, -48, -48, -48, -53, -61, -66,
  116015. -66, -68, -67, -70, -76, -76, -72, -73,
  116016. -75, -76, -78, -79, -83, -88, -93, -100,
  116017. -110, -999, -999, -999, -999, -999, -999, -999,
  116018. -999, -999, -999, -999, -999, -999, -999, -999,
  116019. -999, -999, -999, -999, -999, -999, -999, -999},
  116020. { -37, -37, -37, -37, -37, -37, -37, -37,
  116021. -38, -40, -42, -46, -48, -53, -55, -62,
  116022. -65, -58, -56, -56, -61, -60, -65, -67,
  116023. -69, -71, -77, -77, -78, -80, -82, -84,
  116024. -88, -93, -98, -106, -112, -999, -999, -999,
  116025. -999, -999, -999, -999, -999, -999, -999, -999,
  116026. -999, -999, -999, -999, -999, -999, -999, -999},
  116027. { -25, -25, -25, -25, -25, -25, -25, -25,
  116028. -25, -26, -27, -29, -32, -38, -48, -52,
  116029. -52, -50, -48, -48, -51, -52, -54, -60,
  116030. -67, -67, -66, -68, -69, -73, -73, -76,
  116031. -80, -81, -81, -85, -85, -86, -88, -93,
  116032. -100, -110, -999, -999, -999, -999, -999, -999,
  116033. -999, -999, -999, -999, -999, -999, -999, -999},
  116034. { -16, -16, -16, -16, -16, -16, -16, -16,
  116035. -17, -19, -20, -22, -26, -28, -31, -40,
  116036. -47, -39, -39, -40, -42, -43, -47, -51,
  116037. -57, -52, -55, -55, -60, -58, -62, -63,
  116038. -70, -67, -69, -72, -73, -77, -80, -82,
  116039. -83, -87, -90, -94, -98, -104, -115, -999,
  116040. -999, -999, -999, -999, -999, -999, -999, -999},
  116041. { -8, -8, -8, -8, -8, -8, -8, -8,
  116042. -8, -8, -10, -11, -15, -19, -25, -30,
  116043. -34, -31, -30, -31, -29, -32, -35, -42,
  116044. -48, -42, -44, -46, -50, -50, -51, -52,
  116045. -59, -54, -55, -55, -58, -62, -63, -66,
  116046. -72, -73, -76, -75, -78, -80, -80, -81,
  116047. -84, -88, -90, -94, -98, -101, -106, -110}},
  116048. /* 88Hz */
  116049. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116050. -66, -66, -66, -66, -66, -67, -67, -67,
  116051. -76, -72, -71, -74, -76, -76, -75, -78,
  116052. -79, -79, -81, -83, -86, -89, -93, -97,
  116053. -100, -105, -110, -999, -999, -999, -999, -999,
  116054. -999, -999, -999, -999, -999, -999, -999, -999,
  116055. -999, -999, -999, -999, -999, -999, -999, -999},
  116056. { -47, -47, -47, -47, -47, -47, -47, -47,
  116057. -47, -47, -47, -48, -51, -55, -59, -66,
  116058. -66, -66, -67, -66, -68, -69, -70, -74,
  116059. -79, -77, -77, -78, -80, -81, -82, -84,
  116060. -86, -88, -91, -95, -100, -108, -116, -999,
  116061. -999, -999, -999, -999, -999, -999, -999, -999,
  116062. -999, -999, -999, -999, -999, -999, -999, -999},
  116063. { -36, -36, -36, -36, -36, -36, -36, -36,
  116064. -36, -37, -37, -41, -44, -48, -51, -58,
  116065. -62, -60, -57, -59, -59, -60, -63, -65,
  116066. -72, -71, -70, -72, -74, -77, -76, -78,
  116067. -81, -81, -80, -83, -86, -91, -96, -100,
  116068. -105, -110, -999, -999, -999, -999, -999, -999,
  116069. -999, -999, -999, -999, -999, -999, -999, -999},
  116070. { -28, -28, -28, -28, -28, -28, -28, -28,
  116071. -28, -30, -32, -32, -33, -35, -41, -49,
  116072. -50, -49, -47, -48, -48, -52, -51, -57,
  116073. -65, -61, -59, -61, -64, -69, -70, -74,
  116074. -77, -77, -78, -81, -84, -85, -87, -90,
  116075. -92, -96, -100, -107, -112, -999, -999, -999,
  116076. -999, -999, -999, -999, -999, -999, -999, -999},
  116077. { -19, -19, -19, -19, -19, -19, -19, -19,
  116078. -20, -21, -23, -27, -30, -35, -36, -41,
  116079. -46, -44, -42, -40, -41, -41, -43, -48,
  116080. -55, -53, -52, -53, -56, -59, -58, -60,
  116081. -67, -66, -69, -71, -72, -75, -79, -81,
  116082. -84, -87, -90, -93, -97, -101, -107, -114,
  116083. -999, -999, -999, -999, -999, -999, -999, -999},
  116084. { -9, -9, -9, -9, -9, -9, -9, -9,
  116085. -11, -12, -12, -15, -16, -20, -23, -30,
  116086. -37, -34, -33, -34, -31, -32, -32, -38,
  116087. -47, -44, -41, -40, -47, -49, -46, -46,
  116088. -58, -50, -50, -54, -58, -62, -64, -67,
  116089. -67, -70, -72, -76, -79, -83, -87, -91,
  116090. -96, -100, -104, -110, -999, -999, -999, -999}},
  116091. /* 125 Hz */
  116092. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116093. -62, -62, -63, -64, -66, -67, -66, -68,
  116094. -75, -72, -76, -75, -76, -78, -79, -82,
  116095. -84, -85, -90, -94, -101, -110, -999, -999,
  116096. -999, -999, -999, -999, -999, -999, -999, -999,
  116097. -999, -999, -999, -999, -999, -999, -999, -999,
  116098. -999, -999, -999, -999, -999, -999, -999, -999},
  116099. { -59, -59, -59, -59, -59, -59, -59, -59,
  116100. -59, -59, -59, -60, -60, -61, -63, -66,
  116101. -71, -68, -70, -70, -71, -72, -72, -75,
  116102. -81, -78, -79, -82, -83, -86, -90, -97,
  116103. -103, -113, -999, -999, -999, -999, -999, -999,
  116104. -999, -999, -999, -999, -999, -999, -999, -999,
  116105. -999, -999, -999, -999, -999, -999, -999, -999},
  116106. { -53, -53, -53, -53, -53, -53, -53, -53,
  116107. -53, -54, -55, -57, -56, -57, -55, -61,
  116108. -65, -60, -60, -62, -63, -63, -66, -68,
  116109. -74, -73, -75, -75, -78, -80, -80, -82,
  116110. -85, -90, -96, -101, -108, -999, -999, -999,
  116111. -999, -999, -999, -999, -999, -999, -999, -999,
  116112. -999, -999, -999, -999, -999, -999, -999, -999},
  116113. { -46, -46, -46, -46, -46, -46, -46, -46,
  116114. -46, -46, -47, -47, -47, -47, -48, -51,
  116115. -57, -51, -49, -50, -51, -53, -54, -59,
  116116. -66, -60, -62, -67, -67, -70, -72, -75,
  116117. -76, -78, -81, -85, -88, -94, -97, -104,
  116118. -112, -999, -999, -999, -999, -999, -999, -999,
  116119. -999, -999, -999, -999, -999, -999, -999, -999},
  116120. { -36, -36, -36, -36, -36, -36, -36, -36,
  116121. -39, -41, -42, -42, -39, -38, -41, -43,
  116122. -52, -44, -40, -39, -37, -37, -40, -47,
  116123. -54, -50, -48, -50, -55, -61, -59, -62,
  116124. -66, -66, -66, -69, -69, -73, -74, -74,
  116125. -75, -77, -79, -82, -87, -91, -95, -100,
  116126. -108, -115, -999, -999, -999, -999, -999, -999},
  116127. { -28, -26, -24, -22, -20, -20, -23, -29,
  116128. -30, -31, -28, -27, -28, -28, -28, -35,
  116129. -40, -33, -32, -29, -30, -30, -30, -37,
  116130. -45, -41, -37, -38, -45, -47, -47, -48,
  116131. -53, -49, -48, -50, -49, -49, -51, -52,
  116132. -58, -56, -57, -56, -60, -61, -62, -70,
  116133. -72, -74, -78, -83, -88, -93, -100, -106}},
  116134. /* 177 Hz */
  116135. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116136. -999, -110, -105, -100, -95, -91, -87, -83,
  116137. -80, -78, -76, -78, -78, -81, -83, -85,
  116138. -86, -85, -86, -87, -90, -97, -107, -999,
  116139. -999, -999, -999, -999, -999, -999, -999, -999,
  116140. -999, -999, -999, -999, -999, -999, -999, -999,
  116141. -999, -999, -999, -999, -999, -999, -999, -999},
  116142. {-999, -999, -999, -110, -105, -100, -95, -90,
  116143. -85, -81, -77, -73, -70, -67, -67, -68,
  116144. -75, -73, -70, -69, -70, -72, -75, -79,
  116145. -84, -83, -84, -86, -88, -89, -89, -93,
  116146. -98, -105, -112, -999, -999, -999, -999, -999,
  116147. -999, -999, -999, -999, -999, -999, -999, -999,
  116148. -999, -999, -999, -999, -999, -999, -999, -999},
  116149. {-105, -100, -95, -90, -85, -80, -76, -71,
  116150. -68, -68, -65, -63, -63, -62, -62, -64,
  116151. -65, -64, -61, -62, -63, -64, -66, -68,
  116152. -73, -73, -74, -75, -76, -81, -83, -85,
  116153. -88, -89, -92, -95, -100, -108, -999, -999,
  116154. -999, -999, -999, -999, -999, -999, -999, -999,
  116155. -999, -999, -999, -999, -999, -999, -999, -999},
  116156. { -80, -75, -71, -68, -65, -63, -62, -61,
  116157. -61, -61, -61, -59, -56, -57, -53, -50,
  116158. -58, -52, -50, -50, -52, -53, -54, -58,
  116159. -67, -63, -67, -68, -72, -75, -78, -80,
  116160. -81, -81, -82, -85, -89, -90, -93, -97,
  116161. -101, -107, -114, -999, -999, -999, -999, -999,
  116162. -999, -999, -999, -999, -999, -999, -999, -999},
  116163. { -65, -61, -59, -57, -56, -55, -55, -56,
  116164. -56, -57, -55, -53, -52, -47, -44, -44,
  116165. -50, -44, -41, -39, -39, -42, -40, -46,
  116166. -51, -49, -50, -53, -54, -63, -60, -61,
  116167. -62, -66, -66, -66, -70, -73, -74, -75,
  116168. -76, -75, -79, -85, -89, -91, -96, -102,
  116169. -110, -999, -999, -999, -999, -999, -999, -999},
  116170. { -52, -50, -49, -49, -48, -48, -48, -49,
  116171. -50, -50, -49, -46, -43, -39, -35, -33,
  116172. -38, -36, -32, -29, -32, -32, -32, -35,
  116173. -44, -39, -38, -38, -46, -50, -45, -46,
  116174. -53, -50, -50, -50, -54, -54, -53, -53,
  116175. -56, -57, -59, -66, -70, -72, -74, -79,
  116176. -83, -85, -90, -97, -114, -999, -999, -999}},
  116177. /* 250 Hz */
  116178. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116179. -100, -95, -90, -86, -80, -75, -75, -79,
  116180. -80, -79, -80, -81, -82, -88, -95, -103,
  116181. -110, -999, -999, -999, -999, -999, -999, -999,
  116182. -999, -999, -999, -999, -999, -999, -999, -999,
  116183. -999, -999, -999, -999, -999, -999, -999, -999,
  116184. -999, -999, -999, -999, -999, -999, -999, -999},
  116185. {-999, -999, -999, -999, -108, -103, -98, -93,
  116186. -88, -83, -79, -78, -75, -71, -67, -68,
  116187. -73, -73, -72, -73, -75, -77, -80, -82,
  116188. -88, -93, -100, -107, -114, -999, -999, -999,
  116189. -999, -999, -999, -999, -999, -999, -999, -999,
  116190. -999, -999, -999, -999, -999, -999, -999, -999,
  116191. -999, -999, -999, -999, -999, -999, -999, -999},
  116192. {-999, -999, -999, -110, -105, -101, -96, -90,
  116193. -86, -81, -77, -73, -69, -66, -61, -62,
  116194. -66, -64, -62, -65, -66, -70, -72, -76,
  116195. -81, -80, -84, -90, -95, -102, -110, -999,
  116196. -999, -999, -999, -999, -999, -999, -999, -999,
  116197. -999, -999, -999, -999, -999, -999, -999, -999,
  116198. -999, -999, -999, -999, -999, -999, -999, -999},
  116199. {-999, -999, -999, -107, -103, -97, -92, -88,
  116200. -83, -79, -74, -70, -66, -59, -53, -58,
  116201. -62, -55, -54, -54, -54, -58, -61, -62,
  116202. -72, -70, -72, -75, -78, -80, -81, -80,
  116203. -83, -83, -88, -93, -100, -107, -115, -999,
  116204. -999, -999, -999, -999, -999, -999, -999, -999,
  116205. -999, -999, -999, -999, -999, -999, -999, -999},
  116206. {-999, -999, -999, -105, -100, -95, -90, -85,
  116207. -80, -75, -70, -66, -62, -56, -48, -44,
  116208. -48, -46, -46, -43, -46, -48, -48, -51,
  116209. -58, -58, -59, -60, -62, -62, -61, -61,
  116210. -65, -64, -65, -68, -70, -74, -75, -78,
  116211. -81, -86, -95, -110, -999, -999, -999, -999,
  116212. -999, -999, -999, -999, -999, -999, -999, -999},
  116213. {-999, -999, -105, -100, -95, -90, -85, -80,
  116214. -75, -70, -65, -61, -55, -49, -39, -33,
  116215. -40, -35, -32, -38, -40, -33, -35, -37,
  116216. -46, -41, -45, -44, -46, -42, -45, -46,
  116217. -52, -50, -50, -50, -54, -54, -55, -57,
  116218. -62, -64, -66, -68, -70, -76, -81, -90,
  116219. -100, -110, -999, -999, -999, -999, -999, -999}},
  116220. /* 354 hz */
  116221. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116222. -105, -98, -90, -85, -82, -83, -80, -78,
  116223. -84, -79, -80, -83, -87, -89, -91, -93,
  116224. -99, -106, -117, -999, -999, -999, -999, -999,
  116225. -999, -999, -999, -999, -999, -999, -999, -999,
  116226. -999, -999, -999, -999, -999, -999, -999, -999,
  116227. -999, -999, -999, -999, -999, -999, -999, -999},
  116228. {-999, -999, -999, -999, -999, -999, -999, -999,
  116229. -105, -98, -90, -85, -80, -75, -70, -68,
  116230. -74, -72, -74, -77, -80, -82, -85, -87,
  116231. -92, -89, -91, -95, -100, -106, -112, -999,
  116232. -999, -999, -999, -999, -999, -999, -999, -999,
  116233. -999, -999, -999, -999, -999, -999, -999, -999,
  116234. -999, -999, -999, -999, -999, -999, -999, -999},
  116235. {-999, -999, -999, -999, -999, -999, -999, -999,
  116236. -105, -98, -90, -83, -75, -71, -63, -64,
  116237. -67, -62, -64, -67, -70, -73, -77, -81,
  116238. -84, -83, -85, -89, -90, -93, -98, -104,
  116239. -109, -114, -999, -999, -999, -999, -999, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999,
  116241. -999, -999, -999, -999, -999, -999, -999, -999},
  116242. {-999, -999, -999, -999, -999, -999, -999, -999,
  116243. -103, -96, -88, -81, -75, -68, -58, -54,
  116244. -56, -54, -56, -56, -58, -60, -63, -66,
  116245. -74, -69, -72, -72, -75, -74, -77, -81,
  116246. -81, -82, -84, -87, -93, -96, -99, -104,
  116247. -110, -999, -999, -999, -999, -999, -999, -999,
  116248. -999, -999, -999, -999, -999, -999, -999, -999},
  116249. {-999, -999, -999, -999, -999, -108, -102, -96,
  116250. -91, -85, -80, -74, -68, -60, -51, -46,
  116251. -48, -46, -43, -45, -47, -47, -49, -48,
  116252. -56, -53, -55, -58, -57, -63, -58, -60,
  116253. -66, -64, -67, -70, -70, -74, -77, -84,
  116254. -86, -89, -91, -93, -94, -101, -109, -118,
  116255. -999, -999, -999, -999, -999, -999, -999, -999},
  116256. {-999, -999, -999, -108, -103, -98, -93, -88,
  116257. -83, -78, -73, -68, -60, -53, -44, -35,
  116258. -38, -38, -34, -34, -36, -40, -41, -44,
  116259. -51, -45, -46, -47, -46, -54, -50, -49,
  116260. -50, -50, -50, -51, -54, -57, -58, -60,
  116261. -66, -66, -66, -64, -65, -68, -77, -82,
  116262. -87, -95, -110, -999, -999, -999, -999, -999}},
  116263. /* 500 Hz */
  116264. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116265. -107, -102, -97, -92, -87, -83, -78, -75,
  116266. -82, -79, -83, -85, -89, -92, -95, -98,
  116267. -101, -105, -109, -113, -999, -999, -999, -999,
  116268. -999, -999, -999, -999, -999, -999, -999, -999,
  116269. -999, -999, -999, -999, -999, -999, -999, -999,
  116270. -999, -999, -999, -999, -999, -999, -999, -999},
  116271. {-999, -999, -999, -999, -999, -999, -999, -106,
  116272. -100, -95, -90, -86, -81, -78, -74, -69,
  116273. -74, -74, -76, -79, -83, -84, -86, -89,
  116274. -92, -97, -93, -100, -103, -107, -110, -999,
  116275. -999, -999, -999, -999, -999, -999, -999, -999,
  116276. -999, -999, -999, -999, -999, -999, -999, -999,
  116277. -999, -999, -999, -999, -999, -999, -999, -999},
  116278. {-999, -999, -999, -999, -999, -999, -106, -100,
  116279. -95, -90, -87, -83, -80, -75, -69, -60,
  116280. -66, -66, -68, -70, -74, -78, -79, -81,
  116281. -81, -83, -84, -87, -93, -96, -99, -103,
  116282. -107, -110, -999, -999, -999, -999, -999, -999,
  116283. -999, -999, -999, -999, -999, -999, -999, -999,
  116284. -999, -999, -999, -999, -999, -999, -999, -999},
  116285. {-999, -999, -999, -999, -999, -108, -103, -98,
  116286. -93, -89, -85, -82, -78, -71, -62, -55,
  116287. -58, -58, -54, -54, -55, -59, -61, -62,
  116288. -70, -66, -66, -67, -70, -72, -75, -78,
  116289. -84, -84, -84, -88, -91, -90, -95, -98,
  116290. -102, -103, -106, -110, -999, -999, -999, -999,
  116291. -999, -999, -999, -999, -999, -999, -999, -999},
  116292. {-999, -999, -999, -999, -108, -103, -98, -94,
  116293. -90, -87, -82, -79, -73, -67, -58, -47,
  116294. -50, -45, -41, -45, -48, -44, -44, -49,
  116295. -54, -51, -48, -47, -49, -50, -51, -57,
  116296. -58, -60, -63, -69, -70, -69, -71, -74,
  116297. -78, -82, -90, -95, -101, -105, -110, -999,
  116298. -999, -999, -999, -999, -999, -999, -999, -999},
  116299. {-999, -999, -999, -105, -101, -97, -93, -90,
  116300. -85, -80, -77, -72, -65, -56, -48, -37,
  116301. -40, -36, -34, -40, -50, -47, -38, -41,
  116302. -47, -38, -35, -39, -38, -43, -40, -45,
  116303. -50, -45, -44, -47, -50, -55, -48, -48,
  116304. -52, -66, -70, -76, -82, -90, -97, -105,
  116305. -110, -999, -999, -999, -999, -999, -999, -999}},
  116306. /* 707 Hz */
  116307. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116308. -999, -108, -103, -98, -93, -86, -79, -76,
  116309. -83, -81, -85, -87, -89, -93, -98, -102,
  116310. -107, -112, -999, -999, -999, -999, -999, -999,
  116311. -999, -999, -999, -999, -999, -999, -999, -999,
  116312. -999, -999, -999, -999, -999, -999, -999, -999,
  116313. -999, -999, -999, -999, -999, -999, -999, -999},
  116314. {-999, -999, -999, -999, -999, -999, -999, -999,
  116315. -999, -108, -103, -98, -93, -86, -79, -71,
  116316. -77, -74, -77, -79, -81, -84, -85, -90,
  116317. -92, -93, -92, -98, -101, -108, -112, -999,
  116318. -999, -999, -999, -999, -999, -999, -999, -999,
  116319. -999, -999, -999, -999, -999, -999, -999, -999,
  116320. -999, -999, -999, -999, -999, -999, -999, -999},
  116321. {-999, -999, -999, -999, -999, -999, -999, -999,
  116322. -108, -103, -98, -93, -87, -78, -68, -65,
  116323. -66, -62, -65, -67, -70, -73, -75, -78,
  116324. -82, -82, -83, -84, -91, -93, -98, -102,
  116325. -106, -110, -999, -999, -999, -999, -999, -999,
  116326. -999, -999, -999, -999, -999, -999, -999, -999,
  116327. -999, -999, -999, -999, -999, -999, -999, -999},
  116328. {-999, -999, -999, -999, -999, -999, -999, -999,
  116329. -105, -100, -95, -90, -82, -74, -62, -57,
  116330. -58, -56, -51, -52, -52, -54, -54, -58,
  116331. -66, -59, -60, -63, -66, -69, -73, -79,
  116332. -83, -84, -80, -81, -81, -82, -88, -92,
  116333. -98, -105, -113, -999, -999, -999, -999, -999,
  116334. -999, -999, -999, -999, -999, -999, -999, -999},
  116335. {-999, -999, -999, -999, -999, -999, -999, -107,
  116336. -102, -97, -92, -84, -79, -69, -57, -47,
  116337. -52, -47, -44, -45, -50, -52, -42, -42,
  116338. -53, -43, -43, -48, -51, -56, -55, -52,
  116339. -57, -59, -61, -62, -67, -71, -78, -83,
  116340. -86, -94, -98, -103, -110, -999, -999, -999,
  116341. -999, -999, -999, -999, -999, -999, -999, -999},
  116342. {-999, -999, -999, -999, -999, -999, -105, -100,
  116343. -95, -90, -84, -78, -70, -61, -51, -41,
  116344. -40, -38, -40, -46, -52, -51, -41, -40,
  116345. -46, -40, -38, -38, -41, -46, -41, -46,
  116346. -47, -43, -43, -45, -41, -45, -56, -67,
  116347. -68, -83, -87, -90, -95, -102, -107, -113,
  116348. -999, -999, -999, -999, -999, -999, -999, -999}},
  116349. /* 1000 Hz */
  116350. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116351. -999, -109, -105, -101, -96, -91, -84, -77,
  116352. -82, -82, -85, -89, -94, -100, -106, -110,
  116353. -999, -999, -999, -999, -999, -999, -999, -999,
  116354. -999, -999, -999, -999, -999, -999, -999, -999,
  116355. -999, -999, -999, -999, -999, -999, -999, -999,
  116356. -999, -999, -999, -999, -999, -999, -999, -999},
  116357. {-999, -999, -999, -999, -999, -999, -999, -999,
  116358. -999, -106, -103, -98, -92, -85, -80, -71,
  116359. -75, -72, -76, -80, -84, -86, -89, -93,
  116360. -100, -107, -113, -999, -999, -999, -999, -999,
  116361. -999, -999, -999, -999, -999, -999, -999, -999,
  116362. -999, -999, -999, -999, -999, -999, -999, -999,
  116363. -999, -999, -999, -999, -999, -999, -999, -999},
  116364. {-999, -999, -999, -999, -999, -999, -999, -107,
  116365. -104, -101, -97, -92, -88, -84, -80, -64,
  116366. -66, -63, -64, -66, -69, -73, -77, -83,
  116367. -83, -86, -91, -98, -104, -111, -999, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999,
  116369. -999, -999, -999, -999, -999, -999, -999, -999,
  116370. -999, -999, -999, -999, -999, -999, -999, -999},
  116371. {-999, -999, -999, -999, -999, -999, -999, -107,
  116372. -104, -101, -97, -92, -90, -84, -74, -57,
  116373. -58, -52, -55, -54, -50, -52, -50, -52,
  116374. -63, -62, -69, -76, -77, -78, -78, -79,
  116375. -82, -88, -94, -100, -106, -111, -999, -999,
  116376. -999, -999, -999, -999, -999, -999, -999, -999,
  116377. -999, -999, -999, -999, -999, -999, -999, -999},
  116378. {-999, -999, -999, -999, -999, -999, -106, -102,
  116379. -98, -95, -90, -85, -83, -78, -70, -50,
  116380. -50, -41, -44, -49, -47, -50, -50, -44,
  116381. -55, -46, -47, -48, -48, -54, -49, -49,
  116382. -58, -62, -71, -81, -87, -92, -97, -102,
  116383. -108, -114, -999, -999, -999, -999, -999, -999,
  116384. -999, -999, -999, -999, -999, -999, -999, -999},
  116385. {-999, -999, -999, -999, -999, -999, -106, -102,
  116386. -98, -95, -90, -85, -83, -78, -70, -45,
  116387. -43, -41, -47, -50, -51, -50, -49, -45,
  116388. -47, -41, -44, -41, -39, -43, -38, -37,
  116389. -40, -41, -44, -50, -58, -65, -73, -79,
  116390. -85, -92, -97, -101, -105, -109, -113, -999,
  116391. -999, -999, -999, -999, -999, -999, -999, -999}},
  116392. /* 1414 Hz */
  116393. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116394. -999, -999, -999, -107, -100, -95, -87, -81,
  116395. -85, -83, -88, -93, -100, -107, -114, -999,
  116396. -999, -999, -999, -999, -999, -999, -999, -999,
  116397. -999, -999, -999, -999, -999, -999, -999, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999,
  116399. -999, -999, -999, -999, -999, -999, -999, -999},
  116400. {-999, -999, -999, -999, -999, -999, -999, -999,
  116401. -999, -999, -107, -101, -95, -88, -83, -76,
  116402. -73, -72, -79, -84, -90, -95, -100, -105,
  116403. -110, -115, -999, -999, -999, -999, -999, -999,
  116404. -999, -999, -999, -999, -999, -999, -999, -999,
  116405. -999, -999, -999, -999, -999, -999, -999, -999,
  116406. -999, -999, -999, -999, -999, -999, -999, -999},
  116407. {-999, -999, -999, -999, -999, -999, -999, -999,
  116408. -999, -999, -104, -98, -92, -87, -81, -70,
  116409. -65, -62, -67, -71, -74, -80, -85, -91,
  116410. -95, -99, -103, -108, -111, -114, -999, -999,
  116411. -999, -999, -999, -999, -999, -999, -999, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999,
  116413. -999, -999, -999, -999, -999, -999, -999, -999},
  116414. {-999, -999, -999, -999, -999, -999, -999, -999,
  116415. -999, -999, -103, -97, -90, -85, -76, -60,
  116416. -56, -54, -60, -62, -61, -56, -63, -65,
  116417. -73, -74, -77, -75, -78, -81, -86, -87,
  116418. -88, -91, -94, -98, -103, -110, -999, -999,
  116419. -999, -999, -999, -999, -999, -999, -999, -999,
  116420. -999, -999, -999, -999, -999, -999, -999, -999},
  116421. {-999, -999, -999, -999, -999, -999, -999, -105,
  116422. -100, -97, -92, -86, -81, -79, -70, -57,
  116423. -51, -47, -51, -58, -60, -56, -53, -50,
  116424. -58, -52, -50, -50, -53, -55, -64, -69,
  116425. -71, -85, -82, -78, -81, -85, -95, -102,
  116426. -112, -999, -999, -999, -999, -999, -999, -999,
  116427. -999, -999, -999, -999, -999, -999, -999, -999},
  116428. {-999, -999, -999, -999, -999, -999, -999, -105,
  116429. -100, -97, -92, -85, -83, -79, -72, -49,
  116430. -40, -43, -43, -54, -56, -51, -50, -40,
  116431. -43, -38, -36, -35, -37, -38, -37, -44,
  116432. -54, -60, -57, -60, -70, -75, -84, -92,
  116433. -103, -112, -999, -999, -999, -999, -999, -999,
  116434. -999, -999, -999, -999, -999, -999, -999, -999}},
  116435. /* 2000 Hz */
  116436. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116437. -999, -999, -999, -110, -102, -95, -89, -82,
  116438. -83, -84, -90, -92, -99, -107, -113, -999,
  116439. -999, -999, -999, -999, -999, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999,
  116442. -999, -999, -999, -999, -999, -999, -999, -999},
  116443. {-999, -999, -999, -999, -999, -999, -999, -999,
  116444. -999, -999, -107, -101, -95, -89, -83, -72,
  116445. -74, -78, -85, -88, -88, -90, -92, -98,
  116446. -105, -111, -999, -999, -999, -999, -999, -999,
  116447. -999, -999, -999, -999, -999, -999, -999, -999,
  116448. -999, -999, -999, -999, -999, -999, -999, -999,
  116449. -999, -999, -999, -999, -999, -999, -999, -999},
  116450. {-999, -999, -999, -999, -999, -999, -999, -999,
  116451. -999, -109, -103, -97, -93, -87, -81, -70,
  116452. -70, -67, -75, -73, -76, -79, -81, -83,
  116453. -88, -89, -97, -103, -110, -999, -999, -999,
  116454. -999, -999, -999, -999, -999, -999, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999,
  116456. -999, -999, -999, -999, -999, -999, -999, -999},
  116457. {-999, -999, -999, -999, -999, -999, -999, -999,
  116458. -999, -107, -100, -94, -88, -83, -75, -63,
  116459. -59, -59, -63, -66, -60, -62, -67, -67,
  116460. -77, -76, -81, -88, -86, -92, -96, -102,
  116461. -109, -116, -999, -999, -999, -999, -999, -999,
  116462. -999, -999, -999, -999, -999, -999, -999, -999,
  116463. -999, -999, -999, -999, -999, -999, -999, -999},
  116464. {-999, -999, -999, -999, -999, -999, -999, -999,
  116465. -999, -105, -98, -92, -86, -81, -73, -56,
  116466. -52, -47, -55, -60, -58, -52, -51, -45,
  116467. -49, -50, -53, -54, -61, -71, -70, -69,
  116468. -78, -79, -87, -90, -96, -104, -112, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999,
  116470. -999, -999, -999, -999, -999, -999, -999, -999},
  116471. {-999, -999, -999, -999, -999, -999, -999, -999,
  116472. -999, -103, -96, -90, -86, -78, -70, -51,
  116473. -42, -47, -48, -55, -54, -54, -53, -42,
  116474. -35, -28, -33, -38, -37, -44, -47, -49,
  116475. -54, -63, -68, -78, -82, -89, -94, -99,
  116476. -104, -109, -114, -999, -999, -999, -999, -999,
  116477. -999, -999, -999, -999, -999, -999, -999, -999}},
  116478. /* 2828 Hz */
  116479. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116480. -999, -999, -999, -999, -110, -100, -90, -79,
  116481. -85, -81, -82, -82, -89, -94, -99, -103,
  116482. -109, -115, -999, -999, -999, -999, -999, -999,
  116483. -999, -999, -999, -999, -999, -999, -999, -999,
  116484. -999, -999, -999, -999, -999, -999, -999, -999,
  116485. -999, -999, -999, -999, -999, -999, -999, -999},
  116486. {-999, -999, -999, -999, -999, -999, -999, -999,
  116487. -999, -999, -999, -999, -105, -97, -85, -72,
  116488. -74, -70, -70, -70, -76, -85, -91, -93,
  116489. -97, -103, -109, -115, -999, -999, -999, -999,
  116490. -999, -999, -999, -999, -999, -999, -999, -999,
  116491. -999, -999, -999, -999, -999, -999, -999, -999,
  116492. -999, -999, -999, -999, -999, -999, -999, -999},
  116493. {-999, -999, -999, -999, -999, -999, -999, -999,
  116494. -999, -999, -999, -999, -112, -93, -81, -68,
  116495. -62, -60, -60, -57, -63, -70, -77, -82,
  116496. -90, -93, -98, -104, -109, -113, -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, -999},
  116500. {-999, -999, -999, -999, -999, -999, -999, -999,
  116501. -999, -999, -999, -113, -100, -93, -84, -63,
  116502. -58, -48, -53, -54, -52, -52, -57, -64,
  116503. -66, -76, -83, -81, -85, -85, -90, -95,
  116504. -98, -101, -103, -106, -108, -111, -999, -999,
  116505. -999, -999, -999, -999, -999, -999, -999, -999,
  116506. -999, -999, -999, -999, -999, -999, -999, -999},
  116507. {-999, -999, -999, -999, -999, -999, -999, -999,
  116508. -999, -999, -999, -105, -95, -86, -74, -53,
  116509. -50, -38, -43, -49, -43, -42, -39, -39,
  116510. -46, -52, -57, -56, -72, -69, -74, -81,
  116511. -87, -92, -94, -97, -99, -102, -105, -108,
  116512. -999, -999, -999, -999, -999, -999, -999, -999,
  116513. -999, -999, -999, -999, -999, -999, -999, -999},
  116514. {-999, -999, -999, -999, -999, -999, -999, -999,
  116515. -999, -999, -108, -99, -90, -76, -66, -45,
  116516. -43, -41, -44, -47, -43, -47, -40, -30,
  116517. -31, -31, -39, -33, -40, -41, -43, -53,
  116518. -59, -70, -73, -77, -79, -82, -84, -87,
  116519. -999, -999, -999, -999, -999, -999, -999, -999,
  116520. -999, -999, -999, -999, -999, -999, -999, -999}},
  116521. /* 4000 Hz */
  116522. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116523. -999, -999, -999, -999, -999, -110, -91, -76,
  116524. -75, -85, -93, -98, -104, -110, -999, -999,
  116525. -999, -999, -999, -999, -999, -999, -999, -999,
  116526. -999, -999, -999, -999, -999, -999, -999, -999,
  116527. -999, -999, -999, -999, -999, -999, -999, -999,
  116528. -999, -999, -999, -999, -999, -999, -999, -999},
  116529. {-999, -999, -999, -999, -999, -999, -999, -999,
  116530. -999, -999, -999, -999, -999, -110, -91, -70,
  116531. -70, -75, -86, -89, -94, -98, -101, -106,
  116532. -110, -999, -999, -999, -999, -999, -999, -999,
  116533. -999, -999, -999, -999, -999, -999, -999, -999,
  116534. -999, -999, -999, -999, -999, -999, -999, -999,
  116535. -999, -999, -999, -999, -999, -999, -999, -999},
  116536. {-999, -999, -999, -999, -999, -999, -999, -999,
  116537. -999, -999, -999, -999, -110, -95, -80, -60,
  116538. -65, -64, -74, -83, -88, -91, -95, -99,
  116539. -103, -107, -110, -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, -999, -999, -999, -999, -999, -999, -999,
  116544. -999, -999, -999, -999, -110, -95, -80, -58,
  116545. -55, -49, -66, -68, -71, -78, -78, -80,
  116546. -88, -85, -89, -97, -100, -105, -110, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  116551. -999, -999, -999, -999, -110, -95, -80, -53,
  116552. -52, -41, -59, -59, -49, -58, -56, -63,
  116553. -86, -79, -90, -93, -98, -103, -107, -112,
  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. {-999, -999, -999, -999, -999, -999, -999, -999,
  116558. -999, -999, -999, -110, -97, -91, -73, -45,
  116559. -40, -33, -53, -61, -49, -54, -50, -50,
  116560. -60, -52, -67, -74, -81, -92, -96, -100,
  116561. -105, -110, -999, -999, -999, -999, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999,
  116563. -999, -999, -999, -999, -999, -999, -999, -999}},
  116564. /* 5657 Hz */
  116565. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116566. -999, -999, -999, -113, -106, -99, -92, -77,
  116567. -80, -88, -97, -106, -115, -999, -999, -999,
  116568. -999, -999, -999, -999, -999, -999, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999,
  116570. -999, -999, -999, -999, -999, -999, -999, -999,
  116571. -999, -999, -999, -999, -999, -999, -999, -999},
  116572. {-999, -999, -999, -999, -999, -999, -999, -999,
  116573. -999, -999, -116, -109, -102, -95, -89, -74,
  116574. -72, -88, -87, -95, -102, -109, -116, -999,
  116575. -999, -999, -999, -999, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999,
  116577. -999, -999, -999, -999, -999, -999, -999, -999,
  116578. -999, -999, -999, -999, -999, -999, -999, -999},
  116579. {-999, -999, -999, -999, -999, -999, -999, -999,
  116580. -999, -999, -116, -109, -102, -95, -89, -75,
  116581. -66, -74, -77, -78, -86, -87, -90, -96,
  116582. -105, -115, -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, -999, -999, -999, -999, -999, -999, -999,
  116587. -999, -999, -115, -108, -101, -94, -88, -66,
  116588. -56, -61, -70, -65, -78, -72, -83, -84,
  116589. -93, -98, -105, -110, -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, -999},
  116593. {-999, -999, -999, -999, -999, -999, -999, -999,
  116594. -999, -999, -110, -105, -95, -89, -82, -57,
  116595. -52, -52, -59, -56, -59, -58, -69, -67,
  116596. -88, -82, -82, -89, -94, -100, -108, -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, -999},
  116600. {-999, -999, -999, -999, -999, -999, -999, -999,
  116601. -999, -110, -101, -96, -90, -83, -77, -54,
  116602. -43, -38, -50, -48, -52, -48, -42, -42,
  116603. -51, -52, -53, -59, -65, -71, -78, -85,
  116604. -95, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999}},
  116607. /* 8000 Hz */
  116608. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116609. -999, -999, -999, -999, -120, -105, -86, -68,
  116610. -78, -79, -90, -100, -110, -999, -999, -999,
  116611. -999, -999, -999, -999, -999, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999,
  116613. -999, -999, -999, -999, -999, -999, -999, -999,
  116614. -999, -999, -999, -999, -999, -999, -999, -999},
  116615. {-999, -999, -999, -999, -999, -999, -999, -999,
  116616. -999, -999, -999, -999, -120, -105, -86, -66,
  116617. -73, -77, -88, -96, -105, -115, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999,
  116620. -999, -999, -999, -999, -999, -999, -999, -999,
  116621. -999, -999, -999, -999, -999, -999, -999, -999},
  116622. {-999, -999, -999, -999, -999, -999, -999, -999,
  116623. -999, -999, -999, -120, -105, -92, -80, -61,
  116624. -64, -68, -80, -87, -92, -100, -110, -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, -999, -999, -999, -999, -999, -999,
  116630. -999, -999, -999, -120, -104, -91, -79, -52,
  116631. -60, -54, -64, -69, -77, -80, -82, -84,
  116632. -85, -87, -88, -90, -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, -999, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -118, -100, -87, -77, -49,
  116638. -50, -44, -58, -61, -61, -67, -65, -62,
  116639. -62, -62, -65, -68, -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, -999, -999, -999, -999, -999, -999,
  116644. -999, -999, -999, -115, -98, -84, -62, -49,
  116645. -44, -38, -46, -49, -49, -46, -39, -37,
  116646. -39, -40, -42, -43, -999, -999, -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, -999}},
  116650. /* 11314 Hz */
  116651. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116652. -999, -999, -999, -999, -999, -110, -88, -74,
  116653. -77, -82, -82, -85, -90, -94, -99, -104,
  116654. -999, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999,
  116656. -999, -999, -999, -999, -999, -999, -999, -999,
  116657. -999, -999, -999, -999, -999, -999, -999, -999},
  116658. {-999, -999, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -999, -999, -110, -88, -66,
  116660. -70, -81, -80, -81, -84, -88, -91, -93,
  116661. -999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999,
  116663. -999, -999, -999, -999, -999, -999, -999, -999,
  116664. -999, -999, -999, -999, -999, -999, -999, -999},
  116665. {-999, -999, -999, -999, -999, -999, -999, -999,
  116666. -999, -999, -999, -999, -999, -110, -88, -61,
  116667. -63, -70, -71, -74, -77, -80, -83, -85,
  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, -999, -999, -999, -999, -999, -999,
  116673. -999, -999, -999, -999, -999, -110, -86, -62,
  116674. -63, -62, -62, -58, -52, -50, -50, -52,
  116675. -54, -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, -999, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -999, -118, -108, -84, -53,
  116681. -50, -50, -50, -55, -47, -45, -40, -40,
  116682. -40, -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, -999, -999, -999, -999, -999, -999, -999,
  116687. -999, -999, -999, -999, -118, -100, -73, -43,
  116688. -37, -42, -43, -53, -38, -37, -35, -35,
  116689. -38, -999, -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. /* 16000 Hz */
  116694. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116695. -999, -999, -999, -110, -100, -91, -84, -74,
  116696. -80, -80, -80, -80, -80, -999, -999, -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, -999, -999, -999, -999, -999, -999, -999},
  116701. {-999, -999, -999, -999, -999, -999, -999, -999,
  116702. -999, -999, -999, -110, -100, -91, -84, -74,
  116703. -68, -68, -68, -68, -68, -999, -999, -999,
  116704. -999, -999, -999, -999, -999, -999, -999, -999,
  116705. -999, -999, -999, -999, -999, -999, -999, -999,
  116706. -999, -999, -999, -999, -999, -999, -999, -999,
  116707. -999, -999, -999, -999, -999, -999, -999, -999},
  116708. {-999, -999, -999, -999, -999, -999, -999, -999,
  116709. -999, -999, -999, -110, -100, -86, -78, -70,
  116710. -60, -45, -30, -21, -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, -999, -999, -999, -999,
  116716. -999, -999, -999, -110, -100, -87, -78, -67,
  116717. -48, -38, -29, -21, -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, -999, -999, -999, -999,
  116723. -999, -999, -999, -110, -100, -86, -69, -56,
  116724. -45, -35, -33, -29, -999, -999, -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, -999, -999, -999, -999, -999,
  116730. -999, -999, -999, -110, -100, -83, -71, -48,
  116731. -27, -38, -37, -34, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -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. };
  116737. #endif
  116738. /*** End of inlined file: masking.h ***/
  116739. #define NEGINF -9999.f
  116740. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116741. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116742. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116743. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116744. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116745. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116746. look->channels=vi->channels;
  116747. look->ampmax=-9999.;
  116748. look->gi=gi;
  116749. return(look);
  116750. }
  116751. void _vp_global_free(vorbis_look_psy_global *look){
  116752. if(look){
  116753. memset(look,0,sizeof(*look));
  116754. _ogg_free(look);
  116755. }
  116756. }
  116757. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116758. if(i){
  116759. memset(i,0,sizeof(*i));
  116760. _ogg_free(i);
  116761. }
  116762. }
  116763. void _vi_psy_free(vorbis_info_psy *i){
  116764. if(i){
  116765. memset(i,0,sizeof(*i));
  116766. _ogg_free(i);
  116767. }
  116768. }
  116769. static void min_curve(float *c,
  116770. float *c2){
  116771. int i;
  116772. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116773. }
  116774. static void max_curve(float *c,
  116775. float *c2){
  116776. int i;
  116777. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116778. }
  116779. static void attenuate_curve(float *c,float att){
  116780. int i;
  116781. for(i=0;i<EHMER_MAX;i++)
  116782. c[i]+=att;
  116783. }
  116784. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116785. float center_boost, float center_decay_rate){
  116786. int i,j,k,m;
  116787. float ath[EHMER_MAX];
  116788. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116789. float athc[P_LEVELS][EHMER_MAX];
  116790. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116791. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116792. memset(workc,0,sizeof(workc));
  116793. for(i=0;i<P_BANDS;i++){
  116794. /* we add back in the ATH to avoid low level curves falling off to
  116795. -infinity and unnecessarily cutting off high level curves in the
  116796. curve limiting (last step). */
  116797. /* A half-band's settings must be valid over the whole band, and
  116798. it's better to mask too little than too much */
  116799. int ath_offset=i*4;
  116800. for(j=0;j<EHMER_MAX;j++){
  116801. float min=999.;
  116802. for(k=0;k<4;k++)
  116803. if(j+k+ath_offset<MAX_ATH){
  116804. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116805. }else{
  116806. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116807. }
  116808. ath[j]=min;
  116809. }
  116810. /* copy curves into working space, replicate the 50dB curve to 30
  116811. and 40, replicate the 100dB curve to 110 */
  116812. for(j=0;j<6;j++)
  116813. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116814. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116815. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116816. /* apply centered curve boost/decay */
  116817. for(j=0;j<P_LEVELS;j++){
  116818. for(k=0;k<EHMER_MAX;k++){
  116819. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116820. if(adj<0. && center_boost>0)adj=0.;
  116821. if(adj>0. && center_boost<0)adj=0.;
  116822. workc[i][j][k]+=adj;
  116823. }
  116824. }
  116825. /* normalize curves so the driving amplitude is 0dB */
  116826. /* make temp curves with the ATH overlayed */
  116827. for(j=0;j<P_LEVELS;j++){
  116828. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116829. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116830. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116831. max_curve(athc[j],workc[i][j]);
  116832. }
  116833. /* Now limit the louder curves.
  116834. the idea is this: We don't know what the playback attenuation
  116835. will be; 0dB SL moves every time the user twiddles the volume
  116836. knob. So that means we have to use a single 'most pessimal' curve
  116837. for all masking amplitudes, right? Wrong. The *loudest* sound
  116838. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116839. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116840. etc... */
  116841. for(j=1;j<P_LEVELS;j++){
  116842. min_curve(athc[j],athc[j-1]);
  116843. min_curve(workc[i][j],athc[j]);
  116844. }
  116845. }
  116846. for(i=0;i<P_BANDS;i++){
  116847. int hi_curve,lo_curve,bin;
  116848. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116849. /* low frequency curves are measured with greater resolution than
  116850. the MDCT/FFT will actually give us; we want the curve applied
  116851. to the tone data to be pessimistic and thus apply the minimum
  116852. masking possible for a given bin. That means that a single bin
  116853. could span more than one octave and that the curve will be a
  116854. composite of multiple octaves. It also may mean that a single
  116855. bin may span > an eighth of an octave and that the eighth
  116856. octave values may also be composited. */
  116857. /* which octave curves will we be compositing? */
  116858. bin=floor(fromOC(i*.5)/binHz);
  116859. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116860. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116861. if(lo_curve>i)lo_curve=i;
  116862. if(lo_curve<0)lo_curve=0;
  116863. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116864. for(m=0;m<P_LEVELS;m++){
  116865. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116866. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116867. /* render the curve into bins, then pull values back into curve.
  116868. The point is that any inherent subsampling aliasing results in
  116869. a safe minimum */
  116870. for(k=lo_curve;k<=hi_curve;k++){
  116871. int l=0;
  116872. for(j=0;j<EHMER_MAX;j++){
  116873. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116874. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116875. if(lo_bin<0)lo_bin=0;
  116876. if(lo_bin>n)lo_bin=n;
  116877. if(lo_bin<l)l=lo_bin;
  116878. if(hi_bin<0)hi_bin=0;
  116879. if(hi_bin>n)hi_bin=n;
  116880. for(;l<hi_bin && l<n;l++)
  116881. if(brute_buffer[l]>workc[k][m][j])
  116882. brute_buffer[l]=workc[k][m][j];
  116883. }
  116884. for(;l<n;l++)
  116885. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116886. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116887. }
  116888. /* be equally paranoid about being valid up to next half ocatve */
  116889. if(i+1<P_BANDS){
  116890. int l=0;
  116891. k=i+1;
  116892. for(j=0;j<EHMER_MAX;j++){
  116893. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116894. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116895. if(lo_bin<0)lo_bin=0;
  116896. if(lo_bin>n)lo_bin=n;
  116897. if(lo_bin<l)l=lo_bin;
  116898. if(hi_bin<0)hi_bin=0;
  116899. if(hi_bin>n)hi_bin=n;
  116900. for(;l<hi_bin && l<n;l++)
  116901. if(brute_buffer[l]>workc[k][m][j])
  116902. brute_buffer[l]=workc[k][m][j];
  116903. }
  116904. for(;l<n;l++)
  116905. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116906. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116907. }
  116908. for(j=0;j<EHMER_MAX;j++){
  116909. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116910. if(bin<0){
  116911. ret[i][m][j+2]=-999.;
  116912. }else{
  116913. if(bin>=n){
  116914. ret[i][m][j+2]=-999.;
  116915. }else{
  116916. ret[i][m][j+2]=brute_buffer[bin];
  116917. }
  116918. }
  116919. }
  116920. /* add fenceposts */
  116921. for(j=0;j<EHMER_OFFSET;j++)
  116922. if(ret[i][m][j+2]>-200.f)break;
  116923. ret[i][m][0]=j;
  116924. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116925. if(ret[i][m][j+2]>-200.f)
  116926. break;
  116927. ret[i][m][1]=j;
  116928. }
  116929. }
  116930. return(ret);
  116931. }
  116932. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116933. vorbis_info_psy_global *gi,int n,long rate){
  116934. long i,j,lo=-99,hi=1;
  116935. long maxoc;
  116936. memset(p,0,sizeof(*p));
  116937. p->eighth_octave_lines=gi->eighth_octave_lines;
  116938. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116939. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116940. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116941. p->total_octave_lines=maxoc-p->firstoc+1;
  116942. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116943. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116944. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116945. p->vi=vi;
  116946. p->n=n;
  116947. p->rate=rate;
  116948. /* AoTuV HF weighting */
  116949. p->m_val = 1.;
  116950. if(rate < 26000) p->m_val = 0;
  116951. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116952. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116953. /* set up the lookups for a given blocksize and sample rate */
  116954. for(i=0,j=0;i<MAX_ATH-1;i++){
  116955. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116956. float base=ATH[i];
  116957. if(j<endpos){
  116958. float delta=(ATH[i+1]-base)/(endpos-j);
  116959. for(;j<endpos && j<n;j++){
  116960. p->ath[j]=base+100.;
  116961. base+=delta;
  116962. }
  116963. }
  116964. }
  116965. for(i=0;i<n;i++){
  116966. float bark=toBARK(rate/(2*n)*i);
  116967. for(;lo+vi->noisewindowlomin<i &&
  116968. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116969. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116970. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116971. p->bark[i]=((lo-1)<<16)+(hi-1);
  116972. }
  116973. for(i=0;i<n;i++)
  116974. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116975. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116976. vi->tone_centerboost,vi->tone_decay);
  116977. /* set up rolling noise median */
  116978. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116979. for(i=0;i<P_NOISECURVES;i++)
  116980. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116981. for(i=0;i<n;i++){
  116982. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116983. int inthalfoc;
  116984. float del;
  116985. if(halfoc<0)halfoc=0;
  116986. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116987. inthalfoc=(int)halfoc;
  116988. del=halfoc-inthalfoc;
  116989. for(j=0;j<P_NOISECURVES;j++)
  116990. p->noiseoffset[j][i]=
  116991. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116992. p->vi->noiseoff[j][inthalfoc+1]*del;
  116993. }
  116994. #if 0
  116995. {
  116996. static int ls=0;
  116997. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116998. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116999. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117000. }
  117001. #endif
  117002. }
  117003. void _vp_psy_clear(vorbis_look_psy *p){
  117004. int i,j;
  117005. if(p){
  117006. if(p->ath)_ogg_free(p->ath);
  117007. if(p->octave)_ogg_free(p->octave);
  117008. if(p->bark)_ogg_free(p->bark);
  117009. if(p->tonecurves){
  117010. for(i=0;i<P_BANDS;i++){
  117011. for(j=0;j<P_LEVELS;j++){
  117012. _ogg_free(p->tonecurves[i][j]);
  117013. }
  117014. _ogg_free(p->tonecurves[i]);
  117015. }
  117016. _ogg_free(p->tonecurves);
  117017. }
  117018. if(p->noiseoffset){
  117019. for(i=0;i<P_NOISECURVES;i++){
  117020. _ogg_free(p->noiseoffset[i]);
  117021. }
  117022. _ogg_free(p->noiseoffset);
  117023. }
  117024. memset(p,0,sizeof(*p));
  117025. }
  117026. }
  117027. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117028. static void seed_curve(float *seed,
  117029. const float **curves,
  117030. float amp,
  117031. int oc, int n,
  117032. int linesper,float dBoffset){
  117033. int i,post1;
  117034. int seedptr;
  117035. const float *posts,*curve;
  117036. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117037. choice=max(choice,0);
  117038. choice=min(choice,P_LEVELS-1);
  117039. posts=curves[choice];
  117040. curve=posts+2;
  117041. post1=(int)posts[1];
  117042. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117043. for(i=posts[0];i<post1;i++){
  117044. if(seedptr>0){
  117045. float lin=amp+curve[i];
  117046. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117047. }
  117048. seedptr+=linesper;
  117049. if(seedptr>=n)break;
  117050. }
  117051. }
  117052. static void seed_loop(vorbis_look_psy *p,
  117053. const float ***curves,
  117054. const float *f,
  117055. const float *flr,
  117056. float *seed,
  117057. float specmax){
  117058. vorbis_info_psy *vi=p->vi;
  117059. long n=p->n,i;
  117060. float dBoffset=vi->max_curve_dB-specmax;
  117061. /* prime the working vector with peak values */
  117062. for(i=0;i<n;i++){
  117063. float max=f[i];
  117064. long oc=p->octave[i];
  117065. while(i+1<n && p->octave[i+1]==oc){
  117066. i++;
  117067. if(f[i]>max)max=f[i];
  117068. }
  117069. if(max+6.f>flr[i]){
  117070. oc=oc>>p->shiftoc;
  117071. if(oc>=P_BANDS)oc=P_BANDS-1;
  117072. if(oc<0)oc=0;
  117073. seed_curve(seed,
  117074. curves[oc],
  117075. max,
  117076. p->octave[i]-p->firstoc,
  117077. p->total_octave_lines,
  117078. p->eighth_octave_lines,
  117079. dBoffset);
  117080. }
  117081. }
  117082. }
  117083. static void seed_chase(float *seeds, int linesper, long n){
  117084. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117085. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117086. long stack=0;
  117087. long pos=0;
  117088. long i;
  117089. for(i=0;i<n;i++){
  117090. if(stack<2){
  117091. posstack[stack]=i;
  117092. ampstack[stack++]=seeds[i];
  117093. }else{
  117094. while(1){
  117095. if(seeds[i]<ampstack[stack-1]){
  117096. posstack[stack]=i;
  117097. ampstack[stack++]=seeds[i];
  117098. break;
  117099. }else{
  117100. if(i<posstack[stack-1]+linesper){
  117101. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117102. i<posstack[stack-2]+linesper){
  117103. /* we completely overlap, making stack-1 irrelevant. pop it */
  117104. stack--;
  117105. continue;
  117106. }
  117107. }
  117108. posstack[stack]=i;
  117109. ampstack[stack++]=seeds[i];
  117110. break;
  117111. }
  117112. }
  117113. }
  117114. }
  117115. /* the stack now contains only the positions that are relevant. Scan
  117116. 'em straight through */
  117117. for(i=0;i<stack;i++){
  117118. long endpos;
  117119. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117120. endpos=posstack[i+1];
  117121. }else{
  117122. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117123. discarded in short frames */
  117124. }
  117125. if(endpos>n)endpos=n;
  117126. for(;pos<endpos;pos++)
  117127. seeds[pos]=ampstack[i];
  117128. }
  117129. /* there. Linear time. I now remember this was on a problem set I
  117130. had in Grad Skool... I didn't solve it at the time ;-) */
  117131. }
  117132. /* bleaugh, this is more complicated than it needs to be */
  117133. #include<stdio.h>
  117134. static void max_seeds(vorbis_look_psy *p,
  117135. float *seed,
  117136. float *flr){
  117137. long n=p->total_octave_lines;
  117138. int linesper=p->eighth_octave_lines;
  117139. long linpos=0;
  117140. long pos;
  117141. seed_chase(seed,linesper,n); /* for masking */
  117142. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117143. while(linpos+1<p->n){
  117144. float minV=seed[pos];
  117145. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117146. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117147. while(pos+1<=end){
  117148. pos++;
  117149. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117150. minV=seed[pos];
  117151. }
  117152. end=pos+p->firstoc;
  117153. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117154. if(flr[linpos]<minV)flr[linpos]=minV;
  117155. }
  117156. {
  117157. float minV=seed[p->total_octave_lines-1];
  117158. for(;linpos<p->n;linpos++)
  117159. if(flr[linpos]<minV)flr[linpos]=minV;
  117160. }
  117161. }
  117162. static void bark_noise_hybridmp(int n,const long *b,
  117163. const float *f,
  117164. float *noise,
  117165. const float offset,
  117166. const int fixed){
  117167. float *N=(float*) alloca(n*sizeof(*N));
  117168. float *X=(float*) alloca(n*sizeof(*N));
  117169. float *XX=(float*) alloca(n*sizeof(*N));
  117170. float *Y=(float*) alloca(n*sizeof(*N));
  117171. float *XY=(float*) alloca(n*sizeof(*N));
  117172. float tN, tX, tXX, tY, tXY;
  117173. int i;
  117174. int lo, hi;
  117175. float R, A, B, D;
  117176. float w, x, y;
  117177. tN = tX = tXX = tY = tXY = 0.f;
  117178. y = f[0] + offset;
  117179. if (y < 1.f) y = 1.f;
  117180. w = y * y * .5;
  117181. tN += w;
  117182. tX += w;
  117183. tY += w * y;
  117184. N[0] = tN;
  117185. X[0] = tX;
  117186. XX[0] = tXX;
  117187. Y[0] = tY;
  117188. XY[0] = tXY;
  117189. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117190. y = f[i] + offset;
  117191. if (y < 1.f) y = 1.f;
  117192. w = y * y;
  117193. tN += w;
  117194. tX += w * x;
  117195. tXX += w * x * x;
  117196. tY += w * y;
  117197. tXY += w * x * y;
  117198. N[i] = tN;
  117199. X[i] = tX;
  117200. XX[i] = tXX;
  117201. Y[i] = tY;
  117202. XY[i] = tXY;
  117203. }
  117204. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117205. lo = b[i] >> 16;
  117206. if( lo>=0 ) break;
  117207. hi = b[i] & 0xffff;
  117208. tN = N[hi] + N[-lo];
  117209. tX = X[hi] - X[-lo];
  117210. tXX = XX[hi] + XX[-lo];
  117211. tY = Y[hi] + Y[-lo];
  117212. tXY = XY[hi] - XY[-lo];
  117213. A = tY * tXX - tX * tXY;
  117214. B = tN * tXY - tX * tY;
  117215. D = tN * tXX - tX * tX;
  117216. R = (A + x * B) / D;
  117217. if (R < 0.f)
  117218. R = 0.f;
  117219. noise[i] = R - offset;
  117220. }
  117221. for ( ;; i++, x += 1.f) {
  117222. lo = b[i] >> 16;
  117223. hi = b[i] & 0xffff;
  117224. if(hi>=n)break;
  117225. tN = N[hi] - N[lo];
  117226. tX = X[hi] - X[lo];
  117227. tXX = XX[hi] - XX[lo];
  117228. tY = Y[hi] - Y[lo];
  117229. tXY = XY[hi] - XY[lo];
  117230. A = tY * tXX - tX * tXY;
  117231. B = tN * tXY - tX * tY;
  117232. D = tN * tXX - tX * tX;
  117233. R = (A + x * B) / D;
  117234. if (R < 0.f) R = 0.f;
  117235. noise[i] = R - offset;
  117236. }
  117237. for ( ; i < n; i++, x += 1.f) {
  117238. R = (A + x * B) / D;
  117239. if (R < 0.f) R = 0.f;
  117240. noise[i] = R - offset;
  117241. }
  117242. if (fixed <= 0) return;
  117243. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117244. hi = i + fixed / 2;
  117245. lo = hi - fixed;
  117246. if(lo>=0)break;
  117247. tN = N[hi] + N[-lo];
  117248. tX = X[hi] - X[-lo];
  117249. tXX = XX[hi] + XX[-lo];
  117250. tY = Y[hi] + Y[-lo];
  117251. tXY = XY[hi] - XY[-lo];
  117252. A = tY * tXX - tX * tXY;
  117253. B = tN * tXY - tX * tY;
  117254. D = tN * tXX - tX * tX;
  117255. R = (A + x * B) / D;
  117256. if (R - offset < noise[i]) noise[i] = R - offset;
  117257. }
  117258. for ( ;; i++, x += 1.f) {
  117259. hi = i + fixed / 2;
  117260. lo = hi - fixed;
  117261. if(hi>=n)break;
  117262. tN = N[hi] - N[lo];
  117263. tX = X[hi] - X[lo];
  117264. tXX = XX[hi] - XX[lo];
  117265. tY = Y[hi] - Y[lo];
  117266. tXY = XY[hi] - XY[lo];
  117267. A = tY * tXX - tX * tXY;
  117268. B = tN * tXY - tX * tY;
  117269. D = tN * tXX - tX * tX;
  117270. R = (A + x * B) / D;
  117271. if (R - offset < noise[i]) noise[i] = R - offset;
  117272. }
  117273. for ( ; i < n; i++, x += 1.f) {
  117274. R = (A + x * B) / D;
  117275. if (R - offset < noise[i]) noise[i] = R - offset;
  117276. }
  117277. }
  117278. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117279. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117280. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117281. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117282. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117283. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117284. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117285. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117286. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117287. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117288. 973377.F, 913981.F, 858210.F, 805842.F,
  117289. 756669.F, 710497.F, 667142.F, 626433.F,
  117290. 588208.F, 552316.F, 518613.F, 486967.F,
  117291. 457252.F, 429351.F, 403152.F, 378551.F,
  117292. 355452.F, 333762.F, 313396.F, 294273.F,
  117293. 276316.F, 259455.F, 243623.F, 228757.F,
  117294. 214798.F, 201691.F, 189384.F, 177828.F,
  117295. 166977.F, 156788.F, 147221.F, 138237.F,
  117296. 129802.F, 121881.F, 114444.F, 107461.F,
  117297. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117298. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117299. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117300. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117301. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117302. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117303. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117304. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117305. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117306. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117307. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117308. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117309. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117310. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117311. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117312. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117313. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117314. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117315. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117316. 842.910F, 791.475F, 743.179F, 697.830F,
  117317. 655.249F, 615.265F, 577.722F, 542.469F,
  117318. 509.367F, 478.286F, 449.101F, 421.696F,
  117319. 395.964F, 371.803F, 349.115F, 327.812F,
  117320. 307.809F, 289.026F, 271.390F, 254.830F,
  117321. 239.280F, 224.679F, 210.969F, 198.096F,
  117322. 186.008F, 174.658F, 164.000F, 153.993F,
  117323. 144.596F, 135.773F, 127.488F, 119.708F,
  117324. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117325. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117326. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117327. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117328. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117329. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117330. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117331. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117332. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117333. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117334. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117335. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117336. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117337. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117338. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117339. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117340. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117341. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117342. 1.20790F, 1.13419F, 1.06499F, 1.F
  117343. };
  117344. void _vp_remove_floor(vorbis_look_psy *p,
  117345. float *mdct,
  117346. int *codedflr,
  117347. float *residue,
  117348. int sliding_lowpass){
  117349. int i,n=p->n;
  117350. if(sliding_lowpass>n)sliding_lowpass=n;
  117351. for(i=0;i<sliding_lowpass;i++){
  117352. residue[i]=
  117353. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117354. }
  117355. for(;i<n;i++)
  117356. residue[i]=0.;
  117357. }
  117358. void _vp_noisemask(vorbis_look_psy *p,
  117359. float *logmdct,
  117360. float *logmask){
  117361. int i,n=p->n;
  117362. float *work=(float*) alloca(n*sizeof(*work));
  117363. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117364. 140.,-1);
  117365. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117366. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117367. p->vi->noisewindowfixed);
  117368. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117369. #if 0
  117370. {
  117371. static int seq=0;
  117372. float work2[n];
  117373. for(i=0;i<n;i++){
  117374. work2[i]=logmask[i]+work[i];
  117375. }
  117376. if(seq&1)
  117377. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117378. else
  117379. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117380. if(seq&1)
  117381. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117382. else
  117383. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117384. seq++;
  117385. }
  117386. #endif
  117387. for(i=0;i<n;i++){
  117388. int dB=logmask[i]+.5;
  117389. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117390. if(dB<0)dB=0;
  117391. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117392. }
  117393. }
  117394. void _vp_tonemask(vorbis_look_psy *p,
  117395. float *logfft,
  117396. float *logmask,
  117397. float global_specmax,
  117398. float local_specmax){
  117399. int i,n=p->n;
  117400. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117401. float att=local_specmax+p->vi->ath_adjatt;
  117402. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117403. /* set the ATH (floating below localmax, not global max by a
  117404. specified att) */
  117405. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117406. for(i=0;i<n;i++)
  117407. logmask[i]=p->ath[i]+att;
  117408. /* tone masking */
  117409. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117410. max_seeds(p,seed,logmask);
  117411. }
  117412. void _vp_offset_and_mix(vorbis_look_psy *p,
  117413. float *noise,
  117414. float *tone,
  117415. int offset_select,
  117416. float *logmask,
  117417. float *mdct,
  117418. float *logmdct){
  117419. int i,n=p->n;
  117420. float de, coeffi, cx;/* AoTuV */
  117421. float toneatt=p->vi->tone_masteratt[offset_select];
  117422. cx = p->m_val;
  117423. for(i=0;i<n;i++){
  117424. float val= noise[i]+p->noiseoffset[offset_select][i];
  117425. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117426. logmask[i]=max(val,tone[i]+toneatt);
  117427. /* AoTuV */
  117428. /** @ M1 **
  117429. The following codes improve a noise problem.
  117430. A fundamental idea uses the value of masking and carries out
  117431. the relative compensation of the MDCT.
  117432. However, this code is not perfect and all noise problems cannot be solved.
  117433. by Aoyumi @ 2004/04/18
  117434. */
  117435. if(offset_select == 1) {
  117436. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117437. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117438. if(val > coeffi){
  117439. /* mdct value is > -17.2 dB below floor */
  117440. de = 1.0-((val-coeffi)*0.005*cx);
  117441. /* pro-rated attenuation:
  117442. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117443. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117444. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117445. etc... */
  117446. if(de < 0) de = 0.0001;
  117447. }else
  117448. /* mdct value is <= -17.2 dB below floor */
  117449. de = 1.0-((val-coeffi)*0.0003*cx);
  117450. /* pro-rated attenuation:
  117451. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117452. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117453. etc... */
  117454. mdct[i] *= de;
  117455. }
  117456. }
  117457. }
  117458. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117459. vorbis_info *vi=vd->vi;
  117460. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117461. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117462. int n=ci->blocksizes[vd->W]/2;
  117463. float secs=(float)n/vi->rate;
  117464. amp+=secs*gi->ampmax_att_per_sec;
  117465. if(amp<-9999)amp=-9999;
  117466. return(amp);
  117467. }
  117468. static void couple_lossless(float A, float B,
  117469. float *qA, float *qB){
  117470. int test1=fabs(*qA)>fabs(*qB);
  117471. test1-= fabs(*qA)<fabs(*qB);
  117472. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117473. if(test1==1){
  117474. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117475. }else{
  117476. float temp=*qB;
  117477. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117478. *qA=temp;
  117479. }
  117480. if(*qB>fabs(*qA)*1.9999f){
  117481. *qB= -fabs(*qA)*2.f;
  117482. *qA= -*qA;
  117483. }
  117484. }
  117485. static float hypot_lookup[32]={
  117486. -0.009935, -0.011245, -0.012726, -0.014397,
  117487. -0.016282, -0.018407, -0.020800, -0.023494,
  117488. -0.026522, -0.029923, -0.033737, -0.038010,
  117489. -0.042787, -0.048121, -0.054064, -0.060671,
  117490. -0.068000, -0.076109, -0.085054, -0.094892,
  117491. -0.105675, -0.117451, -0.130260, -0.144134,
  117492. -0.159093, -0.175146, -0.192286, -0.210490,
  117493. -0.229718, -0.249913, -0.271001, -0.292893};
  117494. static void precomputed_couple_point(float premag,
  117495. int floorA,int floorB,
  117496. float *mag, float *ang){
  117497. int test=(floorA>floorB)-1;
  117498. int offset=31-abs(floorA-floorB);
  117499. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117500. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117501. *mag=premag*floormag;
  117502. *ang=0.f;
  117503. }
  117504. /* just like below, this is currently set up to only do
  117505. single-step-depth coupling. Otherwise, we'd have to do more
  117506. copying (which will be inevitable later) */
  117507. /* doing the real circular magnitude calculation is audibly superior
  117508. to (A+B)/sqrt(2) */
  117509. static float dipole_hypot(float a, float b){
  117510. if(a>0.){
  117511. if(b>0.)return sqrt(a*a+b*b);
  117512. if(a>-b)return sqrt(a*a-b*b);
  117513. return -sqrt(b*b-a*a);
  117514. }
  117515. if(b<0.)return -sqrt(a*a+b*b);
  117516. if(-a>b)return -sqrt(a*a-b*b);
  117517. return sqrt(b*b-a*a);
  117518. }
  117519. static float round_hypot(float a, float b){
  117520. if(a>0.){
  117521. if(b>0.)return sqrt(a*a+b*b);
  117522. if(a>-b)return sqrt(a*a+b*b);
  117523. return -sqrt(b*b+a*a);
  117524. }
  117525. if(b<0.)return -sqrt(a*a+b*b);
  117526. if(-a>b)return -sqrt(a*a+b*b);
  117527. return sqrt(b*b+a*a);
  117528. }
  117529. /* revert to round hypot for now */
  117530. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117531. vorbis_info_psy_global *g,
  117532. vorbis_look_psy *p,
  117533. vorbis_info_mapping0 *vi,
  117534. float **mdct){
  117535. int i,j,n=p->n;
  117536. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117537. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117538. for(i=0;i<vi->coupling_steps;i++){
  117539. float *mdctM=mdct[vi->coupling_mag[i]];
  117540. float *mdctA=mdct[vi->coupling_ang[i]];
  117541. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117542. for(j=0;j<limit;j++)
  117543. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117544. for(;j<n;j++)
  117545. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117546. }
  117547. return(ret);
  117548. }
  117549. /* this is for per-channel noise normalization */
  117550. static int JUCE_CDECL apsort(const void *a, const void *b){
  117551. float f1=fabs(**(float**)a);
  117552. float f2=fabs(**(float**)b);
  117553. return (f1<f2)-(f1>f2);
  117554. }
  117555. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117556. vorbis_look_psy *p,
  117557. vorbis_info_mapping0 *vi,
  117558. float **mags){
  117559. if(p->vi->normal_point_p){
  117560. int i,j,k,n=p->n;
  117561. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117562. int partition=p->vi->normal_partition;
  117563. float **work=(float**) alloca(sizeof(*work)*partition);
  117564. for(i=0;i<vi->coupling_steps;i++){
  117565. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117566. for(j=0;j<n;j+=partition){
  117567. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117568. qsort(work,partition,sizeof(*work),apsort);
  117569. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117570. }
  117571. }
  117572. return(ret);
  117573. }
  117574. return(NULL);
  117575. }
  117576. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117577. float *magnitudes,int *sortedindex){
  117578. int i,j,n=p->n;
  117579. vorbis_info_psy *vi=p->vi;
  117580. int partition=vi->normal_partition;
  117581. float **work=(float**) alloca(sizeof(*work)*partition);
  117582. int start=vi->normal_start;
  117583. for(j=start;j<n;j+=partition){
  117584. if(j+partition>n)partition=n-j;
  117585. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117586. qsort(work,partition,sizeof(*work),apsort);
  117587. for(i=0;i<partition;i++){
  117588. sortedindex[i+j-start]=work[i]-magnitudes;
  117589. }
  117590. }
  117591. }
  117592. void _vp_noise_normalize(vorbis_look_psy *p,
  117593. float *in,float *out,int *sortedindex){
  117594. int flag=0,i,j=0,n=p->n;
  117595. vorbis_info_psy *vi=p->vi;
  117596. int partition=vi->normal_partition;
  117597. int start=vi->normal_start;
  117598. if(start>n)start=n;
  117599. if(vi->normal_channel_p){
  117600. for(;j<start;j++)
  117601. out[j]=rint(in[j]);
  117602. for(;j+partition<=n;j+=partition){
  117603. float acc=0.;
  117604. int k;
  117605. for(i=j;i<j+partition;i++)
  117606. acc+=in[i]*in[i];
  117607. for(i=0;i<partition;i++){
  117608. k=sortedindex[i+j-start];
  117609. if(in[k]*in[k]>=.25f){
  117610. out[k]=rint(in[k]);
  117611. acc-=in[k]*in[k];
  117612. flag=1;
  117613. }else{
  117614. if(acc<vi->normal_thresh)break;
  117615. out[k]=unitnorm(in[k]);
  117616. acc-=1.;
  117617. }
  117618. }
  117619. for(;i<partition;i++){
  117620. k=sortedindex[i+j-start];
  117621. out[k]=0.;
  117622. }
  117623. }
  117624. }
  117625. for(;j<n;j++)
  117626. out[j]=rint(in[j]);
  117627. }
  117628. void _vp_couple(int blobno,
  117629. vorbis_info_psy_global *g,
  117630. vorbis_look_psy *p,
  117631. vorbis_info_mapping0 *vi,
  117632. float **res,
  117633. float **mag_memo,
  117634. int **mag_sort,
  117635. int **ifloor,
  117636. int *nonzero,
  117637. int sliding_lowpass){
  117638. int i,j,k,n=p->n;
  117639. /* perform any requested channel coupling */
  117640. /* point stereo can only be used in a first stage (in this encoder)
  117641. because of the dependency on floor lookups */
  117642. for(i=0;i<vi->coupling_steps;i++){
  117643. /* once we're doing multistage coupling in which a channel goes
  117644. through more than one coupling step, the floor vector
  117645. magnitudes will also have to be recalculated an propogated
  117646. along with PCM. Right now, we're not (that will wait until 5.1
  117647. most likely), so the code isn't here yet. The memory management
  117648. here is all assuming single depth couplings anyway. */
  117649. /* make sure coupling a zero and a nonzero channel results in two
  117650. nonzero channels. */
  117651. if(nonzero[vi->coupling_mag[i]] ||
  117652. nonzero[vi->coupling_ang[i]]){
  117653. float *rM=res[vi->coupling_mag[i]];
  117654. float *rA=res[vi->coupling_ang[i]];
  117655. float *qM=rM+n;
  117656. float *qA=rA+n;
  117657. int *floorM=ifloor[vi->coupling_mag[i]];
  117658. int *floorA=ifloor[vi->coupling_ang[i]];
  117659. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117660. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117661. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117662. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117663. int pointlimit=limit;
  117664. nonzero[vi->coupling_mag[i]]=1;
  117665. nonzero[vi->coupling_ang[i]]=1;
  117666. /* The threshold of a stereo is changed with the size of n */
  117667. if(n > 1000)
  117668. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117669. for(j=0;j<p->n;j+=partition){
  117670. float acc=0.f;
  117671. for(k=0;k<partition;k++){
  117672. int l=k+j;
  117673. if(l<sliding_lowpass){
  117674. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117675. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117676. precomputed_couple_point(mag_memo[i][l],
  117677. floorM[l],floorA[l],
  117678. qM+l,qA+l);
  117679. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117680. }else{
  117681. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117682. }
  117683. }else{
  117684. qM[l]=0.;
  117685. qA[l]=0.;
  117686. }
  117687. }
  117688. if(p->vi->normal_point_p){
  117689. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117690. int l=mag_sort[i][j+k];
  117691. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117692. qM[l]=unitnorm(qM[l]);
  117693. acc-=1.f;
  117694. }
  117695. }
  117696. }
  117697. }
  117698. }
  117699. }
  117700. }
  117701. /* AoTuV */
  117702. /** @ M2 **
  117703. The boost problem by the combination of noise normalization and point stereo is eased.
  117704. However, this is a temporary patch.
  117705. by Aoyumi @ 2004/04/18
  117706. */
  117707. void hf_reduction(vorbis_info_psy_global *g,
  117708. vorbis_look_psy *p,
  117709. vorbis_info_mapping0 *vi,
  117710. float **mdct){
  117711. int i,j,n=p->n, de=0.3*p->m_val;
  117712. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117713. for(i=0; i<vi->coupling_steps; i++){
  117714. /* for(j=start; j<limit; j++){} // ???*/
  117715. for(j=limit; j<n; j++)
  117716. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117717. }
  117718. }
  117719. #endif
  117720. /*** End of inlined file: psy.c ***/
  117721. /*** Start of inlined file: registry.c ***/
  117722. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117723. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117724. // tasks..
  117725. #if JUCE_MSVC
  117726. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117727. #endif
  117728. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117729. #if JUCE_USE_OGGVORBIS
  117730. /* seems like major overkill now; the backend numbers will grow into
  117731. the infrastructure soon enough */
  117732. extern vorbis_func_floor floor0_exportbundle;
  117733. extern vorbis_func_floor floor1_exportbundle;
  117734. extern vorbis_func_residue residue0_exportbundle;
  117735. extern vorbis_func_residue residue1_exportbundle;
  117736. extern vorbis_func_residue residue2_exportbundle;
  117737. extern vorbis_func_mapping mapping0_exportbundle;
  117738. vorbis_func_floor *_floor_P[]={
  117739. &floor0_exportbundle,
  117740. &floor1_exportbundle,
  117741. };
  117742. vorbis_func_residue *_residue_P[]={
  117743. &residue0_exportbundle,
  117744. &residue1_exportbundle,
  117745. &residue2_exportbundle,
  117746. };
  117747. vorbis_func_mapping *_mapping_P[]={
  117748. &mapping0_exportbundle,
  117749. };
  117750. #endif
  117751. /*** End of inlined file: registry.c ***/
  117752. /*** Start of inlined file: res0.c ***/
  117753. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117754. encode/decode loops are coded for clarity and performance is not
  117755. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117756. it's slow. */
  117757. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117758. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117759. // tasks..
  117760. #if JUCE_MSVC
  117761. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117762. #endif
  117763. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117764. #if JUCE_USE_OGGVORBIS
  117765. #include <stdlib.h>
  117766. #include <string.h>
  117767. #include <math.h>
  117768. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117769. #include <stdio.h>
  117770. #endif
  117771. typedef struct {
  117772. vorbis_info_residue0 *info;
  117773. int parts;
  117774. int stages;
  117775. codebook *fullbooks;
  117776. codebook *phrasebook;
  117777. codebook ***partbooks;
  117778. int partvals;
  117779. int **decodemap;
  117780. long postbits;
  117781. long phrasebits;
  117782. long frames;
  117783. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117784. int train_seq;
  117785. long *training_data[8][64];
  117786. float training_max[8][64];
  117787. float training_min[8][64];
  117788. float tmin;
  117789. float tmax;
  117790. #endif
  117791. } vorbis_look_residue0;
  117792. void res0_free_info(vorbis_info_residue *i){
  117793. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117794. if(info){
  117795. memset(info,0,sizeof(*info));
  117796. _ogg_free(info);
  117797. }
  117798. }
  117799. void res0_free_look(vorbis_look_residue *i){
  117800. int j;
  117801. if(i){
  117802. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117803. #ifdef TRAIN_RES
  117804. {
  117805. int j,k,l;
  117806. for(j=0;j<look->parts;j++){
  117807. /*fprintf(stderr,"partition %d: ",j);*/
  117808. for(k=0;k<8;k++)
  117809. if(look->training_data[k][j]){
  117810. char buffer[80];
  117811. FILE *of;
  117812. codebook *statebook=look->partbooks[j][k];
  117813. /* long and short into the same bucket by current convention */
  117814. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117815. of=fopen(buffer,"a");
  117816. for(l=0;l<statebook->entries;l++)
  117817. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117818. fclose(of);
  117819. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117820. look->training_min[k][j],look->training_max[k][j]);*/
  117821. _ogg_free(look->training_data[k][j]);
  117822. look->training_data[k][j]=NULL;
  117823. }
  117824. /*fprintf(stderr,"\n");*/
  117825. }
  117826. }
  117827. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117828. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117829. (float)look->phrasebits/look->frames,
  117830. (float)look->postbits/look->frames,
  117831. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117832. #endif
  117833. /*vorbis_info_residue0 *info=look->info;
  117834. fprintf(stderr,
  117835. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117836. "(%g/frame) \n",look->frames,look->phrasebits,
  117837. look->resbitsflat,
  117838. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117839. for(j=0;j<look->parts;j++){
  117840. long acc=0;
  117841. fprintf(stderr,"\t[%d] == ",j);
  117842. for(k=0;k<look->stages;k++)
  117843. if((info->secondstages[j]>>k)&1){
  117844. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117845. acc+=look->resbits[j][k];
  117846. }
  117847. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117848. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117849. }
  117850. fprintf(stderr,"\n");*/
  117851. for(j=0;j<look->parts;j++)
  117852. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117853. _ogg_free(look->partbooks);
  117854. for(j=0;j<look->partvals;j++)
  117855. _ogg_free(look->decodemap[j]);
  117856. _ogg_free(look->decodemap);
  117857. memset(look,0,sizeof(*look));
  117858. _ogg_free(look);
  117859. }
  117860. }
  117861. static int icount(unsigned int v){
  117862. int ret=0;
  117863. while(v){
  117864. ret+=v&1;
  117865. v>>=1;
  117866. }
  117867. return(ret);
  117868. }
  117869. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117870. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117871. int j,acc=0;
  117872. oggpack_write(opb,info->begin,24);
  117873. oggpack_write(opb,info->end,24);
  117874. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117875. code with a partitioned book */
  117876. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117877. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117878. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117879. bitmask of one indicates this partition class has bits to write
  117880. this pass */
  117881. for(j=0;j<info->partitions;j++){
  117882. if(ilog(info->secondstages[j])>3){
  117883. /* yes, this is a minor hack due to not thinking ahead */
  117884. oggpack_write(opb,info->secondstages[j],3);
  117885. oggpack_write(opb,1,1);
  117886. oggpack_write(opb,info->secondstages[j]>>3,5);
  117887. }else
  117888. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117889. acc+=icount(info->secondstages[j]);
  117890. }
  117891. for(j=0;j<acc;j++)
  117892. oggpack_write(opb,info->booklist[j],8);
  117893. }
  117894. /* vorbis_info is for range checking */
  117895. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117896. int j,acc=0;
  117897. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117898. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117899. info->begin=oggpack_read(opb,24);
  117900. info->end=oggpack_read(opb,24);
  117901. info->grouping=oggpack_read(opb,24)+1;
  117902. info->partitions=oggpack_read(opb,6)+1;
  117903. info->groupbook=oggpack_read(opb,8);
  117904. for(j=0;j<info->partitions;j++){
  117905. int cascade=oggpack_read(opb,3);
  117906. if(oggpack_read(opb,1))
  117907. cascade|=(oggpack_read(opb,5)<<3);
  117908. info->secondstages[j]=cascade;
  117909. acc+=icount(cascade);
  117910. }
  117911. for(j=0;j<acc;j++)
  117912. info->booklist[j]=oggpack_read(opb,8);
  117913. if(info->groupbook>=ci->books)goto errout;
  117914. for(j=0;j<acc;j++)
  117915. if(info->booklist[j]>=ci->books)goto errout;
  117916. return(info);
  117917. errout:
  117918. res0_free_info(info);
  117919. return(NULL);
  117920. }
  117921. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117922. vorbis_info_residue *vr){
  117923. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117924. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117925. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117926. int j,k,acc=0;
  117927. int dim;
  117928. int maxstage=0;
  117929. look->info=info;
  117930. look->parts=info->partitions;
  117931. look->fullbooks=ci->fullbooks;
  117932. look->phrasebook=ci->fullbooks+info->groupbook;
  117933. dim=look->phrasebook->dim;
  117934. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117935. for(j=0;j<look->parts;j++){
  117936. int stages=ilog(info->secondstages[j]);
  117937. if(stages){
  117938. if(stages>maxstage)maxstage=stages;
  117939. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117940. for(k=0;k<stages;k++)
  117941. if(info->secondstages[j]&(1<<k)){
  117942. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117943. #ifdef TRAIN_RES
  117944. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117945. sizeof(***look->training_data));
  117946. #endif
  117947. }
  117948. }
  117949. }
  117950. look->partvals=rint(pow((float)look->parts,(float)dim));
  117951. look->stages=maxstage;
  117952. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117953. for(j=0;j<look->partvals;j++){
  117954. long val=j;
  117955. long mult=look->partvals/look->parts;
  117956. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117957. for(k=0;k<dim;k++){
  117958. long deco=val/mult;
  117959. val-=deco*mult;
  117960. mult/=look->parts;
  117961. look->decodemap[j][k]=deco;
  117962. }
  117963. }
  117964. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117965. {
  117966. static int train_seq=0;
  117967. look->train_seq=train_seq++;
  117968. }
  117969. #endif
  117970. return(look);
  117971. }
  117972. /* break an abstraction and copy some code for performance purposes */
  117973. static int local_book_besterror(codebook *book,float *a){
  117974. int dim=book->dim,i,k,o;
  117975. int best=0;
  117976. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117977. /* find the quant val of each scalar */
  117978. for(k=0,o=dim;k<dim;++k){
  117979. float val=a[--o];
  117980. i=tt->threshvals>>1;
  117981. if(val<tt->quantthresh[i]){
  117982. if(val<tt->quantthresh[i-1]){
  117983. for(--i;i>0;--i)
  117984. if(val>=tt->quantthresh[i-1])
  117985. break;
  117986. }
  117987. }else{
  117988. for(++i;i<tt->threshvals-1;++i)
  117989. if(val<tt->quantthresh[i])break;
  117990. }
  117991. best=(best*tt->quantvals)+tt->quantmap[i];
  117992. }
  117993. /* regular lattices are easy :-) */
  117994. if(book->c->lengthlist[best]<=0){
  117995. const static_codebook *c=book->c;
  117996. int i,j;
  117997. float bestf=0.f;
  117998. float *e=book->valuelist;
  117999. best=-1;
  118000. for(i=0;i<book->entries;i++){
  118001. if(c->lengthlist[i]>0){
  118002. float thisx=0.f;
  118003. for(j=0;j<dim;j++){
  118004. float val=(e[j]-a[j]);
  118005. thisx+=val*val;
  118006. }
  118007. if(best==-1 || thisx<bestf){
  118008. bestf=thisx;
  118009. best=i;
  118010. }
  118011. }
  118012. e+=dim;
  118013. }
  118014. }
  118015. {
  118016. float *ptr=book->valuelist+best*dim;
  118017. for(i=0;i<dim;i++)
  118018. *a++ -= *ptr++;
  118019. }
  118020. return(best);
  118021. }
  118022. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118023. codebook *book,long *acc){
  118024. int i,bits=0;
  118025. int dim=book->dim;
  118026. int step=n/dim;
  118027. for(i=0;i<step;i++){
  118028. int entry=local_book_besterror(book,vec+i*dim);
  118029. #ifdef TRAIN_RES
  118030. acc[entry]++;
  118031. #endif
  118032. bits+=vorbis_book_encode(book,entry,opb);
  118033. }
  118034. return(bits);
  118035. }
  118036. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118037. float **in,int ch){
  118038. long i,j,k;
  118039. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118040. vorbis_info_residue0 *info=look->info;
  118041. /* move all this setup out later */
  118042. int samples_per_partition=info->grouping;
  118043. int possible_partitions=info->partitions;
  118044. int n=info->end-info->begin;
  118045. int partvals=n/samples_per_partition;
  118046. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118047. float scale=100./samples_per_partition;
  118048. /* we find the partition type for each partition of each
  118049. channel. We'll go back and do the interleaved encoding in a
  118050. bit. For now, clarity */
  118051. for(i=0;i<ch;i++){
  118052. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118053. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118054. }
  118055. for(i=0;i<partvals;i++){
  118056. int offset=i*samples_per_partition+info->begin;
  118057. for(j=0;j<ch;j++){
  118058. float max=0.;
  118059. float ent=0.;
  118060. for(k=0;k<samples_per_partition;k++){
  118061. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118062. ent+=fabs(rint(in[j][offset+k]));
  118063. }
  118064. ent*=scale;
  118065. for(k=0;k<possible_partitions-1;k++)
  118066. if(max<=info->classmetric1[k] &&
  118067. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118068. break;
  118069. partword[j][i]=k;
  118070. }
  118071. }
  118072. #ifdef TRAIN_RESAUX
  118073. {
  118074. FILE *of;
  118075. char buffer[80];
  118076. for(i=0;i<ch;i++){
  118077. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118078. of=fopen(buffer,"a");
  118079. for(j=0;j<partvals;j++)
  118080. fprintf(of,"%ld, ",partword[i][j]);
  118081. fprintf(of,"\n");
  118082. fclose(of);
  118083. }
  118084. }
  118085. #endif
  118086. look->frames++;
  118087. return(partword);
  118088. }
  118089. /* designed for stereo or other modes where the partition size is an
  118090. integer multiple of the number of channels encoded in the current
  118091. submap */
  118092. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118093. int ch){
  118094. long i,j,k,l;
  118095. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118096. vorbis_info_residue0 *info=look->info;
  118097. /* move all this setup out later */
  118098. int samples_per_partition=info->grouping;
  118099. int possible_partitions=info->partitions;
  118100. int n=info->end-info->begin;
  118101. int partvals=n/samples_per_partition;
  118102. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118103. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118104. FILE *of;
  118105. char buffer[80];
  118106. #endif
  118107. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118108. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118109. for(i=0,l=info->begin/ch;i<partvals;i++){
  118110. float magmax=0.f;
  118111. float angmax=0.f;
  118112. for(j=0;j<samples_per_partition;j+=ch){
  118113. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118114. for(k=1;k<ch;k++)
  118115. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118116. l++;
  118117. }
  118118. for(j=0;j<possible_partitions-1;j++)
  118119. if(magmax<=info->classmetric1[j] &&
  118120. angmax<=info->classmetric2[j])
  118121. break;
  118122. partword[0][i]=j;
  118123. }
  118124. #ifdef TRAIN_RESAUX
  118125. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118126. of=fopen(buffer,"a");
  118127. for(i=0;i<partvals;i++)
  118128. fprintf(of,"%ld, ",partword[0][i]);
  118129. fprintf(of,"\n");
  118130. fclose(of);
  118131. #endif
  118132. look->frames++;
  118133. return(partword);
  118134. }
  118135. static int _01forward(oggpack_buffer *opb,
  118136. vorbis_block *vb,vorbis_look_residue *vl,
  118137. float **in,int ch,
  118138. long **partword,
  118139. int (*encode)(oggpack_buffer *,float *,int,
  118140. codebook *,long *)){
  118141. long i,j,k,s;
  118142. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118143. vorbis_info_residue0 *info=look->info;
  118144. /* move all this setup out later */
  118145. int samples_per_partition=info->grouping;
  118146. int possible_partitions=info->partitions;
  118147. int partitions_per_word=look->phrasebook->dim;
  118148. int n=info->end-info->begin;
  118149. int partvals=n/samples_per_partition;
  118150. long resbits[128];
  118151. long resvals[128];
  118152. #ifdef TRAIN_RES
  118153. for(i=0;i<ch;i++)
  118154. for(j=info->begin;j<info->end;j++){
  118155. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118156. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118157. }
  118158. #endif
  118159. memset(resbits,0,sizeof(resbits));
  118160. memset(resvals,0,sizeof(resvals));
  118161. /* we code the partition words for each channel, then the residual
  118162. words for a partition per channel until we've written all the
  118163. residual words for that partition word. Then write the next
  118164. partition channel words... */
  118165. for(s=0;s<look->stages;s++){
  118166. for(i=0;i<partvals;){
  118167. /* first we encode a partition codeword for each channel */
  118168. if(s==0){
  118169. for(j=0;j<ch;j++){
  118170. long val=partword[j][i];
  118171. for(k=1;k<partitions_per_word;k++){
  118172. val*=possible_partitions;
  118173. if(i+k<partvals)
  118174. val+=partword[j][i+k];
  118175. }
  118176. /* training hack */
  118177. if(val<look->phrasebook->entries)
  118178. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118179. #if 0 /*def TRAIN_RES*/
  118180. else
  118181. fprintf(stderr,"!");
  118182. #endif
  118183. }
  118184. }
  118185. /* now we encode interleaved residual values for the partitions */
  118186. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118187. long offset=i*samples_per_partition+info->begin;
  118188. for(j=0;j<ch;j++){
  118189. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118190. if(info->secondstages[partword[j][i]]&(1<<s)){
  118191. codebook *statebook=look->partbooks[partword[j][i]][s];
  118192. if(statebook){
  118193. int ret;
  118194. long *accumulator=NULL;
  118195. #ifdef TRAIN_RES
  118196. accumulator=look->training_data[s][partword[j][i]];
  118197. {
  118198. int l;
  118199. float *samples=in[j]+offset;
  118200. for(l=0;l<samples_per_partition;l++){
  118201. if(samples[l]<look->training_min[s][partword[j][i]])
  118202. look->training_min[s][partword[j][i]]=samples[l];
  118203. if(samples[l]>look->training_max[s][partword[j][i]])
  118204. look->training_max[s][partword[j][i]]=samples[l];
  118205. }
  118206. }
  118207. #endif
  118208. ret=encode(opb,in[j]+offset,samples_per_partition,
  118209. statebook,accumulator);
  118210. look->postbits+=ret;
  118211. resbits[partword[j][i]]+=ret;
  118212. }
  118213. }
  118214. }
  118215. }
  118216. }
  118217. }
  118218. /*{
  118219. long total=0;
  118220. long totalbits=0;
  118221. fprintf(stderr,"%d :: ",vb->mode);
  118222. for(k=0;k<possible_partitions;k++){
  118223. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118224. total+=resvals[k];
  118225. totalbits+=resbits[k];
  118226. }
  118227. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118228. }*/
  118229. return(0);
  118230. }
  118231. /* a truncated packet here just means 'stop working'; it's not an error */
  118232. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118233. float **in,int ch,
  118234. long (*decodepart)(codebook *, float *,
  118235. oggpack_buffer *,int)){
  118236. long i,j,k,l,s;
  118237. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118238. vorbis_info_residue0 *info=look->info;
  118239. /* move all this setup out later */
  118240. int samples_per_partition=info->grouping;
  118241. int partitions_per_word=look->phrasebook->dim;
  118242. int n=info->end-info->begin;
  118243. int partvals=n/samples_per_partition;
  118244. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118245. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118246. for(j=0;j<ch;j++)
  118247. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118248. for(s=0;s<look->stages;s++){
  118249. /* each loop decodes on partition codeword containing
  118250. partitions_pre_word partitions */
  118251. for(i=0,l=0;i<partvals;l++){
  118252. if(s==0){
  118253. /* fetch the partition word for each channel */
  118254. for(j=0;j<ch;j++){
  118255. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118256. if(temp==-1)goto eopbreak;
  118257. partword[j][l]=look->decodemap[temp];
  118258. if(partword[j][l]==NULL)goto errout;
  118259. }
  118260. }
  118261. /* now we decode residual values for the partitions */
  118262. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118263. for(j=0;j<ch;j++){
  118264. long offset=info->begin+i*samples_per_partition;
  118265. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118266. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118267. if(stagebook){
  118268. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118269. samples_per_partition)==-1)goto eopbreak;
  118270. }
  118271. }
  118272. }
  118273. }
  118274. }
  118275. errout:
  118276. eopbreak:
  118277. return(0);
  118278. }
  118279. #if 0
  118280. /* residue 0 and 1 are just slight variants of one another. 0 is
  118281. interleaved, 1 is not */
  118282. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118283. float **in,int *nonzero,int ch){
  118284. /* we encode only the nonzero parts of a bundle */
  118285. int i,used=0;
  118286. for(i=0;i<ch;i++)
  118287. if(nonzero[i])
  118288. in[used++]=in[i];
  118289. if(used)
  118290. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118291. return(_01class(vb,vl,in,used));
  118292. else
  118293. return(0);
  118294. }
  118295. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118296. float **in,float **out,int *nonzero,int ch,
  118297. long **partword){
  118298. /* we encode only the nonzero parts of a bundle */
  118299. int i,j,used=0,n=vb->pcmend/2;
  118300. for(i=0;i<ch;i++)
  118301. if(nonzero[i]){
  118302. if(out)
  118303. for(j=0;j<n;j++)
  118304. out[i][j]+=in[i][j];
  118305. in[used++]=in[i];
  118306. }
  118307. if(used){
  118308. int ret=_01forward(vb,vl,in,used,partword,
  118309. _interleaved_encodepart);
  118310. if(out){
  118311. used=0;
  118312. for(i=0;i<ch;i++)
  118313. if(nonzero[i]){
  118314. for(j=0;j<n;j++)
  118315. out[i][j]-=in[used][j];
  118316. used++;
  118317. }
  118318. }
  118319. return(ret);
  118320. }else{
  118321. return(0);
  118322. }
  118323. }
  118324. #endif
  118325. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118326. float **in,int *nonzero,int ch){
  118327. int i,used=0;
  118328. for(i=0;i<ch;i++)
  118329. if(nonzero[i])
  118330. in[used++]=in[i];
  118331. if(used)
  118332. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118333. else
  118334. return(0);
  118335. }
  118336. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118337. float **in,float **out,int *nonzero,int ch,
  118338. long **partword){
  118339. int i,j,used=0,n=vb->pcmend/2;
  118340. for(i=0;i<ch;i++)
  118341. if(nonzero[i]){
  118342. if(out)
  118343. for(j=0;j<n;j++)
  118344. out[i][j]+=in[i][j];
  118345. in[used++]=in[i];
  118346. }
  118347. if(used){
  118348. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118349. if(out){
  118350. used=0;
  118351. for(i=0;i<ch;i++)
  118352. if(nonzero[i]){
  118353. for(j=0;j<n;j++)
  118354. out[i][j]-=in[used][j];
  118355. used++;
  118356. }
  118357. }
  118358. return(ret);
  118359. }else{
  118360. return(0);
  118361. }
  118362. }
  118363. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118364. float **in,int *nonzero,int ch){
  118365. int i,used=0;
  118366. for(i=0;i<ch;i++)
  118367. if(nonzero[i])
  118368. in[used++]=in[i];
  118369. if(used)
  118370. return(_01class(vb,vl,in,used));
  118371. else
  118372. return(0);
  118373. }
  118374. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118375. float **in,int *nonzero,int ch){
  118376. int i,used=0;
  118377. for(i=0;i<ch;i++)
  118378. if(nonzero[i])
  118379. in[used++]=in[i];
  118380. if(used)
  118381. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118382. else
  118383. return(0);
  118384. }
  118385. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118386. float **in,int *nonzero,int ch){
  118387. int i,used=0;
  118388. for(i=0;i<ch;i++)
  118389. if(nonzero[i])used++;
  118390. if(used)
  118391. return(_2class(vb,vl,in,ch));
  118392. else
  118393. return(0);
  118394. }
  118395. /* res2 is slightly more different; all the channels are interleaved
  118396. into a single vector and encoded. */
  118397. int res2_forward(oggpack_buffer *opb,
  118398. vorbis_block *vb,vorbis_look_residue *vl,
  118399. float **in,float **out,int *nonzero,int ch,
  118400. long **partword){
  118401. long i,j,k,n=vb->pcmend/2,used=0;
  118402. /* don't duplicate the code; use a working vector hack for now and
  118403. reshape ourselves into a single channel res1 */
  118404. /* ugly; reallocs for each coupling pass :-( */
  118405. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118406. for(i=0;i<ch;i++){
  118407. float *pcm=in[i];
  118408. if(nonzero[i])used++;
  118409. for(j=0,k=i;j<n;j++,k+=ch)
  118410. work[k]=pcm[j];
  118411. }
  118412. if(used){
  118413. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118414. /* update the sofar vector */
  118415. if(out){
  118416. for(i=0;i<ch;i++){
  118417. float *pcm=in[i];
  118418. float *sofar=out[i];
  118419. for(j=0,k=i;j<n;j++,k+=ch)
  118420. sofar[j]+=pcm[j]-work[k];
  118421. }
  118422. }
  118423. return(ret);
  118424. }else{
  118425. return(0);
  118426. }
  118427. }
  118428. /* duplicate code here as speed is somewhat more important */
  118429. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118430. float **in,int *nonzero,int ch){
  118431. long i,k,l,s;
  118432. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118433. vorbis_info_residue0 *info=look->info;
  118434. /* move all this setup out later */
  118435. int samples_per_partition=info->grouping;
  118436. int partitions_per_word=look->phrasebook->dim;
  118437. int n=info->end-info->begin;
  118438. int partvals=n/samples_per_partition;
  118439. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118440. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118441. for(i=0;i<ch;i++)if(nonzero[i])break;
  118442. if(i==ch)return(0); /* no nonzero vectors */
  118443. for(s=0;s<look->stages;s++){
  118444. for(i=0,l=0;i<partvals;l++){
  118445. if(s==0){
  118446. /* fetch the partition word */
  118447. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118448. if(temp==-1)goto eopbreak;
  118449. partword[l]=look->decodemap[temp];
  118450. if(partword[l]==NULL)goto errout;
  118451. }
  118452. /* now we decode residual values for the partitions */
  118453. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118454. if(info->secondstages[partword[l][k]]&(1<<s)){
  118455. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118456. if(stagebook){
  118457. if(vorbis_book_decodevv_add(stagebook,in,
  118458. i*samples_per_partition+info->begin,ch,
  118459. &vb->opb,samples_per_partition)==-1)
  118460. goto eopbreak;
  118461. }
  118462. }
  118463. }
  118464. }
  118465. errout:
  118466. eopbreak:
  118467. return(0);
  118468. }
  118469. vorbis_func_residue residue0_exportbundle={
  118470. NULL,
  118471. &res0_unpack,
  118472. &res0_look,
  118473. &res0_free_info,
  118474. &res0_free_look,
  118475. NULL,
  118476. NULL,
  118477. &res0_inverse
  118478. };
  118479. vorbis_func_residue residue1_exportbundle={
  118480. &res0_pack,
  118481. &res0_unpack,
  118482. &res0_look,
  118483. &res0_free_info,
  118484. &res0_free_look,
  118485. &res1_class,
  118486. &res1_forward,
  118487. &res1_inverse
  118488. };
  118489. vorbis_func_residue residue2_exportbundle={
  118490. &res0_pack,
  118491. &res0_unpack,
  118492. &res0_look,
  118493. &res0_free_info,
  118494. &res0_free_look,
  118495. &res2_class,
  118496. &res2_forward,
  118497. &res2_inverse
  118498. };
  118499. #endif
  118500. /*** End of inlined file: res0.c ***/
  118501. /*** Start of inlined file: sharedbook.c ***/
  118502. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118503. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118504. // tasks..
  118505. #if JUCE_MSVC
  118506. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118507. #endif
  118508. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118509. #if JUCE_USE_OGGVORBIS
  118510. #include <stdlib.h>
  118511. #include <math.h>
  118512. #include <string.h>
  118513. /**** pack/unpack helpers ******************************************/
  118514. int _ilog(unsigned int v){
  118515. int ret=0;
  118516. while(v){
  118517. ret++;
  118518. v>>=1;
  118519. }
  118520. return(ret);
  118521. }
  118522. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118523. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118524. Why not IEEE? It's just not that important here. */
  118525. #define VQ_FEXP 10
  118526. #define VQ_FMAN 21
  118527. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118528. /* doesn't currently guard under/overflow */
  118529. long _float32_pack(float val){
  118530. int sign=0;
  118531. long exp;
  118532. long mant;
  118533. if(val<0){
  118534. sign=0x80000000;
  118535. val= -val;
  118536. }
  118537. exp= floor(log(val)/log(2.f));
  118538. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118539. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118540. return(sign|exp|mant);
  118541. }
  118542. float _float32_unpack(long val){
  118543. double mant=val&0x1fffff;
  118544. int sign=val&0x80000000;
  118545. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118546. if(sign)mant= -mant;
  118547. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118548. }
  118549. /* given a list of word lengths, generate a list of codewords. Works
  118550. for length ordered or unordered, always assigns the lowest valued
  118551. codewords first. Extended to handle unused entries (length 0) */
  118552. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118553. long i,j,count=0;
  118554. ogg_uint32_t marker[33];
  118555. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118556. memset(marker,0,sizeof(marker));
  118557. for(i=0;i<n;i++){
  118558. long length=l[i];
  118559. if(length>0){
  118560. ogg_uint32_t entry=marker[length];
  118561. /* when we claim a node for an entry, we also claim the nodes
  118562. below it (pruning off the imagined tree that may have dangled
  118563. from it) as well as blocking the use of any nodes directly
  118564. above for leaves */
  118565. /* update ourself */
  118566. if(length<32 && (entry>>length)){
  118567. /* error condition; the lengths must specify an overpopulated tree */
  118568. _ogg_free(r);
  118569. return(NULL);
  118570. }
  118571. r[count++]=entry;
  118572. /* Look to see if the next shorter marker points to the node
  118573. above. if so, update it and repeat. */
  118574. {
  118575. for(j=length;j>0;j--){
  118576. if(marker[j]&1){
  118577. /* have to jump branches */
  118578. if(j==1)
  118579. marker[1]++;
  118580. else
  118581. marker[j]=marker[j-1]<<1;
  118582. break; /* invariant says next upper marker would already
  118583. have been moved if it was on the same path */
  118584. }
  118585. marker[j]++;
  118586. }
  118587. }
  118588. /* prune the tree; the implicit invariant says all the longer
  118589. markers were dangling from our just-taken node. Dangle them
  118590. from our *new* node. */
  118591. for(j=length+1;j<33;j++)
  118592. if((marker[j]>>1) == entry){
  118593. entry=marker[j];
  118594. marker[j]=marker[j-1]<<1;
  118595. }else
  118596. break;
  118597. }else
  118598. if(sparsecount==0)count++;
  118599. }
  118600. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118601. endian */
  118602. for(i=0,count=0;i<n;i++){
  118603. ogg_uint32_t temp=0;
  118604. for(j=0;j<l[i];j++){
  118605. temp<<=1;
  118606. temp|=(r[count]>>j)&1;
  118607. }
  118608. if(sparsecount){
  118609. if(l[i])
  118610. r[count++]=temp;
  118611. }else
  118612. r[count++]=temp;
  118613. }
  118614. return(r);
  118615. }
  118616. /* there might be a straightforward one-line way to do the below
  118617. that's portable and totally safe against roundoff, but I haven't
  118618. thought of it. Therefore, we opt on the side of caution */
  118619. long _book_maptype1_quantvals(const static_codebook *b){
  118620. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118621. /* the above *should* be reliable, but we'll not assume that FP is
  118622. ever reliable when bitstream sync is at stake; verify via integer
  118623. means that vals really is the greatest value of dim for which
  118624. vals^b->bim <= b->entries */
  118625. /* treat the above as an initial guess */
  118626. while(1){
  118627. long acc=1;
  118628. long acc1=1;
  118629. int i;
  118630. for(i=0;i<b->dim;i++){
  118631. acc*=vals;
  118632. acc1*=vals+1;
  118633. }
  118634. if(acc<=b->entries && acc1>b->entries){
  118635. return(vals);
  118636. }else{
  118637. if(acc>b->entries){
  118638. vals--;
  118639. }else{
  118640. vals++;
  118641. }
  118642. }
  118643. }
  118644. }
  118645. /* unpack the quantized list of values for encode/decode ***********/
  118646. /* we need to deal with two map types: in map type 1, the values are
  118647. generated algorithmically (each column of the vector counts through
  118648. the values in the quant vector). in map type 2, all the values came
  118649. in in an explicit list. Both value lists must be unpacked */
  118650. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118651. long j,k,count=0;
  118652. if(b->maptype==1 || b->maptype==2){
  118653. int quantvals;
  118654. float mindel=_float32_unpack(b->q_min);
  118655. float delta=_float32_unpack(b->q_delta);
  118656. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118657. /* maptype 1 and 2 both use a quantized value vector, but
  118658. different sizes */
  118659. switch(b->maptype){
  118660. case 1:
  118661. /* most of the time, entries%dimensions == 0, but we need to be
  118662. well defined. We define that the possible vales at each
  118663. scalar is values == entries/dim. If entries%dim != 0, we'll
  118664. have 'too few' values (values*dim<entries), which means that
  118665. we'll have 'left over' entries; left over entries use zeroed
  118666. values (and are wasted). So don't generate codebooks like
  118667. that */
  118668. quantvals=_book_maptype1_quantvals(b);
  118669. for(j=0;j<b->entries;j++){
  118670. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118671. float last=0.f;
  118672. int indexdiv=1;
  118673. for(k=0;k<b->dim;k++){
  118674. int index= (j/indexdiv)%quantvals;
  118675. float val=b->quantlist[index];
  118676. val=fabs(val)*delta+mindel+last;
  118677. if(b->q_sequencep)last=val;
  118678. if(sparsemap)
  118679. r[sparsemap[count]*b->dim+k]=val;
  118680. else
  118681. r[count*b->dim+k]=val;
  118682. indexdiv*=quantvals;
  118683. }
  118684. count++;
  118685. }
  118686. }
  118687. break;
  118688. case 2:
  118689. for(j=0;j<b->entries;j++){
  118690. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118691. float last=0.f;
  118692. for(k=0;k<b->dim;k++){
  118693. float val=b->quantlist[j*b->dim+k];
  118694. val=fabs(val)*delta+mindel+last;
  118695. if(b->q_sequencep)last=val;
  118696. if(sparsemap)
  118697. r[sparsemap[count]*b->dim+k]=val;
  118698. else
  118699. r[count*b->dim+k]=val;
  118700. }
  118701. count++;
  118702. }
  118703. }
  118704. break;
  118705. }
  118706. return(r);
  118707. }
  118708. return(NULL);
  118709. }
  118710. void vorbis_staticbook_clear(static_codebook *b){
  118711. if(b->allocedp){
  118712. if(b->quantlist)_ogg_free(b->quantlist);
  118713. if(b->lengthlist)_ogg_free(b->lengthlist);
  118714. if(b->nearest_tree){
  118715. _ogg_free(b->nearest_tree->ptr0);
  118716. _ogg_free(b->nearest_tree->ptr1);
  118717. _ogg_free(b->nearest_tree->p);
  118718. _ogg_free(b->nearest_tree->q);
  118719. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118720. _ogg_free(b->nearest_tree);
  118721. }
  118722. if(b->thresh_tree){
  118723. _ogg_free(b->thresh_tree->quantthresh);
  118724. _ogg_free(b->thresh_tree->quantmap);
  118725. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118726. _ogg_free(b->thresh_tree);
  118727. }
  118728. memset(b,0,sizeof(*b));
  118729. }
  118730. }
  118731. void vorbis_staticbook_destroy(static_codebook *b){
  118732. if(b->allocedp){
  118733. vorbis_staticbook_clear(b);
  118734. _ogg_free(b);
  118735. }
  118736. }
  118737. void vorbis_book_clear(codebook *b){
  118738. /* static book is not cleared; we're likely called on the lookup and
  118739. the static codebook belongs to the info struct */
  118740. if(b->valuelist)_ogg_free(b->valuelist);
  118741. if(b->codelist)_ogg_free(b->codelist);
  118742. if(b->dec_index)_ogg_free(b->dec_index);
  118743. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118744. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118745. memset(b,0,sizeof(*b));
  118746. }
  118747. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118748. memset(c,0,sizeof(*c));
  118749. c->c=s;
  118750. c->entries=s->entries;
  118751. c->used_entries=s->entries;
  118752. c->dim=s->dim;
  118753. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118754. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118755. return(0);
  118756. }
  118757. static int JUCE_CDECL sort32a(const void *a,const void *b){
  118758. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118759. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118760. }
  118761. /* decode codebook arrangement is more heavily optimized than encode */
  118762. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118763. int i,j,n=0,tabn;
  118764. int *sortindex;
  118765. memset(c,0,sizeof(*c));
  118766. /* count actually used entries */
  118767. for(i=0;i<s->entries;i++)
  118768. if(s->lengthlist[i]>0)
  118769. n++;
  118770. c->entries=s->entries;
  118771. c->used_entries=n;
  118772. c->dim=s->dim;
  118773. /* two different remappings go on here.
  118774. First, we collapse the likely sparse codebook down only to
  118775. actually represented values/words. This collapsing needs to be
  118776. indexed as map-valueless books are used to encode original entry
  118777. positions as integers.
  118778. Second, we reorder all vectors, including the entry index above,
  118779. by sorted bitreversed codeword to allow treeless decode. */
  118780. {
  118781. /* perform sort */
  118782. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118783. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118784. if(codes==NULL)goto err_out;
  118785. for(i=0;i<n;i++){
  118786. codes[i]=ogg_bitreverse(codes[i]);
  118787. codep[i]=codes+i;
  118788. }
  118789. qsort(codep,n,sizeof(*codep),sort32a);
  118790. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118791. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118792. /* the index is a reverse index */
  118793. for(i=0;i<n;i++){
  118794. int position=codep[i]-codes;
  118795. sortindex[position]=i;
  118796. }
  118797. for(i=0;i<n;i++)
  118798. c->codelist[sortindex[i]]=codes[i];
  118799. _ogg_free(codes);
  118800. }
  118801. c->valuelist=_book_unquantize(s,n,sortindex);
  118802. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118803. for(n=0,i=0;i<s->entries;i++)
  118804. if(s->lengthlist[i]>0)
  118805. c->dec_index[sortindex[n++]]=i;
  118806. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118807. for(n=0,i=0;i<s->entries;i++)
  118808. if(s->lengthlist[i]>0)
  118809. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118810. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118811. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118812. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118813. tabn=1<<c->dec_firsttablen;
  118814. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118815. c->dec_maxlength=0;
  118816. for(i=0;i<n;i++){
  118817. if(c->dec_maxlength<c->dec_codelengths[i])
  118818. c->dec_maxlength=c->dec_codelengths[i];
  118819. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118820. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118821. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118822. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118823. }
  118824. }
  118825. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118826. hints for the non-direct-hits */
  118827. {
  118828. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118829. long lo=0,hi=0;
  118830. for(i=0;i<tabn;i++){
  118831. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118832. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118833. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118834. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118835. /* we only actually have 15 bits per hint to play with here.
  118836. In order to overflow gracefully (nothing breaks, efficiency
  118837. just drops), encode as the difference from the extremes. */
  118838. {
  118839. unsigned long loval=lo;
  118840. unsigned long hival=n-hi;
  118841. if(loval>0x7fff)loval=0x7fff;
  118842. if(hival>0x7fff)hival=0x7fff;
  118843. c->dec_firsttable[ogg_bitreverse(word)]=
  118844. 0x80000000UL | (loval<<15) | hival;
  118845. }
  118846. }
  118847. }
  118848. }
  118849. return(0);
  118850. err_out:
  118851. vorbis_book_clear(c);
  118852. return(-1);
  118853. }
  118854. static float _dist(int el,float *ref, float *b,int step){
  118855. int i;
  118856. float acc=0.f;
  118857. for(i=0;i<el;i++){
  118858. float val=(ref[i]-b[i*step]);
  118859. acc+=val*val;
  118860. }
  118861. return(acc);
  118862. }
  118863. int _best(codebook *book, float *a, int step){
  118864. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118865. #if 0
  118866. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118867. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118868. #endif
  118869. int dim=book->dim;
  118870. int k,o;
  118871. /*int savebest=-1;
  118872. float saverr;*/
  118873. /* do we have a threshhold encode hint? */
  118874. if(tt){
  118875. int index=0,i;
  118876. /* find the quant val of each scalar */
  118877. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118878. i=tt->threshvals>>1;
  118879. if(a[o]<tt->quantthresh[i]){
  118880. for(;i>0;i--)
  118881. if(a[o]>=tt->quantthresh[i-1])
  118882. break;
  118883. }else{
  118884. for(i++;i<tt->threshvals-1;i++)
  118885. if(a[o]<tt->quantthresh[i])break;
  118886. }
  118887. index=(index*tt->quantvals)+tt->quantmap[i];
  118888. }
  118889. /* regular lattices are easy :-) */
  118890. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118891. use a decision tree after all
  118892. and fall through*/
  118893. return(index);
  118894. }
  118895. #if 0
  118896. /* do we have a pigeonhole encode hint? */
  118897. if(pt){
  118898. const static_codebook *c=book->c;
  118899. int i,besti=-1;
  118900. float best=0.f;
  118901. int entry=0;
  118902. /* dealing with sequentialness is a pain in the ass */
  118903. if(c->q_sequencep){
  118904. int pv;
  118905. long mul=1;
  118906. float qlast=0;
  118907. for(k=0,o=0;k<dim;k++,o+=step){
  118908. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118909. if(pv<0 || pv>=pt->mapentries)break;
  118910. entry+=pt->pigeonmap[pv]*mul;
  118911. mul*=pt->quantvals;
  118912. qlast+=pv*pt->del+pt->min;
  118913. }
  118914. }else{
  118915. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118916. int pv=(int)((a[o]-pt->min)/pt->del);
  118917. if(pv<0 || pv>=pt->mapentries)break;
  118918. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118919. }
  118920. }
  118921. /* must be within the pigeonholable range; if we quant outside (or
  118922. in an entry that we define no list for), brute force it */
  118923. if(k==dim && pt->fitlength[entry]){
  118924. /* search the abbreviated list */
  118925. long *list=pt->fitlist+pt->fitmap[entry];
  118926. for(i=0;i<pt->fitlength[entry];i++){
  118927. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118928. if(besti==-1 || this<best){
  118929. best=this;
  118930. besti=list[i];
  118931. }
  118932. }
  118933. return(besti);
  118934. }
  118935. }
  118936. if(nt){
  118937. /* optimized using the decision tree */
  118938. while(1){
  118939. float c=0.f;
  118940. float *p=book->valuelist+nt->p[ptr];
  118941. float *q=book->valuelist+nt->q[ptr];
  118942. for(k=0,o=0;k<dim;k++,o+=step)
  118943. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118944. if(c>0.f) /* in A */
  118945. ptr= -nt->ptr0[ptr];
  118946. else /* in B */
  118947. ptr= -nt->ptr1[ptr];
  118948. if(ptr<=0)break;
  118949. }
  118950. return(-ptr);
  118951. }
  118952. #endif
  118953. /* brute force it! */
  118954. {
  118955. const static_codebook *c=book->c;
  118956. int i,besti=-1;
  118957. float best=0.f;
  118958. float *e=book->valuelist;
  118959. for(i=0;i<book->entries;i++){
  118960. if(c->lengthlist[i]>0){
  118961. float thisx=_dist(dim,e,a,step);
  118962. if(besti==-1 || thisx<best){
  118963. best=thisx;
  118964. besti=i;
  118965. }
  118966. }
  118967. e+=dim;
  118968. }
  118969. /*if(savebest!=-1 && savebest!=besti){
  118970. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118971. "original:");
  118972. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118973. fprintf(stderr,"\n"
  118974. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118975. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118976. (book->valuelist+savebest*dim)[i]);
  118977. fprintf(stderr,"\n"
  118978. "bruteforce (entry %d, err %g):",besti,best);
  118979. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118980. (book->valuelist+besti*dim)[i]);
  118981. fprintf(stderr,"\n");
  118982. }*/
  118983. return(besti);
  118984. }
  118985. }
  118986. long vorbis_book_codeword(codebook *book,int entry){
  118987. if(book->c) /* only use with encode; decode optimizations are
  118988. allowed to break this */
  118989. return book->codelist[entry];
  118990. return -1;
  118991. }
  118992. long vorbis_book_codelen(codebook *book,int entry){
  118993. if(book->c) /* only use with encode; decode optimizations are
  118994. allowed to break this */
  118995. return book->c->lengthlist[entry];
  118996. return -1;
  118997. }
  118998. #ifdef _V_SELFTEST
  118999. /* Unit tests of the dequantizer; this stuff will be OK
  119000. cross-platform, I simply want to be sure that special mapping cases
  119001. actually work properly; a bug could go unnoticed for a while */
  119002. #include <stdio.h>
  119003. /* cases:
  119004. no mapping
  119005. full, explicit mapping
  119006. algorithmic mapping
  119007. nonsequential
  119008. sequential
  119009. */
  119010. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119011. static long partial_quantlist1[]={0,7,2};
  119012. /* no mapping */
  119013. static_codebook test1={
  119014. 4,16,
  119015. NULL,
  119016. 0,
  119017. 0,0,0,0,
  119018. NULL,
  119019. NULL,NULL
  119020. };
  119021. static float *test1_result=NULL;
  119022. /* linear, full mapping, nonsequential */
  119023. static_codebook test2={
  119024. 4,3,
  119025. NULL,
  119026. 2,
  119027. -533200896,1611661312,4,0,
  119028. full_quantlist1,
  119029. NULL,NULL
  119030. };
  119031. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119032. /* linear, full mapping, sequential */
  119033. static_codebook test3={
  119034. 4,3,
  119035. NULL,
  119036. 2,
  119037. -533200896,1611661312,4,1,
  119038. full_quantlist1,
  119039. NULL,NULL
  119040. };
  119041. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119042. /* linear, algorithmic mapping, nonsequential */
  119043. static_codebook test4={
  119044. 3,27,
  119045. NULL,
  119046. 1,
  119047. -533200896,1611661312,4,0,
  119048. partial_quantlist1,
  119049. NULL,NULL
  119050. };
  119051. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119052. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119053. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119054. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119055. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119056. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119057. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119058. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119059. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119060. /* linear, algorithmic mapping, sequential */
  119061. static_codebook test5={
  119062. 3,27,
  119063. NULL,
  119064. 1,
  119065. -533200896,1611661312,4,1,
  119066. partial_quantlist1,
  119067. NULL,NULL
  119068. };
  119069. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119070. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119071. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119072. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119073. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119074. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119075. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119076. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119077. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119078. void run_test(static_codebook *b,float *comp){
  119079. float *out=_book_unquantize(b,b->entries,NULL);
  119080. int i;
  119081. if(comp){
  119082. if(!out){
  119083. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119084. exit(1);
  119085. }
  119086. for(i=0;i<b->entries*b->dim;i++)
  119087. if(fabs(out[i]-comp[i])>.0001){
  119088. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119089. "position %d, %g != %g\n",i,out[i],comp[i]);
  119090. exit(1);
  119091. }
  119092. }else{
  119093. if(out){
  119094. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119095. " correct result should have been NULL\n");
  119096. exit(1);
  119097. }
  119098. }
  119099. }
  119100. int main(){
  119101. /* run the nine dequant tests, and compare to the hand-rolled results */
  119102. fprintf(stderr,"Dequant test 1... ");
  119103. run_test(&test1,test1_result);
  119104. fprintf(stderr,"OK\nDequant test 2... ");
  119105. run_test(&test2,test2_result);
  119106. fprintf(stderr,"OK\nDequant test 3... ");
  119107. run_test(&test3,test3_result);
  119108. fprintf(stderr,"OK\nDequant test 4... ");
  119109. run_test(&test4,test4_result);
  119110. fprintf(stderr,"OK\nDequant test 5... ");
  119111. run_test(&test5,test5_result);
  119112. fprintf(stderr,"OK\n\n");
  119113. return(0);
  119114. }
  119115. #endif
  119116. #endif
  119117. /*** End of inlined file: sharedbook.c ***/
  119118. /*** Start of inlined file: smallft.c ***/
  119119. /* FFT implementation from OggSquish, minus cosine transforms,
  119120. * minus all but radix 2/4 case. In Vorbis we only need this
  119121. * cut-down version.
  119122. *
  119123. * To do more than just power-of-two sized vectors, see the full
  119124. * version I wrote for NetLib.
  119125. *
  119126. * Note that the packing is a little strange; rather than the FFT r/i
  119127. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119128. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119129. * FORTRAN version
  119130. */
  119131. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119132. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119133. // tasks..
  119134. #if JUCE_MSVC
  119135. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119136. #endif
  119137. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119138. #if JUCE_USE_OGGVORBIS
  119139. #include <stdlib.h>
  119140. #include <string.h>
  119141. #include <math.h>
  119142. static void drfti1(int n, float *wa, int *ifac){
  119143. static int ntryh[4] = { 4,2,3,5 };
  119144. static float tpi = 6.28318530717958648f;
  119145. float arg,argh,argld,fi;
  119146. int ntry=0,i,j=-1;
  119147. int k1, l1, l2, ib;
  119148. int ld, ii, ip, is, nq, nr;
  119149. int ido, ipm, nfm1;
  119150. int nl=n;
  119151. int nf=0;
  119152. L101:
  119153. j++;
  119154. if (j < 4)
  119155. ntry=ntryh[j];
  119156. else
  119157. ntry+=2;
  119158. L104:
  119159. nq=nl/ntry;
  119160. nr=nl-ntry*nq;
  119161. if (nr!=0) goto L101;
  119162. nf++;
  119163. ifac[nf+1]=ntry;
  119164. nl=nq;
  119165. if(ntry!=2)goto L107;
  119166. if(nf==1)goto L107;
  119167. for (i=1;i<nf;i++){
  119168. ib=nf-i+1;
  119169. ifac[ib+1]=ifac[ib];
  119170. }
  119171. ifac[2] = 2;
  119172. L107:
  119173. if(nl!=1)goto L104;
  119174. ifac[0]=n;
  119175. ifac[1]=nf;
  119176. argh=tpi/n;
  119177. is=0;
  119178. nfm1=nf-1;
  119179. l1=1;
  119180. if(nfm1==0)return;
  119181. for (k1=0;k1<nfm1;k1++){
  119182. ip=ifac[k1+2];
  119183. ld=0;
  119184. l2=l1*ip;
  119185. ido=n/l2;
  119186. ipm=ip-1;
  119187. for (j=0;j<ipm;j++){
  119188. ld+=l1;
  119189. i=is;
  119190. argld=(float)ld*argh;
  119191. fi=0.f;
  119192. for (ii=2;ii<ido;ii+=2){
  119193. fi+=1.f;
  119194. arg=fi*argld;
  119195. wa[i++]=cos(arg);
  119196. wa[i++]=sin(arg);
  119197. }
  119198. is+=ido;
  119199. }
  119200. l1=l2;
  119201. }
  119202. }
  119203. static void fdrffti(int n, float *wsave, int *ifac){
  119204. if (n == 1) return;
  119205. drfti1(n, wsave+n, ifac);
  119206. }
  119207. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119208. int i,k;
  119209. float ti2,tr2;
  119210. int t0,t1,t2,t3,t4,t5,t6;
  119211. t1=0;
  119212. t0=(t2=l1*ido);
  119213. t3=ido<<1;
  119214. for(k=0;k<l1;k++){
  119215. ch[t1<<1]=cc[t1]+cc[t2];
  119216. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119217. t1+=ido;
  119218. t2+=ido;
  119219. }
  119220. if(ido<2)return;
  119221. if(ido==2)goto L105;
  119222. t1=0;
  119223. t2=t0;
  119224. for(k=0;k<l1;k++){
  119225. t3=t2;
  119226. t4=(t1<<1)+(ido<<1);
  119227. t5=t1;
  119228. t6=t1+t1;
  119229. for(i=2;i<ido;i+=2){
  119230. t3+=2;
  119231. t4-=2;
  119232. t5+=2;
  119233. t6+=2;
  119234. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119235. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119236. ch[t6]=cc[t5]+ti2;
  119237. ch[t4]=ti2-cc[t5];
  119238. ch[t6-1]=cc[t5-1]+tr2;
  119239. ch[t4-1]=cc[t5-1]-tr2;
  119240. }
  119241. t1+=ido;
  119242. t2+=ido;
  119243. }
  119244. if(ido%2==1)return;
  119245. L105:
  119246. t3=(t2=(t1=ido)-1);
  119247. t2+=t0;
  119248. for(k=0;k<l1;k++){
  119249. ch[t1]=-cc[t2];
  119250. ch[t1-1]=cc[t3];
  119251. t1+=ido<<1;
  119252. t2+=ido;
  119253. t3+=ido;
  119254. }
  119255. }
  119256. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119257. float *wa2,float *wa3){
  119258. static float hsqt2 = .70710678118654752f;
  119259. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119260. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119261. t0=l1*ido;
  119262. t1=t0;
  119263. t4=t1<<1;
  119264. t2=t1+(t1<<1);
  119265. t3=0;
  119266. for(k=0;k<l1;k++){
  119267. tr1=cc[t1]+cc[t2];
  119268. tr2=cc[t3]+cc[t4];
  119269. ch[t5=t3<<2]=tr1+tr2;
  119270. ch[(ido<<2)+t5-1]=tr2-tr1;
  119271. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119272. ch[t5]=cc[t2]-cc[t1];
  119273. t1+=ido;
  119274. t2+=ido;
  119275. t3+=ido;
  119276. t4+=ido;
  119277. }
  119278. if(ido<2)return;
  119279. if(ido==2)goto L105;
  119280. t1=0;
  119281. for(k=0;k<l1;k++){
  119282. t2=t1;
  119283. t4=t1<<2;
  119284. t5=(t6=ido<<1)+t4;
  119285. for(i=2;i<ido;i+=2){
  119286. t3=(t2+=2);
  119287. t4+=2;
  119288. t5-=2;
  119289. t3+=t0;
  119290. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119291. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119292. t3+=t0;
  119293. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119294. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119295. t3+=t0;
  119296. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119297. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119298. tr1=cr2+cr4;
  119299. tr4=cr4-cr2;
  119300. ti1=ci2+ci4;
  119301. ti4=ci2-ci4;
  119302. ti2=cc[t2]+ci3;
  119303. ti3=cc[t2]-ci3;
  119304. tr2=cc[t2-1]+cr3;
  119305. tr3=cc[t2-1]-cr3;
  119306. ch[t4-1]=tr1+tr2;
  119307. ch[t4]=ti1+ti2;
  119308. ch[t5-1]=tr3-ti4;
  119309. ch[t5]=tr4-ti3;
  119310. ch[t4+t6-1]=ti4+tr3;
  119311. ch[t4+t6]=tr4+ti3;
  119312. ch[t5+t6-1]=tr2-tr1;
  119313. ch[t5+t6]=ti1-ti2;
  119314. }
  119315. t1+=ido;
  119316. }
  119317. if(ido&1)return;
  119318. L105:
  119319. t2=(t1=t0+ido-1)+(t0<<1);
  119320. t3=ido<<2;
  119321. t4=ido;
  119322. t5=ido<<1;
  119323. t6=ido;
  119324. for(k=0;k<l1;k++){
  119325. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119326. tr1=hsqt2*(cc[t1]-cc[t2]);
  119327. ch[t4-1]=tr1+cc[t6-1];
  119328. ch[t4+t5-1]=cc[t6-1]-tr1;
  119329. ch[t4]=ti1-cc[t1+t0];
  119330. ch[t4+t5]=ti1+cc[t1+t0];
  119331. t1+=ido;
  119332. t2+=ido;
  119333. t4+=t3;
  119334. t6+=ido;
  119335. }
  119336. }
  119337. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119338. float *c2,float *ch,float *ch2,float *wa){
  119339. static float tpi=6.283185307179586f;
  119340. int idij,ipph,i,j,k,l,ic,ik,is;
  119341. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119342. float dc2,ai1,ai2,ar1,ar2,ds2;
  119343. int nbd;
  119344. float dcp,arg,dsp,ar1h,ar2h;
  119345. int idp2,ipp2;
  119346. arg=tpi/(float)ip;
  119347. dcp=cos(arg);
  119348. dsp=sin(arg);
  119349. ipph=(ip+1)>>1;
  119350. ipp2=ip;
  119351. idp2=ido;
  119352. nbd=(ido-1)>>1;
  119353. t0=l1*ido;
  119354. t10=ip*ido;
  119355. if(ido==1)goto L119;
  119356. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119357. t1=0;
  119358. for(j=1;j<ip;j++){
  119359. t1+=t0;
  119360. t2=t1;
  119361. for(k=0;k<l1;k++){
  119362. ch[t2]=c1[t2];
  119363. t2+=ido;
  119364. }
  119365. }
  119366. is=-ido;
  119367. t1=0;
  119368. if(nbd>l1){
  119369. for(j=1;j<ip;j++){
  119370. t1+=t0;
  119371. is+=ido;
  119372. t2= -ido+t1;
  119373. for(k=0;k<l1;k++){
  119374. idij=is-1;
  119375. t2+=ido;
  119376. t3=t2;
  119377. for(i=2;i<ido;i+=2){
  119378. idij+=2;
  119379. t3+=2;
  119380. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119381. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119382. }
  119383. }
  119384. }
  119385. }else{
  119386. for(j=1;j<ip;j++){
  119387. is+=ido;
  119388. idij=is-1;
  119389. t1+=t0;
  119390. t2=t1;
  119391. for(i=2;i<ido;i+=2){
  119392. idij+=2;
  119393. t2+=2;
  119394. t3=t2;
  119395. for(k=0;k<l1;k++){
  119396. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119397. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119398. t3+=ido;
  119399. }
  119400. }
  119401. }
  119402. }
  119403. t1=0;
  119404. t2=ipp2*t0;
  119405. if(nbd<l1){
  119406. for(j=1;j<ipph;j++){
  119407. t1+=t0;
  119408. t2-=t0;
  119409. t3=t1;
  119410. t4=t2;
  119411. for(i=2;i<ido;i+=2){
  119412. t3+=2;
  119413. t4+=2;
  119414. t5=t3-ido;
  119415. t6=t4-ido;
  119416. for(k=0;k<l1;k++){
  119417. t5+=ido;
  119418. t6+=ido;
  119419. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119420. c1[t6-1]=ch[t5]-ch[t6];
  119421. c1[t5]=ch[t5]+ch[t6];
  119422. c1[t6]=ch[t6-1]-ch[t5-1];
  119423. }
  119424. }
  119425. }
  119426. }else{
  119427. for(j=1;j<ipph;j++){
  119428. t1+=t0;
  119429. t2-=t0;
  119430. t3=t1;
  119431. t4=t2;
  119432. for(k=0;k<l1;k++){
  119433. t5=t3;
  119434. t6=t4;
  119435. for(i=2;i<ido;i+=2){
  119436. t5+=2;
  119437. t6+=2;
  119438. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119439. c1[t6-1]=ch[t5]-ch[t6];
  119440. c1[t5]=ch[t5]+ch[t6];
  119441. c1[t6]=ch[t6-1]-ch[t5-1];
  119442. }
  119443. t3+=ido;
  119444. t4+=ido;
  119445. }
  119446. }
  119447. }
  119448. L119:
  119449. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119450. t1=0;
  119451. t2=ipp2*idl1;
  119452. for(j=1;j<ipph;j++){
  119453. t1+=t0;
  119454. t2-=t0;
  119455. t3=t1-ido;
  119456. t4=t2-ido;
  119457. for(k=0;k<l1;k++){
  119458. t3+=ido;
  119459. t4+=ido;
  119460. c1[t3]=ch[t3]+ch[t4];
  119461. c1[t4]=ch[t4]-ch[t3];
  119462. }
  119463. }
  119464. ar1=1.f;
  119465. ai1=0.f;
  119466. t1=0;
  119467. t2=ipp2*idl1;
  119468. t3=(ip-1)*idl1;
  119469. for(l=1;l<ipph;l++){
  119470. t1+=idl1;
  119471. t2-=idl1;
  119472. ar1h=dcp*ar1-dsp*ai1;
  119473. ai1=dcp*ai1+dsp*ar1;
  119474. ar1=ar1h;
  119475. t4=t1;
  119476. t5=t2;
  119477. t6=t3;
  119478. t7=idl1;
  119479. for(ik=0;ik<idl1;ik++){
  119480. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119481. ch2[t5++]=ai1*c2[t6++];
  119482. }
  119483. dc2=ar1;
  119484. ds2=ai1;
  119485. ar2=ar1;
  119486. ai2=ai1;
  119487. t4=idl1;
  119488. t5=(ipp2-1)*idl1;
  119489. for(j=2;j<ipph;j++){
  119490. t4+=idl1;
  119491. t5-=idl1;
  119492. ar2h=dc2*ar2-ds2*ai2;
  119493. ai2=dc2*ai2+ds2*ar2;
  119494. ar2=ar2h;
  119495. t6=t1;
  119496. t7=t2;
  119497. t8=t4;
  119498. t9=t5;
  119499. for(ik=0;ik<idl1;ik++){
  119500. ch2[t6++]+=ar2*c2[t8++];
  119501. ch2[t7++]+=ai2*c2[t9++];
  119502. }
  119503. }
  119504. }
  119505. t1=0;
  119506. for(j=1;j<ipph;j++){
  119507. t1+=idl1;
  119508. t2=t1;
  119509. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119510. }
  119511. if(ido<l1)goto L132;
  119512. t1=0;
  119513. t2=0;
  119514. for(k=0;k<l1;k++){
  119515. t3=t1;
  119516. t4=t2;
  119517. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119518. t1+=ido;
  119519. t2+=t10;
  119520. }
  119521. goto L135;
  119522. L132:
  119523. for(i=0;i<ido;i++){
  119524. t1=i;
  119525. t2=i;
  119526. for(k=0;k<l1;k++){
  119527. cc[t2]=ch[t1];
  119528. t1+=ido;
  119529. t2+=t10;
  119530. }
  119531. }
  119532. L135:
  119533. t1=0;
  119534. t2=ido<<1;
  119535. t3=0;
  119536. t4=ipp2*t0;
  119537. for(j=1;j<ipph;j++){
  119538. t1+=t2;
  119539. t3+=t0;
  119540. t4-=t0;
  119541. t5=t1;
  119542. t6=t3;
  119543. t7=t4;
  119544. for(k=0;k<l1;k++){
  119545. cc[t5-1]=ch[t6];
  119546. cc[t5]=ch[t7];
  119547. t5+=t10;
  119548. t6+=ido;
  119549. t7+=ido;
  119550. }
  119551. }
  119552. if(ido==1)return;
  119553. if(nbd<l1)goto L141;
  119554. t1=-ido;
  119555. t3=0;
  119556. t4=0;
  119557. t5=ipp2*t0;
  119558. for(j=1;j<ipph;j++){
  119559. t1+=t2;
  119560. t3+=t2;
  119561. t4+=t0;
  119562. t5-=t0;
  119563. t6=t1;
  119564. t7=t3;
  119565. t8=t4;
  119566. t9=t5;
  119567. for(k=0;k<l1;k++){
  119568. for(i=2;i<ido;i+=2){
  119569. ic=idp2-i;
  119570. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119571. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119572. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119573. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119574. }
  119575. t6+=t10;
  119576. t7+=t10;
  119577. t8+=ido;
  119578. t9+=ido;
  119579. }
  119580. }
  119581. return;
  119582. L141:
  119583. t1=-ido;
  119584. t3=0;
  119585. t4=0;
  119586. t5=ipp2*t0;
  119587. for(j=1;j<ipph;j++){
  119588. t1+=t2;
  119589. t3+=t2;
  119590. t4+=t0;
  119591. t5-=t0;
  119592. for(i=2;i<ido;i+=2){
  119593. t6=idp2+t1-i;
  119594. t7=i+t3;
  119595. t8=i+t4;
  119596. t9=i+t5;
  119597. for(k=0;k<l1;k++){
  119598. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119599. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119600. cc[t7]=ch[t8]+ch[t9];
  119601. cc[t6]=ch[t9]-ch[t8];
  119602. t6+=t10;
  119603. t7+=t10;
  119604. t8+=ido;
  119605. t9+=ido;
  119606. }
  119607. }
  119608. }
  119609. }
  119610. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119611. int i,k1,l1,l2;
  119612. int na,kh,nf;
  119613. int ip,iw,ido,idl1,ix2,ix3;
  119614. nf=ifac[1];
  119615. na=1;
  119616. l2=n;
  119617. iw=n;
  119618. for(k1=0;k1<nf;k1++){
  119619. kh=nf-k1;
  119620. ip=ifac[kh+1];
  119621. l1=l2/ip;
  119622. ido=n/l2;
  119623. idl1=ido*l1;
  119624. iw-=(ip-1)*ido;
  119625. na=1-na;
  119626. if(ip!=4)goto L102;
  119627. ix2=iw+ido;
  119628. ix3=ix2+ido;
  119629. if(na!=0)
  119630. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119631. else
  119632. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119633. goto L110;
  119634. L102:
  119635. if(ip!=2)goto L104;
  119636. if(na!=0)goto L103;
  119637. dradf2(ido,l1,c,ch,wa+iw-1);
  119638. goto L110;
  119639. L103:
  119640. dradf2(ido,l1,ch,c,wa+iw-1);
  119641. goto L110;
  119642. L104:
  119643. if(ido==1)na=1-na;
  119644. if(na!=0)goto L109;
  119645. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119646. na=1;
  119647. goto L110;
  119648. L109:
  119649. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119650. na=0;
  119651. L110:
  119652. l2=l1;
  119653. }
  119654. if(na==1)return;
  119655. for(i=0;i<n;i++)c[i]=ch[i];
  119656. }
  119657. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119658. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119659. float ti2,tr2;
  119660. t0=l1*ido;
  119661. t1=0;
  119662. t2=0;
  119663. t3=(ido<<1)-1;
  119664. for(k=0;k<l1;k++){
  119665. ch[t1]=cc[t2]+cc[t3+t2];
  119666. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119667. t2=(t1+=ido)<<1;
  119668. }
  119669. if(ido<2)return;
  119670. if(ido==2)goto L105;
  119671. t1=0;
  119672. t2=0;
  119673. for(k=0;k<l1;k++){
  119674. t3=t1;
  119675. t5=(t4=t2)+(ido<<1);
  119676. t6=t0+t1;
  119677. for(i=2;i<ido;i+=2){
  119678. t3+=2;
  119679. t4+=2;
  119680. t5-=2;
  119681. t6+=2;
  119682. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119683. tr2=cc[t4-1]-cc[t5-1];
  119684. ch[t3]=cc[t4]-cc[t5];
  119685. ti2=cc[t4]+cc[t5];
  119686. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119687. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119688. }
  119689. t2=(t1+=ido)<<1;
  119690. }
  119691. if(ido%2==1)return;
  119692. L105:
  119693. t1=ido-1;
  119694. t2=ido-1;
  119695. for(k=0;k<l1;k++){
  119696. ch[t1]=cc[t2]+cc[t2];
  119697. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119698. t1+=ido;
  119699. t2+=ido<<1;
  119700. }
  119701. }
  119702. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119703. float *wa2){
  119704. static float taur = -.5f;
  119705. static float taui = .8660254037844386f;
  119706. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119707. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119708. t0=l1*ido;
  119709. t1=0;
  119710. t2=t0<<1;
  119711. t3=ido<<1;
  119712. t4=ido+(ido<<1);
  119713. t5=0;
  119714. for(k=0;k<l1;k++){
  119715. tr2=cc[t3-1]+cc[t3-1];
  119716. cr2=cc[t5]+(taur*tr2);
  119717. ch[t1]=cc[t5]+tr2;
  119718. ci3=taui*(cc[t3]+cc[t3]);
  119719. ch[t1+t0]=cr2-ci3;
  119720. ch[t1+t2]=cr2+ci3;
  119721. t1+=ido;
  119722. t3+=t4;
  119723. t5+=t4;
  119724. }
  119725. if(ido==1)return;
  119726. t1=0;
  119727. t3=ido<<1;
  119728. for(k=0;k<l1;k++){
  119729. t7=t1+(t1<<1);
  119730. t6=(t5=t7+t3);
  119731. t8=t1;
  119732. t10=(t9=t1+t0)+t0;
  119733. for(i=2;i<ido;i+=2){
  119734. t5+=2;
  119735. t6-=2;
  119736. t7+=2;
  119737. t8+=2;
  119738. t9+=2;
  119739. t10+=2;
  119740. tr2=cc[t5-1]+cc[t6-1];
  119741. cr2=cc[t7-1]+(taur*tr2);
  119742. ch[t8-1]=cc[t7-1]+tr2;
  119743. ti2=cc[t5]-cc[t6];
  119744. ci2=cc[t7]+(taur*ti2);
  119745. ch[t8]=cc[t7]+ti2;
  119746. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119747. ci3=taui*(cc[t5]+cc[t6]);
  119748. dr2=cr2-ci3;
  119749. dr3=cr2+ci3;
  119750. di2=ci2+cr3;
  119751. di3=ci2-cr3;
  119752. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119753. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119754. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119755. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119756. }
  119757. t1+=ido;
  119758. }
  119759. }
  119760. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119761. float *wa2,float *wa3){
  119762. static float sqrt2=1.414213562373095f;
  119763. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119764. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119765. t0=l1*ido;
  119766. t1=0;
  119767. t2=ido<<2;
  119768. t3=0;
  119769. t6=ido<<1;
  119770. for(k=0;k<l1;k++){
  119771. t4=t3+t6;
  119772. t5=t1;
  119773. tr3=cc[t4-1]+cc[t4-1];
  119774. tr4=cc[t4]+cc[t4];
  119775. tr1=cc[t3]-cc[(t4+=t6)-1];
  119776. tr2=cc[t3]+cc[t4-1];
  119777. ch[t5]=tr2+tr3;
  119778. ch[t5+=t0]=tr1-tr4;
  119779. ch[t5+=t0]=tr2-tr3;
  119780. ch[t5+=t0]=tr1+tr4;
  119781. t1+=ido;
  119782. t3+=t2;
  119783. }
  119784. if(ido<2)return;
  119785. if(ido==2)goto L105;
  119786. t1=0;
  119787. for(k=0;k<l1;k++){
  119788. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119789. t7=t1;
  119790. for(i=2;i<ido;i+=2){
  119791. t2+=2;
  119792. t3+=2;
  119793. t4-=2;
  119794. t5-=2;
  119795. t7+=2;
  119796. ti1=cc[t2]+cc[t5];
  119797. ti2=cc[t2]-cc[t5];
  119798. ti3=cc[t3]-cc[t4];
  119799. tr4=cc[t3]+cc[t4];
  119800. tr1=cc[t2-1]-cc[t5-1];
  119801. tr2=cc[t2-1]+cc[t5-1];
  119802. ti4=cc[t3-1]-cc[t4-1];
  119803. tr3=cc[t3-1]+cc[t4-1];
  119804. ch[t7-1]=tr2+tr3;
  119805. cr3=tr2-tr3;
  119806. ch[t7]=ti2+ti3;
  119807. ci3=ti2-ti3;
  119808. cr2=tr1-tr4;
  119809. cr4=tr1+tr4;
  119810. ci2=ti1+ti4;
  119811. ci4=ti1-ti4;
  119812. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119813. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119814. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119815. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119816. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119817. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119818. }
  119819. t1+=ido;
  119820. }
  119821. if(ido%2 == 1)return;
  119822. L105:
  119823. t1=ido;
  119824. t2=ido<<2;
  119825. t3=ido-1;
  119826. t4=ido+(ido<<1);
  119827. for(k=0;k<l1;k++){
  119828. t5=t3;
  119829. ti1=cc[t1]+cc[t4];
  119830. ti2=cc[t4]-cc[t1];
  119831. tr1=cc[t1-1]-cc[t4-1];
  119832. tr2=cc[t1-1]+cc[t4-1];
  119833. ch[t5]=tr2+tr2;
  119834. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119835. ch[t5+=t0]=ti2+ti2;
  119836. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119837. t3+=ido;
  119838. t1+=t2;
  119839. t4+=t2;
  119840. }
  119841. }
  119842. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119843. float *c2,float *ch,float *ch2,float *wa){
  119844. static float tpi=6.283185307179586f;
  119845. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119846. t11,t12;
  119847. float dc2,ai1,ai2,ar1,ar2,ds2;
  119848. int nbd;
  119849. float dcp,arg,dsp,ar1h,ar2h;
  119850. int ipp2;
  119851. t10=ip*ido;
  119852. t0=l1*ido;
  119853. arg=tpi/(float)ip;
  119854. dcp=cos(arg);
  119855. dsp=sin(arg);
  119856. nbd=(ido-1)>>1;
  119857. ipp2=ip;
  119858. ipph=(ip+1)>>1;
  119859. if(ido<l1)goto L103;
  119860. t1=0;
  119861. t2=0;
  119862. for(k=0;k<l1;k++){
  119863. t3=t1;
  119864. t4=t2;
  119865. for(i=0;i<ido;i++){
  119866. ch[t3]=cc[t4];
  119867. t3++;
  119868. t4++;
  119869. }
  119870. t1+=ido;
  119871. t2+=t10;
  119872. }
  119873. goto L106;
  119874. L103:
  119875. t1=0;
  119876. for(i=0;i<ido;i++){
  119877. t2=t1;
  119878. t3=t1;
  119879. for(k=0;k<l1;k++){
  119880. ch[t2]=cc[t3];
  119881. t2+=ido;
  119882. t3+=t10;
  119883. }
  119884. t1++;
  119885. }
  119886. L106:
  119887. t1=0;
  119888. t2=ipp2*t0;
  119889. t7=(t5=ido<<1);
  119890. for(j=1;j<ipph;j++){
  119891. t1+=t0;
  119892. t2-=t0;
  119893. t3=t1;
  119894. t4=t2;
  119895. t6=t5;
  119896. for(k=0;k<l1;k++){
  119897. ch[t3]=cc[t6-1]+cc[t6-1];
  119898. ch[t4]=cc[t6]+cc[t6];
  119899. t3+=ido;
  119900. t4+=ido;
  119901. t6+=t10;
  119902. }
  119903. t5+=t7;
  119904. }
  119905. if (ido == 1)goto L116;
  119906. if(nbd<l1)goto L112;
  119907. t1=0;
  119908. t2=ipp2*t0;
  119909. t7=0;
  119910. for(j=1;j<ipph;j++){
  119911. t1+=t0;
  119912. t2-=t0;
  119913. t3=t1;
  119914. t4=t2;
  119915. t7+=(ido<<1);
  119916. t8=t7;
  119917. for(k=0;k<l1;k++){
  119918. t5=t3;
  119919. t6=t4;
  119920. t9=t8;
  119921. t11=t8;
  119922. for(i=2;i<ido;i+=2){
  119923. t5+=2;
  119924. t6+=2;
  119925. t9+=2;
  119926. t11-=2;
  119927. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119928. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119929. ch[t5]=cc[t9]-cc[t11];
  119930. ch[t6]=cc[t9]+cc[t11];
  119931. }
  119932. t3+=ido;
  119933. t4+=ido;
  119934. t8+=t10;
  119935. }
  119936. }
  119937. goto L116;
  119938. L112:
  119939. t1=0;
  119940. t2=ipp2*t0;
  119941. t7=0;
  119942. for(j=1;j<ipph;j++){
  119943. t1+=t0;
  119944. t2-=t0;
  119945. t3=t1;
  119946. t4=t2;
  119947. t7+=(ido<<1);
  119948. t8=t7;
  119949. t9=t7;
  119950. for(i=2;i<ido;i+=2){
  119951. t3+=2;
  119952. t4+=2;
  119953. t8+=2;
  119954. t9-=2;
  119955. t5=t3;
  119956. t6=t4;
  119957. t11=t8;
  119958. t12=t9;
  119959. for(k=0;k<l1;k++){
  119960. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119961. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119962. ch[t5]=cc[t11]-cc[t12];
  119963. ch[t6]=cc[t11]+cc[t12];
  119964. t5+=ido;
  119965. t6+=ido;
  119966. t11+=t10;
  119967. t12+=t10;
  119968. }
  119969. }
  119970. }
  119971. L116:
  119972. ar1=1.f;
  119973. ai1=0.f;
  119974. t1=0;
  119975. t9=(t2=ipp2*idl1);
  119976. t3=(ip-1)*idl1;
  119977. for(l=1;l<ipph;l++){
  119978. t1+=idl1;
  119979. t2-=idl1;
  119980. ar1h=dcp*ar1-dsp*ai1;
  119981. ai1=dcp*ai1+dsp*ar1;
  119982. ar1=ar1h;
  119983. t4=t1;
  119984. t5=t2;
  119985. t6=0;
  119986. t7=idl1;
  119987. t8=t3;
  119988. for(ik=0;ik<idl1;ik++){
  119989. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119990. c2[t5++]=ai1*ch2[t8++];
  119991. }
  119992. dc2=ar1;
  119993. ds2=ai1;
  119994. ar2=ar1;
  119995. ai2=ai1;
  119996. t6=idl1;
  119997. t7=t9-idl1;
  119998. for(j=2;j<ipph;j++){
  119999. t6+=idl1;
  120000. t7-=idl1;
  120001. ar2h=dc2*ar2-ds2*ai2;
  120002. ai2=dc2*ai2+ds2*ar2;
  120003. ar2=ar2h;
  120004. t4=t1;
  120005. t5=t2;
  120006. t11=t6;
  120007. t12=t7;
  120008. for(ik=0;ik<idl1;ik++){
  120009. c2[t4++]+=ar2*ch2[t11++];
  120010. c2[t5++]+=ai2*ch2[t12++];
  120011. }
  120012. }
  120013. }
  120014. t1=0;
  120015. for(j=1;j<ipph;j++){
  120016. t1+=idl1;
  120017. t2=t1;
  120018. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120019. }
  120020. t1=0;
  120021. t2=ipp2*t0;
  120022. for(j=1;j<ipph;j++){
  120023. t1+=t0;
  120024. t2-=t0;
  120025. t3=t1;
  120026. t4=t2;
  120027. for(k=0;k<l1;k++){
  120028. ch[t3]=c1[t3]-c1[t4];
  120029. ch[t4]=c1[t3]+c1[t4];
  120030. t3+=ido;
  120031. t4+=ido;
  120032. }
  120033. }
  120034. if(ido==1)goto L132;
  120035. if(nbd<l1)goto L128;
  120036. t1=0;
  120037. t2=ipp2*t0;
  120038. for(j=1;j<ipph;j++){
  120039. t1+=t0;
  120040. t2-=t0;
  120041. t3=t1;
  120042. t4=t2;
  120043. for(k=0;k<l1;k++){
  120044. t5=t3;
  120045. t6=t4;
  120046. for(i=2;i<ido;i+=2){
  120047. t5+=2;
  120048. t6+=2;
  120049. ch[t5-1]=c1[t5-1]-c1[t6];
  120050. ch[t6-1]=c1[t5-1]+c1[t6];
  120051. ch[t5]=c1[t5]+c1[t6-1];
  120052. ch[t6]=c1[t5]-c1[t6-1];
  120053. }
  120054. t3+=ido;
  120055. t4+=ido;
  120056. }
  120057. }
  120058. goto L132;
  120059. L128:
  120060. t1=0;
  120061. t2=ipp2*t0;
  120062. for(j=1;j<ipph;j++){
  120063. t1+=t0;
  120064. t2-=t0;
  120065. t3=t1;
  120066. t4=t2;
  120067. for(i=2;i<ido;i+=2){
  120068. t3+=2;
  120069. t4+=2;
  120070. t5=t3;
  120071. t6=t4;
  120072. for(k=0;k<l1;k++){
  120073. ch[t5-1]=c1[t5-1]-c1[t6];
  120074. ch[t6-1]=c1[t5-1]+c1[t6];
  120075. ch[t5]=c1[t5]+c1[t6-1];
  120076. ch[t6]=c1[t5]-c1[t6-1];
  120077. t5+=ido;
  120078. t6+=ido;
  120079. }
  120080. }
  120081. }
  120082. L132:
  120083. if(ido==1)return;
  120084. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120085. t1=0;
  120086. for(j=1;j<ip;j++){
  120087. t2=(t1+=t0);
  120088. for(k=0;k<l1;k++){
  120089. c1[t2]=ch[t2];
  120090. t2+=ido;
  120091. }
  120092. }
  120093. if(nbd>l1)goto L139;
  120094. is= -ido-1;
  120095. t1=0;
  120096. for(j=1;j<ip;j++){
  120097. is+=ido;
  120098. t1+=t0;
  120099. idij=is;
  120100. t2=t1;
  120101. for(i=2;i<ido;i+=2){
  120102. t2+=2;
  120103. idij+=2;
  120104. t3=t2;
  120105. for(k=0;k<l1;k++){
  120106. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120107. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120108. t3+=ido;
  120109. }
  120110. }
  120111. }
  120112. return;
  120113. L139:
  120114. is= -ido-1;
  120115. t1=0;
  120116. for(j=1;j<ip;j++){
  120117. is+=ido;
  120118. t1+=t0;
  120119. t2=t1;
  120120. for(k=0;k<l1;k++){
  120121. idij=is;
  120122. t3=t2;
  120123. for(i=2;i<ido;i+=2){
  120124. idij+=2;
  120125. t3+=2;
  120126. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120127. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120128. }
  120129. t2+=ido;
  120130. }
  120131. }
  120132. }
  120133. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120134. int i,k1,l1,l2;
  120135. int na;
  120136. int nf,ip,iw,ix2,ix3,ido,idl1;
  120137. nf=ifac[1];
  120138. na=0;
  120139. l1=1;
  120140. iw=1;
  120141. for(k1=0;k1<nf;k1++){
  120142. ip=ifac[k1 + 2];
  120143. l2=ip*l1;
  120144. ido=n/l2;
  120145. idl1=ido*l1;
  120146. if(ip!=4)goto L103;
  120147. ix2=iw+ido;
  120148. ix3=ix2+ido;
  120149. if(na!=0)
  120150. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120151. else
  120152. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120153. na=1-na;
  120154. goto L115;
  120155. L103:
  120156. if(ip!=2)goto L106;
  120157. if(na!=0)
  120158. dradb2(ido,l1,ch,c,wa+iw-1);
  120159. else
  120160. dradb2(ido,l1,c,ch,wa+iw-1);
  120161. na=1-na;
  120162. goto L115;
  120163. L106:
  120164. if(ip!=3)goto L109;
  120165. ix2=iw+ido;
  120166. if(na!=0)
  120167. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120168. else
  120169. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120170. na=1-na;
  120171. goto L115;
  120172. L109:
  120173. /* The radix five case can be translated later..... */
  120174. /* if(ip!=5)goto L112;
  120175. ix2=iw+ido;
  120176. ix3=ix2+ido;
  120177. ix4=ix3+ido;
  120178. if(na!=0)
  120179. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120180. else
  120181. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120182. na=1-na;
  120183. goto L115;
  120184. L112:*/
  120185. if(na!=0)
  120186. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120187. else
  120188. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120189. if(ido==1)na=1-na;
  120190. L115:
  120191. l1=l2;
  120192. iw+=(ip-1)*ido;
  120193. }
  120194. if(na==0)return;
  120195. for(i=0;i<n;i++)c[i]=ch[i];
  120196. }
  120197. void drft_forward(drft_lookup *l,float *data){
  120198. if(l->n==1)return;
  120199. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120200. }
  120201. void drft_backward(drft_lookup *l,float *data){
  120202. if (l->n==1)return;
  120203. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120204. }
  120205. void drft_init(drft_lookup *l,int n){
  120206. l->n=n;
  120207. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120208. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120209. fdrffti(n, l->trigcache, l->splitcache);
  120210. }
  120211. void drft_clear(drft_lookup *l){
  120212. if(l){
  120213. if(l->trigcache)_ogg_free(l->trigcache);
  120214. if(l->splitcache)_ogg_free(l->splitcache);
  120215. memset(l,0,sizeof(*l));
  120216. }
  120217. }
  120218. #endif
  120219. /*** End of inlined file: smallft.c ***/
  120220. /*** Start of inlined file: synthesis.c ***/
  120221. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120222. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120223. // tasks..
  120224. #if JUCE_MSVC
  120225. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120226. #endif
  120227. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120228. #if JUCE_USE_OGGVORBIS
  120229. #include <stdio.h>
  120230. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120231. vorbis_dsp_state *vd=vb->vd;
  120232. private_state *b=(private_state*)vd->backend_state;
  120233. vorbis_info *vi=vd->vi;
  120234. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120235. oggpack_buffer *opb=&vb->opb;
  120236. int type,mode,i;
  120237. /* first things first. Make sure decode is ready */
  120238. _vorbis_block_ripcord(vb);
  120239. oggpack_readinit(opb,op->packet,op->bytes);
  120240. /* Check the packet type */
  120241. if(oggpack_read(opb,1)!=0){
  120242. /* Oops. This is not an audio data packet */
  120243. return(OV_ENOTAUDIO);
  120244. }
  120245. /* read our mode and pre/post windowsize */
  120246. mode=oggpack_read(opb,b->modebits);
  120247. if(mode==-1)return(OV_EBADPACKET);
  120248. vb->mode=mode;
  120249. vb->W=ci->mode_param[mode]->blockflag;
  120250. if(vb->W){
  120251. /* this doesn;t get mapped through mode selection as it's used
  120252. only for window selection */
  120253. vb->lW=oggpack_read(opb,1);
  120254. vb->nW=oggpack_read(opb,1);
  120255. if(vb->nW==-1) return(OV_EBADPACKET);
  120256. }else{
  120257. vb->lW=0;
  120258. vb->nW=0;
  120259. }
  120260. /* more setup */
  120261. vb->granulepos=op->granulepos;
  120262. vb->sequence=op->packetno;
  120263. vb->eofflag=op->e_o_s;
  120264. /* alloc pcm passback storage */
  120265. vb->pcmend=ci->blocksizes[vb->W];
  120266. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120267. for(i=0;i<vi->channels;i++)
  120268. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120269. /* unpack_header enforces range checking */
  120270. type=ci->map_type[ci->mode_param[mode]->mapping];
  120271. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120272. mapping]));
  120273. }
  120274. /* used to track pcm position without actually performing decode.
  120275. Useful for sequential 'fast forward' */
  120276. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120277. vorbis_dsp_state *vd=vb->vd;
  120278. private_state *b=(private_state*)vd->backend_state;
  120279. vorbis_info *vi=vd->vi;
  120280. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120281. oggpack_buffer *opb=&vb->opb;
  120282. int mode;
  120283. /* first things first. Make sure decode is ready */
  120284. _vorbis_block_ripcord(vb);
  120285. oggpack_readinit(opb,op->packet,op->bytes);
  120286. /* Check the packet type */
  120287. if(oggpack_read(opb,1)!=0){
  120288. /* Oops. This is not an audio data packet */
  120289. return(OV_ENOTAUDIO);
  120290. }
  120291. /* read our mode and pre/post windowsize */
  120292. mode=oggpack_read(opb,b->modebits);
  120293. if(mode==-1)return(OV_EBADPACKET);
  120294. vb->mode=mode;
  120295. vb->W=ci->mode_param[mode]->blockflag;
  120296. if(vb->W){
  120297. vb->lW=oggpack_read(opb,1);
  120298. vb->nW=oggpack_read(opb,1);
  120299. if(vb->nW==-1) return(OV_EBADPACKET);
  120300. }else{
  120301. vb->lW=0;
  120302. vb->nW=0;
  120303. }
  120304. /* more setup */
  120305. vb->granulepos=op->granulepos;
  120306. vb->sequence=op->packetno;
  120307. vb->eofflag=op->e_o_s;
  120308. /* no pcm */
  120309. vb->pcmend=0;
  120310. vb->pcm=NULL;
  120311. return(0);
  120312. }
  120313. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120314. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120315. oggpack_buffer opb;
  120316. int mode;
  120317. oggpack_readinit(&opb,op->packet,op->bytes);
  120318. /* Check the packet type */
  120319. if(oggpack_read(&opb,1)!=0){
  120320. /* Oops. This is not an audio data packet */
  120321. return(OV_ENOTAUDIO);
  120322. }
  120323. {
  120324. int modebits=0;
  120325. int v=ci->modes;
  120326. while(v>1){
  120327. modebits++;
  120328. v>>=1;
  120329. }
  120330. /* read our mode and pre/post windowsize */
  120331. mode=oggpack_read(&opb,modebits);
  120332. }
  120333. if(mode==-1)return(OV_EBADPACKET);
  120334. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120335. }
  120336. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120337. /* set / clear half-sample-rate mode */
  120338. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120339. /* right now, our MDCT can't handle < 64 sample windows. */
  120340. if(ci->blocksizes[0]<=64 && flag)return -1;
  120341. ci->halfrate_flag=(flag?1:0);
  120342. return 0;
  120343. }
  120344. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120345. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120346. return ci->halfrate_flag;
  120347. }
  120348. #endif
  120349. /*** End of inlined file: synthesis.c ***/
  120350. /*** Start of inlined file: vorbisenc.c ***/
  120351. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120352. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120353. // tasks..
  120354. #if JUCE_MSVC
  120355. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120356. #endif
  120357. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120358. #if JUCE_USE_OGGVORBIS
  120359. #include <stdlib.h>
  120360. #include <string.h>
  120361. #include <math.h>
  120362. /* careful with this; it's using static array sizing to make managing
  120363. all the modes a little less annoying. If we use a residue backend
  120364. with > 12 partition types, or a different division of iteration,
  120365. this needs to be updated. */
  120366. typedef struct {
  120367. static_codebook *books[12][3];
  120368. } static_bookblock;
  120369. typedef struct {
  120370. int res_type;
  120371. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120372. vorbis_info_residue0 *res;
  120373. static_codebook *book_aux;
  120374. static_codebook *book_aux_managed;
  120375. static_bookblock *books_base;
  120376. static_bookblock *books_base_managed;
  120377. } vorbis_residue_template;
  120378. typedef struct {
  120379. vorbis_info_mapping0 *map;
  120380. vorbis_residue_template *res;
  120381. } vorbis_mapping_template;
  120382. typedef struct vp_adjblock{
  120383. int block[P_BANDS];
  120384. } vp_adjblock;
  120385. typedef struct {
  120386. int data[NOISE_COMPAND_LEVELS];
  120387. } compandblock;
  120388. /* high level configuration information for setting things up
  120389. step-by-step with the detailed vorbis_encode_ctl interface.
  120390. There's a fair amount of redundancy such that interactive setup
  120391. does not directly deal with any vorbis_info or codec_setup_info
  120392. initialization; it's all stored (until full init) in this highlevel
  120393. setup, then flushed out to the real codec setup structs later. */
  120394. typedef struct {
  120395. int att[P_NOISECURVES];
  120396. float boost;
  120397. float decay;
  120398. } att3;
  120399. typedef struct { int data[P_NOISECURVES]; } adj3;
  120400. typedef struct {
  120401. int pre[PACKETBLOBS];
  120402. int post[PACKETBLOBS];
  120403. float kHz[PACKETBLOBS];
  120404. float lowpasskHz[PACKETBLOBS];
  120405. } adj_stereo;
  120406. typedef struct {
  120407. int lo;
  120408. int hi;
  120409. int fixed;
  120410. } noiseguard;
  120411. typedef struct {
  120412. int data[P_NOISECURVES][17];
  120413. } noise3;
  120414. typedef struct {
  120415. int mappings;
  120416. double *rate_mapping;
  120417. double *quality_mapping;
  120418. int coupling_restriction;
  120419. long samplerate_min_restriction;
  120420. long samplerate_max_restriction;
  120421. int *blocksize_short;
  120422. int *blocksize_long;
  120423. att3 *psy_tone_masteratt;
  120424. int *psy_tone_0dB;
  120425. int *psy_tone_dBsuppress;
  120426. vp_adjblock *psy_tone_adj_impulse;
  120427. vp_adjblock *psy_tone_adj_long;
  120428. vp_adjblock *psy_tone_adj_other;
  120429. noiseguard *psy_noiseguards;
  120430. noise3 *psy_noise_bias_impulse;
  120431. noise3 *psy_noise_bias_padding;
  120432. noise3 *psy_noise_bias_trans;
  120433. noise3 *psy_noise_bias_long;
  120434. int *psy_noise_dBsuppress;
  120435. compandblock *psy_noise_compand;
  120436. double *psy_noise_compand_short_mapping;
  120437. double *psy_noise_compand_long_mapping;
  120438. int *psy_noise_normal_start[2];
  120439. int *psy_noise_normal_partition[2];
  120440. double *psy_noise_normal_thresh;
  120441. int *psy_ath_float;
  120442. int *psy_ath_abs;
  120443. double *psy_lowpass;
  120444. vorbis_info_psy_global *global_params;
  120445. double *global_mapping;
  120446. adj_stereo *stereo_modes;
  120447. static_codebook ***floor_books;
  120448. vorbis_info_floor1 *floor_params;
  120449. int *floor_short_mapping;
  120450. int *floor_long_mapping;
  120451. vorbis_mapping_template *maps;
  120452. } ve_setup_data_template;
  120453. /* a few static coder conventions */
  120454. static vorbis_info_mode _mode_template[2]={
  120455. {0,0,0,0},
  120456. {1,0,0,1}
  120457. };
  120458. static vorbis_info_mapping0 _map_nominal[2]={
  120459. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120460. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120461. };
  120462. /*** Start of inlined file: setup_44.h ***/
  120463. /*** Start of inlined file: floor_all.h ***/
  120464. /*** Start of inlined file: floor_books.h ***/
  120465. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120466. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120467. };
  120468. static static_codebook _huff_book_line_256x7_0sub1 = {
  120469. 1, 9,
  120470. _huff_lengthlist_line_256x7_0sub1,
  120471. 0, 0, 0, 0, 0,
  120472. NULL,
  120473. NULL,
  120474. NULL,
  120475. NULL,
  120476. 0
  120477. };
  120478. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120480. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120481. };
  120482. static static_codebook _huff_book_line_256x7_0sub2 = {
  120483. 1, 25,
  120484. _huff_lengthlist_line_256x7_0sub2,
  120485. 0, 0, 0, 0, 0,
  120486. NULL,
  120487. NULL,
  120488. NULL,
  120489. NULL,
  120490. 0
  120491. };
  120492. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120495. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120496. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120497. };
  120498. static static_codebook _huff_book_line_256x7_0sub3 = {
  120499. 1, 64,
  120500. _huff_lengthlist_line_256x7_0sub3,
  120501. 0, 0, 0, 0, 0,
  120502. NULL,
  120503. NULL,
  120504. NULL,
  120505. NULL,
  120506. 0
  120507. };
  120508. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120509. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120510. };
  120511. static static_codebook _huff_book_line_256x7_1sub1 = {
  120512. 1, 9,
  120513. _huff_lengthlist_line_256x7_1sub1,
  120514. 0, 0, 0, 0, 0,
  120515. NULL,
  120516. NULL,
  120517. NULL,
  120518. NULL,
  120519. 0
  120520. };
  120521. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120523. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120524. };
  120525. static static_codebook _huff_book_line_256x7_1sub2 = {
  120526. 1, 25,
  120527. _huff_lengthlist_line_256x7_1sub2,
  120528. 0, 0, 0, 0, 0,
  120529. NULL,
  120530. NULL,
  120531. NULL,
  120532. NULL,
  120533. 0
  120534. };
  120535. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120538. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120539. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120540. };
  120541. static static_codebook _huff_book_line_256x7_1sub3 = {
  120542. 1, 64,
  120543. _huff_lengthlist_line_256x7_1sub3,
  120544. 0, 0, 0, 0, 0,
  120545. NULL,
  120546. NULL,
  120547. NULL,
  120548. NULL,
  120549. 0
  120550. };
  120551. static long _huff_lengthlist_line_256x7_class0[] = {
  120552. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120553. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120554. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120555. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120556. };
  120557. static static_codebook _huff_book_line_256x7_class0 = {
  120558. 1, 64,
  120559. _huff_lengthlist_line_256x7_class0,
  120560. 0, 0, 0, 0, 0,
  120561. NULL,
  120562. NULL,
  120563. NULL,
  120564. NULL,
  120565. 0
  120566. };
  120567. static long _huff_lengthlist_line_256x7_class1[] = {
  120568. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120569. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120570. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120571. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120572. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120573. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120574. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120575. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120576. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120577. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120578. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120579. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120580. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120581. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120582. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120583. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120584. };
  120585. static static_codebook _huff_book_line_256x7_class1 = {
  120586. 1, 256,
  120587. _huff_lengthlist_line_256x7_class1,
  120588. 0, 0, 0, 0, 0,
  120589. NULL,
  120590. NULL,
  120591. NULL,
  120592. NULL,
  120593. 0
  120594. };
  120595. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120596. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120597. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120598. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120599. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120600. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120601. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120602. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120603. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120604. };
  120605. static static_codebook _huff_book_line_512x17_0sub0 = {
  120606. 1, 128,
  120607. _huff_lengthlist_line_512x17_0sub0,
  120608. 0, 0, 0, 0, 0,
  120609. NULL,
  120610. NULL,
  120611. NULL,
  120612. NULL,
  120613. 0
  120614. };
  120615. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120616. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120617. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120618. };
  120619. static static_codebook _huff_book_line_512x17_1sub0 = {
  120620. 1, 32,
  120621. _huff_lengthlist_line_512x17_1sub0,
  120622. 0, 0, 0, 0, 0,
  120623. NULL,
  120624. NULL,
  120625. NULL,
  120626. NULL,
  120627. 0
  120628. };
  120629. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120632. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120633. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120634. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120635. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120636. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120637. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120638. };
  120639. static static_codebook _huff_book_line_512x17_1sub1 = {
  120640. 1, 128,
  120641. _huff_lengthlist_line_512x17_1sub1,
  120642. 0, 0, 0, 0, 0,
  120643. NULL,
  120644. NULL,
  120645. NULL,
  120646. NULL,
  120647. 0
  120648. };
  120649. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120650. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120651. 5, 3,
  120652. };
  120653. static static_codebook _huff_book_line_512x17_2sub1 = {
  120654. 1, 18,
  120655. _huff_lengthlist_line_512x17_2sub1,
  120656. 0, 0, 0, 0, 0,
  120657. NULL,
  120658. NULL,
  120659. NULL,
  120660. NULL,
  120661. 0
  120662. };
  120663. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120665. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120666. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120667. 9, 8,
  120668. };
  120669. static static_codebook _huff_book_line_512x17_2sub2 = {
  120670. 1, 50,
  120671. _huff_lengthlist_line_512x17_2sub2,
  120672. 0, 0, 0, 0, 0,
  120673. NULL,
  120674. NULL,
  120675. NULL,
  120676. NULL,
  120677. 0
  120678. };
  120679. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120683. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120684. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120685. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120686. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120688. };
  120689. static static_codebook _huff_book_line_512x17_2sub3 = {
  120690. 1, 128,
  120691. _huff_lengthlist_line_512x17_2sub3,
  120692. 0, 0, 0, 0, 0,
  120693. NULL,
  120694. NULL,
  120695. NULL,
  120696. NULL,
  120697. 0
  120698. };
  120699. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120700. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120701. 5, 5,
  120702. };
  120703. static static_codebook _huff_book_line_512x17_3sub1 = {
  120704. 1, 18,
  120705. _huff_lengthlist_line_512x17_3sub1,
  120706. 0, 0, 0, 0, 0,
  120707. NULL,
  120708. NULL,
  120709. NULL,
  120710. NULL,
  120711. 0
  120712. };
  120713. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120715. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120716. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120717. 11,14,
  120718. };
  120719. static static_codebook _huff_book_line_512x17_3sub2 = {
  120720. 1, 50,
  120721. _huff_lengthlist_line_512x17_3sub2,
  120722. 0, 0, 0, 0, 0,
  120723. NULL,
  120724. NULL,
  120725. NULL,
  120726. NULL,
  120727. 0
  120728. };
  120729. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120733. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120734. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120735. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120736. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120737. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120738. };
  120739. static static_codebook _huff_book_line_512x17_3sub3 = {
  120740. 1, 128,
  120741. _huff_lengthlist_line_512x17_3sub3,
  120742. 0, 0, 0, 0, 0,
  120743. NULL,
  120744. NULL,
  120745. NULL,
  120746. NULL,
  120747. 0
  120748. };
  120749. static long _huff_lengthlist_line_512x17_class1[] = {
  120750. 1, 2, 3, 6, 5, 4, 7, 7,
  120751. };
  120752. static static_codebook _huff_book_line_512x17_class1 = {
  120753. 1, 8,
  120754. _huff_lengthlist_line_512x17_class1,
  120755. 0, 0, 0, 0, 0,
  120756. NULL,
  120757. NULL,
  120758. NULL,
  120759. NULL,
  120760. 0
  120761. };
  120762. static long _huff_lengthlist_line_512x17_class2[] = {
  120763. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120764. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120765. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120766. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120767. };
  120768. static static_codebook _huff_book_line_512x17_class2 = {
  120769. 1, 64,
  120770. _huff_lengthlist_line_512x17_class2,
  120771. 0, 0, 0, 0, 0,
  120772. NULL,
  120773. NULL,
  120774. NULL,
  120775. NULL,
  120776. 0
  120777. };
  120778. static long _huff_lengthlist_line_512x17_class3[] = {
  120779. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120780. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120781. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120782. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120783. };
  120784. static static_codebook _huff_book_line_512x17_class3 = {
  120785. 1, 64,
  120786. _huff_lengthlist_line_512x17_class3,
  120787. 0, 0, 0, 0, 0,
  120788. NULL,
  120789. NULL,
  120790. NULL,
  120791. NULL,
  120792. 0
  120793. };
  120794. static long _huff_lengthlist_line_128x4_class0[] = {
  120795. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120796. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120797. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120798. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120799. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120800. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120801. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120802. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120803. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120804. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120805. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120806. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120807. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120808. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120809. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120810. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120811. };
  120812. static static_codebook _huff_book_line_128x4_class0 = {
  120813. 1, 256,
  120814. _huff_lengthlist_line_128x4_class0,
  120815. 0, 0, 0, 0, 0,
  120816. NULL,
  120817. NULL,
  120818. NULL,
  120819. NULL,
  120820. 0
  120821. };
  120822. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120823. 2, 2, 2, 2,
  120824. };
  120825. static static_codebook _huff_book_line_128x4_0sub0 = {
  120826. 1, 4,
  120827. _huff_lengthlist_line_128x4_0sub0,
  120828. 0, 0, 0, 0, 0,
  120829. NULL,
  120830. NULL,
  120831. NULL,
  120832. NULL,
  120833. 0
  120834. };
  120835. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120836. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120837. };
  120838. static static_codebook _huff_book_line_128x4_0sub1 = {
  120839. 1, 10,
  120840. _huff_lengthlist_line_128x4_0sub1,
  120841. 0, 0, 0, 0, 0,
  120842. NULL,
  120843. NULL,
  120844. NULL,
  120845. NULL,
  120846. 0
  120847. };
  120848. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120850. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120851. };
  120852. static static_codebook _huff_book_line_128x4_0sub2 = {
  120853. 1, 25,
  120854. _huff_lengthlist_line_128x4_0sub2,
  120855. 0, 0, 0, 0, 0,
  120856. NULL,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. 0
  120861. };
  120862. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120865. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120866. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120867. };
  120868. static static_codebook _huff_book_line_128x4_0sub3 = {
  120869. 1, 64,
  120870. _huff_lengthlist_line_128x4_0sub3,
  120871. 0, 0, 0, 0, 0,
  120872. NULL,
  120873. NULL,
  120874. NULL,
  120875. NULL,
  120876. 0
  120877. };
  120878. static long _huff_lengthlist_line_256x4_class0[] = {
  120879. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120880. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120881. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120882. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120883. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120884. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120885. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120886. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120887. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120888. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120889. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120890. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120891. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120892. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120893. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120894. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120895. };
  120896. static static_codebook _huff_book_line_256x4_class0 = {
  120897. 1, 256,
  120898. _huff_lengthlist_line_256x4_class0,
  120899. 0, 0, 0, 0, 0,
  120900. NULL,
  120901. NULL,
  120902. NULL,
  120903. NULL,
  120904. 0
  120905. };
  120906. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120907. 2, 2, 2, 2,
  120908. };
  120909. static static_codebook _huff_book_line_256x4_0sub0 = {
  120910. 1, 4,
  120911. _huff_lengthlist_line_256x4_0sub0,
  120912. 0, 0, 0, 0, 0,
  120913. NULL,
  120914. NULL,
  120915. NULL,
  120916. NULL,
  120917. 0
  120918. };
  120919. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120920. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120921. };
  120922. static static_codebook _huff_book_line_256x4_0sub1 = {
  120923. 1, 10,
  120924. _huff_lengthlist_line_256x4_0sub1,
  120925. 0, 0, 0, 0, 0,
  120926. NULL,
  120927. NULL,
  120928. NULL,
  120929. NULL,
  120930. 0
  120931. };
  120932. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120934. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120935. };
  120936. static static_codebook _huff_book_line_256x4_0sub2 = {
  120937. 1, 25,
  120938. _huff_lengthlist_line_256x4_0sub2,
  120939. 0, 0, 0, 0, 0,
  120940. NULL,
  120941. NULL,
  120942. NULL,
  120943. NULL,
  120944. 0
  120945. };
  120946. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120949. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120950. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120951. };
  120952. static static_codebook _huff_book_line_256x4_0sub3 = {
  120953. 1, 64,
  120954. _huff_lengthlist_line_256x4_0sub3,
  120955. 0, 0, 0, 0, 0,
  120956. NULL,
  120957. NULL,
  120958. NULL,
  120959. NULL,
  120960. 0
  120961. };
  120962. static long _huff_lengthlist_line_128x7_class0[] = {
  120963. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120964. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120965. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120966. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120967. };
  120968. static static_codebook _huff_book_line_128x7_class0 = {
  120969. 1, 64,
  120970. _huff_lengthlist_line_128x7_class0,
  120971. 0, 0, 0, 0, 0,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. NULL,
  120976. 0
  120977. };
  120978. static long _huff_lengthlist_line_128x7_class1[] = {
  120979. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120980. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120981. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120982. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120983. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120984. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120985. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120986. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120987. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120988. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120989. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120990. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120991. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120992. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120993. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120994. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120995. };
  120996. static static_codebook _huff_book_line_128x7_class1 = {
  120997. 1, 256,
  120998. _huff_lengthlist_line_128x7_class1,
  120999. 0, 0, 0, 0, 0,
  121000. NULL,
  121001. NULL,
  121002. NULL,
  121003. NULL,
  121004. 0
  121005. };
  121006. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121007. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121008. };
  121009. static static_codebook _huff_book_line_128x7_0sub1 = {
  121010. 1, 9,
  121011. _huff_lengthlist_line_128x7_0sub1,
  121012. 0, 0, 0, 0, 0,
  121013. NULL,
  121014. NULL,
  121015. NULL,
  121016. NULL,
  121017. 0
  121018. };
  121019. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121021. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121022. };
  121023. static static_codebook _huff_book_line_128x7_0sub2 = {
  121024. 1, 25,
  121025. _huff_lengthlist_line_128x7_0sub2,
  121026. 0, 0, 0, 0, 0,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. 0
  121032. };
  121033. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121036. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121037. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121038. };
  121039. static static_codebook _huff_book_line_128x7_0sub3 = {
  121040. 1, 64,
  121041. _huff_lengthlist_line_128x7_0sub3,
  121042. 0, 0, 0, 0, 0,
  121043. NULL,
  121044. NULL,
  121045. NULL,
  121046. NULL,
  121047. 0
  121048. };
  121049. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121050. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121051. };
  121052. static static_codebook _huff_book_line_128x7_1sub1 = {
  121053. 1, 9,
  121054. _huff_lengthlist_line_128x7_1sub1,
  121055. 0, 0, 0, 0, 0,
  121056. NULL,
  121057. NULL,
  121058. NULL,
  121059. NULL,
  121060. 0
  121061. };
  121062. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121064. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121065. };
  121066. static static_codebook _huff_book_line_128x7_1sub2 = {
  121067. 1, 25,
  121068. _huff_lengthlist_line_128x7_1sub2,
  121069. 0, 0, 0, 0, 0,
  121070. NULL,
  121071. NULL,
  121072. NULL,
  121073. NULL,
  121074. 0
  121075. };
  121076. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121079. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121080. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121081. };
  121082. static static_codebook _huff_book_line_128x7_1sub3 = {
  121083. 1, 64,
  121084. _huff_lengthlist_line_128x7_1sub3,
  121085. 0, 0, 0, 0, 0,
  121086. NULL,
  121087. NULL,
  121088. NULL,
  121089. NULL,
  121090. 0
  121091. };
  121092. static long _huff_lengthlist_line_128x11_class1[] = {
  121093. 1, 6, 3, 7, 2, 4, 5, 7,
  121094. };
  121095. static static_codebook _huff_book_line_128x11_class1 = {
  121096. 1, 8,
  121097. _huff_lengthlist_line_128x11_class1,
  121098. 0, 0, 0, 0, 0,
  121099. NULL,
  121100. NULL,
  121101. NULL,
  121102. NULL,
  121103. 0
  121104. };
  121105. static long _huff_lengthlist_line_128x11_class2[] = {
  121106. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121107. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121108. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121109. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121110. };
  121111. static static_codebook _huff_book_line_128x11_class2 = {
  121112. 1, 64,
  121113. _huff_lengthlist_line_128x11_class2,
  121114. 0, 0, 0, 0, 0,
  121115. NULL,
  121116. NULL,
  121117. NULL,
  121118. NULL,
  121119. 0
  121120. };
  121121. static long _huff_lengthlist_line_128x11_class3[] = {
  121122. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121123. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121124. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121125. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121126. };
  121127. static static_codebook _huff_book_line_128x11_class3 = {
  121128. 1, 64,
  121129. _huff_lengthlist_line_128x11_class3,
  121130. 0, 0, 0, 0, 0,
  121131. NULL,
  121132. NULL,
  121133. NULL,
  121134. NULL,
  121135. 0
  121136. };
  121137. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121138. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121139. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121140. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121141. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121142. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121143. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121144. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121145. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121146. };
  121147. static static_codebook _huff_book_line_128x11_0sub0 = {
  121148. 1, 128,
  121149. _huff_lengthlist_line_128x11_0sub0,
  121150. 0, 0, 0, 0, 0,
  121151. NULL,
  121152. NULL,
  121153. NULL,
  121154. NULL,
  121155. 0
  121156. };
  121157. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121158. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121159. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121160. };
  121161. static static_codebook _huff_book_line_128x11_1sub0 = {
  121162. 1, 32,
  121163. _huff_lengthlist_line_128x11_1sub0,
  121164. 0, 0, 0, 0, 0,
  121165. NULL,
  121166. NULL,
  121167. NULL,
  121168. NULL,
  121169. 0
  121170. };
  121171. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121174. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121175. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121176. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121177. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121178. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121179. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121180. };
  121181. static static_codebook _huff_book_line_128x11_1sub1 = {
  121182. 1, 128,
  121183. _huff_lengthlist_line_128x11_1sub1,
  121184. 0, 0, 0, 0, 0,
  121185. NULL,
  121186. NULL,
  121187. NULL,
  121188. NULL,
  121189. 0
  121190. };
  121191. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121192. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121193. 5, 5,
  121194. };
  121195. static static_codebook _huff_book_line_128x11_2sub1 = {
  121196. 1, 18,
  121197. _huff_lengthlist_line_128x11_2sub1,
  121198. 0, 0, 0, 0, 0,
  121199. NULL,
  121200. NULL,
  121201. NULL,
  121202. NULL,
  121203. 0
  121204. };
  121205. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121207. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121208. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121209. 8,11,
  121210. };
  121211. static static_codebook _huff_book_line_128x11_2sub2 = {
  121212. 1, 50,
  121213. _huff_lengthlist_line_128x11_2sub2,
  121214. 0, 0, 0, 0, 0,
  121215. NULL,
  121216. NULL,
  121217. NULL,
  121218. NULL,
  121219. 0
  121220. };
  121221. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121225. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121226. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121227. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121228. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121229. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121230. };
  121231. static static_codebook _huff_book_line_128x11_2sub3 = {
  121232. 1, 128,
  121233. _huff_lengthlist_line_128x11_2sub3,
  121234. 0, 0, 0, 0, 0,
  121235. NULL,
  121236. NULL,
  121237. NULL,
  121238. NULL,
  121239. 0
  121240. };
  121241. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121242. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121243. 5, 4,
  121244. };
  121245. static static_codebook _huff_book_line_128x11_3sub1 = {
  121246. 1, 18,
  121247. _huff_lengthlist_line_128x11_3sub1,
  121248. 0, 0, 0, 0, 0,
  121249. NULL,
  121250. NULL,
  121251. NULL,
  121252. NULL,
  121253. 0
  121254. };
  121255. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121257. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121258. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121259. 12, 6,
  121260. };
  121261. static static_codebook _huff_book_line_128x11_3sub2 = {
  121262. 1, 50,
  121263. _huff_lengthlist_line_128x11_3sub2,
  121264. 0, 0, 0, 0, 0,
  121265. NULL,
  121266. NULL,
  121267. NULL,
  121268. NULL,
  121269. 0
  121270. };
  121271. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121275. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121276. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121277. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121280. };
  121281. static static_codebook _huff_book_line_128x11_3sub3 = {
  121282. 1, 128,
  121283. _huff_lengthlist_line_128x11_3sub3,
  121284. 0, 0, 0, 0, 0,
  121285. NULL,
  121286. NULL,
  121287. NULL,
  121288. NULL,
  121289. 0
  121290. };
  121291. static long _huff_lengthlist_line_128x17_class1[] = {
  121292. 1, 3, 4, 7, 2, 5, 6, 7,
  121293. };
  121294. static static_codebook _huff_book_line_128x17_class1 = {
  121295. 1, 8,
  121296. _huff_lengthlist_line_128x17_class1,
  121297. 0, 0, 0, 0, 0,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. 0
  121303. };
  121304. static long _huff_lengthlist_line_128x17_class2[] = {
  121305. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121306. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121307. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121308. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121309. };
  121310. static static_codebook _huff_book_line_128x17_class2 = {
  121311. 1, 64,
  121312. _huff_lengthlist_line_128x17_class2,
  121313. 0, 0, 0, 0, 0,
  121314. NULL,
  121315. NULL,
  121316. NULL,
  121317. NULL,
  121318. 0
  121319. };
  121320. static long _huff_lengthlist_line_128x17_class3[] = {
  121321. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121322. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121323. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121324. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121325. };
  121326. static static_codebook _huff_book_line_128x17_class3 = {
  121327. 1, 64,
  121328. _huff_lengthlist_line_128x17_class3,
  121329. 0, 0, 0, 0, 0,
  121330. NULL,
  121331. NULL,
  121332. NULL,
  121333. NULL,
  121334. 0
  121335. };
  121336. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121337. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121338. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121339. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121340. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121341. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121342. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121343. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121344. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121345. };
  121346. static static_codebook _huff_book_line_128x17_0sub0 = {
  121347. 1, 128,
  121348. _huff_lengthlist_line_128x17_0sub0,
  121349. 0, 0, 0, 0, 0,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. NULL,
  121354. 0
  121355. };
  121356. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121357. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121358. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121359. };
  121360. static static_codebook _huff_book_line_128x17_1sub0 = {
  121361. 1, 32,
  121362. _huff_lengthlist_line_128x17_1sub0,
  121363. 0, 0, 0, 0, 0,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. NULL,
  121368. 0
  121369. };
  121370. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121374. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121375. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121376. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121377. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121378. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121379. };
  121380. static static_codebook _huff_book_line_128x17_1sub1 = {
  121381. 1, 128,
  121382. _huff_lengthlist_line_128x17_1sub1,
  121383. 0, 0, 0, 0, 0,
  121384. NULL,
  121385. NULL,
  121386. NULL,
  121387. NULL,
  121388. 0
  121389. };
  121390. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121391. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121392. 9, 4,
  121393. };
  121394. static static_codebook _huff_book_line_128x17_2sub1 = {
  121395. 1, 18,
  121396. _huff_lengthlist_line_128x17_2sub1,
  121397. 0, 0, 0, 0, 0,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. NULL,
  121402. 0
  121403. };
  121404. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121407. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121408. 13,13,
  121409. };
  121410. static static_codebook _huff_book_line_128x17_2sub2 = {
  121411. 1, 50,
  121412. _huff_lengthlist_line_128x17_2sub2,
  121413. 0, 0, 0, 0, 0,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. NULL,
  121418. 0
  121419. };
  121420. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121424. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121425. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121426. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121427. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121428. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121429. };
  121430. static static_codebook _huff_book_line_128x17_2sub3 = {
  121431. 1, 128,
  121432. _huff_lengthlist_line_128x17_2sub3,
  121433. 0, 0, 0, 0, 0,
  121434. NULL,
  121435. NULL,
  121436. NULL,
  121437. NULL,
  121438. 0
  121439. };
  121440. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121441. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121442. 6, 4,
  121443. };
  121444. static static_codebook _huff_book_line_128x17_3sub1 = {
  121445. 1, 18,
  121446. _huff_lengthlist_line_128x17_3sub1,
  121447. 0, 0, 0, 0, 0,
  121448. NULL,
  121449. NULL,
  121450. NULL,
  121451. NULL,
  121452. 0
  121453. };
  121454. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121456. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121457. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121458. 10, 8,
  121459. };
  121460. static static_codebook _huff_book_line_128x17_3sub2 = {
  121461. 1, 50,
  121462. _huff_lengthlist_line_128x17_3sub2,
  121463. 0, 0, 0, 0, 0,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. 0
  121469. };
  121470. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121474. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121475. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121476. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121479. };
  121480. static static_codebook _huff_book_line_128x17_3sub3 = {
  121481. 1, 128,
  121482. _huff_lengthlist_line_128x17_3sub3,
  121483. 0, 0, 0, 0, 0,
  121484. NULL,
  121485. NULL,
  121486. NULL,
  121487. NULL,
  121488. 0
  121489. };
  121490. static long _huff_lengthlist_line_1024x27_class1[] = {
  121491. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121492. };
  121493. static static_codebook _huff_book_line_1024x27_class1 = {
  121494. 1, 16,
  121495. _huff_lengthlist_line_1024x27_class1,
  121496. 0, 0, 0, 0, 0,
  121497. NULL,
  121498. NULL,
  121499. NULL,
  121500. NULL,
  121501. 0
  121502. };
  121503. static long _huff_lengthlist_line_1024x27_class2[] = {
  121504. 1, 4, 2, 6, 3, 7, 5, 7,
  121505. };
  121506. static static_codebook _huff_book_line_1024x27_class2 = {
  121507. 1, 8,
  121508. _huff_lengthlist_line_1024x27_class2,
  121509. 0, 0, 0, 0, 0,
  121510. NULL,
  121511. NULL,
  121512. NULL,
  121513. NULL,
  121514. 0
  121515. };
  121516. static long _huff_lengthlist_line_1024x27_class3[] = {
  121517. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121518. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121519. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121520. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121521. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121522. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121523. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121524. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121525. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121526. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121527. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121528. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121529. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121530. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121531. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121532. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121533. };
  121534. static static_codebook _huff_book_line_1024x27_class3 = {
  121535. 1, 256,
  121536. _huff_lengthlist_line_1024x27_class3,
  121537. 0, 0, 0, 0, 0,
  121538. NULL,
  121539. NULL,
  121540. NULL,
  121541. NULL,
  121542. 0
  121543. };
  121544. static long _huff_lengthlist_line_1024x27_class4[] = {
  121545. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121546. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121547. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121548. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121549. };
  121550. static static_codebook _huff_book_line_1024x27_class4 = {
  121551. 1, 64,
  121552. _huff_lengthlist_line_1024x27_class4,
  121553. 0, 0, 0, 0, 0,
  121554. NULL,
  121555. NULL,
  121556. NULL,
  121557. NULL,
  121558. 0
  121559. };
  121560. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121561. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121562. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121563. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121564. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121565. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121566. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121567. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121568. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121569. };
  121570. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121571. 1, 128,
  121572. _huff_lengthlist_line_1024x27_0sub0,
  121573. 0, 0, 0, 0, 0,
  121574. NULL,
  121575. NULL,
  121576. NULL,
  121577. NULL,
  121578. 0
  121579. };
  121580. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121581. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121582. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121583. };
  121584. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121585. 1, 32,
  121586. _huff_lengthlist_line_1024x27_1sub0,
  121587. 0, 0, 0, 0, 0,
  121588. NULL,
  121589. NULL,
  121590. NULL,
  121591. NULL,
  121592. 0
  121593. };
  121594. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121598. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121599. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121600. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121601. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121602. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121603. };
  121604. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121605. 1, 128,
  121606. _huff_lengthlist_line_1024x27_1sub1,
  121607. 0, 0, 0, 0, 0,
  121608. NULL,
  121609. NULL,
  121610. NULL,
  121611. NULL,
  121612. 0
  121613. };
  121614. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121615. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121616. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121617. };
  121618. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121619. 1, 32,
  121620. _huff_lengthlist_line_1024x27_2sub0,
  121621. 0, 0, 0, 0, 0,
  121622. NULL,
  121623. NULL,
  121624. NULL,
  121625. NULL,
  121626. 0
  121627. };
  121628. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121631. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121632. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121633. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121634. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121635. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121636. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121637. };
  121638. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121639. 1, 128,
  121640. _huff_lengthlist_line_1024x27_2sub1,
  121641. 0, 0, 0, 0, 0,
  121642. NULL,
  121643. NULL,
  121644. NULL,
  121645. NULL,
  121646. 0
  121647. };
  121648. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121649. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121650. 5, 5,
  121651. };
  121652. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121653. 1, 18,
  121654. _huff_lengthlist_line_1024x27_3sub1,
  121655. 0, 0, 0, 0, 0,
  121656. NULL,
  121657. NULL,
  121658. NULL,
  121659. NULL,
  121660. 0
  121661. };
  121662. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121664. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121665. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121666. 9,11,
  121667. };
  121668. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121669. 1, 50,
  121670. _huff_lengthlist_line_1024x27_3sub2,
  121671. 0, 0, 0, 0, 0,
  121672. NULL,
  121673. NULL,
  121674. NULL,
  121675. NULL,
  121676. 0
  121677. };
  121678. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121683. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121684. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121685. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121686. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121687. };
  121688. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121689. 1, 128,
  121690. _huff_lengthlist_line_1024x27_3sub3,
  121691. 0, 0, 0, 0, 0,
  121692. NULL,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. 0
  121697. };
  121698. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121699. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121700. 5, 4,
  121701. };
  121702. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121703. 1, 18,
  121704. _huff_lengthlist_line_1024x27_4sub1,
  121705. 0, 0, 0, 0, 0,
  121706. NULL,
  121707. NULL,
  121708. NULL,
  121709. NULL,
  121710. 0
  121711. };
  121712. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121715. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121716. 9,12,
  121717. };
  121718. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121719. 1, 50,
  121720. _huff_lengthlist_line_1024x27_4sub2,
  121721. 0, 0, 0, 0, 0,
  121722. NULL,
  121723. NULL,
  121724. NULL,
  121725. NULL,
  121726. 0
  121727. };
  121728. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121733. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121736. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121737. };
  121738. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121739. 1, 128,
  121740. _huff_lengthlist_line_1024x27_4sub3,
  121741. 0, 0, 0, 0, 0,
  121742. NULL,
  121743. NULL,
  121744. NULL,
  121745. NULL,
  121746. 0
  121747. };
  121748. static long _huff_lengthlist_line_2048x27_class1[] = {
  121749. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121750. };
  121751. static static_codebook _huff_book_line_2048x27_class1 = {
  121752. 1, 16,
  121753. _huff_lengthlist_line_2048x27_class1,
  121754. 0, 0, 0, 0, 0,
  121755. NULL,
  121756. NULL,
  121757. NULL,
  121758. NULL,
  121759. 0
  121760. };
  121761. static long _huff_lengthlist_line_2048x27_class2[] = {
  121762. 1, 2, 3, 6, 4, 7, 5, 7,
  121763. };
  121764. static static_codebook _huff_book_line_2048x27_class2 = {
  121765. 1, 8,
  121766. _huff_lengthlist_line_2048x27_class2,
  121767. 0, 0, 0, 0, 0,
  121768. NULL,
  121769. NULL,
  121770. NULL,
  121771. NULL,
  121772. 0
  121773. };
  121774. static long _huff_lengthlist_line_2048x27_class3[] = {
  121775. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121776. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121777. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121778. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121779. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121780. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121781. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121782. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121783. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121784. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121785. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121786. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121787. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121788. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121789. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121790. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121791. };
  121792. static static_codebook _huff_book_line_2048x27_class3 = {
  121793. 1, 256,
  121794. _huff_lengthlist_line_2048x27_class3,
  121795. 0, 0, 0, 0, 0,
  121796. NULL,
  121797. NULL,
  121798. NULL,
  121799. NULL,
  121800. 0
  121801. };
  121802. static long _huff_lengthlist_line_2048x27_class4[] = {
  121803. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121804. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121805. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121806. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121807. };
  121808. static static_codebook _huff_book_line_2048x27_class4 = {
  121809. 1, 64,
  121810. _huff_lengthlist_line_2048x27_class4,
  121811. 0, 0, 0, 0, 0,
  121812. NULL,
  121813. NULL,
  121814. NULL,
  121815. NULL,
  121816. 0
  121817. };
  121818. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121819. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121820. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121821. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121822. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121823. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121824. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121825. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121826. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121827. };
  121828. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121829. 1, 128,
  121830. _huff_lengthlist_line_2048x27_0sub0,
  121831. 0, 0, 0, 0, 0,
  121832. NULL,
  121833. NULL,
  121834. NULL,
  121835. NULL,
  121836. 0
  121837. };
  121838. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121839. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121840. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121841. };
  121842. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121843. 1, 32,
  121844. _huff_lengthlist_line_2048x27_1sub0,
  121845. 0, 0, 0, 0, 0,
  121846. NULL,
  121847. NULL,
  121848. NULL,
  121849. NULL,
  121850. 0
  121851. };
  121852. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121855. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121856. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121857. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121858. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121859. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121860. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121861. };
  121862. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121863. 1, 128,
  121864. _huff_lengthlist_line_2048x27_1sub1,
  121865. 0, 0, 0, 0, 0,
  121866. NULL,
  121867. NULL,
  121868. NULL,
  121869. NULL,
  121870. 0
  121871. };
  121872. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121873. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121874. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121875. };
  121876. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121877. 1, 32,
  121878. _huff_lengthlist_line_2048x27_2sub0,
  121879. 0, 0, 0, 0, 0,
  121880. NULL,
  121881. NULL,
  121882. NULL,
  121883. NULL,
  121884. 0
  121885. };
  121886. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121889. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121890. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121891. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121892. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121893. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121894. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121895. };
  121896. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121897. 1, 128,
  121898. _huff_lengthlist_line_2048x27_2sub1,
  121899. 0, 0, 0, 0, 0,
  121900. NULL,
  121901. NULL,
  121902. NULL,
  121903. NULL,
  121904. 0
  121905. };
  121906. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121907. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121908. 5, 5,
  121909. };
  121910. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121911. 1, 18,
  121912. _huff_lengthlist_line_2048x27_3sub1,
  121913. 0, 0, 0, 0, 0,
  121914. NULL,
  121915. NULL,
  121916. NULL,
  121917. NULL,
  121918. 0
  121919. };
  121920. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121922. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121923. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121924. 10,12,
  121925. };
  121926. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121927. 1, 50,
  121928. _huff_lengthlist_line_2048x27_3sub2,
  121929. 0, 0, 0, 0, 0,
  121930. NULL,
  121931. NULL,
  121932. NULL,
  121933. NULL,
  121934. 0
  121935. };
  121936. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121941. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121942. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121943. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121944. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121945. };
  121946. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121947. 1, 128,
  121948. _huff_lengthlist_line_2048x27_3sub3,
  121949. 0, 0, 0, 0, 0,
  121950. NULL,
  121951. NULL,
  121952. NULL,
  121953. NULL,
  121954. 0
  121955. };
  121956. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121957. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121958. 4, 5,
  121959. };
  121960. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121961. 1, 18,
  121962. _huff_lengthlist_line_2048x27_4sub1,
  121963. 0, 0, 0, 0, 0,
  121964. NULL,
  121965. NULL,
  121966. NULL,
  121967. NULL,
  121968. 0
  121969. };
  121970. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121973. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121974. 10,10,
  121975. };
  121976. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121977. 1, 50,
  121978. _huff_lengthlist_line_2048x27_4sub2,
  121979. 0, 0, 0, 0, 0,
  121980. NULL,
  121981. NULL,
  121982. NULL,
  121983. NULL,
  121984. 0
  121985. };
  121986. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121990. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121991. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121992. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121993. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121994. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121995. };
  121996. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121997. 1, 128,
  121998. _huff_lengthlist_line_2048x27_4sub3,
  121999. 0, 0, 0, 0, 0,
  122000. NULL,
  122001. NULL,
  122002. NULL,
  122003. NULL,
  122004. 0
  122005. };
  122006. static long _huff_lengthlist_line_256x4low_class0[] = {
  122007. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122008. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122009. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122010. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122011. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122012. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122013. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122014. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122015. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122016. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122017. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122018. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122019. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122020. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122021. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122022. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122023. };
  122024. static static_codebook _huff_book_line_256x4low_class0 = {
  122025. 1, 256,
  122026. _huff_lengthlist_line_256x4low_class0,
  122027. 0, 0, 0, 0, 0,
  122028. NULL,
  122029. NULL,
  122030. NULL,
  122031. NULL,
  122032. 0
  122033. };
  122034. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122035. 1, 3, 2, 3,
  122036. };
  122037. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122038. 1, 4,
  122039. _huff_lengthlist_line_256x4low_0sub0,
  122040. 0, 0, 0, 0, 0,
  122041. NULL,
  122042. NULL,
  122043. NULL,
  122044. NULL,
  122045. 0
  122046. };
  122047. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122048. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122049. };
  122050. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122051. 1, 10,
  122052. _huff_lengthlist_line_256x4low_0sub1,
  122053. 0, 0, 0, 0, 0,
  122054. NULL,
  122055. NULL,
  122056. NULL,
  122057. NULL,
  122058. 0
  122059. };
  122060. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122062. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122063. };
  122064. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122065. 1, 25,
  122066. _huff_lengthlist_line_256x4low_0sub2,
  122067. 0, 0, 0, 0, 0,
  122068. NULL,
  122069. NULL,
  122070. NULL,
  122071. NULL,
  122072. 0
  122073. };
  122074. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122077. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122078. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122079. };
  122080. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122081. 1, 64,
  122082. _huff_lengthlist_line_256x4low_0sub3,
  122083. 0, 0, 0, 0, 0,
  122084. NULL,
  122085. NULL,
  122086. NULL,
  122087. NULL,
  122088. 0
  122089. };
  122090. /*** End of inlined file: floor_books.h ***/
  122091. static static_codebook *_floor_128x4_books[]={
  122092. &_huff_book_line_128x4_class0,
  122093. &_huff_book_line_128x4_0sub0,
  122094. &_huff_book_line_128x4_0sub1,
  122095. &_huff_book_line_128x4_0sub2,
  122096. &_huff_book_line_128x4_0sub3,
  122097. };
  122098. static static_codebook *_floor_256x4_books[]={
  122099. &_huff_book_line_256x4_class0,
  122100. &_huff_book_line_256x4_0sub0,
  122101. &_huff_book_line_256x4_0sub1,
  122102. &_huff_book_line_256x4_0sub2,
  122103. &_huff_book_line_256x4_0sub3,
  122104. };
  122105. static static_codebook *_floor_128x7_books[]={
  122106. &_huff_book_line_128x7_class0,
  122107. &_huff_book_line_128x7_class1,
  122108. &_huff_book_line_128x7_0sub1,
  122109. &_huff_book_line_128x7_0sub2,
  122110. &_huff_book_line_128x7_0sub3,
  122111. &_huff_book_line_128x7_1sub1,
  122112. &_huff_book_line_128x7_1sub2,
  122113. &_huff_book_line_128x7_1sub3,
  122114. };
  122115. static static_codebook *_floor_256x7_books[]={
  122116. &_huff_book_line_256x7_class0,
  122117. &_huff_book_line_256x7_class1,
  122118. &_huff_book_line_256x7_0sub1,
  122119. &_huff_book_line_256x7_0sub2,
  122120. &_huff_book_line_256x7_0sub3,
  122121. &_huff_book_line_256x7_1sub1,
  122122. &_huff_book_line_256x7_1sub2,
  122123. &_huff_book_line_256x7_1sub3,
  122124. };
  122125. static static_codebook *_floor_128x11_books[]={
  122126. &_huff_book_line_128x11_class1,
  122127. &_huff_book_line_128x11_class2,
  122128. &_huff_book_line_128x11_class3,
  122129. &_huff_book_line_128x11_0sub0,
  122130. &_huff_book_line_128x11_1sub0,
  122131. &_huff_book_line_128x11_1sub1,
  122132. &_huff_book_line_128x11_2sub1,
  122133. &_huff_book_line_128x11_2sub2,
  122134. &_huff_book_line_128x11_2sub3,
  122135. &_huff_book_line_128x11_3sub1,
  122136. &_huff_book_line_128x11_3sub2,
  122137. &_huff_book_line_128x11_3sub3,
  122138. };
  122139. static static_codebook *_floor_128x17_books[]={
  122140. &_huff_book_line_128x17_class1,
  122141. &_huff_book_line_128x17_class2,
  122142. &_huff_book_line_128x17_class3,
  122143. &_huff_book_line_128x17_0sub0,
  122144. &_huff_book_line_128x17_1sub0,
  122145. &_huff_book_line_128x17_1sub1,
  122146. &_huff_book_line_128x17_2sub1,
  122147. &_huff_book_line_128x17_2sub2,
  122148. &_huff_book_line_128x17_2sub3,
  122149. &_huff_book_line_128x17_3sub1,
  122150. &_huff_book_line_128x17_3sub2,
  122151. &_huff_book_line_128x17_3sub3,
  122152. };
  122153. static static_codebook *_floor_256x4low_books[]={
  122154. &_huff_book_line_256x4low_class0,
  122155. &_huff_book_line_256x4low_0sub0,
  122156. &_huff_book_line_256x4low_0sub1,
  122157. &_huff_book_line_256x4low_0sub2,
  122158. &_huff_book_line_256x4low_0sub3,
  122159. };
  122160. static static_codebook *_floor_1024x27_books[]={
  122161. &_huff_book_line_1024x27_class1,
  122162. &_huff_book_line_1024x27_class2,
  122163. &_huff_book_line_1024x27_class3,
  122164. &_huff_book_line_1024x27_class4,
  122165. &_huff_book_line_1024x27_0sub0,
  122166. &_huff_book_line_1024x27_1sub0,
  122167. &_huff_book_line_1024x27_1sub1,
  122168. &_huff_book_line_1024x27_2sub0,
  122169. &_huff_book_line_1024x27_2sub1,
  122170. &_huff_book_line_1024x27_3sub1,
  122171. &_huff_book_line_1024x27_3sub2,
  122172. &_huff_book_line_1024x27_3sub3,
  122173. &_huff_book_line_1024x27_4sub1,
  122174. &_huff_book_line_1024x27_4sub2,
  122175. &_huff_book_line_1024x27_4sub3,
  122176. };
  122177. static static_codebook *_floor_2048x27_books[]={
  122178. &_huff_book_line_2048x27_class1,
  122179. &_huff_book_line_2048x27_class2,
  122180. &_huff_book_line_2048x27_class3,
  122181. &_huff_book_line_2048x27_class4,
  122182. &_huff_book_line_2048x27_0sub0,
  122183. &_huff_book_line_2048x27_1sub0,
  122184. &_huff_book_line_2048x27_1sub1,
  122185. &_huff_book_line_2048x27_2sub0,
  122186. &_huff_book_line_2048x27_2sub1,
  122187. &_huff_book_line_2048x27_3sub1,
  122188. &_huff_book_line_2048x27_3sub2,
  122189. &_huff_book_line_2048x27_3sub3,
  122190. &_huff_book_line_2048x27_4sub1,
  122191. &_huff_book_line_2048x27_4sub2,
  122192. &_huff_book_line_2048x27_4sub3,
  122193. };
  122194. static static_codebook *_floor_512x17_books[]={
  122195. &_huff_book_line_512x17_class1,
  122196. &_huff_book_line_512x17_class2,
  122197. &_huff_book_line_512x17_class3,
  122198. &_huff_book_line_512x17_0sub0,
  122199. &_huff_book_line_512x17_1sub0,
  122200. &_huff_book_line_512x17_1sub1,
  122201. &_huff_book_line_512x17_2sub1,
  122202. &_huff_book_line_512x17_2sub2,
  122203. &_huff_book_line_512x17_2sub3,
  122204. &_huff_book_line_512x17_3sub1,
  122205. &_huff_book_line_512x17_3sub2,
  122206. &_huff_book_line_512x17_3sub3,
  122207. };
  122208. static static_codebook **_floor_books[10]={
  122209. _floor_128x4_books,
  122210. _floor_256x4_books,
  122211. _floor_128x7_books,
  122212. _floor_256x7_books,
  122213. _floor_128x11_books,
  122214. _floor_128x17_books,
  122215. _floor_256x4low_books,
  122216. _floor_1024x27_books,
  122217. _floor_2048x27_books,
  122218. _floor_512x17_books,
  122219. };
  122220. static vorbis_info_floor1 _floor[10]={
  122221. /* 128 x 4 */
  122222. {
  122223. 1,{0},{4},{2},{0},
  122224. {{1,2,3,4}},
  122225. 4,{0,128, 33,8,16,70},
  122226. 60,30,500, 1.,18., -1
  122227. },
  122228. /* 256 x 4 */
  122229. {
  122230. 1,{0},{4},{2},{0},
  122231. {{1,2,3,4}},
  122232. 4,{0,256, 66,16,32,140},
  122233. 60,30,500, 1.,18., -1
  122234. },
  122235. /* 128 x 7 */
  122236. {
  122237. 2,{0,1},{3,4},{2,2},{0,1},
  122238. {{-1,2,3,4},{-1,5,6,7}},
  122239. 4,{0,128, 14,4,58, 2,8,28,90},
  122240. 60,30,500, 1.,18., -1
  122241. },
  122242. /* 256 x 7 */
  122243. {
  122244. 2,{0,1},{3,4},{2,2},{0,1},
  122245. {{-1,2,3,4},{-1,5,6,7}},
  122246. 4,{0,256, 28,8,116, 4,16,56,180},
  122247. 60,30,500, 1.,18., -1
  122248. },
  122249. /* 128 x 11 */
  122250. {
  122251. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122252. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122253. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122254. 60,30,500, 1,18., -1
  122255. },
  122256. /* 128 x 17 */
  122257. {
  122258. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122259. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122260. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122261. 60,30,500, 1,18., -1
  122262. },
  122263. /* 256 x 4 (low bitrate version) */
  122264. {
  122265. 1,{0},{4},{2},{0},
  122266. {{1,2,3,4}},
  122267. 4,{0,256, 66,16,32,140},
  122268. 60,30,500, 1.,18., -1
  122269. },
  122270. /* 1024 x 27 */
  122271. {
  122272. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122273. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122274. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122275. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122276. 60,30,500, 3,18., -1 /* lowpass */
  122277. },
  122278. /* 2048 x 27 */
  122279. {
  122280. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122281. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122282. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122283. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122284. 60,30,500, 3,18., -1 /* lowpass */
  122285. },
  122286. /* 512 x 17 */
  122287. {
  122288. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122289. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122290. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122291. 7,23,39, 55,79,110, 156,232,360},
  122292. 60,30,500, 1,18., -1 /* lowpass! */
  122293. },
  122294. };
  122295. /*** End of inlined file: floor_all.h ***/
  122296. /*** Start of inlined file: residue_44.h ***/
  122297. /*** Start of inlined file: res_books_stereo.h ***/
  122298. static long _vq_quantlist__16c0_s_p1_0[] = {
  122299. 1,
  122300. 0,
  122301. 2,
  122302. };
  122303. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122304. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122305. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122310. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122315. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122350. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122355. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122360. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122396. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122401. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122406. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122715. };
  122716. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122717. -0.5, 0.5,
  122718. };
  122719. static long _vq_quantmap__16c0_s_p1_0[] = {
  122720. 1, 0, 2,
  122721. };
  122722. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122723. _vq_quantthresh__16c0_s_p1_0,
  122724. _vq_quantmap__16c0_s_p1_0,
  122725. 3,
  122726. 3
  122727. };
  122728. static static_codebook _16c0_s_p1_0 = {
  122729. 8, 6561,
  122730. _vq_lengthlist__16c0_s_p1_0,
  122731. 1, -535822336, 1611661312, 2, 0,
  122732. _vq_quantlist__16c0_s_p1_0,
  122733. NULL,
  122734. &_vq_auxt__16c0_s_p1_0,
  122735. NULL,
  122736. 0
  122737. };
  122738. static long _vq_quantlist__16c0_s_p2_0[] = {
  122739. 2,
  122740. 1,
  122741. 3,
  122742. 0,
  122743. 4,
  122744. };
  122745. static long _vq_lengthlist__16c0_s_p2_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,
  122786. };
  122787. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122788. -1.5, -0.5, 0.5, 1.5,
  122789. };
  122790. static long _vq_quantmap__16c0_s_p2_0[] = {
  122791. 3, 1, 0, 2, 4,
  122792. };
  122793. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122794. _vq_quantthresh__16c0_s_p2_0,
  122795. _vq_quantmap__16c0_s_p2_0,
  122796. 5,
  122797. 5
  122798. };
  122799. static static_codebook _16c0_s_p2_0 = {
  122800. 4, 625,
  122801. _vq_lengthlist__16c0_s_p2_0,
  122802. 1, -533725184, 1611661312, 3, 0,
  122803. _vq_quantlist__16c0_s_p2_0,
  122804. NULL,
  122805. &_vq_auxt__16c0_s_p2_0,
  122806. NULL,
  122807. 0
  122808. };
  122809. static long _vq_quantlist__16c0_s_p3_0[] = {
  122810. 2,
  122811. 1,
  122812. 3,
  122813. 0,
  122814. 4,
  122815. };
  122816. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122817. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  122857. };
  122858. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122859. -1.5, -0.5, 0.5, 1.5,
  122860. };
  122861. static long _vq_quantmap__16c0_s_p3_0[] = {
  122862. 3, 1, 0, 2, 4,
  122863. };
  122864. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122865. _vq_quantthresh__16c0_s_p3_0,
  122866. _vq_quantmap__16c0_s_p3_0,
  122867. 5,
  122868. 5
  122869. };
  122870. static static_codebook _16c0_s_p3_0 = {
  122871. 4, 625,
  122872. _vq_lengthlist__16c0_s_p3_0,
  122873. 1, -533725184, 1611661312, 3, 0,
  122874. _vq_quantlist__16c0_s_p3_0,
  122875. NULL,
  122876. &_vq_auxt__16c0_s_p3_0,
  122877. NULL,
  122878. 0
  122879. };
  122880. static long _vq_quantlist__16c0_s_p4_0[] = {
  122881. 4,
  122882. 3,
  122883. 5,
  122884. 2,
  122885. 6,
  122886. 1,
  122887. 7,
  122888. 0,
  122889. 8,
  122890. };
  122891. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122892. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122893. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122894. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122895. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122896. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0,
  122898. };
  122899. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122900. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122901. };
  122902. static long _vq_quantmap__16c0_s_p4_0[] = {
  122903. 7, 5, 3, 1, 0, 2, 4, 6,
  122904. 8,
  122905. };
  122906. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122907. _vq_quantthresh__16c0_s_p4_0,
  122908. _vq_quantmap__16c0_s_p4_0,
  122909. 9,
  122910. 9
  122911. };
  122912. static static_codebook _16c0_s_p4_0 = {
  122913. 2, 81,
  122914. _vq_lengthlist__16c0_s_p4_0,
  122915. 1, -531628032, 1611661312, 4, 0,
  122916. _vq_quantlist__16c0_s_p4_0,
  122917. NULL,
  122918. &_vq_auxt__16c0_s_p4_0,
  122919. NULL,
  122920. 0
  122921. };
  122922. static long _vq_quantlist__16c0_s_p5_0[] = {
  122923. 4,
  122924. 3,
  122925. 5,
  122926. 2,
  122927. 6,
  122928. 1,
  122929. 7,
  122930. 0,
  122931. 8,
  122932. };
  122933. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122934. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122935. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122936. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122937. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122938. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122939. 10,
  122940. };
  122941. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122942. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122943. };
  122944. static long _vq_quantmap__16c0_s_p5_0[] = {
  122945. 7, 5, 3, 1, 0, 2, 4, 6,
  122946. 8,
  122947. };
  122948. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122949. _vq_quantthresh__16c0_s_p5_0,
  122950. _vq_quantmap__16c0_s_p5_0,
  122951. 9,
  122952. 9
  122953. };
  122954. static static_codebook _16c0_s_p5_0 = {
  122955. 2, 81,
  122956. _vq_lengthlist__16c0_s_p5_0,
  122957. 1, -531628032, 1611661312, 4, 0,
  122958. _vq_quantlist__16c0_s_p5_0,
  122959. NULL,
  122960. &_vq_auxt__16c0_s_p5_0,
  122961. NULL,
  122962. 0
  122963. };
  122964. static long _vq_quantlist__16c0_s_p6_0[] = {
  122965. 8,
  122966. 7,
  122967. 9,
  122968. 6,
  122969. 10,
  122970. 5,
  122971. 11,
  122972. 4,
  122973. 12,
  122974. 3,
  122975. 13,
  122976. 2,
  122977. 14,
  122978. 1,
  122979. 15,
  122980. 0,
  122981. 16,
  122982. };
  122983. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122984. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122985. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122986. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122987. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122988. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122989. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122990. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122991. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122992. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122993. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122994. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122995. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122996. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122997. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122998. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122999. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123000. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123002. 14,
  123003. };
  123004. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123005. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123006. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123007. };
  123008. static long _vq_quantmap__16c0_s_p6_0[] = {
  123009. 15, 13, 11, 9, 7, 5, 3, 1,
  123010. 0, 2, 4, 6, 8, 10, 12, 14,
  123011. 16,
  123012. };
  123013. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123014. _vq_quantthresh__16c0_s_p6_0,
  123015. _vq_quantmap__16c0_s_p6_0,
  123016. 17,
  123017. 17
  123018. };
  123019. static static_codebook _16c0_s_p6_0 = {
  123020. 2, 289,
  123021. _vq_lengthlist__16c0_s_p6_0,
  123022. 1, -529530880, 1611661312, 5, 0,
  123023. _vq_quantlist__16c0_s_p6_0,
  123024. NULL,
  123025. &_vq_auxt__16c0_s_p6_0,
  123026. NULL,
  123027. 0
  123028. };
  123029. static long _vq_quantlist__16c0_s_p7_0[] = {
  123030. 1,
  123031. 0,
  123032. 2,
  123033. };
  123034. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123035. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123036. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123037. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123038. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123039. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123040. 13,
  123041. };
  123042. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123043. -5.5, 5.5,
  123044. };
  123045. static long _vq_quantmap__16c0_s_p7_0[] = {
  123046. 1, 0, 2,
  123047. };
  123048. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123049. _vq_quantthresh__16c0_s_p7_0,
  123050. _vq_quantmap__16c0_s_p7_0,
  123051. 3,
  123052. 3
  123053. };
  123054. static static_codebook _16c0_s_p7_0 = {
  123055. 4, 81,
  123056. _vq_lengthlist__16c0_s_p7_0,
  123057. 1, -529137664, 1618345984, 2, 0,
  123058. _vq_quantlist__16c0_s_p7_0,
  123059. NULL,
  123060. &_vq_auxt__16c0_s_p7_0,
  123061. NULL,
  123062. 0
  123063. };
  123064. static long _vq_quantlist__16c0_s_p7_1[] = {
  123065. 5,
  123066. 4,
  123067. 6,
  123068. 3,
  123069. 7,
  123070. 2,
  123071. 8,
  123072. 1,
  123073. 9,
  123074. 0,
  123075. 10,
  123076. };
  123077. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123078. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123079. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123080. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123081. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123082. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123083. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123084. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123085. 11,11,11, 9, 9, 9, 9,10,10,
  123086. };
  123087. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123088. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123089. 3.5, 4.5,
  123090. };
  123091. static long _vq_quantmap__16c0_s_p7_1[] = {
  123092. 9, 7, 5, 3, 1, 0, 2, 4,
  123093. 6, 8, 10,
  123094. };
  123095. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123096. _vq_quantthresh__16c0_s_p7_1,
  123097. _vq_quantmap__16c0_s_p7_1,
  123098. 11,
  123099. 11
  123100. };
  123101. static static_codebook _16c0_s_p7_1 = {
  123102. 2, 121,
  123103. _vq_lengthlist__16c0_s_p7_1,
  123104. 1, -531365888, 1611661312, 4, 0,
  123105. _vq_quantlist__16c0_s_p7_1,
  123106. NULL,
  123107. &_vq_auxt__16c0_s_p7_1,
  123108. NULL,
  123109. 0
  123110. };
  123111. static long _vq_quantlist__16c0_s_p8_0[] = {
  123112. 6,
  123113. 5,
  123114. 7,
  123115. 4,
  123116. 8,
  123117. 3,
  123118. 9,
  123119. 2,
  123120. 10,
  123121. 1,
  123122. 11,
  123123. 0,
  123124. 12,
  123125. };
  123126. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123127. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123128. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123129. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123130. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123131. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123132. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123133. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123134. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123135. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123136. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123137. 0,12,13,13,12,13,14,14,14,
  123138. };
  123139. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123140. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123141. 12.5, 17.5, 22.5, 27.5,
  123142. };
  123143. static long _vq_quantmap__16c0_s_p8_0[] = {
  123144. 11, 9, 7, 5, 3, 1, 0, 2,
  123145. 4, 6, 8, 10, 12,
  123146. };
  123147. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123148. _vq_quantthresh__16c0_s_p8_0,
  123149. _vq_quantmap__16c0_s_p8_0,
  123150. 13,
  123151. 13
  123152. };
  123153. static static_codebook _16c0_s_p8_0 = {
  123154. 2, 169,
  123155. _vq_lengthlist__16c0_s_p8_0,
  123156. 1, -526516224, 1616117760, 4, 0,
  123157. _vq_quantlist__16c0_s_p8_0,
  123158. NULL,
  123159. &_vq_auxt__16c0_s_p8_0,
  123160. NULL,
  123161. 0
  123162. };
  123163. static long _vq_quantlist__16c0_s_p8_1[] = {
  123164. 2,
  123165. 1,
  123166. 3,
  123167. 0,
  123168. 4,
  123169. };
  123170. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123171. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123172. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123173. };
  123174. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123175. -1.5, -0.5, 0.5, 1.5,
  123176. };
  123177. static long _vq_quantmap__16c0_s_p8_1[] = {
  123178. 3, 1, 0, 2, 4,
  123179. };
  123180. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123181. _vq_quantthresh__16c0_s_p8_1,
  123182. _vq_quantmap__16c0_s_p8_1,
  123183. 5,
  123184. 5
  123185. };
  123186. static static_codebook _16c0_s_p8_1 = {
  123187. 2, 25,
  123188. _vq_lengthlist__16c0_s_p8_1,
  123189. 1, -533725184, 1611661312, 3, 0,
  123190. _vq_quantlist__16c0_s_p8_1,
  123191. NULL,
  123192. &_vq_auxt__16c0_s_p8_1,
  123193. NULL,
  123194. 0
  123195. };
  123196. static long _vq_quantlist__16c0_s_p9_0[] = {
  123197. 1,
  123198. 0,
  123199. 2,
  123200. };
  123201. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123202. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123203. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123204. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123205. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123206. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123207. 7,
  123208. };
  123209. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123210. -157.5, 157.5,
  123211. };
  123212. static long _vq_quantmap__16c0_s_p9_0[] = {
  123213. 1, 0, 2,
  123214. };
  123215. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123216. _vq_quantthresh__16c0_s_p9_0,
  123217. _vq_quantmap__16c0_s_p9_0,
  123218. 3,
  123219. 3
  123220. };
  123221. static static_codebook _16c0_s_p9_0 = {
  123222. 4, 81,
  123223. _vq_lengthlist__16c0_s_p9_0,
  123224. 1, -518803456, 1628680192, 2, 0,
  123225. _vq_quantlist__16c0_s_p9_0,
  123226. NULL,
  123227. &_vq_auxt__16c0_s_p9_0,
  123228. NULL,
  123229. 0
  123230. };
  123231. static long _vq_quantlist__16c0_s_p9_1[] = {
  123232. 7,
  123233. 6,
  123234. 8,
  123235. 5,
  123236. 9,
  123237. 4,
  123238. 10,
  123239. 3,
  123240. 11,
  123241. 2,
  123242. 12,
  123243. 1,
  123244. 13,
  123245. 0,
  123246. 14,
  123247. };
  123248. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123249. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123250. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123251. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123252. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123253. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123254. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123255. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123256. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123257. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123258. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123259. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123260. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123261. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123262. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123263. 10,
  123264. };
  123265. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123266. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123267. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123268. };
  123269. static long _vq_quantmap__16c0_s_p9_1[] = {
  123270. 13, 11, 9, 7, 5, 3, 1, 0,
  123271. 2, 4, 6, 8, 10, 12, 14,
  123272. };
  123273. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123274. _vq_quantthresh__16c0_s_p9_1,
  123275. _vq_quantmap__16c0_s_p9_1,
  123276. 15,
  123277. 15
  123278. };
  123279. static static_codebook _16c0_s_p9_1 = {
  123280. 2, 225,
  123281. _vq_lengthlist__16c0_s_p9_1,
  123282. 1, -520986624, 1620377600, 4, 0,
  123283. _vq_quantlist__16c0_s_p9_1,
  123284. NULL,
  123285. &_vq_auxt__16c0_s_p9_1,
  123286. NULL,
  123287. 0
  123288. };
  123289. static long _vq_quantlist__16c0_s_p9_2[] = {
  123290. 10,
  123291. 9,
  123292. 11,
  123293. 8,
  123294. 12,
  123295. 7,
  123296. 13,
  123297. 6,
  123298. 14,
  123299. 5,
  123300. 15,
  123301. 4,
  123302. 16,
  123303. 3,
  123304. 17,
  123305. 2,
  123306. 18,
  123307. 1,
  123308. 19,
  123309. 0,
  123310. 20,
  123311. };
  123312. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123313. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123314. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123315. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123316. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123317. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123318. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123319. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123320. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123321. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123322. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123323. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123324. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123325. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123326. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123327. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123328. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123329. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123330. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123331. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123332. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123333. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123334. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123335. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123336. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123337. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123338. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123339. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123340. 10,11,10,10,11, 9,10,10,10,
  123341. };
  123342. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123343. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123344. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123345. 6.5, 7.5, 8.5, 9.5,
  123346. };
  123347. static long _vq_quantmap__16c0_s_p9_2[] = {
  123348. 19, 17, 15, 13, 11, 9, 7, 5,
  123349. 3, 1, 0, 2, 4, 6, 8, 10,
  123350. 12, 14, 16, 18, 20,
  123351. };
  123352. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123353. _vq_quantthresh__16c0_s_p9_2,
  123354. _vq_quantmap__16c0_s_p9_2,
  123355. 21,
  123356. 21
  123357. };
  123358. static static_codebook _16c0_s_p9_2 = {
  123359. 2, 441,
  123360. _vq_lengthlist__16c0_s_p9_2,
  123361. 1, -529268736, 1611661312, 5, 0,
  123362. _vq_quantlist__16c0_s_p9_2,
  123363. NULL,
  123364. &_vq_auxt__16c0_s_p9_2,
  123365. NULL,
  123366. 0
  123367. };
  123368. static long _huff_lengthlist__16c0_s_single[] = {
  123369. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123370. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123371. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123372. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123373. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123374. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123375. 16,16,18,18,
  123376. };
  123377. static static_codebook _huff_book__16c0_s_single = {
  123378. 2, 100,
  123379. _huff_lengthlist__16c0_s_single,
  123380. 0, 0, 0, 0, 0,
  123381. NULL,
  123382. NULL,
  123383. NULL,
  123384. NULL,
  123385. 0
  123386. };
  123387. static long _huff_lengthlist__16c1_s_long[] = {
  123388. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123389. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123390. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123391. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123392. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123393. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123394. 12,11,11,13,
  123395. };
  123396. static static_codebook _huff_book__16c1_s_long = {
  123397. 2, 100,
  123398. _huff_lengthlist__16c1_s_long,
  123399. 0, 0, 0, 0, 0,
  123400. NULL,
  123401. NULL,
  123402. NULL,
  123403. NULL,
  123404. 0
  123405. };
  123406. static long _vq_quantlist__16c1_s_p1_0[] = {
  123407. 1,
  123408. 0,
  123409. 2,
  123410. };
  123411. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123412. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123413. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123418. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123423. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123458. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123463. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123468. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123504. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123509. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123514. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  123823. };
  123824. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123825. -0.5, 0.5,
  123826. };
  123827. static long _vq_quantmap__16c1_s_p1_0[] = {
  123828. 1, 0, 2,
  123829. };
  123830. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123831. _vq_quantthresh__16c1_s_p1_0,
  123832. _vq_quantmap__16c1_s_p1_0,
  123833. 3,
  123834. 3
  123835. };
  123836. static static_codebook _16c1_s_p1_0 = {
  123837. 8, 6561,
  123838. _vq_lengthlist__16c1_s_p1_0,
  123839. 1, -535822336, 1611661312, 2, 0,
  123840. _vq_quantlist__16c1_s_p1_0,
  123841. NULL,
  123842. &_vq_auxt__16c1_s_p1_0,
  123843. NULL,
  123844. 0
  123845. };
  123846. static long _vq_quantlist__16c1_s_p2_0[] = {
  123847. 2,
  123848. 1,
  123849. 3,
  123850. 0,
  123851. 4,
  123852. };
  123853. static long _vq_lengthlist__16c1_s_p2_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,
  123894. };
  123895. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123896. -1.5, -0.5, 0.5, 1.5,
  123897. };
  123898. static long _vq_quantmap__16c1_s_p2_0[] = {
  123899. 3, 1, 0, 2, 4,
  123900. };
  123901. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123902. _vq_quantthresh__16c1_s_p2_0,
  123903. _vq_quantmap__16c1_s_p2_0,
  123904. 5,
  123905. 5
  123906. };
  123907. static static_codebook _16c1_s_p2_0 = {
  123908. 4, 625,
  123909. _vq_lengthlist__16c1_s_p2_0,
  123910. 1, -533725184, 1611661312, 3, 0,
  123911. _vq_quantlist__16c1_s_p2_0,
  123912. NULL,
  123913. &_vq_auxt__16c1_s_p2_0,
  123914. NULL,
  123915. 0
  123916. };
  123917. static long _vq_quantlist__16c1_s_p3_0[] = {
  123918. 2,
  123919. 1,
  123920. 3,
  123921. 0,
  123922. 4,
  123923. };
  123924. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123925. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  123965. };
  123966. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123967. -1.5, -0.5, 0.5, 1.5,
  123968. };
  123969. static long _vq_quantmap__16c1_s_p3_0[] = {
  123970. 3, 1, 0, 2, 4,
  123971. };
  123972. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123973. _vq_quantthresh__16c1_s_p3_0,
  123974. _vq_quantmap__16c1_s_p3_0,
  123975. 5,
  123976. 5
  123977. };
  123978. static static_codebook _16c1_s_p3_0 = {
  123979. 4, 625,
  123980. _vq_lengthlist__16c1_s_p3_0,
  123981. 1, -533725184, 1611661312, 3, 0,
  123982. _vq_quantlist__16c1_s_p3_0,
  123983. NULL,
  123984. &_vq_auxt__16c1_s_p3_0,
  123985. NULL,
  123986. 0
  123987. };
  123988. static long _vq_quantlist__16c1_s_p4_0[] = {
  123989. 4,
  123990. 3,
  123991. 5,
  123992. 2,
  123993. 6,
  123994. 1,
  123995. 7,
  123996. 0,
  123997. 8,
  123998. };
  123999. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124000. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124001. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124002. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124003. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124004. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0,
  124006. };
  124007. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124008. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124009. };
  124010. static long _vq_quantmap__16c1_s_p4_0[] = {
  124011. 7, 5, 3, 1, 0, 2, 4, 6,
  124012. 8,
  124013. };
  124014. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124015. _vq_quantthresh__16c1_s_p4_0,
  124016. _vq_quantmap__16c1_s_p4_0,
  124017. 9,
  124018. 9
  124019. };
  124020. static static_codebook _16c1_s_p4_0 = {
  124021. 2, 81,
  124022. _vq_lengthlist__16c1_s_p4_0,
  124023. 1, -531628032, 1611661312, 4, 0,
  124024. _vq_quantlist__16c1_s_p4_0,
  124025. NULL,
  124026. &_vq_auxt__16c1_s_p4_0,
  124027. NULL,
  124028. 0
  124029. };
  124030. static long _vq_quantlist__16c1_s_p5_0[] = {
  124031. 4,
  124032. 3,
  124033. 5,
  124034. 2,
  124035. 6,
  124036. 1,
  124037. 7,
  124038. 0,
  124039. 8,
  124040. };
  124041. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124042. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124043. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124044. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124045. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124046. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124047. 10,
  124048. };
  124049. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124050. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124051. };
  124052. static long _vq_quantmap__16c1_s_p5_0[] = {
  124053. 7, 5, 3, 1, 0, 2, 4, 6,
  124054. 8,
  124055. };
  124056. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124057. _vq_quantthresh__16c1_s_p5_0,
  124058. _vq_quantmap__16c1_s_p5_0,
  124059. 9,
  124060. 9
  124061. };
  124062. static static_codebook _16c1_s_p5_0 = {
  124063. 2, 81,
  124064. _vq_lengthlist__16c1_s_p5_0,
  124065. 1, -531628032, 1611661312, 4, 0,
  124066. _vq_quantlist__16c1_s_p5_0,
  124067. NULL,
  124068. &_vq_auxt__16c1_s_p5_0,
  124069. NULL,
  124070. 0
  124071. };
  124072. static long _vq_quantlist__16c1_s_p6_0[] = {
  124073. 8,
  124074. 7,
  124075. 9,
  124076. 6,
  124077. 10,
  124078. 5,
  124079. 11,
  124080. 4,
  124081. 12,
  124082. 3,
  124083. 13,
  124084. 2,
  124085. 14,
  124086. 1,
  124087. 15,
  124088. 0,
  124089. 16,
  124090. };
  124091. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124092. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124093. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124094. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124095. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124096. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124097. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124098. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124099. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124100. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124101. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124102. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124103. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124104. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124105. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124106. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124107. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124108. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124110. 14,
  124111. };
  124112. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124113. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124114. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124115. };
  124116. static long _vq_quantmap__16c1_s_p6_0[] = {
  124117. 15, 13, 11, 9, 7, 5, 3, 1,
  124118. 0, 2, 4, 6, 8, 10, 12, 14,
  124119. 16,
  124120. };
  124121. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124122. _vq_quantthresh__16c1_s_p6_0,
  124123. _vq_quantmap__16c1_s_p6_0,
  124124. 17,
  124125. 17
  124126. };
  124127. static static_codebook _16c1_s_p6_0 = {
  124128. 2, 289,
  124129. _vq_lengthlist__16c1_s_p6_0,
  124130. 1, -529530880, 1611661312, 5, 0,
  124131. _vq_quantlist__16c1_s_p6_0,
  124132. NULL,
  124133. &_vq_auxt__16c1_s_p6_0,
  124134. NULL,
  124135. 0
  124136. };
  124137. static long _vq_quantlist__16c1_s_p7_0[] = {
  124138. 1,
  124139. 0,
  124140. 2,
  124141. };
  124142. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124143. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124144. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124145. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124146. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124147. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124148. 11,
  124149. };
  124150. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124151. -5.5, 5.5,
  124152. };
  124153. static long _vq_quantmap__16c1_s_p7_0[] = {
  124154. 1, 0, 2,
  124155. };
  124156. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124157. _vq_quantthresh__16c1_s_p7_0,
  124158. _vq_quantmap__16c1_s_p7_0,
  124159. 3,
  124160. 3
  124161. };
  124162. static static_codebook _16c1_s_p7_0 = {
  124163. 4, 81,
  124164. _vq_lengthlist__16c1_s_p7_0,
  124165. 1, -529137664, 1618345984, 2, 0,
  124166. _vq_quantlist__16c1_s_p7_0,
  124167. NULL,
  124168. &_vq_auxt__16c1_s_p7_0,
  124169. NULL,
  124170. 0
  124171. };
  124172. static long _vq_quantlist__16c1_s_p7_1[] = {
  124173. 5,
  124174. 4,
  124175. 6,
  124176. 3,
  124177. 7,
  124178. 2,
  124179. 8,
  124180. 1,
  124181. 9,
  124182. 0,
  124183. 10,
  124184. };
  124185. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124186. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124187. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124188. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124189. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124190. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124191. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124192. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124193. 10,10,10, 8, 8, 8, 8, 9, 9,
  124194. };
  124195. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124196. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124197. 3.5, 4.5,
  124198. };
  124199. static long _vq_quantmap__16c1_s_p7_1[] = {
  124200. 9, 7, 5, 3, 1, 0, 2, 4,
  124201. 6, 8, 10,
  124202. };
  124203. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124204. _vq_quantthresh__16c1_s_p7_1,
  124205. _vq_quantmap__16c1_s_p7_1,
  124206. 11,
  124207. 11
  124208. };
  124209. static static_codebook _16c1_s_p7_1 = {
  124210. 2, 121,
  124211. _vq_lengthlist__16c1_s_p7_1,
  124212. 1, -531365888, 1611661312, 4, 0,
  124213. _vq_quantlist__16c1_s_p7_1,
  124214. NULL,
  124215. &_vq_auxt__16c1_s_p7_1,
  124216. NULL,
  124217. 0
  124218. };
  124219. static long _vq_quantlist__16c1_s_p8_0[] = {
  124220. 6,
  124221. 5,
  124222. 7,
  124223. 4,
  124224. 8,
  124225. 3,
  124226. 9,
  124227. 2,
  124228. 10,
  124229. 1,
  124230. 11,
  124231. 0,
  124232. 12,
  124233. };
  124234. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124235. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124236. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124237. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124238. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124239. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124240. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124241. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124242. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124243. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124244. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124245. 0,12,12,12,12,13,13,14,15,
  124246. };
  124247. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124248. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124249. 12.5, 17.5, 22.5, 27.5,
  124250. };
  124251. static long _vq_quantmap__16c1_s_p8_0[] = {
  124252. 11, 9, 7, 5, 3, 1, 0, 2,
  124253. 4, 6, 8, 10, 12,
  124254. };
  124255. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124256. _vq_quantthresh__16c1_s_p8_0,
  124257. _vq_quantmap__16c1_s_p8_0,
  124258. 13,
  124259. 13
  124260. };
  124261. static static_codebook _16c1_s_p8_0 = {
  124262. 2, 169,
  124263. _vq_lengthlist__16c1_s_p8_0,
  124264. 1, -526516224, 1616117760, 4, 0,
  124265. _vq_quantlist__16c1_s_p8_0,
  124266. NULL,
  124267. &_vq_auxt__16c1_s_p8_0,
  124268. NULL,
  124269. 0
  124270. };
  124271. static long _vq_quantlist__16c1_s_p8_1[] = {
  124272. 2,
  124273. 1,
  124274. 3,
  124275. 0,
  124276. 4,
  124277. };
  124278. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124279. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124280. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124281. };
  124282. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124283. -1.5, -0.5, 0.5, 1.5,
  124284. };
  124285. static long _vq_quantmap__16c1_s_p8_1[] = {
  124286. 3, 1, 0, 2, 4,
  124287. };
  124288. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124289. _vq_quantthresh__16c1_s_p8_1,
  124290. _vq_quantmap__16c1_s_p8_1,
  124291. 5,
  124292. 5
  124293. };
  124294. static static_codebook _16c1_s_p8_1 = {
  124295. 2, 25,
  124296. _vq_lengthlist__16c1_s_p8_1,
  124297. 1, -533725184, 1611661312, 3, 0,
  124298. _vq_quantlist__16c1_s_p8_1,
  124299. NULL,
  124300. &_vq_auxt__16c1_s_p8_1,
  124301. NULL,
  124302. 0
  124303. };
  124304. static long _vq_quantlist__16c1_s_p9_0[] = {
  124305. 6,
  124306. 5,
  124307. 7,
  124308. 4,
  124309. 8,
  124310. 3,
  124311. 9,
  124312. 2,
  124313. 10,
  124314. 1,
  124315. 11,
  124316. 0,
  124317. 12,
  124318. };
  124319. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124320. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124321. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124322. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124323. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124324. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124325. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124326. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124327. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124328. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124329. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124330. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124331. };
  124332. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124333. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124334. 787.5, 1102.5, 1417.5, 1732.5,
  124335. };
  124336. static long _vq_quantmap__16c1_s_p9_0[] = {
  124337. 11, 9, 7, 5, 3, 1, 0, 2,
  124338. 4, 6, 8, 10, 12,
  124339. };
  124340. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124341. _vq_quantthresh__16c1_s_p9_0,
  124342. _vq_quantmap__16c1_s_p9_0,
  124343. 13,
  124344. 13
  124345. };
  124346. static static_codebook _16c1_s_p9_0 = {
  124347. 2, 169,
  124348. _vq_lengthlist__16c1_s_p9_0,
  124349. 1, -513964032, 1628680192, 4, 0,
  124350. _vq_quantlist__16c1_s_p9_0,
  124351. NULL,
  124352. &_vq_auxt__16c1_s_p9_0,
  124353. NULL,
  124354. 0
  124355. };
  124356. static long _vq_quantlist__16c1_s_p9_1[] = {
  124357. 7,
  124358. 6,
  124359. 8,
  124360. 5,
  124361. 9,
  124362. 4,
  124363. 10,
  124364. 3,
  124365. 11,
  124366. 2,
  124367. 12,
  124368. 1,
  124369. 13,
  124370. 0,
  124371. 14,
  124372. };
  124373. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124374. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124375. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124376. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124377. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124378. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124379. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124380. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124381. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124382. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124383. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124384. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124385. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124386. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124387. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124388. 13,
  124389. };
  124390. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124391. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124392. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124393. };
  124394. static long _vq_quantmap__16c1_s_p9_1[] = {
  124395. 13, 11, 9, 7, 5, 3, 1, 0,
  124396. 2, 4, 6, 8, 10, 12, 14,
  124397. };
  124398. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124399. _vq_quantthresh__16c1_s_p9_1,
  124400. _vq_quantmap__16c1_s_p9_1,
  124401. 15,
  124402. 15
  124403. };
  124404. static static_codebook _16c1_s_p9_1 = {
  124405. 2, 225,
  124406. _vq_lengthlist__16c1_s_p9_1,
  124407. 1, -520986624, 1620377600, 4, 0,
  124408. _vq_quantlist__16c1_s_p9_1,
  124409. NULL,
  124410. &_vq_auxt__16c1_s_p9_1,
  124411. NULL,
  124412. 0
  124413. };
  124414. static long _vq_quantlist__16c1_s_p9_2[] = {
  124415. 10,
  124416. 9,
  124417. 11,
  124418. 8,
  124419. 12,
  124420. 7,
  124421. 13,
  124422. 6,
  124423. 14,
  124424. 5,
  124425. 15,
  124426. 4,
  124427. 16,
  124428. 3,
  124429. 17,
  124430. 2,
  124431. 18,
  124432. 1,
  124433. 19,
  124434. 0,
  124435. 20,
  124436. };
  124437. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124438. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124439. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124440. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124441. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124442. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124443. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124444. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124445. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124446. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124447. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124448. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124449. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124450. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124451. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124452. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124453. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124454. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124455. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124456. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124457. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124458. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124459. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124460. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124461. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124462. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124463. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124464. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124465. 11,11,11,11,12,11,11,12,11,
  124466. };
  124467. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124468. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124469. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124470. 6.5, 7.5, 8.5, 9.5,
  124471. };
  124472. static long _vq_quantmap__16c1_s_p9_2[] = {
  124473. 19, 17, 15, 13, 11, 9, 7, 5,
  124474. 3, 1, 0, 2, 4, 6, 8, 10,
  124475. 12, 14, 16, 18, 20,
  124476. };
  124477. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124478. _vq_quantthresh__16c1_s_p9_2,
  124479. _vq_quantmap__16c1_s_p9_2,
  124480. 21,
  124481. 21
  124482. };
  124483. static static_codebook _16c1_s_p9_2 = {
  124484. 2, 441,
  124485. _vq_lengthlist__16c1_s_p9_2,
  124486. 1, -529268736, 1611661312, 5, 0,
  124487. _vq_quantlist__16c1_s_p9_2,
  124488. NULL,
  124489. &_vq_auxt__16c1_s_p9_2,
  124490. NULL,
  124491. 0
  124492. };
  124493. static long _huff_lengthlist__16c1_s_short[] = {
  124494. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124495. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124496. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124497. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124498. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124499. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124500. 9, 9,10,13,
  124501. };
  124502. static static_codebook _huff_book__16c1_s_short = {
  124503. 2, 100,
  124504. _huff_lengthlist__16c1_s_short,
  124505. 0, 0, 0, 0, 0,
  124506. NULL,
  124507. NULL,
  124508. NULL,
  124509. NULL,
  124510. 0
  124511. };
  124512. static long _huff_lengthlist__16c2_s_long[] = {
  124513. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124514. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124515. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124516. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124517. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124518. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124519. 14,14,16,18,
  124520. };
  124521. static static_codebook _huff_book__16c2_s_long = {
  124522. 2, 100,
  124523. _huff_lengthlist__16c2_s_long,
  124524. 0, 0, 0, 0, 0,
  124525. NULL,
  124526. NULL,
  124527. NULL,
  124528. NULL,
  124529. 0
  124530. };
  124531. static long _vq_quantlist__16c2_s_p1_0[] = {
  124532. 1,
  124533. 0,
  124534. 2,
  124535. };
  124536. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124537. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124538. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124542. 0,
  124543. };
  124544. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124545. -0.5, 0.5,
  124546. };
  124547. static long _vq_quantmap__16c2_s_p1_0[] = {
  124548. 1, 0, 2,
  124549. };
  124550. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124551. _vq_quantthresh__16c2_s_p1_0,
  124552. _vq_quantmap__16c2_s_p1_0,
  124553. 3,
  124554. 3
  124555. };
  124556. static static_codebook _16c2_s_p1_0 = {
  124557. 4, 81,
  124558. _vq_lengthlist__16c2_s_p1_0,
  124559. 1, -535822336, 1611661312, 2, 0,
  124560. _vq_quantlist__16c2_s_p1_0,
  124561. NULL,
  124562. &_vq_auxt__16c2_s_p1_0,
  124563. NULL,
  124564. 0
  124565. };
  124566. static long _vq_quantlist__16c2_s_p2_0[] = {
  124567. 2,
  124568. 1,
  124569. 3,
  124570. 0,
  124571. 4,
  124572. };
  124573. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124574. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124575. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124576. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124577. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124578. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124579. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124580. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124581. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124587. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124588. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124589. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124595. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124596. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124597. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124602. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124603. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124604. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124605. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124610. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124611. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124612. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124613. 13,
  124614. };
  124615. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124616. -1.5, -0.5, 0.5, 1.5,
  124617. };
  124618. static long _vq_quantmap__16c2_s_p2_0[] = {
  124619. 3, 1, 0, 2, 4,
  124620. };
  124621. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124622. _vq_quantthresh__16c2_s_p2_0,
  124623. _vq_quantmap__16c2_s_p2_0,
  124624. 5,
  124625. 5
  124626. };
  124627. static static_codebook _16c2_s_p2_0 = {
  124628. 4, 625,
  124629. _vq_lengthlist__16c2_s_p2_0,
  124630. 1, -533725184, 1611661312, 3, 0,
  124631. _vq_quantlist__16c2_s_p2_0,
  124632. NULL,
  124633. &_vq_auxt__16c2_s_p2_0,
  124634. NULL,
  124635. 0
  124636. };
  124637. static long _vq_quantlist__16c2_s_p3_0[] = {
  124638. 4,
  124639. 3,
  124640. 5,
  124641. 2,
  124642. 6,
  124643. 1,
  124644. 7,
  124645. 0,
  124646. 8,
  124647. };
  124648. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124649. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124650. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124651. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124652. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0,
  124655. };
  124656. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124657. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124658. };
  124659. static long _vq_quantmap__16c2_s_p3_0[] = {
  124660. 7, 5, 3, 1, 0, 2, 4, 6,
  124661. 8,
  124662. };
  124663. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124664. _vq_quantthresh__16c2_s_p3_0,
  124665. _vq_quantmap__16c2_s_p3_0,
  124666. 9,
  124667. 9
  124668. };
  124669. static static_codebook _16c2_s_p3_0 = {
  124670. 2, 81,
  124671. _vq_lengthlist__16c2_s_p3_0,
  124672. 1, -531628032, 1611661312, 4, 0,
  124673. _vq_quantlist__16c2_s_p3_0,
  124674. NULL,
  124675. &_vq_auxt__16c2_s_p3_0,
  124676. NULL,
  124677. 0
  124678. };
  124679. static long _vq_quantlist__16c2_s_p4_0[] = {
  124680. 8,
  124681. 7,
  124682. 9,
  124683. 6,
  124684. 10,
  124685. 5,
  124686. 11,
  124687. 4,
  124688. 12,
  124689. 3,
  124690. 13,
  124691. 2,
  124692. 14,
  124693. 1,
  124694. 15,
  124695. 0,
  124696. 16,
  124697. };
  124698. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124699. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124700. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124701. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124702. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124703. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124704. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124705. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124706. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124707. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124708. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0,
  124718. };
  124719. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124722. };
  124723. static long _vq_quantmap__16c2_s_p4_0[] = {
  124724. 15, 13, 11, 9, 7, 5, 3, 1,
  124725. 0, 2, 4, 6, 8, 10, 12, 14,
  124726. 16,
  124727. };
  124728. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124729. _vq_quantthresh__16c2_s_p4_0,
  124730. _vq_quantmap__16c2_s_p4_0,
  124731. 17,
  124732. 17
  124733. };
  124734. static static_codebook _16c2_s_p4_0 = {
  124735. 2, 289,
  124736. _vq_lengthlist__16c2_s_p4_0,
  124737. 1, -529530880, 1611661312, 5, 0,
  124738. _vq_quantlist__16c2_s_p4_0,
  124739. NULL,
  124740. &_vq_auxt__16c2_s_p4_0,
  124741. NULL,
  124742. 0
  124743. };
  124744. static long _vq_quantlist__16c2_s_p5_0[] = {
  124745. 1,
  124746. 0,
  124747. 2,
  124748. };
  124749. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124750. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124751. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124752. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124753. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124754. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124755. 12,
  124756. };
  124757. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124758. -5.5, 5.5,
  124759. };
  124760. static long _vq_quantmap__16c2_s_p5_0[] = {
  124761. 1, 0, 2,
  124762. };
  124763. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124764. _vq_quantthresh__16c2_s_p5_0,
  124765. _vq_quantmap__16c2_s_p5_0,
  124766. 3,
  124767. 3
  124768. };
  124769. static static_codebook _16c2_s_p5_0 = {
  124770. 4, 81,
  124771. _vq_lengthlist__16c2_s_p5_0,
  124772. 1, -529137664, 1618345984, 2, 0,
  124773. _vq_quantlist__16c2_s_p5_0,
  124774. NULL,
  124775. &_vq_auxt__16c2_s_p5_0,
  124776. NULL,
  124777. 0
  124778. };
  124779. static long _vq_quantlist__16c2_s_p5_1[] = {
  124780. 5,
  124781. 4,
  124782. 6,
  124783. 3,
  124784. 7,
  124785. 2,
  124786. 8,
  124787. 1,
  124788. 9,
  124789. 0,
  124790. 10,
  124791. };
  124792. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124793. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124794. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124795. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124796. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124797. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124798. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124799. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124800. 11,11,11, 7, 7, 8, 8, 8, 8,
  124801. };
  124802. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124803. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124804. 3.5, 4.5,
  124805. };
  124806. static long _vq_quantmap__16c2_s_p5_1[] = {
  124807. 9, 7, 5, 3, 1, 0, 2, 4,
  124808. 6, 8, 10,
  124809. };
  124810. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124811. _vq_quantthresh__16c2_s_p5_1,
  124812. _vq_quantmap__16c2_s_p5_1,
  124813. 11,
  124814. 11
  124815. };
  124816. static static_codebook _16c2_s_p5_1 = {
  124817. 2, 121,
  124818. _vq_lengthlist__16c2_s_p5_1,
  124819. 1, -531365888, 1611661312, 4, 0,
  124820. _vq_quantlist__16c2_s_p5_1,
  124821. NULL,
  124822. &_vq_auxt__16c2_s_p5_1,
  124823. NULL,
  124824. 0
  124825. };
  124826. static long _vq_quantlist__16c2_s_p6_0[] = {
  124827. 6,
  124828. 5,
  124829. 7,
  124830. 4,
  124831. 8,
  124832. 3,
  124833. 9,
  124834. 2,
  124835. 10,
  124836. 1,
  124837. 11,
  124838. 0,
  124839. 12,
  124840. };
  124841. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124842. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124843. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124844. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124845. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124846. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124847. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. };
  124854. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124856. 12.5, 17.5, 22.5, 27.5,
  124857. };
  124858. static long _vq_quantmap__16c2_s_p6_0[] = {
  124859. 11, 9, 7, 5, 3, 1, 0, 2,
  124860. 4, 6, 8, 10, 12,
  124861. };
  124862. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124863. _vq_quantthresh__16c2_s_p6_0,
  124864. _vq_quantmap__16c2_s_p6_0,
  124865. 13,
  124866. 13
  124867. };
  124868. static static_codebook _16c2_s_p6_0 = {
  124869. 2, 169,
  124870. _vq_lengthlist__16c2_s_p6_0,
  124871. 1, -526516224, 1616117760, 4, 0,
  124872. _vq_quantlist__16c2_s_p6_0,
  124873. NULL,
  124874. &_vq_auxt__16c2_s_p6_0,
  124875. NULL,
  124876. 0
  124877. };
  124878. static long _vq_quantlist__16c2_s_p6_1[] = {
  124879. 2,
  124880. 1,
  124881. 3,
  124882. 0,
  124883. 4,
  124884. };
  124885. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124886. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124887. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124888. };
  124889. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124890. -1.5, -0.5, 0.5, 1.5,
  124891. };
  124892. static long _vq_quantmap__16c2_s_p6_1[] = {
  124893. 3, 1, 0, 2, 4,
  124894. };
  124895. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124896. _vq_quantthresh__16c2_s_p6_1,
  124897. _vq_quantmap__16c2_s_p6_1,
  124898. 5,
  124899. 5
  124900. };
  124901. static static_codebook _16c2_s_p6_1 = {
  124902. 2, 25,
  124903. _vq_lengthlist__16c2_s_p6_1,
  124904. 1, -533725184, 1611661312, 3, 0,
  124905. _vq_quantlist__16c2_s_p6_1,
  124906. NULL,
  124907. &_vq_auxt__16c2_s_p6_1,
  124908. NULL,
  124909. 0
  124910. };
  124911. static long _vq_quantlist__16c2_s_p7_0[] = {
  124912. 6,
  124913. 5,
  124914. 7,
  124915. 4,
  124916. 8,
  124917. 3,
  124918. 9,
  124919. 2,
  124920. 10,
  124921. 1,
  124922. 11,
  124923. 0,
  124924. 12,
  124925. };
  124926. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124927. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124928. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124929. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124930. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124931. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124932. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124933. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124934. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124935. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124936. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124937. 18,13,14,13,13,14,13,15,14,
  124938. };
  124939. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124940. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124941. 27.5, 38.5, 49.5, 60.5,
  124942. };
  124943. static long _vq_quantmap__16c2_s_p7_0[] = {
  124944. 11, 9, 7, 5, 3, 1, 0, 2,
  124945. 4, 6, 8, 10, 12,
  124946. };
  124947. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124948. _vq_quantthresh__16c2_s_p7_0,
  124949. _vq_quantmap__16c2_s_p7_0,
  124950. 13,
  124951. 13
  124952. };
  124953. static static_codebook _16c2_s_p7_0 = {
  124954. 2, 169,
  124955. _vq_lengthlist__16c2_s_p7_0,
  124956. 1, -523206656, 1618345984, 4, 0,
  124957. _vq_quantlist__16c2_s_p7_0,
  124958. NULL,
  124959. &_vq_auxt__16c2_s_p7_0,
  124960. NULL,
  124961. 0
  124962. };
  124963. static long _vq_quantlist__16c2_s_p7_1[] = {
  124964. 5,
  124965. 4,
  124966. 6,
  124967. 3,
  124968. 7,
  124969. 2,
  124970. 8,
  124971. 1,
  124972. 9,
  124973. 0,
  124974. 10,
  124975. };
  124976. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124977. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124978. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124979. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124980. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124981. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124982. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124983. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124984. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124985. };
  124986. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124987. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124988. 3.5, 4.5,
  124989. };
  124990. static long _vq_quantmap__16c2_s_p7_1[] = {
  124991. 9, 7, 5, 3, 1, 0, 2, 4,
  124992. 6, 8, 10,
  124993. };
  124994. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124995. _vq_quantthresh__16c2_s_p7_1,
  124996. _vq_quantmap__16c2_s_p7_1,
  124997. 11,
  124998. 11
  124999. };
  125000. static static_codebook _16c2_s_p7_1 = {
  125001. 2, 121,
  125002. _vq_lengthlist__16c2_s_p7_1,
  125003. 1, -531365888, 1611661312, 4, 0,
  125004. _vq_quantlist__16c2_s_p7_1,
  125005. NULL,
  125006. &_vq_auxt__16c2_s_p7_1,
  125007. NULL,
  125008. 0
  125009. };
  125010. static long _vq_quantlist__16c2_s_p8_0[] = {
  125011. 7,
  125012. 6,
  125013. 8,
  125014. 5,
  125015. 9,
  125016. 4,
  125017. 10,
  125018. 3,
  125019. 11,
  125020. 2,
  125021. 12,
  125022. 1,
  125023. 13,
  125024. 0,
  125025. 14,
  125026. };
  125027. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125028. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125029. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125030. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125031. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125032. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125033. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125034. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125035. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125036. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125037. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125038. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125039. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125040. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125041. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125042. 13,
  125043. };
  125044. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125045. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125046. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125047. };
  125048. static long _vq_quantmap__16c2_s_p8_0[] = {
  125049. 13, 11, 9, 7, 5, 3, 1, 0,
  125050. 2, 4, 6, 8, 10, 12, 14,
  125051. };
  125052. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125053. _vq_quantthresh__16c2_s_p8_0,
  125054. _vq_quantmap__16c2_s_p8_0,
  125055. 15,
  125056. 15
  125057. };
  125058. static static_codebook _16c2_s_p8_0 = {
  125059. 2, 225,
  125060. _vq_lengthlist__16c2_s_p8_0,
  125061. 1, -520986624, 1620377600, 4, 0,
  125062. _vq_quantlist__16c2_s_p8_0,
  125063. NULL,
  125064. &_vq_auxt__16c2_s_p8_0,
  125065. NULL,
  125066. 0
  125067. };
  125068. static long _vq_quantlist__16c2_s_p8_1[] = {
  125069. 10,
  125070. 9,
  125071. 11,
  125072. 8,
  125073. 12,
  125074. 7,
  125075. 13,
  125076. 6,
  125077. 14,
  125078. 5,
  125079. 15,
  125080. 4,
  125081. 16,
  125082. 3,
  125083. 17,
  125084. 2,
  125085. 18,
  125086. 1,
  125087. 19,
  125088. 0,
  125089. 20,
  125090. };
  125091. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125092. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125093. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125094. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125095. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125096. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125097. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125098. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125099. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125100. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125101. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125102. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125103. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125104. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125105. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125106. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125107. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125108. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125109. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125110. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125111. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125112. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125113. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125114. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125115. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125116. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125117. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125118. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125119. 10,11,10,10,10,10,10,10,10,
  125120. };
  125121. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125122. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125123. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125124. 6.5, 7.5, 8.5, 9.5,
  125125. };
  125126. static long _vq_quantmap__16c2_s_p8_1[] = {
  125127. 19, 17, 15, 13, 11, 9, 7, 5,
  125128. 3, 1, 0, 2, 4, 6, 8, 10,
  125129. 12, 14, 16, 18, 20,
  125130. };
  125131. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125132. _vq_quantthresh__16c2_s_p8_1,
  125133. _vq_quantmap__16c2_s_p8_1,
  125134. 21,
  125135. 21
  125136. };
  125137. static static_codebook _16c2_s_p8_1 = {
  125138. 2, 441,
  125139. _vq_lengthlist__16c2_s_p8_1,
  125140. 1, -529268736, 1611661312, 5, 0,
  125141. _vq_quantlist__16c2_s_p8_1,
  125142. NULL,
  125143. &_vq_auxt__16c2_s_p8_1,
  125144. NULL,
  125145. 0
  125146. };
  125147. static long _vq_quantlist__16c2_s_p9_0[] = {
  125148. 6,
  125149. 5,
  125150. 7,
  125151. 4,
  125152. 8,
  125153. 3,
  125154. 9,
  125155. 2,
  125156. 10,
  125157. 1,
  125158. 11,
  125159. 0,
  125160. 12,
  125161. };
  125162. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125163. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125164. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125165. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125166. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125167. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125168. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125169. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125170. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125171. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125172. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125173. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125174. };
  125175. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125176. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125177. 2327.5, 3258.5, 4189.5, 5120.5,
  125178. };
  125179. static long _vq_quantmap__16c2_s_p9_0[] = {
  125180. 11, 9, 7, 5, 3, 1, 0, 2,
  125181. 4, 6, 8, 10, 12,
  125182. };
  125183. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125184. _vq_quantthresh__16c2_s_p9_0,
  125185. _vq_quantmap__16c2_s_p9_0,
  125186. 13,
  125187. 13
  125188. };
  125189. static static_codebook _16c2_s_p9_0 = {
  125190. 2, 169,
  125191. _vq_lengthlist__16c2_s_p9_0,
  125192. 1, -510275072, 1631393792, 4, 0,
  125193. _vq_quantlist__16c2_s_p9_0,
  125194. NULL,
  125195. &_vq_auxt__16c2_s_p9_0,
  125196. NULL,
  125197. 0
  125198. };
  125199. static long _vq_quantlist__16c2_s_p9_1[] = {
  125200. 8,
  125201. 7,
  125202. 9,
  125203. 6,
  125204. 10,
  125205. 5,
  125206. 11,
  125207. 4,
  125208. 12,
  125209. 3,
  125210. 13,
  125211. 2,
  125212. 14,
  125213. 1,
  125214. 15,
  125215. 0,
  125216. 16,
  125217. };
  125218. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125219. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125220. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125221. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125222. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125223. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125224. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125225. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125226. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125227. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125228. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125229. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125230. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125231. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125232. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125233. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125234. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125235. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125236. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125237. 10,
  125238. };
  125239. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125240. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125241. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125242. };
  125243. static long _vq_quantmap__16c2_s_p9_1[] = {
  125244. 15, 13, 11, 9, 7, 5, 3, 1,
  125245. 0, 2, 4, 6, 8, 10, 12, 14,
  125246. 16,
  125247. };
  125248. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125249. _vq_quantthresh__16c2_s_p9_1,
  125250. _vq_quantmap__16c2_s_p9_1,
  125251. 17,
  125252. 17
  125253. };
  125254. static static_codebook _16c2_s_p9_1 = {
  125255. 2, 289,
  125256. _vq_lengthlist__16c2_s_p9_1,
  125257. 1, -518488064, 1622704128, 5, 0,
  125258. _vq_quantlist__16c2_s_p9_1,
  125259. NULL,
  125260. &_vq_auxt__16c2_s_p9_1,
  125261. NULL,
  125262. 0
  125263. };
  125264. static long _vq_quantlist__16c2_s_p9_2[] = {
  125265. 13,
  125266. 12,
  125267. 14,
  125268. 11,
  125269. 15,
  125270. 10,
  125271. 16,
  125272. 9,
  125273. 17,
  125274. 8,
  125275. 18,
  125276. 7,
  125277. 19,
  125278. 6,
  125279. 20,
  125280. 5,
  125281. 21,
  125282. 4,
  125283. 22,
  125284. 3,
  125285. 23,
  125286. 2,
  125287. 24,
  125288. 1,
  125289. 25,
  125290. 0,
  125291. 26,
  125292. };
  125293. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125294. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125295. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125296. };
  125297. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125298. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125299. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125300. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125301. 11.5, 12.5,
  125302. };
  125303. static long _vq_quantmap__16c2_s_p9_2[] = {
  125304. 25, 23, 21, 19, 17, 15, 13, 11,
  125305. 9, 7, 5, 3, 1, 0, 2, 4,
  125306. 6, 8, 10, 12, 14, 16, 18, 20,
  125307. 22, 24, 26,
  125308. };
  125309. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125310. _vq_quantthresh__16c2_s_p9_2,
  125311. _vq_quantmap__16c2_s_p9_2,
  125312. 27,
  125313. 27
  125314. };
  125315. static static_codebook _16c2_s_p9_2 = {
  125316. 1, 27,
  125317. _vq_lengthlist__16c2_s_p9_2,
  125318. 1, -528875520, 1611661312, 5, 0,
  125319. _vq_quantlist__16c2_s_p9_2,
  125320. NULL,
  125321. &_vq_auxt__16c2_s_p9_2,
  125322. NULL,
  125323. 0
  125324. };
  125325. static long _huff_lengthlist__16c2_s_short[] = {
  125326. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125327. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125328. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125329. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125330. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125331. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125332. 15,12,14,14,
  125333. };
  125334. static static_codebook _huff_book__16c2_s_short = {
  125335. 2, 100,
  125336. _huff_lengthlist__16c2_s_short,
  125337. 0, 0, 0, 0, 0,
  125338. NULL,
  125339. NULL,
  125340. NULL,
  125341. NULL,
  125342. 0
  125343. };
  125344. static long _vq_quantlist__8c0_s_p1_0[] = {
  125345. 1,
  125346. 0,
  125347. 2,
  125348. };
  125349. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125350. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125351. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125356. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125361. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125396. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125401. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125406. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125442. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125447. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125452. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  125761. };
  125762. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125763. -0.5, 0.5,
  125764. };
  125765. static long _vq_quantmap__8c0_s_p1_0[] = {
  125766. 1, 0, 2,
  125767. };
  125768. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125769. _vq_quantthresh__8c0_s_p1_0,
  125770. _vq_quantmap__8c0_s_p1_0,
  125771. 3,
  125772. 3
  125773. };
  125774. static static_codebook _8c0_s_p1_0 = {
  125775. 8, 6561,
  125776. _vq_lengthlist__8c0_s_p1_0,
  125777. 1, -535822336, 1611661312, 2, 0,
  125778. _vq_quantlist__8c0_s_p1_0,
  125779. NULL,
  125780. &_vq_auxt__8c0_s_p1_0,
  125781. NULL,
  125782. 0
  125783. };
  125784. static long _vq_quantlist__8c0_s_p2_0[] = {
  125785. 2,
  125786. 1,
  125787. 3,
  125788. 0,
  125789. 4,
  125790. };
  125791. static long _vq_lengthlist__8c0_s_p2_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,
  125832. };
  125833. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125834. -1.5, -0.5, 0.5, 1.5,
  125835. };
  125836. static long _vq_quantmap__8c0_s_p2_0[] = {
  125837. 3, 1, 0, 2, 4,
  125838. };
  125839. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125840. _vq_quantthresh__8c0_s_p2_0,
  125841. _vq_quantmap__8c0_s_p2_0,
  125842. 5,
  125843. 5
  125844. };
  125845. static static_codebook _8c0_s_p2_0 = {
  125846. 4, 625,
  125847. _vq_lengthlist__8c0_s_p2_0,
  125848. 1, -533725184, 1611661312, 3, 0,
  125849. _vq_quantlist__8c0_s_p2_0,
  125850. NULL,
  125851. &_vq_auxt__8c0_s_p2_0,
  125852. NULL,
  125853. 0
  125854. };
  125855. static long _vq_quantlist__8c0_s_p3_0[] = {
  125856. 2,
  125857. 1,
  125858. 3,
  125859. 0,
  125860. 4,
  125861. };
  125862. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125863. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  125903. };
  125904. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125905. -1.5, -0.5, 0.5, 1.5,
  125906. };
  125907. static long _vq_quantmap__8c0_s_p3_0[] = {
  125908. 3, 1, 0, 2, 4,
  125909. };
  125910. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125911. _vq_quantthresh__8c0_s_p3_0,
  125912. _vq_quantmap__8c0_s_p3_0,
  125913. 5,
  125914. 5
  125915. };
  125916. static static_codebook _8c0_s_p3_0 = {
  125917. 4, 625,
  125918. _vq_lengthlist__8c0_s_p3_0,
  125919. 1, -533725184, 1611661312, 3, 0,
  125920. _vq_quantlist__8c0_s_p3_0,
  125921. NULL,
  125922. &_vq_auxt__8c0_s_p3_0,
  125923. NULL,
  125924. 0
  125925. };
  125926. static long _vq_quantlist__8c0_s_p4_0[] = {
  125927. 4,
  125928. 3,
  125929. 5,
  125930. 2,
  125931. 6,
  125932. 1,
  125933. 7,
  125934. 0,
  125935. 8,
  125936. };
  125937. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125938. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125939. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125940. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125941. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125942. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0,
  125944. };
  125945. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125946. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125947. };
  125948. static long _vq_quantmap__8c0_s_p4_0[] = {
  125949. 7, 5, 3, 1, 0, 2, 4, 6,
  125950. 8,
  125951. };
  125952. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125953. _vq_quantthresh__8c0_s_p4_0,
  125954. _vq_quantmap__8c0_s_p4_0,
  125955. 9,
  125956. 9
  125957. };
  125958. static static_codebook _8c0_s_p4_0 = {
  125959. 2, 81,
  125960. _vq_lengthlist__8c0_s_p4_0,
  125961. 1, -531628032, 1611661312, 4, 0,
  125962. _vq_quantlist__8c0_s_p4_0,
  125963. NULL,
  125964. &_vq_auxt__8c0_s_p4_0,
  125965. NULL,
  125966. 0
  125967. };
  125968. static long _vq_quantlist__8c0_s_p5_0[] = {
  125969. 4,
  125970. 3,
  125971. 5,
  125972. 2,
  125973. 6,
  125974. 1,
  125975. 7,
  125976. 0,
  125977. 8,
  125978. };
  125979. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125980. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125981. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125982. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125983. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125984. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125985. 10,
  125986. };
  125987. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125988. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125989. };
  125990. static long _vq_quantmap__8c0_s_p5_0[] = {
  125991. 7, 5, 3, 1, 0, 2, 4, 6,
  125992. 8,
  125993. };
  125994. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125995. _vq_quantthresh__8c0_s_p5_0,
  125996. _vq_quantmap__8c0_s_p5_0,
  125997. 9,
  125998. 9
  125999. };
  126000. static static_codebook _8c0_s_p5_0 = {
  126001. 2, 81,
  126002. _vq_lengthlist__8c0_s_p5_0,
  126003. 1, -531628032, 1611661312, 4, 0,
  126004. _vq_quantlist__8c0_s_p5_0,
  126005. NULL,
  126006. &_vq_auxt__8c0_s_p5_0,
  126007. NULL,
  126008. 0
  126009. };
  126010. static long _vq_quantlist__8c0_s_p6_0[] = {
  126011. 8,
  126012. 7,
  126013. 9,
  126014. 6,
  126015. 10,
  126016. 5,
  126017. 11,
  126018. 4,
  126019. 12,
  126020. 3,
  126021. 13,
  126022. 2,
  126023. 14,
  126024. 1,
  126025. 15,
  126026. 0,
  126027. 16,
  126028. };
  126029. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126030. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126031. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126032. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126033. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126034. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126035. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126036. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126037. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126038. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126039. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126040. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126041. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126042. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126043. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126044. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126045. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126046. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126048. 14,
  126049. };
  126050. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126051. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126052. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126053. };
  126054. static long _vq_quantmap__8c0_s_p6_0[] = {
  126055. 15, 13, 11, 9, 7, 5, 3, 1,
  126056. 0, 2, 4, 6, 8, 10, 12, 14,
  126057. 16,
  126058. };
  126059. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126060. _vq_quantthresh__8c0_s_p6_0,
  126061. _vq_quantmap__8c0_s_p6_0,
  126062. 17,
  126063. 17
  126064. };
  126065. static static_codebook _8c0_s_p6_0 = {
  126066. 2, 289,
  126067. _vq_lengthlist__8c0_s_p6_0,
  126068. 1, -529530880, 1611661312, 5, 0,
  126069. _vq_quantlist__8c0_s_p6_0,
  126070. NULL,
  126071. &_vq_auxt__8c0_s_p6_0,
  126072. NULL,
  126073. 0
  126074. };
  126075. static long _vq_quantlist__8c0_s_p7_0[] = {
  126076. 1,
  126077. 0,
  126078. 2,
  126079. };
  126080. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126081. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126082. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126083. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126084. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126085. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126086. 10,
  126087. };
  126088. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126089. -5.5, 5.5,
  126090. };
  126091. static long _vq_quantmap__8c0_s_p7_0[] = {
  126092. 1, 0, 2,
  126093. };
  126094. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126095. _vq_quantthresh__8c0_s_p7_0,
  126096. _vq_quantmap__8c0_s_p7_0,
  126097. 3,
  126098. 3
  126099. };
  126100. static static_codebook _8c0_s_p7_0 = {
  126101. 4, 81,
  126102. _vq_lengthlist__8c0_s_p7_0,
  126103. 1, -529137664, 1618345984, 2, 0,
  126104. _vq_quantlist__8c0_s_p7_0,
  126105. NULL,
  126106. &_vq_auxt__8c0_s_p7_0,
  126107. NULL,
  126108. 0
  126109. };
  126110. static long _vq_quantlist__8c0_s_p7_1[] = {
  126111. 5,
  126112. 4,
  126113. 6,
  126114. 3,
  126115. 7,
  126116. 2,
  126117. 8,
  126118. 1,
  126119. 9,
  126120. 0,
  126121. 10,
  126122. };
  126123. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126124. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126125. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126126. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126127. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126128. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126129. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126130. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126131. 10,10,10, 9, 9, 9,10,10,10,
  126132. };
  126133. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126134. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126135. 3.5, 4.5,
  126136. };
  126137. static long _vq_quantmap__8c0_s_p7_1[] = {
  126138. 9, 7, 5, 3, 1, 0, 2, 4,
  126139. 6, 8, 10,
  126140. };
  126141. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126142. _vq_quantthresh__8c0_s_p7_1,
  126143. _vq_quantmap__8c0_s_p7_1,
  126144. 11,
  126145. 11
  126146. };
  126147. static static_codebook _8c0_s_p7_1 = {
  126148. 2, 121,
  126149. _vq_lengthlist__8c0_s_p7_1,
  126150. 1, -531365888, 1611661312, 4, 0,
  126151. _vq_quantlist__8c0_s_p7_1,
  126152. NULL,
  126153. &_vq_auxt__8c0_s_p7_1,
  126154. NULL,
  126155. 0
  126156. };
  126157. static long _vq_quantlist__8c0_s_p8_0[] = {
  126158. 6,
  126159. 5,
  126160. 7,
  126161. 4,
  126162. 8,
  126163. 3,
  126164. 9,
  126165. 2,
  126166. 10,
  126167. 1,
  126168. 11,
  126169. 0,
  126170. 12,
  126171. };
  126172. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126173. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126174. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126175. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126176. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126177. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126178. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126179. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126180. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126181. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126182. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126183. 0, 0,13,13,11,13,13,11,12,
  126184. };
  126185. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126186. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126187. 12.5, 17.5, 22.5, 27.5,
  126188. };
  126189. static long _vq_quantmap__8c0_s_p8_0[] = {
  126190. 11, 9, 7, 5, 3, 1, 0, 2,
  126191. 4, 6, 8, 10, 12,
  126192. };
  126193. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126194. _vq_quantthresh__8c0_s_p8_0,
  126195. _vq_quantmap__8c0_s_p8_0,
  126196. 13,
  126197. 13
  126198. };
  126199. static static_codebook _8c0_s_p8_0 = {
  126200. 2, 169,
  126201. _vq_lengthlist__8c0_s_p8_0,
  126202. 1, -526516224, 1616117760, 4, 0,
  126203. _vq_quantlist__8c0_s_p8_0,
  126204. NULL,
  126205. &_vq_auxt__8c0_s_p8_0,
  126206. NULL,
  126207. 0
  126208. };
  126209. static long _vq_quantlist__8c0_s_p8_1[] = {
  126210. 2,
  126211. 1,
  126212. 3,
  126213. 0,
  126214. 4,
  126215. };
  126216. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126217. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126218. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126219. };
  126220. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126221. -1.5, -0.5, 0.5, 1.5,
  126222. };
  126223. static long _vq_quantmap__8c0_s_p8_1[] = {
  126224. 3, 1, 0, 2, 4,
  126225. };
  126226. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126227. _vq_quantthresh__8c0_s_p8_1,
  126228. _vq_quantmap__8c0_s_p8_1,
  126229. 5,
  126230. 5
  126231. };
  126232. static static_codebook _8c0_s_p8_1 = {
  126233. 2, 25,
  126234. _vq_lengthlist__8c0_s_p8_1,
  126235. 1, -533725184, 1611661312, 3, 0,
  126236. _vq_quantlist__8c0_s_p8_1,
  126237. NULL,
  126238. &_vq_auxt__8c0_s_p8_1,
  126239. NULL,
  126240. 0
  126241. };
  126242. static long _vq_quantlist__8c0_s_p9_0[] = {
  126243. 1,
  126244. 0,
  126245. 2,
  126246. };
  126247. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126248. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126249. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126250. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126251. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126252. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126253. 7,
  126254. };
  126255. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126256. -157.5, 157.5,
  126257. };
  126258. static long _vq_quantmap__8c0_s_p9_0[] = {
  126259. 1, 0, 2,
  126260. };
  126261. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126262. _vq_quantthresh__8c0_s_p9_0,
  126263. _vq_quantmap__8c0_s_p9_0,
  126264. 3,
  126265. 3
  126266. };
  126267. static static_codebook _8c0_s_p9_0 = {
  126268. 4, 81,
  126269. _vq_lengthlist__8c0_s_p9_0,
  126270. 1, -518803456, 1628680192, 2, 0,
  126271. _vq_quantlist__8c0_s_p9_0,
  126272. NULL,
  126273. &_vq_auxt__8c0_s_p9_0,
  126274. NULL,
  126275. 0
  126276. };
  126277. static long _vq_quantlist__8c0_s_p9_1[] = {
  126278. 7,
  126279. 6,
  126280. 8,
  126281. 5,
  126282. 9,
  126283. 4,
  126284. 10,
  126285. 3,
  126286. 11,
  126287. 2,
  126288. 12,
  126289. 1,
  126290. 13,
  126291. 0,
  126292. 14,
  126293. };
  126294. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126295. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126296. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126297. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126298. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126299. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126300. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126301. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126302. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126303. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126304. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126305. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126306. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126307. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126308. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126309. 11,
  126310. };
  126311. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126312. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126313. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126314. };
  126315. static long _vq_quantmap__8c0_s_p9_1[] = {
  126316. 13, 11, 9, 7, 5, 3, 1, 0,
  126317. 2, 4, 6, 8, 10, 12, 14,
  126318. };
  126319. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126320. _vq_quantthresh__8c0_s_p9_1,
  126321. _vq_quantmap__8c0_s_p9_1,
  126322. 15,
  126323. 15
  126324. };
  126325. static static_codebook _8c0_s_p9_1 = {
  126326. 2, 225,
  126327. _vq_lengthlist__8c0_s_p9_1,
  126328. 1, -520986624, 1620377600, 4, 0,
  126329. _vq_quantlist__8c0_s_p9_1,
  126330. NULL,
  126331. &_vq_auxt__8c0_s_p9_1,
  126332. NULL,
  126333. 0
  126334. };
  126335. static long _vq_quantlist__8c0_s_p9_2[] = {
  126336. 10,
  126337. 9,
  126338. 11,
  126339. 8,
  126340. 12,
  126341. 7,
  126342. 13,
  126343. 6,
  126344. 14,
  126345. 5,
  126346. 15,
  126347. 4,
  126348. 16,
  126349. 3,
  126350. 17,
  126351. 2,
  126352. 18,
  126353. 1,
  126354. 19,
  126355. 0,
  126356. 20,
  126357. };
  126358. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126359. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126360. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126361. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126362. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126363. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126364. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126365. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126366. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126367. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126368. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126369. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126370. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126371. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126372. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126373. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126374. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126375. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126376. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126377. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126378. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126379. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126380. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126381. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126382. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126383. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126384. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126385. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126386. 10,11, 9,11,10, 9,10, 9,10,
  126387. };
  126388. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126389. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126390. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126391. 6.5, 7.5, 8.5, 9.5,
  126392. };
  126393. static long _vq_quantmap__8c0_s_p9_2[] = {
  126394. 19, 17, 15, 13, 11, 9, 7, 5,
  126395. 3, 1, 0, 2, 4, 6, 8, 10,
  126396. 12, 14, 16, 18, 20,
  126397. };
  126398. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126399. _vq_quantthresh__8c0_s_p9_2,
  126400. _vq_quantmap__8c0_s_p9_2,
  126401. 21,
  126402. 21
  126403. };
  126404. static static_codebook _8c0_s_p9_2 = {
  126405. 2, 441,
  126406. _vq_lengthlist__8c0_s_p9_2,
  126407. 1, -529268736, 1611661312, 5, 0,
  126408. _vq_quantlist__8c0_s_p9_2,
  126409. NULL,
  126410. &_vq_auxt__8c0_s_p9_2,
  126411. NULL,
  126412. 0
  126413. };
  126414. static long _huff_lengthlist__8c0_s_single[] = {
  126415. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126416. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126417. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126418. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126419. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126420. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126421. 17,16,17,17,
  126422. };
  126423. static static_codebook _huff_book__8c0_s_single = {
  126424. 2, 100,
  126425. _huff_lengthlist__8c0_s_single,
  126426. 0, 0, 0, 0, 0,
  126427. NULL,
  126428. NULL,
  126429. NULL,
  126430. NULL,
  126431. 0
  126432. };
  126433. static long _vq_quantlist__8c1_s_p1_0[] = {
  126434. 1,
  126435. 0,
  126436. 2,
  126437. };
  126438. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126439. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126440. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126445. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126450. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126485. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126490. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126495. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126531. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126536. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126541. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  126850. };
  126851. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126852. -0.5, 0.5,
  126853. };
  126854. static long _vq_quantmap__8c1_s_p1_0[] = {
  126855. 1, 0, 2,
  126856. };
  126857. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126858. _vq_quantthresh__8c1_s_p1_0,
  126859. _vq_quantmap__8c1_s_p1_0,
  126860. 3,
  126861. 3
  126862. };
  126863. static static_codebook _8c1_s_p1_0 = {
  126864. 8, 6561,
  126865. _vq_lengthlist__8c1_s_p1_0,
  126866. 1, -535822336, 1611661312, 2, 0,
  126867. _vq_quantlist__8c1_s_p1_0,
  126868. NULL,
  126869. &_vq_auxt__8c1_s_p1_0,
  126870. NULL,
  126871. 0
  126872. };
  126873. static long _vq_quantlist__8c1_s_p2_0[] = {
  126874. 2,
  126875. 1,
  126876. 3,
  126877. 0,
  126878. 4,
  126879. };
  126880. static long _vq_lengthlist__8c1_s_p2_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,
  126921. };
  126922. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126923. -1.5, -0.5, 0.5, 1.5,
  126924. };
  126925. static long _vq_quantmap__8c1_s_p2_0[] = {
  126926. 3, 1, 0, 2, 4,
  126927. };
  126928. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126929. _vq_quantthresh__8c1_s_p2_0,
  126930. _vq_quantmap__8c1_s_p2_0,
  126931. 5,
  126932. 5
  126933. };
  126934. static static_codebook _8c1_s_p2_0 = {
  126935. 4, 625,
  126936. _vq_lengthlist__8c1_s_p2_0,
  126937. 1, -533725184, 1611661312, 3, 0,
  126938. _vq_quantlist__8c1_s_p2_0,
  126939. NULL,
  126940. &_vq_auxt__8c1_s_p2_0,
  126941. NULL,
  126942. 0
  126943. };
  126944. static long _vq_quantlist__8c1_s_p3_0[] = {
  126945. 2,
  126946. 1,
  126947. 3,
  126948. 0,
  126949. 4,
  126950. };
  126951. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126952. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  126992. };
  126993. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126994. -1.5, -0.5, 0.5, 1.5,
  126995. };
  126996. static long _vq_quantmap__8c1_s_p3_0[] = {
  126997. 3, 1, 0, 2, 4,
  126998. };
  126999. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127000. _vq_quantthresh__8c1_s_p3_0,
  127001. _vq_quantmap__8c1_s_p3_0,
  127002. 5,
  127003. 5
  127004. };
  127005. static static_codebook _8c1_s_p3_0 = {
  127006. 4, 625,
  127007. _vq_lengthlist__8c1_s_p3_0,
  127008. 1, -533725184, 1611661312, 3, 0,
  127009. _vq_quantlist__8c1_s_p3_0,
  127010. NULL,
  127011. &_vq_auxt__8c1_s_p3_0,
  127012. NULL,
  127013. 0
  127014. };
  127015. static long _vq_quantlist__8c1_s_p4_0[] = {
  127016. 4,
  127017. 3,
  127018. 5,
  127019. 2,
  127020. 6,
  127021. 1,
  127022. 7,
  127023. 0,
  127024. 8,
  127025. };
  127026. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127027. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127028. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127029. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127030. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127031. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0,
  127033. };
  127034. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127035. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127036. };
  127037. static long _vq_quantmap__8c1_s_p4_0[] = {
  127038. 7, 5, 3, 1, 0, 2, 4, 6,
  127039. 8,
  127040. };
  127041. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127042. _vq_quantthresh__8c1_s_p4_0,
  127043. _vq_quantmap__8c1_s_p4_0,
  127044. 9,
  127045. 9
  127046. };
  127047. static static_codebook _8c1_s_p4_0 = {
  127048. 2, 81,
  127049. _vq_lengthlist__8c1_s_p4_0,
  127050. 1, -531628032, 1611661312, 4, 0,
  127051. _vq_quantlist__8c1_s_p4_0,
  127052. NULL,
  127053. &_vq_auxt__8c1_s_p4_0,
  127054. NULL,
  127055. 0
  127056. };
  127057. static long _vq_quantlist__8c1_s_p5_0[] = {
  127058. 4,
  127059. 3,
  127060. 5,
  127061. 2,
  127062. 6,
  127063. 1,
  127064. 7,
  127065. 0,
  127066. 8,
  127067. };
  127068. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127069. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127070. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127071. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127072. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127073. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127074. 10,
  127075. };
  127076. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127077. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127078. };
  127079. static long _vq_quantmap__8c1_s_p5_0[] = {
  127080. 7, 5, 3, 1, 0, 2, 4, 6,
  127081. 8,
  127082. };
  127083. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127084. _vq_quantthresh__8c1_s_p5_0,
  127085. _vq_quantmap__8c1_s_p5_0,
  127086. 9,
  127087. 9
  127088. };
  127089. static static_codebook _8c1_s_p5_0 = {
  127090. 2, 81,
  127091. _vq_lengthlist__8c1_s_p5_0,
  127092. 1, -531628032, 1611661312, 4, 0,
  127093. _vq_quantlist__8c1_s_p5_0,
  127094. NULL,
  127095. &_vq_auxt__8c1_s_p5_0,
  127096. NULL,
  127097. 0
  127098. };
  127099. static long _vq_quantlist__8c1_s_p6_0[] = {
  127100. 8,
  127101. 7,
  127102. 9,
  127103. 6,
  127104. 10,
  127105. 5,
  127106. 11,
  127107. 4,
  127108. 12,
  127109. 3,
  127110. 13,
  127111. 2,
  127112. 14,
  127113. 1,
  127114. 15,
  127115. 0,
  127116. 16,
  127117. };
  127118. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127119. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127120. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127121. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127122. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127123. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127124. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127125. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127126. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127127. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127128. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127129. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127130. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127131. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127132. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127133. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127134. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127135. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127137. 14,
  127138. };
  127139. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127140. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127141. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127142. };
  127143. static long _vq_quantmap__8c1_s_p6_0[] = {
  127144. 15, 13, 11, 9, 7, 5, 3, 1,
  127145. 0, 2, 4, 6, 8, 10, 12, 14,
  127146. 16,
  127147. };
  127148. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127149. _vq_quantthresh__8c1_s_p6_0,
  127150. _vq_quantmap__8c1_s_p6_0,
  127151. 17,
  127152. 17
  127153. };
  127154. static static_codebook _8c1_s_p6_0 = {
  127155. 2, 289,
  127156. _vq_lengthlist__8c1_s_p6_0,
  127157. 1, -529530880, 1611661312, 5, 0,
  127158. _vq_quantlist__8c1_s_p6_0,
  127159. NULL,
  127160. &_vq_auxt__8c1_s_p6_0,
  127161. NULL,
  127162. 0
  127163. };
  127164. static long _vq_quantlist__8c1_s_p7_0[] = {
  127165. 1,
  127166. 0,
  127167. 2,
  127168. };
  127169. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127170. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127171. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127172. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127173. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127174. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127175. 9,
  127176. };
  127177. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127178. -5.5, 5.5,
  127179. };
  127180. static long _vq_quantmap__8c1_s_p7_0[] = {
  127181. 1, 0, 2,
  127182. };
  127183. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127184. _vq_quantthresh__8c1_s_p7_0,
  127185. _vq_quantmap__8c1_s_p7_0,
  127186. 3,
  127187. 3
  127188. };
  127189. static static_codebook _8c1_s_p7_0 = {
  127190. 4, 81,
  127191. _vq_lengthlist__8c1_s_p7_0,
  127192. 1, -529137664, 1618345984, 2, 0,
  127193. _vq_quantlist__8c1_s_p7_0,
  127194. NULL,
  127195. &_vq_auxt__8c1_s_p7_0,
  127196. NULL,
  127197. 0
  127198. };
  127199. static long _vq_quantlist__8c1_s_p7_1[] = {
  127200. 5,
  127201. 4,
  127202. 6,
  127203. 3,
  127204. 7,
  127205. 2,
  127206. 8,
  127207. 1,
  127208. 9,
  127209. 0,
  127210. 10,
  127211. };
  127212. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127213. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127214. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127215. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127216. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127217. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127218. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127219. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127220. 10,10,10, 8, 8, 8, 8, 8, 8,
  127221. };
  127222. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127223. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127224. 3.5, 4.5,
  127225. };
  127226. static long _vq_quantmap__8c1_s_p7_1[] = {
  127227. 9, 7, 5, 3, 1, 0, 2, 4,
  127228. 6, 8, 10,
  127229. };
  127230. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127231. _vq_quantthresh__8c1_s_p7_1,
  127232. _vq_quantmap__8c1_s_p7_1,
  127233. 11,
  127234. 11
  127235. };
  127236. static static_codebook _8c1_s_p7_1 = {
  127237. 2, 121,
  127238. _vq_lengthlist__8c1_s_p7_1,
  127239. 1, -531365888, 1611661312, 4, 0,
  127240. _vq_quantlist__8c1_s_p7_1,
  127241. NULL,
  127242. &_vq_auxt__8c1_s_p7_1,
  127243. NULL,
  127244. 0
  127245. };
  127246. static long _vq_quantlist__8c1_s_p8_0[] = {
  127247. 6,
  127248. 5,
  127249. 7,
  127250. 4,
  127251. 8,
  127252. 3,
  127253. 9,
  127254. 2,
  127255. 10,
  127256. 1,
  127257. 11,
  127258. 0,
  127259. 12,
  127260. };
  127261. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127262. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127263. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127264. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127265. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127266. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127267. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127268. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127269. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127270. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127271. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127272. 0,12,12,11,10,12,11,13,12,
  127273. };
  127274. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127275. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127276. 12.5, 17.5, 22.5, 27.5,
  127277. };
  127278. static long _vq_quantmap__8c1_s_p8_0[] = {
  127279. 11, 9, 7, 5, 3, 1, 0, 2,
  127280. 4, 6, 8, 10, 12,
  127281. };
  127282. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127283. _vq_quantthresh__8c1_s_p8_0,
  127284. _vq_quantmap__8c1_s_p8_0,
  127285. 13,
  127286. 13
  127287. };
  127288. static static_codebook _8c1_s_p8_0 = {
  127289. 2, 169,
  127290. _vq_lengthlist__8c1_s_p8_0,
  127291. 1, -526516224, 1616117760, 4, 0,
  127292. _vq_quantlist__8c1_s_p8_0,
  127293. NULL,
  127294. &_vq_auxt__8c1_s_p8_0,
  127295. NULL,
  127296. 0
  127297. };
  127298. static long _vq_quantlist__8c1_s_p8_1[] = {
  127299. 2,
  127300. 1,
  127301. 3,
  127302. 0,
  127303. 4,
  127304. };
  127305. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127306. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127307. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127308. };
  127309. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127310. -1.5, -0.5, 0.5, 1.5,
  127311. };
  127312. static long _vq_quantmap__8c1_s_p8_1[] = {
  127313. 3, 1, 0, 2, 4,
  127314. };
  127315. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127316. _vq_quantthresh__8c1_s_p8_1,
  127317. _vq_quantmap__8c1_s_p8_1,
  127318. 5,
  127319. 5
  127320. };
  127321. static static_codebook _8c1_s_p8_1 = {
  127322. 2, 25,
  127323. _vq_lengthlist__8c1_s_p8_1,
  127324. 1, -533725184, 1611661312, 3, 0,
  127325. _vq_quantlist__8c1_s_p8_1,
  127326. NULL,
  127327. &_vq_auxt__8c1_s_p8_1,
  127328. NULL,
  127329. 0
  127330. };
  127331. static long _vq_quantlist__8c1_s_p9_0[] = {
  127332. 6,
  127333. 5,
  127334. 7,
  127335. 4,
  127336. 8,
  127337. 3,
  127338. 9,
  127339. 2,
  127340. 10,
  127341. 1,
  127342. 11,
  127343. 0,
  127344. 12,
  127345. };
  127346. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127347. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127348. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127349. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127350. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127351. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127352. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127355. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127357. 10,10,10,10,10, 9, 9, 9, 9,
  127358. };
  127359. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127360. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127361. 787.5, 1102.5, 1417.5, 1732.5,
  127362. };
  127363. static long _vq_quantmap__8c1_s_p9_0[] = {
  127364. 11, 9, 7, 5, 3, 1, 0, 2,
  127365. 4, 6, 8, 10, 12,
  127366. };
  127367. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127368. _vq_quantthresh__8c1_s_p9_0,
  127369. _vq_quantmap__8c1_s_p9_0,
  127370. 13,
  127371. 13
  127372. };
  127373. static static_codebook _8c1_s_p9_0 = {
  127374. 2, 169,
  127375. _vq_lengthlist__8c1_s_p9_0,
  127376. 1, -513964032, 1628680192, 4, 0,
  127377. _vq_quantlist__8c1_s_p9_0,
  127378. NULL,
  127379. &_vq_auxt__8c1_s_p9_0,
  127380. NULL,
  127381. 0
  127382. };
  127383. static long _vq_quantlist__8c1_s_p9_1[] = {
  127384. 7,
  127385. 6,
  127386. 8,
  127387. 5,
  127388. 9,
  127389. 4,
  127390. 10,
  127391. 3,
  127392. 11,
  127393. 2,
  127394. 12,
  127395. 1,
  127396. 13,
  127397. 0,
  127398. 14,
  127399. };
  127400. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127401. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127402. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127403. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127404. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127405. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127406. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127407. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127408. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127409. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127410. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127411. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127412. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127413. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127414. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127415. 15,
  127416. };
  127417. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127418. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127419. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127420. };
  127421. static long _vq_quantmap__8c1_s_p9_1[] = {
  127422. 13, 11, 9, 7, 5, 3, 1, 0,
  127423. 2, 4, 6, 8, 10, 12, 14,
  127424. };
  127425. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127426. _vq_quantthresh__8c1_s_p9_1,
  127427. _vq_quantmap__8c1_s_p9_1,
  127428. 15,
  127429. 15
  127430. };
  127431. static static_codebook _8c1_s_p9_1 = {
  127432. 2, 225,
  127433. _vq_lengthlist__8c1_s_p9_1,
  127434. 1, -520986624, 1620377600, 4, 0,
  127435. _vq_quantlist__8c1_s_p9_1,
  127436. NULL,
  127437. &_vq_auxt__8c1_s_p9_1,
  127438. NULL,
  127439. 0
  127440. };
  127441. static long _vq_quantlist__8c1_s_p9_2[] = {
  127442. 10,
  127443. 9,
  127444. 11,
  127445. 8,
  127446. 12,
  127447. 7,
  127448. 13,
  127449. 6,
  127450. 14,
  127451. 5,
  127452. 15,
  127453. 4,
  127454. 16,
  127455. 3,
  127456. 17,
  127457. 2,
  127458. 18,
  127459. 1,
  127460. 19,
  127461. 0,
  127462. 20,
  127463. };
  127464. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127465. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127466. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127467. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127468. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127469. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127470. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127471. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127472. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127473. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127474. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127475. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127476. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127477. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127478. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127479. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127480. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127481. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127482. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127483. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127484. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127485. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127486. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127487. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127488. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127489. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127490. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127491. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127492. 10,10,10,10,10,10,10,10,10,
  127493. };
  127494. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127495. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127496. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127497. 6.5, 7.5, 8.5, 9.5,
  127498. };
  127499. static long _vq_quantmap__8c1_s_p9_2[] = {
  127500. 19, 17, 15, 13, 11, 9, 7, 5,
  127501. 3, 1, 0, 2, 4, 6, 8, 10,
  127502. 12, 14, 16, 18, 20,
  127503. };
  127504. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127505. _vq_quantthresh__8c1_s_p9_2,
  127506. _vq_quantmap__8c1_s_p9_2,
  127507. 21,
  127508. 21
  127509. };
  127510. static static_codebook _8c1_s_p9_2 = {
  127511. 2, 441,
  127512. _vq_lengthlist__8c1_s_p9_2,
  127513. 1, -529268736, 1611661312, 5, 0,
  127514. _vq_quantlist__8c1_s_p9_2,
  127515. NULL,
  127516. &_vq_auxt__8c1_s_p9_2,
  127517. NULL,
  127518. 0
  127519. };
  127520. static long _huff_lengthlist__8c1_s_single[] = {
  127521. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127522. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127523. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127524. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127525. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127526. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127527. 9, 7, 7, 8,
  127528. };
  127529. static static_codebook _huff_book__8c1_s_single = {
  127530. 2, 100,
  127531. _huff_lengthlist__8c1_s_single,
  127532. 0, 0, 0, 0, 0,
  127533. NULL,
  127534. NULL,
  127535. NULL,
  127536. NULL,
  127537. 0
  127538. };
  127539. static long _huff_lengthlist__44c2_s_long[] = {
  127540. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127541. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127542. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127543. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127544. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127545. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127546. 10, 8, 8, 9,
  127547. };
  127548. static static_codebook _huff_book__44c2_s_long = {
  127549. 2, 100,
  127550. _huff_lengthlist__44c2_s_long,
  127551. 0, 0, 0, 0, 0,
  127552. NULL,
  127553. NULL,
  127554. NULL,
  127555. NULL,
  127556. 0
  127557. };
  127558. static long _vq_quantlist__44c2_s_p1_0[] = {
  127559. 1,
  127560. 0,
  127561. 2,
  127562. };
  127563. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127564. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127565. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127570. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127575. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127610. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127615. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127620. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127656. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127661. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127666. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127793. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127798. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127803. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127975. };
  127976. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127977. -0.5, 0.5,
  127978. };
  127979. static long _vq_quantmap__44c2_s_p1_0[] = {
  127980. 1, 0, 2,
  127981. };
  127982. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127983. _vq_quantthresh__44c2_s_p1_0,
  127984. _vq_quantmap__44c2_s_p1_0,
  127985. 3,
  127986. 3
  127987. };
  127988. static static_codebook _44c2_s_p1_0 = {
  127989. 8, 6561,
  127990. _vq_lengthlist__44c2_s_p1_0,
  127991. 1, -535822336, 1611661312, 2, 0,
  127992. _vq_quantlist__44c2_s_p1_0,
  127993. NULL,
  127994. &_vq_auxt__44c2_s_p1_0,
  127995. NULL,
  127996. 0
  127997. };
  127998. static long _vq_quantlist__44c2_s_p2_0[] = {
  127999. 2,
  128000. 1,
  128001. 3,
  128002. 0,
  128003. 4,
  128004. };
  128005. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128006. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128007. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128008. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128009. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128010. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128016. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128017. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128018. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128024. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128025. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128032. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128033. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  128046. };
  128047. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128048. -1.5, -0.5, 0.5, 1.5,
  128049. };
  128050. static long _vq_quantmap__44c2_s_p2_0[] = {
  128051. 3, 1, 0, 2, 4,
  128052. };
  128053. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128054. _vq_quantthresh__44c2_s_p2_0,
  128055. _vq_quantmap__44c2_s_p2_0,
  128056. 5,
  128057. 5
  128058. };
  128059. static static_codebook _44c2_s_p2_0 = {
  128060. 4, 625,
  128061. _vq_lengthlist__44c2_s_p2_0,
  128062. 1, -533725184, 1611661312, 3, 0,
  128063. _vq_quantlist__44c2_s_p2_0,
  128064. NULL,
  128065. &_vq_auxt__44c2_s_p2_0,
  128066. NULL,
  128067. 0
  128068. };
  128069. static long _vq_quantlist__44c2_s_p3_0[] = {
  128070. 2,
  128071. 1,
  128072. 3,
  128073. 0,
  128074. 4,
  128075. };
  128076. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128077. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128117. };
  128118. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128119. -1.5, -0.5, 0.5, 1.5,
  128120. };
  128121. static long _vq_quantmap__44c2_s_p3_0[] = {
  128122. 3, 1, 0, 2, 4,
  128123. };
  128124. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128125. _vq_quantthresh__44c2_s_p3_0,
  128126. _vq_quantmap__44c2_s_p3_0,
  128127. 5,
  128128. 5
  128129. };
  128130. static static_codebook _44c2_s_p3_0 = {
  128131. 4, 625,
  128132. _vq_lengthlist__44c2_s_p3_0,
  128133. 1, -533725184, 1611661312, 3, 0,
  128134. _vq_quantlist__44c2_s_p3_0,
  128135. NULL,
  128136. &_vq_auxt__44c2_s_p3_0,
  128137. NULL,
  128138. 0
  128139. };
  128140. static long _vq_quantlist__44c2_s_p4_0[] = {
  128141. 4,
  128142. 3,
  128143. 5,
  128144. 2,
  128145. 6,
  128146. 1,
  128147. 7,
  128148. 0,
  128149. 8,
  128150. };
  128151. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128152. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128153. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128154. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128155. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128156. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0,
  128158. };
  128159. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128160. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128161. };
  128162. static long _vq_quantmap__44c2_s_p4_0[] = {
  128163. 7, 5, 3, 1, 0, 2, 4, 6,
  128164. 8,
  128165. };
  128166. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128167. _vq_quantthresh__44c2_s_p4_0,
  128168. _vq_quantmap__44c2_s_p4_0,
  128169. 9,
  128170. 9
  128171. };
  128172. static static_codebook _44c2_s_p4_0 = {
  128173. 2, 81,
  128174. _vq_lengthlist__44c2_s_p4_0,
  128175. 1, -531628032, 1611661312, 4, 0,
  128176. _vq_quantlist__44c2_s_p4_0,
  128177. NULL,
  128178. &_vq_auxt__44c2_s_p4_0,
  128179. NULL,
  128180. 0
  128181. };
  128182. static long _vq_quantlist__44c2_s_p5_0[] = {
  128183. 4,
  128184. 3,
  128185. 5,
  128186. 2,
  128187. 6,
  128188. 1,
  128189. 7,
  128190. 0,
  128191. 8,
  128192. };
  128193. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128194. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128195. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128196. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128197. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128198. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128199. 11,
  128200. };
  128201. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128202. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128203. };
  128204. static long _vq_quantmap__44c2_s_p5_0[] = {
  128205. 7, 5, 3, 1, 0, 2, 4, 6,
  128206. 8,
  128207. };
  128208. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128209. _vq_quantthresh__44c2_s_p5_0,
  128210. _vq_quantmap__44c2_s_p5_0,
  128211. 9,
  128212. 9
  128213. };
  128214. static static_codebook _44c2_s_p5_0 = {
  128215. 2, 81,
  128216. _vq_lengthlist__44c2_s_p5_0,
  128217. 1, -531628032, 1611661312, 4, 0,
  128218. _vq_quantlist__44c2_s_p5_0,
  128219. NULL,
  128220. &_vq_auxt__44c2_s_p5_0,
  128221. NULL,
  128222. 0
  128223. };
  128224. static long _vq_quantlist__44c2_s_p6_0[] = {
  128225. 8,
  128226. 7,
  128227. 9,
  128228. 6,
  128229. 10,
  128230. 5,
  128231. 11,
  128232. 4,
  128233. 12,
  128234. 3,
  128235. 13,
  128236. 2,
  128237. 14,
  128238. 1,
  128239. 15,
  128240. 0,
  128241. 16,
  128242. };
  128243. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128244. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128245. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128246. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128247. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128248. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128249. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128250. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128251. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128252. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128253. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128254. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128255. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128256. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128257. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128258. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128259. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128260. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128262. 14,
  128263. };
  128264. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128265. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128266. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128267. };
  128268. static long _vq_quantmap__44c2_s_p6_0[] = {
  128269. 15, 13, 11, 9, 7, 5, 3, 1,
  128270. 0, 2, 4, 6, 8, 10, 12, 14,
  128271. 16,
  128272. };
  128273. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128274. _vq_quantthresh__44c2_s_p6_0,
  128275. _vq_quantmap__44c2_s_p6_0,
  128276. 17,
  128277. 17
  128278. };
  128279. static static_codebook _44c2_s_p6_0 = {
  128280. 2, 289,
  128281. _vq_lengthlist__44c2_s_p6_0,
  128282. 1, -529530880, 1611661312, 5, 0,
  128283. _vq_quantlist__44c2_s_p6_0,
  128284. NULL,
  128285. &_vq_auxt__44c2_s_p6_0,
  128286. NULL,
  128287. 0
  128288. };
  128289. static long _vq_quantlist__44c2_s_p7_0[] = {
  128290. 1,
  128291. 0,
  128292. 2,
  128293. };
  128294. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128295. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128296. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128297. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128298. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128299. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128300. 11,
  128301. };
  128302. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128303. -5.5, 5.5,
  128304. };
  128305. static long _vq_quantmap__44c2_s_p7_0[] = {
  128306. 1, 0, 2,
  128307. };
  128308. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128309. _vq_quantthresh__44c2_s_p7_0,
  128310. _vq_quantmap__44c2_s_p7_0,
  128311. 3,
  128312. 3
  128313. };
  128314. static static_codebook _44c2_s_p7_0 = {
  128315. 4, 81,
  128316. _vq_lengthlist__44c2_s_p7_0,
  128317. 1, -529137664, 1618345984, 2, 0,
  128318. _vq_quantlist__44c2_s_p7_0,
  128319. NULL,
  128320. &_vq_auxt__44c2_s_p7_0,
  128321. NULL,
  128322. 0
  128323. };
  128324. static long _vq_quantlist__44c2_s_p7_1[] = {
  128325. 5,
  128326. 4,
  128327. 6,
  128328. 3,
  128329. 7,
  128330. 2,
  128331. 8,
  128332. 1,
  128333. 9,
  128334. 0,
  128335. 10,
  128336. };
  128337. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128338. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128339. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128340. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128341. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128342. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128343. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128344. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128345. 10,10,10, 8, 8, 8, 8, 8, 8,
  128346. };
  128347. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128348. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128349. 3.5, 4.5,
  128350. };
  128351. static long _vq_quantmap__44c2_s_p7_1[] = {
  128352. 9, 7, 5, 3, 1, 0, 2, 4,
  128353. 6, 8, 10,
  128354. };
  128355. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128356. _vq_quantthresh__44c2_s_p7_1,
  128357. _vq_quantmap__44c2_s_p7_1,
  128358. 11,
  128359. 11
  128360. };
  128361. static static_codebook _44c2_s_p7_1 = {
  128362. 2, 121,
  128363. _vq_lengthlist__44c2_s_p7_1,
  128364. 1, -531365888, 1611661312, 4, 0,
  128365. _vq_quantlist__44c2_s_p7_1,
  128366. NULL,
  128367. &_vq_auxt__44c2_s_p7_1,
  128368. NULL,
  128369. 0
  128370. };
  128371. static long _vq_quantlist__44c2_s_p8_0[] = {
  128372. 6,
  128373. 5,
  128374. 7,
  128375. 4,
  128376. 8,
  128377. 3,
  128378. 9,
  128379. 2,
  128380. 10,
  128381. 1,
  128382. 11,
  128383. 0,
  128384. 12,
  128385. };
  128386. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128387. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128388. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128389. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128390. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128391. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128392. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128393. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128394. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128395. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128396. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128397. 0,12,12,12,12,13,12,14,14,
  128398. };
  128399. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128400. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128401. 12.5, 17.5, 22.5, 27.5,
  128402. };
  128403. static long _vq_quantmap__44c2_s_p8_0[] = {
  128404. 11, 9, 7, 5, 3, 1, 0, 2,
  128405. 4, 6, 8, 10, 12,
  128406. };
  128407. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128408. _vq_quantthresh__44c2_s_p8_0,
  128409. _vq_quantmap__44c2_s_p8_0,
  128410. 13,
  128411. 13
  128412. };
  128413. static static_codebook _44c2_s_p8_0 = {
  128414. 2, 169,
  128415. _vq_lengthlist__44c2_s_p8_0,
  128416. 1, -526516224, 1616117760, 4, 0,
  128417. _vq_quantlist__44c2_s_p8_0,
  128418. NULL,
  128419. &_vq_auxt__44c2_s_p8_0,
  128420. NULL,
  128421. 0
  128422. };
  128423. static long _vq_quantlist__44c2_s_p8_1[] = {
  128424. 2,
  128425. 1,
  128426. 3,
  128427. 0,
  128428. 4,
  128429. };
  128430. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128431. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128432. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128433. };
  128434. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128435. -1.5, -0.5, 0.5, 1.5,
  128436. };
  128437. static long _vq_quantmap__44c2_s_p8_1[] = {
  128438. 3, 1, 0, 2, 4,
  128439. };
  128440. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128441. _vq_quantthresh__44c2_s_p8_1,
  128442. _vq_quantmap__44c2_s_p8_1,
  128443. 5,
  128444. 5
  128445. };
  128446. static static_codebook _44c2_s_p8_1 = {
  128447. 2, 25,
  128448. _vq_lengthlist__44c2_s_p8_1,
  128449. 1, -533725184, 1611661312, 3, 0,
  128450. _vq_quantlist__44c2_s_p8_1,
  128451. NULL,
  128452. &_vq_auxt__44c2_s_p8_1,
  128453. NULL,
  128454. 0
  128455. };
  128456. static long _vq_quantlist__44c2_s_p9_0[] = {
  128457. 6,
  128458. 5,
  128459. 7,
  128460. 4,
  128461. 8,
  128462. 3,
  128463. 9,
  128464. 2,
  128465. 10,
  128466. 1,
  128467. 11,
  128468. 0,
  128469. 12,
  128470. };
  128471. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128472. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128473. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128475. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128476. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128479. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128480. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128481. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128482. 11,11,11,11,11,11,11,11,11,
  128483. };
  128484. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128485. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128486. 552.5, 773.5, 994.5, 1215.5,
  128487. };
  128488. static long _vq_quantmap__44c2_s_p9_0[] = {
  128489. 11, 9, 7, 5, 3, 1, 0, 2,
  128490. 4, 6, 8, 10, 12,
  128491. };
  128492. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128493. _vq_quantthresh__44c2_s_p9_0,
  128494. _vq_quantmap__44c2_s_p9_0,
  128495. 13,
  128496. 13
  128497. };
  128498. static static_codebook _44c2_s_p9_0 = {
  128499. 2, 169,
  128500. _vq_lengthlist__44c2_s_p9_0,
  128501. 1, -514541568, 1627103232, 4, 0,
  128502. _vq_quantlist__44c2_s_p9_0,
  128503. NULL,
  128504. &_vq_auxt__44c2_s_p9_0,
  128505. NULL,
  128506. 0
  128507. };
  128508. static long _vq_quantlist__44c2_s_p9_1[] = {
  128509. 6,
  128510. 5,
  128511. 7,
  128512. 4,
  128513. 8,
  128514. 3,
  128515. 9,
  128516. 2,
  128517. 10,
  128518. 1,
  128519. 11,
  128520. 0,
  128521. 12,
  128522. };
  128523. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128524. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128525. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128526. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128527. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128528. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128529. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128530. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128531. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128532. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128533. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128534. 17,13,12,12,10,13,11,14,14,
  128535. };
  128536. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128537. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128538. 42.5, 59.5, 76.5, 93.5,
  128539. };
  128540. static long _vq_quantmap__44c2_s_p9_1[] = {
  128541. 11, 9, 7, 5, 3, 1, 0, 2,
  128542. 4, 6, 8, 10, 12,
  128543. };
  128544. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128545. _vq_quantthresh__44c2_s_p9_1,
  128546. _vq_quantmap__44c2_s_p9_1,
  128547. 13,
  128548. 13
  128549. };
  128550. static static_codebook _44c2_s_p9_1 = {
  128551. 2, 169,
  128552. _vq_lengthlist__44c2_s_p9_1,
  128553. 1, -522616832, 1620115456, 4, 0,
  128554. _vq_quantlist__44c2_s_p9_1,
  128555. NULL,
  128556. &_vq_auxt__44c2_s_p9_1,
  128557. NULL,
  128558. 0
  128559. };
  128560. static long _vq_quantlist__44c2_s_p9_2[] = {
  128561. 8,
  128562. 7,
  128563. 9,
  128564. 6,
  128565. 10,
  128566. 5,
  128567. 11,
  128568. 4,
  128569. 12,
  128570. 3,
  128571. 13,
  128572. 2,
  128573. 14,
  128574. 1,
  128575. 15,
  128576. 0,
  128577. 16,
  128578. };
  128579. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128580. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128581. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128582. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128583. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128584. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128585. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128586. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128587. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128588. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128589. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128590. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128591. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128592. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128593. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128594. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128595. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128596. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128597. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128598. 10,
  128599. };
  128600. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128601. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128602. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128603. };
  128604. static long _vq_quantmap__44c2_s_p9_2[] = {
  128605. 15, 13, 11, 9, 7, 5, 3, 1,
  128606. 0, 2, 4, 6, 8, 10, 12, 14,
  128607. 16,
  128608. };
  128609. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128610. _vq_quantthresh__44c2_s_p9_2,
  128611. _vq_quantmap__44c2_s_p9_2,
  128612. 17,
  128613. 17
  128614. };
  128615. static static_codebook _44c2_s_p9_2 = {
  128616. 2, 289,
  128617. _vq_lengthlist__44c2_s_p9_2,
  128618. 1, -529530880, 1611661312, 5, 0,
  128619. _vq_quantlist__44c2_s_p9_2,
  128620. NULL,
  128621. &_vq_auxt__44c2_s_p9_2,
  128622. NULL,
  128623. 0
  128624. };
  128625. static long _huff_lengthlist__44c2_s_short[] = {
  128626. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128627. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128628. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128629. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128630. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128631. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128632. 6, 8, 9,12,
  128633. };
  128634. static static_codebook _huff_book__44c2_s_short = {
  128635. 2, 100,
  128636. _huff_lengthlist__44c2_s_short,
  128637. 0, 0, 0, 0, 0,
  128638. NULL,
  128639. NULL,
  128640. NULL,
  128641. NULL,
  128642. 0
  128643. };
  128644. static long _huff_lengthlist__44c3_s_long[] = {
  128645. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128646. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128647. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128648. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128649. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128650. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128651. 9, 8, 8, 8,
  128652. };
  128653. static static_codebook _huff_book__44c3_s_long = {
  128654. 2, 100,
  128655. _huff_lengthlist__44c3_s_long,
  128656. 0, 0, 0, 0, 0,
  128657. NULL,
  128658. NULL,
  128659. NULL,
  128660. NULL,
  128661. 0
  128662. };
  128663. static long _vq_quantlist__44c3_s_p1_0[] = {
  128664. 1,
  128665. 0,
  128666. 2,
  128667. };
  128668. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128669. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128670. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128675. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128680. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128715. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128720. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128725. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128761. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128766. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128771. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128898. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128903. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128908. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  129080. };
  129081. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129082. -0.5, 0.5,
  129083. };
  129084. static long _vq_quantmap__44c3_s_p1_0[] = {
  129085. 1, 0, 2,
  129086. };
  129087. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129088. _vq_quantthresh__44c3_s_p1_0,
  129089. _vq_quantmap__44c3_s_p1_0,
  129090. 3,
  129091. 3
  129092. };
  129093. static static_codebook _44c3_s_p1_0 = {
  129094. 8, 6561,
  129095. _vq_lengthlist__44c3_s_p1_0,
  129096. 1, -535822336, 1611661312, 2, 0,
  129097. _vq_quantlist__44c3_s_p1_0,
  129098. NULL,
  129099. &_vq_auxt__44c3_s_p1_0,
  129100. NULL,
  129101. 0
  129102. };
  129103. static long _vq_quantlist__44c3_s_p2_0[] = {
  129104. 2,
  129105. 1,
  129106. 3,
  129107. 0,
  129108. 4,
  129109. };
  129110. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129111. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129112. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129113. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129114. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129115. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129121. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129122. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129123. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129129. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129130. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129137. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129138. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129151. };
  129152. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129153. -1.5, -0.5, 0.5, 1.5,
  129154. };
  129155. static long _vq_quantmap__44c3_s_p2_0[] = {
  129156. 3, 1, 0, 2, 4,
  129157. };
  129158. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129159. _vq_quantthresh__44c3_s_p2_0,
  129160. _vq_quantmap__44c3_s_p2_0,
  129161. 5,
  129162. 5
  129163. };
  129164. static static_codebook _44c3_s_p2_0 = {
  129165. 4, 625,
  129166. _vq_lengthlist__44c3_s_p2_0,
  129167. 1, -533725184, 1611661312, 3, 0,
  129168. _vq_quantlist__44c3_s_p2_0,
  129169. NULL,
  129170. &_vq_auxt__44c3_s_p2_0,
  129171. NULL,
  129172. 0
  129173. };
  129174. static long _vq_quantlist__44c3_s_p3_0[] = {
  129175. 2,
  129176. 1,
  129177. 3,
  129178. 0,
  129179. 4,
  129180. };
  129181. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129182. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  129222. };
  129223. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129224. -1.5, -0.5, 0.5, 1.5,
  129225. };
  129226. static long _vq_quantmap__44c3_s_p3_0[] = {
  129227. 3, 1, 0, 2, 4,
  129228. };
  129229. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129230. _vq_quantthresh__44c3_s_p3_0,
  129231. _vq_quantmap__44c3_s_p3_0,
  129232. 5,
  129233. 5
  129234. };
  129235. static static_codebook _44c3_s_p3_0 = {
  129236. 4, 625,
  129237. _vq_lengthlist__44c3_s_p3_0,
  129238. 1, -533725184, 1611661312, 3, 0,
  129239. _vq_quantlist__44c3_s_p3_0,
  129240. NULL,
  129241. &_vq_auxt__44c3_s_p3_0,
  129242. NULL,
  129243. 0
  129244. };
  129245. static long _vq_quantlist__44c3_s_p4_0[] = {
  129246. 4,
  129247. 3,
  129248. 5,
  129249. 2,
  129250. 6,
  129251. 1,
  129252. 7,
  129253. 0,
  129254. 8,
  129255. };
  129256. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129257. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129258. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129259. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129260. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129261. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0,
  129263. };
  129264. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129265. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129266. };
  129267. static long _vq_quantmap__44c3_s_p4_0[] = {
  129268. 7, 5, 3, 1, 0, 2, 4, 6,
  129269. 8,
  129270. };
  129271. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129272. _vq_quantthresh__44c3_s_p4_0,
  129273. _vq_quantmap__44c3_s_p4_0,
  129274. 9,
  129275. 9
  129276. };
  129277. static static_codebook _44c3_s_p4_0 = {
  129278. 2, 81,
  129279. _vq_lengthlist__44c3_s_p4_0,
  129280. 1, -531628032, 1611661312, 4, 0,
  129281. _vq_quantlist__44c3_s_p4_0,
  129282. NULL,
  129283. &_vq_auxt__44c3_s_p4_0,
  129284. NULL,
  129285. 0
  129286. };
  129287. static long _vq_quantlist__44c3_s_p5_0[] = {
  129288. 4,
  129289. 3,
  129290. 5,
  129291. 2,
  129292. 6,
  129293. 1,
  129294. 7,
  129295. 0,
  129296. 8,
  129297. };
  129298. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129299. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129300. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129301. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129302. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129303. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129304. 11,
  129305. };
  129306. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129307. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129308. };
  129309. static long _vq_quantmap__44c3_s_p5_0[] = {
  129310. 7, 5, 3, 1, 0, 2, 4, 6,
  129311. 8,
  129312. };
  129313. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129314. _vq_quantthresh__44c3_s_p5_0,
  129315. _vq_quantmap__44c3_s_p5_0,
  129316. 9,
  129317. 9
  129318. };
  129319. static static_codebook _44c3_s_p5_0 = {
  129320. 2, 81,
  129321. _vq_lengthlist__44c3_s_p5_0,
  129322. 1, -531628032, 1611661312, 4, 0,
  129323. _vq_quantlist__44c3_s_p5_0,
  129324. NULL,
  129325. &_vq_auxt__44c3_s_p5_0,
  129326. NULL,
  129327. 0
  129328. };
  129329. static long _vq_quantlist__44c3_s_p6_0[] = {
  129330. 8,
  129331. 7,
  129332. 9,
  129333. 6,
  129334. 10,
  129335. 5,
  129336. 11,
  129337. 4,
  129338. 12,
  129339. 3,
  129340. 13,
  129341. 2,
  129342. 14,
  129343. 1,
  129344. 15,
  129345. 0,
  129346. 16,
  129347. };
  129348. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129349. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129350. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129351. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129352. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129353. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129354. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129355. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129356. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129357. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129358. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129359. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129360. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129361. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129362. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129363. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129364. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129365. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129367. 13,
  129368. };
  129369. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129370. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129371. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129372. };
  129373. static long _vq_quantmap__44c3_s_p6_0[] = {
  129374. 15, 13, 11, 9, 7, 5, 3, 1,
  129375. 0, 2, 4, 6, 8, 10, 12, 14,
  129376. 16,
  129377. };
  129378. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129379. _vq_quantthresh__44c3_s_p6_0,
  129380. _vq_quantmap__44c3_s_p6_0,
  129381. 17,
  129382. 17
  129383. };
  129384. static static_codebook _44c3_s_p6_0 = {
  129385. 2, 289,
  129386. _vq_lengthlist__44c3_s_p6_0,
  129387. 1, -529530880, 1611661312, 5, 0,
  129388. _vq_quantlist__44c3_s_p6_0,
  129389. NULL,
  129390. &_vq_auxt__44c3_s_p6_0,
  129391. NULL,
  129392. 0
  129393. };
  129394. static long _vq_quantlist__44c3_s_p7_0[] = {
  129395. 1,
  129396. 0,
  129397. 2,
  129398. };
  129399. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129400. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129401. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129402. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129403. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129404. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129405. 10,
  129406. };
  129407. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129408. -5.5, 5.5,
  129409. };
  129410. static long _vq_quantmap__44c3_s_p7_0[] = {
  129411. 1, 0, 2,
  129412. };
  129413. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129414. _vq_quantthresh__44c3_s_p7_0,
  129415. _vq_quantmap__44c3_s_p7_0,
  129416. 3,
  129417. 3
  129418. };
  129419. static static_codebook _44c3_s_p7_0 = {
  129420. 4, 81,
  129421. _vq_lengthlist__44c3_s_p7_0,
  129422. 1, -529137664, 1618345984, 2, 0,
  129423. _vq_quantlist__44c3_s_p7_0,
  129424. NULL,
  129425. &_vq_auxt__44c3_s_p7_0,
  129426. NULL,
  129427. 0
  129428. };
  129429. static long _vq_quantlist__44c3_s_p7_1[] = {
  129430. 5,
  129431. 4,
  129432. 6,
  129433. 3,
  129434. 7,
  129435. 2,
  129436. 8,
  129437. 1,
  129438. 9,
  129439. 0,
  129440. 10,
  129441. };
  129442. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129443. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129444. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129445. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129446. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129447. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129448. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129449. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129450. 10,10,10, 8, 8, 8, 8, 8, 8,
  129451. };
  129452. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129453. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129454. 3.5, 4.5,
  129455. };
  129456. static long _vq_quantmap__44c3_s_p7_1[] = {
  129457. 9, 7, 5, 3, 1, 0, 2, 4,
  129458. 6, 8, 10,
  129459. };
  129460. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129461. _vq_quantthresh__44c3_s_p7_1,
  129462. _vq_quantmap__44c3_s_p7_1,
  129463. 11,
  129464. 11
  129465. };
  129466. static static_codebook _44c3_s_p7_1 = {
  129467. 2, 121,
  129468. _vq_lengthlist__44c3_s_p7_1,
  129469. 1, -531365888, 1611661312, 4, 0,
  129470. _vq_quantlist__44c3_s_p7_1,
  129471. NULL,
  129472. &_vq_auxt__44c3_s_p7_1,
  129473. NULL,
  129474. 0
  129475. };
  129476. static long _vq_quantlist__44c3_s_p8_0[] = {
  129477. 6,
  129478. 5,
  129479. 7,
  129480. 4,
  129481. 8,
  129482. 3,
  129483. 9,
  129484. 2,
  129485. 10,
  129486. 1,
  129487. 11,
  129488. 0,
  129489. 12,
  129490. };
  129491. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129492. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129493. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129494. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129495. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129496. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129497. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129498. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129499. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129500. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129501. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129502. 0,13,13,12,12,13,12,14,13,
  129503. };
  129504. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129505. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129506. 12.5, 17.5, 22.5, 27.5,
  129507. };
  129508. static long _vq_quantmap__44c3_s_p8_0[] = {
  129509. 11, 9, 7, 5, 3, 1, 0, 2,
  129510. 4, 6, 8, 10, 12,
  129511. };
  129512. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129513. _vq_quantthresh__44c3_s_p8_0,
  129514. _vq_quantmap__44c3_s_p8_0,
  129515. 13,
  129516. 13
  129517. };
  129518. static static_codebook _44c3_s_p8_0 = {
  129519. 2, 169,
  129520. _vq_lengthlist__44c3_s_p8_0,
  129521. 1, -526516224, 1616117760, 4, 0,
  129522. _vq_quantlist__44c3_s_p8_0,
  129523. NULL,
  129524. &_vq_auxt__44c3_s_p8_0,
  129525. NULL,
  129526. 0
  129527. };
  129528. static long _vq_quantlist__44c3_s_p8_1[] = {
  129529. 2,
  129530. 1,
  129531. 3,
  129532. 0,
  129533. 4,
  129534. };
  129535. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129536. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129537. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129538. };
  129539. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129540. -1.5, -0.5, 0.5, 1.5,
  129541. };
  129542. static long _vq_quantmap__44c3_s_p8_1[] = {
  129543. 3, 1, 0, 2, 4,
  129544. };
  129545. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129546. _vq_quantthresh__44c3_s_p8_1,
  129547. _vq_quantmap__44c3_s_p8_1,
  129548. 5,
  129549. 5
  129550. };
  129551. static static_codebook _44c3_s_p8_1 = {
  129552. 2, 25,
  129553. _vq_lengthlist__44c3_s_p8_1,
  129554. 1, -533725184, 1611661312, 3, 0,
  129555. _vq_quantlist__44c3_s_p8_1,
  129556. NULL,
  129557. &_vq_auxt__44c3_s_p8_1,
  129558. NULL,
  129559. 0
  129560. };
  129561. static long _vq_quantlist__44c3_s_p9_0[] = {
  129562. 6,
  129563. 5,
  129564. 7,
  129565. 4,
  129566. 8,
  129567. 3,
  129568. 9,
  129569. 2,
  129570. 10,
  129571. 1,
  129572. 11,
  129573. 0,
  129574. 12,
  129575. };
  129576. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129577. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129578. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129579. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129580. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129581. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129582. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129583. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129584. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129585. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129586. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129587. 11,11,11,11,11,11,11,11,11,
  129588. };
  129589. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129590. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129591. 637.5, 892.5, 1147.5, 1402.5,
  129592. };
  129593. static long _vq_quantmap__44c3_s_p9_0[] = {
  129594. 11, 9, 7, 5, 3, 1, 0, 2,
  129595. 4, 6, 8, 10, 12,
  129596. };
  129597. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129598. _vq_quantthresh__44c3_s_p9_0,
  129599. _vq_quantmap__44c3_s_p9_0,
  129600. 13,
  129601. 13
  129602. };
  129603. static static_codebook _44c3_s_p9_0 = {
  129604. 2, 169,
  129605. _vq_lengthlist__44c3_s_p9_0,
  129606. 1, -514332672, 1627381760, 4, 0,
  129607. _vq_quantlist__44c3_s_p9_0,
  129608. NULL,
  129609. &_vq_auxt__44c3_s_p9_0,
  129610. NULL,
  129611. 0
  129612. };
  129613. static long _vq_quantlist__44c3_s_p9_1[] = {
  129614. 7,
  129615. 6,
  129616. 8,
  129617. 5,
  129618. 9,
  129619. 4,
  129620. 10,
  129621. 3,
  129622. 11,
  129623. 2,
  129624. 12,
  129625. 1,
  129626. 13,
  129627. 0,
  129628. 14,
  129629. };
  129630. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129631. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129632. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129633. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129634. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129635. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129636. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129637. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129638. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129639. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129640. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129641. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129642. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129643. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129644. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129645. 15,
  129646. };
  129647. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129648. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129649. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129650. };
  129651. static long _vq_quantmap__44c3_s_p9_1[] = {
  129652. 13, 11, 9, 7, 5, 3, 1, 0,
  129653. 2, 4, 6, 8, 10, 12, 14,
  129654. };
  129655. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129656. _vq_quantthresh__44c3_s_p9_1,
  129657. _vq_quantmap__44c3_s_p9_1,
  129658. 15,
  129659. 15
  129660. };
  129661. static static_codebook _44c3_s_p9_1 = {
  129662. 2, 225,
  129663. _vq_lengthlist__44c3_s_p9_1,
  129664. 1, -522338304, 1620115456, 4, 0,
  129665. _vq_quantlist__44c3_s_p9_1,
  129666. NULL,
  129667. &_vq_auxt__44c3_s_p9_1,
  129668. NULL,
  129669. 0
  129670. };
  129671. static long _vq_quantlist__44c3_s_p9_2[] = {
  129672. 8,
  129673. 7,
  129674. 9,
  129675. 6,
  129676. 10,
  129677. 5,
  129678. 11,
  129679. 4,
  129680. 12,
  129681. 3,
  129682. 13,
  129683. 2,
  129684. 14,
  129685. 1,
  129686. 15,
  129687. 0,
  129688. 16,
  129689. };
  129690. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129691. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129692. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129693. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129694. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129695. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129696. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129697. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129698. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129699. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129700. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129701. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129702. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129703. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129704. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129705. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129706. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129707. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129708. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129709. 10,
  129710. };
  129711. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129712. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129713. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129714. };
  129715. static long _vq_quantmap__44c3_s_p9_2[] = {
  129716. 15, 13, 11, 9, 7, 5, 3, 1,
  129717. 0, 2, 4, 6, 8, 10, 12, 14,
  129718. 16,
  129719. };
  129720. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129721. _vq_quantthresh__44c3_s_p9_2,
  129722. _vq_quantmap__44c3_s_p9_2,
  129723. 17,
  129724. 17
  129725. };
  129726. static static_codebook _44c3_s_p9_2 = {
  129727. 2, 289,
  129728. _vq_lengthlist__44c3_s_p9_2,
  129729. 1, -529530880, 1611661312, 5, 0,
  129730. _vq_quantlist__44c3_s_p9_2,
  129731. NULL,
  129732. &_vq_auxt__44c3_s_p9_2,
  129733. NULL,
  129734. 0
  129735. };
  129736. static long _huff_lengthlist__44c3_s_short[] = {
  129737. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129738. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129739. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129740. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129741. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129742. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129743. 6, 8, 9,11,
  129744. };
  129745. static static_codebook _huff_book__44c3_s_short = {
  129746. 2, 100,
  129747. _huff_lengthlist__44c3_s_short,
  129748. 0, 0, 0, 0, 0,
  129749. NULL,
  129750. NULL,
  129751. NULL,
  129752. NULL,
  129753. 0
  129754. };
  129755. static long _huff_lengthlist__44c4_s_long[] = {
  129756. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129757. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129758. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129759. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129760. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129761. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129762. 9, 8, 7, 7,
  129763. };
  129764. static static_codebook _huff_book__44c4_s_long = {
  129765. 2, 100,
  129766. _huff_lengthlist__44c4_s_long,
  129767. 0, 0, 0, 0, 0,
  129768. NULL,
  129769. NULL,
  129770. NULL,
  129771. NULL,
  129772. 0
  129773. };
  129774. static long _vq_quantlist__44c4_s_p1_0[] = {
  129775. 1,
  129776. 0,
  129777. 2,
  129778. };
  129779. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129780. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129781. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129786. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129791. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129826. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129831. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129836. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129872. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129877. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129882. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130014. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  130191. };
  130192. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130193. -0.5, 0.5,
  130194. };
  130195. static long _vq_quantmap__44c4_s_p1_0[] = {
  130196. 1, 0, 2,
  130197. };
  130198. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130199. _vq_quantthresh__44c4_s_p1_0,
  130200. _vq_quantmap__44c4_s_p1_0,
  130201. 3,
  130202. 3
  130203. };
  130204. static static_codebook _44c4_s_p1_0 = {
  130205. 8, 6561,
  130206. _vq_lengthlist__44c4_s_p1_0,
  130207. 1, -535822336, 1611661312, 2, 0,
  130208. _vq_quantlist__44c4_s_p1_0,
  130209. NULL,
  130210. &_vq_auxt__44c4_s_p1_0,
  130211. NULL,
  130212. 0
  130213. };
  130214. static long _vq_quantlist__44c4_s_p2_0[] = {
  130215. 2,
  130216. 1,
  130217. 3,
  130218. 0,
  130219. 4,
  130220. };
  130221. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130222. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130223. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130224. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130225. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130226. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130232. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130233. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130234. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130240. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130241. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130248. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130249. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130262. };
  130263. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130264. -1.5, -0.5, 0.5, 1.5,
  130265. };
  130266. static long _vq_quantmap__44c4_s_p2_0[] = {
  130267. 3, 1, 0, 2, 4,
  130268. };
  130269. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130270. _vq_quantthresh__44c4_s_p2_0,
  130271. _vq_quantmap__44c4_s_p2_0,
  130272. 5,
  130273. 5
  130274. };
  130275. static static_codebook _44c4_s_p2_0 = {
  130276. 4, 625,
  130277. _vq_lengthlist__44c4_s_p2_0,
  130278. 1, -533725184, 1611661312, 3, 0,
  130279. _vq_quantlist__44c4_s_p2_0,
  130280. NULL,
  130281. &_vq_auxt__44c4_s_p2_0,
  130282. NULL,
  130283. 0
  130284. };
  130285. static long _vq_quantlist__44c4_s_p3_0[] = {
  130286. 2,
  130287. 1,
  130288. 3,
  130289. 0,
  130290. 4,
  130291. };
  130292. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130293. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  130333. };
  130334. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130335. -1.5, -0.5, 0.5, 1.5,
  130336. };
  130337. static long _vq_quantmap__44c4_s_p3_0[] = {
  130338. 3, 1, 0, 2, 4,
  130339. };
  130340. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130341. _vq_quantthresh__44c4_s_p3_0,
  130342. _vq_quantmap__44c4_s_p3_0,
  130343. 5,
  130344. 5
  130345. };
  130346. static static_codebook _44c4_s_p3_0 = {
  130347. 4, 625,
  130348. _vq_lengthlist__44c4_s_p3_0,
  130349. 1, -533725184, 1611661312, 3, 0,
  130350. _vq_quantlist__44c4_s_p3_0,
  130351. NULL,
  130352. &_vq_auxt__44c4_s_p3_0,
  130353. NULL,
  130354. 0
  130355. };
  130356. static long _vq_quantlist__44c4_s_p4_0[] = {
  130357. 4,
  130358. 3,
  130359. 5,
  130360. 2,
  130361. 6,
  130362. 1,
  130363. 7,
  130364. 0,
  130365. 8,
  130366. };
  130367. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130368. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130369. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130370. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130371. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130372. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0,
  130374. };
  130375. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130376. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130377. };
  130378. static long _vq_quantmap__44c4_s_p4_0[] = {
  130379. 7, 5, 3, 1, 0, 2, 4, 6,
  130380. 8,
  130381. };
  130382. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130383. _vq_quantthresh__44c4_s_p4_0,
  130384. _vq_quantmap__44c4_s_p4_0,
  130385. 9,
  130386. 9
  130387. };
  130388. static static_codebook _44c4_s_p4_0 = {
  130389. 2, 81,
  130390. _vq_lengthlist__44c4_s_p4_0,
  130391. 1, -531628032, 1611661312, 4, 0,
  130392. _vq_quantlist__44c4_s_p4_0,
  130393. NULL,
  130394. &_vq_auxt__44c4_s_p4_0,
  130395. NULL,
  130396. 0
  130397. };
  130398. static long _vq_quantlist__44c4_s_p5_0[] = {
  130399. 4,
  130400. 3,
  130401. 5,
  130402. 2,
  130403. 6,
  130404. 1,
  130405. 7,
  130406. 0,
  130407. 8,
  130408. };
  130409. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130410. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130411. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130412. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130413. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130414. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130415. 10,
  130416. };
  130417. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130418. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130419. };
  130420. static long _vq_quantmap__44c4_s_p5_0[] = {
  130421. 7, 5, 3, 1, 0, 2, 4, 6,
  130422. 8,
  130423. };
  130424. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130425. _vq_quantthresh__44c4_s_p5_0,
  130426. _vq_quantmap__44c4_s_p5_0,
  130427. 9,
  130428. 9
  130429. };
  130430. static static_codebook _44c4_s_p5_0 = {
  130431. 2, 81,
  130432. _vq_lengthlist__44c4_s_p5_0,
  130433. 1, -531628032, 1611661312, 4, 0,
  130434. _vq_quantlist__44c4_s_p5_0,
  130435. NULL,
  130436. &_vq_auxt__44c4_s_p5_0,
  130437. NULL,
  130438. 0
  130439. };
  130440. static long _vq_quantlist__44c4_s_p6_0[] = {
  130441. 8,
  130442. 7,
  130443. 9,
  130444. 6,
  130445. 10,
  130446. 5,
  130447. 11,
  130448. 4,
  130449. 12,
  130450. 3,
  130451. 13,
  130452. 2,
  130453. 14,
  130454. 1,
  130455. 15,
  130456. 0,
  130457. 16,
  130458. };
  130459. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130460. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130461. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130462. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130463. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130464. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130465. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130466. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130467. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130468. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130469. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130470. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130471. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130472. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130473. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130474. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130475. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130476. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130478. 13,
  130479. };
  130480. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130481. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130482. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130483. };
  130484. static long _vq_quantmap__44c4_s_p6_0[] = {
  130485. 15, 13, 11, 9, 7, 5, 3, 1,
  130486. 0, 2, 4, 6, 8, 10, 12, 14,
  130487. 16,
  130488. };
  130489. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130490. _vq_quantthresh__44c4_s_p6_0,
  130491. _vq_quantmap__44c4_s_p6_0,
  130492. 17,
  130493. 17
  130494. };
  130495. static static_codebook _44c4_s_p6_0 = {
  130496. 2, 289,
  130497. _vq_lengthlist__44c4_s_p6_0,
  130498. 1, -529530880, 1611661312, 5, 0,
  130499. _vq_quantlist__44c4_s_p6_0,
  130500. NULL,
  130501. &_vq_auxt__44c4_s_p6_0,
  130502. NULL,
  130503. 0
  130504. };
  130505. static long _vq_quantlist__44c4_s_p7_0[] = {
  130506. 1,
  130507. 0,
  130508. 2,
  130509. };
  130510. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130511. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130512. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130513. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130514. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130515. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130516. 10,
  130517. };
  130518. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130519. -5.5, 5.5,
  130520. };
  130521. static long _vq_quantmap__44c4_s_p7_0[] = {
  130522. 1, 0, 2,
  130523. };
  130524. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130525. _vq_quantthresh__44c4_s_p7_0,
  130526. _vq_quantmap__44c4_s_p7_0,
  130527. 3,
  130528. 3
  130529. };
  130530. static static_codebook _44c4_s_p7_0 = {
  130531. 4, 81,
  130532. _vq_lengthlist__44c4_s_p7_0,
  130533. 1, -529137664, 1618345984, 2, 0,
  130534. _vq_quantlist__44c4_s_p7_0,
  130535. NULL,
  130536. &_vq_auxt__44c4_s_p7_0,
  130537. NULL,
  130538. 0
  130539. };
  130540. static long _vq_quantlist__44c4_s_p7_1[] = {
  130541. 5,
  130542. 4,
  130543. 6,
  130544. 3,
  130545. 7,
  130546. 2,
  130547. 8,
  130548. 1,
  130549. 9,
  130550. 0,
  130551. 10,
  130552. };
  130553. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130554. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130555. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130556. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130557. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130558. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130559. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130560. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130561. 10,10,10, 8, 8, 8, 8, 9, 9,
  130562. };
  130563. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130564. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130565. 3.5, 4.5,
  130566. };
  130567. static long _vq_quantmap__44c4_s_p7_1[] = {
  130568. 9, 7, 5, 3, 1, 0, 2, 4,
  130569. 6, 8, 10,
  130570. };
  130571. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130572. _vq_quantthresh__44c4_s_p7_1,
  130573. _vq_quantmap__44c4_s_p7_1,
  130574. 11,
  130575. 11
  130576. };
  130577. static static_codebook _44c4_s_p7_1 = {
  130578. 2, 121,
  130579. _vq_lengthlist__44c4_s_p7_1,
  130580. 1, -531365888, 1611661312, 4, 0,
  130581. _vq_quantlist__44c4_s_p7_1,
  130582. NULL,
  130583. &_vq_auxt__44c4_s_p7_1,
  130584. NULL,
  130585. 0
  130586. };
  130587. static long _vq_quantlist__44c4_s_p8_0[] = {
  130588. 6,
  130589. 5,
  130590. 7,
  130591. 4,
  130592. 8,
  130593. 3,
  130594. 9,
  130595. 2,
  130596. 10,
  130597. 1,
  130598. 11,
  130599. 0,
  130600. 12,
  130601. };
  130602. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130603. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130604. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130605. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130606. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130607. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130608. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130609. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130610. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130611. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130612. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130613. 0,13,12,12,12,12,12,13,13,
  130614. };
  130615. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130616. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130617. 12.5, 17.5, 22.5, 27.5,
  130618. };
  130619. static long _vq_quantmap__44c4_s_p8_0[] = {
  130620. 11, 9, 7, 5, 3, 1, 0, 2,
  130621. 4, 6, 8, 10, 12,
  130622. };
  130623. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130624. _vq_quantthresh__44c4_s_p8_0,
  130625. _vq_quantmap__44c4_s_p8_0,
  130626. 13,
  130627. 13
  130628. };
  130629. static static_codebook _44c4_s_p8_0 = {
  130630. 2, 169,
  130631. _vq_lengthlist__44c4_s_p8_0,
  130632. 1, -526516224, 1616117760, 4, 0,
  130633. _vq_quantlist__44c4_s_p8_0,
  130634. NULL,
  130635. &_vq_auxt__44c4_s_p8_0,
  130636. NULL,
  130637. 0
  130638. };
  130639. static long _vq_quantlist__44c4_s_p8_1[] = {
  130640. 2,
  130641. 1,
  130642. 3,
  130643. 0,
  130644. 4,
  130645. };
  130646. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130647. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130648. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130649. };
  130650. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130651. -1.5, -0.5, 0.5, 1.5,
  130652. };
  130653. static long _vq_quantmap__44c4_s_p8_1[] = {
  130654. 3, 1, 0, 2, 4,
  130655. };
  130656. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130657. _vq_quantthresh__44c4_s_p8_1,
  130658. _vq_quantmap__44c4_s_p8_1,
  130659. 5,
  130660. 5
  130661. };
  130662. static static_codebook _44c4_s_p8_1 = {
  130663. 2, 25,
  130664. _vq_lengthlist__44c4_s_p8_1,
  130665. 1, -533725184, 1611661312, 3, 0,
  130666. _vq_quantlist__44c4_s_p8_1,
  130667. NULL,
  130668. &_vq_auxt__44c4_s_p8_1,
  130669. NULL,
  130670. 0
  130671. };
  130672. static long _vq_quantlist__44c4_s_p9_0[] = {
  130673. 6,
  130674. 5,
  130675. 7,
  130676. 4,
  130677. 8,
  130678. 3,
  130679. 9,
  130680. 2,
  130681. 10,
  130682. 1,
  130683. 11,
  130684. 0,
  130685. 12,
  130686. };
  130687. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130688. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130689. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130690. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130691. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130692. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130694. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130695. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130696. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130697. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130698. 12,12,12,12,12,12,12,12,12,
  130699. };
  130700. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130701. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130702. 787.5, 1102.5, 1417.5, 1732.5,
  130703. };
  130704. static long _vq_quantmap__44c4_s_p9_0[] = {
  130705. 11, 9, 7, 5, 3, 1, 0, 2,
  130706. 4, 6, 8, 10, 12,
  130707. };
  130708. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130709. _vq_quantthresh__44c4_s_p9_0,
  130710. _vq_quantmap__44c4_s_p9_0,
  130711. 13,
  130712. 13
  130713. };
  130714. static static_codebook _44c4_s_p9_0 = {
  130715. 2, 169,
  130716. _vq_lengthlist__44c4_s_p9_0,
  130717. 1, -513964032, 1628680192, 4, 0,
  130718. _vq_quantlist__44c4_s_p9_0,
  130719. NULL,
  130720. &_vq_auxt__44c4_s_p9_0,
  130721. NULL,
  130722. 0
  130723. };
  130724. static long _vq_quantlist__44c4_s_p9_1[] = {
  130725. 7,
  130726. 6,
  130727. 8,
  130728. 5,
  130729. 9,
  130730. 4,
  130731. 10,
  130732. 3,
  130733. 11,
  130734. 2,
  130735. 12,
  130736. 1,
  130737. 13,
  130738. 0,
  130739. 14,
  130740. };
  130741. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130742. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130743. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130744. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130745. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130746. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130747. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130748. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130749. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130750. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130751. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130752. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130753. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130754. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130755. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130756. 15,
  130757. };
  130758. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130759. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130760. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130761. };
  130762. static long _vq_quantmap__44c4_s_p9_1[] = {
  130763. 13, 11, 9, 7, 5, 3, 1, 0,
  130764. 2, 4, 6, 8, 10, 12, 14,
  130765. };
  130766. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130767. _vq_quantthresh__44c4_s_p9_1,
  130768. _vq_quantmap__44c4_s_p9_1,
  130769. 15,
  130770. 15
  130771. };
  130772. static static_codebook _44c4_s_p9_1 = {
  130773. 2, 225,
  130774. _vq_lengthlist__44c4_s_p9_1,
  130775. 1, -520986624, 1620377600, 4, 0,
  130776. _vq_quantlist__44c4_s_p9_1,
  130777. NULL,
  130778. &_vq_auxt__44c4_s_p9_1,
  130779. NULL,
  130780. 0
  130781. };
  130782. static long _vq_quantlist__44c4_s_p9_2[] = {
  130783. 10,
  130784. 9,
  130785. 11,
  130786. 8,
  130787. 12,
  130788. 7,
  130789. 13,
  130790. 6,
  130791. 14,
  130792. 5,
  130793. 15,
  130794. 4,
  130795. 16,
  130796. 3,
  130797. 17,
  130798. 2,
  130799. 18,
  130800. 1,
  130801. 19,
  130802. 0,
  130803. 20,
  130804. };
  130805. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130806. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130807. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130808. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130809. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130810. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130811. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130812. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130813. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130814. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130815. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130816. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130817. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130818. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130819. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130820. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130821. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130822. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130823. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130824. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130825. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130826. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130827. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130828. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130829. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130830. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130831. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130832. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130833. 10,10,10,10,10,10,10,10,10,
  130834. };
  130835. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130836. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130837. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130838. 6.5, 7.5, 8.5, 9.5,
  130839. };
  130840. static long _vq_quantmap__44c4_s_p9_2[] = {
  130841. 19, 17, 15, 13, 11, 9, 7, 5,
  130842. 3, 1, 0, 2, 4, 6, 8, 10,
  130843. 12, 14, 16, 18, 20,
  130844. };
  130845. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130846. _vq_quantthresh__44c4_s_p9_2,
  130847. _vq_quantmap__44c4_s_p9_2,
  130848. 21,
  130849. 21
  130850. };
  130851. static static_codebook _44c4_s_p9_2 = {
  130852. 2, 441,
  130853. _vq_lengthlist__44c4_s_p9_2,
  130854. 1, -529268736, 1611661312, 5, 0,
  130855. _vq_quantlist__44c4_s_p9_2,
  130856. NULL,
  130857. &_vq_auxt__44c4_s_p9_2,
  130858. NULL,
  130859. 0
  130860. };
  130861. static long _huff_lengthlist__44c4_s_short[] = {
  130862. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130863. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130864. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130865. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130866. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130867. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130868. 7, 9,12,17,
  130869. };
  130870. static static_codebook _huff_book__44c4_s_short = {
  130871. 2, 100,
  130872. _huff_lengthlist__44c4_s_short,
  130873. 0, 0, 0, 0, 0,
  130874. NULL,
  130875. NULL,
  130876. NULL,
  130877. NULL,
  130878. 0
  130879. };
  130880. static long _huff_lengthlist__44c5_s_long[] = {
  130881. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130882. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130883. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130884. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130885. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130886. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130887. 9, 8, 7, 7,
  130888. };
  130889. static static_codebook _huff_book__44c5_s_long = {
  130890. 2, 100,
  130891. _huff_lengthlist__44c5_s_long,
  130892. 0, 0, 0, 0, 0,
  130893. NULL,
  130894. NULL,
  130895. NULL,
  130896. NULL,
  130897. 0
  130898. };
  130899. static long _vq_quantlist__44c5_s_p1_0[] = {
  130900. 1,
  130901. 0,
  130902. 2,
  130903. };
  130904. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130905. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130906. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130911. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130916. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130951. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130956. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130961. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130997. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131002. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131007. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131316. };
  131317. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131318. -0.5, 0.5,
  131319. };
  131320. static long _vq_quantmap__44c5_s_p1_0[] = {
  131321. 1, 0, 2,
  131322. };
  131323. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131324. _vq_quantthresh__44c5_s_p1_0,
  131325. _vq_quantmap__44c5_s_p1_0,
  131326. 3,
  131327. 3
  131328. };
  131329. static static_codebook _44c5_s_p1_0 = {
  131330. 8, 6561,
  131331. _vq_lengthlist__44c5_s_p1_0,
  131332. 1, -535822336, 1611661312, 2, 0,
  131333. _vq_quantlist__44c5_s_p1_0,
  131334. NULL,
  131335. &_vq_auxt__44c5_s_p1_0,
  131336. NULL,
  131337. 0
  131338. };
  131339. static long _vq_quantlist__44c5_s_p2_0[] = {
  131340. 2,
  131341. 1,
  131342. 3,
  131343. 0,
  131344. 4,
  131345. };
  131346. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131347. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131348. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131349. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131350. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131351. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131357. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131358. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131359. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131365. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131366. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131373. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131374. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131387. };
  131388. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131389. -1.5, -0.5, 0.5, 1.5,
  131390. };
  131391. static long _vq_quantmap__44c5_s_p2_0[] = {
  131392. 3, 1, 0, 2, 4,
  131393. };
  131394. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131395. _vq_quantthresh__44c5_s_p2_0,
  131396. _vq_quantmap__44c5_s_p2_0,
  131397. 5,
  131398. 5
  131399. };
  131400. static static_codebook _44c5_s_p2_0 = {
  131401. 4, 625,
  131402. _vq_lengthlist__44c5_s_p2_0,
  131403. 1, -533725184, 1611661312, 3, 0,
  131404. _vq_quantlist__44c5_s_p2_0,
  131405. NULL,
  131406. &_vq_auxt__44c5_s_p2_0,
  131407. NULL,
  131408. 0
  131409. };
  131410. static long _vq_quantlist__44c5_s_p3_0[] = {
  131411. 2,
  131412. 1,
  131413. 3,
  131414. 0,
  131415. 4,
  131416. };
  131417. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131418. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  131458. };
  131459. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131460. -1.5, -0.5, 0.5, 1.5,
  131461. };
  131462. static long _vq_quantmap__44c5_s_p3_0[] = {
  131463. 3, 1, 0, 2, 4,
  131464. };
  131465. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131466. _vq_quantthresh__44c5_s_p3_0,
  131467. _vq_quantmap__44c5_s_p3_0,
  131468. 5,
  131469. 5
  131470. };
  131471. static static_codebook _44c5_s_p3_0 = {
  131472. 4, 625,
  131473. _vq_lengthlist__44c5_s_p3_0,
  131474. 1, -533725184, 1611661312, 3, 0,
  131475. _vq_quantlist__44c5_s_p3_0,
  131476. NULL,
  131477. &_vq_auxt__44c5_s_p3_0,
  131478. NULL,
  131479. 0
  131480. };
  131481. static long _vq_quantlist__44c5_s_p4_0[] = {
  131482. 4,
  131483. 3,
  131484. 5,
  131485. 2,
  131486. 6,
  131487. 1,
  131488. 7,
  131489. 0,
  131490. 8,
  131491. };
  131492. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131493. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131494. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131495. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131496. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131497. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0,
  131499. };
  131500. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131501. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131502. };
  131503. static long _vq_quantmap__44c5_s_p4_0[] = {
  131504. 7, 5, 3, 1, 0, 2, 4, 6,
  131505. 8,
  131506. };
  131507. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131508. _vq_quantthresh__44c5_s_p4_0,
  131509. _vq_quantmap__44c5_s_p4_0,
  131510. 9,
  131511. 9
  131512. };
  131513. static static_codebook _44c5_s_p4_0 = {
  131514. 2, 81,
  131515. _vq_lengthlist__44c5_s_p4_0,
  131516. 1, -531628032, 1611661312, 4, 0,
  131517. _vq_quantlist__44c5_s_p4_0,
  131518. NULL,
  131519. &_vq_auxt__44c5_s_p4_0,
  131520. NULL,
  131521. 0
  131522. };
  131523. static long _vq_quantlist__44c5_s_p5_0[] = {
  131524. 4,
  131525. 3,
  131526. 5,
  131527. 2,
  131528. 6,
  131529. 1,
  131530. 7,
  131531. 0,
  131532. 8,
  131533. };
  131534. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131535. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131536. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131537. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131538. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131539. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131540. 10,
  131541. };
  131542. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131543. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131544. };
  131545. static long _vq_quantmap__44c5_s_p5_0[] = {
  131546. 7, 5, 3, 1, 0, 2, 4, 6,
  131547. 8,
  131548. };
  131549. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131550. _vq_quantthresh__44c5_s_p5_0,
  131551. _vq_quantmap__44c5_s_p5_0,
  131552. 9,
  131553. 9
  131554. };
  131555. static static_codebook _44c5_s_p5_0 = {
  131556. 2, 81,
  131557. _vq_lengthlist__44c5_s_p5_0,
  131558. 1, -531628032, 1611661312, 4, 0,
  131559. _vq_quantlist__44c5_s_p5_0,
  131560. NULL,
  131561. &_vq_auxt__44c5_s_p5_0,
  131562. NULL,
  131563. 0
  131564. };
  131565. static long _vq_quantlist__44c5_s_p6_0[] = {
  131566. 8,
  131567. 7,
  131568. 9,
  131569. 6,
  131570. 10,
  131571. 5,
  131572. 11,
  131573. 4,
  131574. 12,
  131575. 3,
  131576. 13,
  131577. 2,
  131578. 14,
  131579. 1,
  131580. 15,
  131581. 0,
  131582. 16,
  131583. };
  131584. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131585. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131586. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131587. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131588. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131589. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131590. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131591. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131592. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131593. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131594. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131595. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131596. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131597. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131598. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131599. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131600. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131601. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131603. 13,
  131604. };
  131605. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131606. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131607. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131608. };
  131609. static long _vq_quantmap__44c5_s_p6_0[] = {
  131610. 15, 13, 11, 9, 7, 5, 3, 1,
  131611. 0, 2, 4, 6, 8, 10, 12, 14,
  131612. 16,
  131613. };
  131614. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131615. _vq_quantthresh__44c5_s_p6_0,
  131616. _vq_quantmap__44c5_s_p6_0,
  131617. 17,
  131618. 17
  131619. };
  131620. static static_codebook _44c5_s_p6_0 = {
  131621. 2, 289,
  131622. _vq_lengthlist__44c5_s_p6_0,
  131623. 1, -529530880, 1611661312, 5, 0,
  131624. _vq_quantlist__44c5_s_p6_0,
  131625. NULL,
  131626. &_vq_auxt__44c5_s_p6_0,
  131627. NULL,
  131628. 0
  131629. };
  131630. static long _vq_quantlist__44c5_s_p7_0[] = {
  131631. 1,
  131632. 0,
  131633. 2,
  131634. };
  131635. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131636. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131637. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131638. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131639. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131640. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131641. 10,
  131642. };
  131643. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131644. -5.5, 5.5,
  131645. };
  131646. static long _vq_quantmap__44c5_s_p7_0[] = {
  131647. 1, 0, 2,
  131648. };
  131649. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131650. _vq_quantthresh__44c5_s_p7_0,
  131651. _vq_quantmap__44c5_s_p7_0,
  131652. 3,
  131653. 3
  131654. };
  131655. static static_codebook _44c5_s_p7_0 = {
  131656. 4, 81,
  131657. _vq_lengthlist__44c5_s_p7_0,
  131658. 1, -529137664, 1618345984, 2, 0,
  131659. _vq_quantlist__44c5_s_p7_0,
  131660. NULL,
  131661. &_vq_auxt__44c5_s_p7_0,
  131662. NULL,
  131663. 0
  131664. };
  131665. static long _vq_quantlist__44c5_s_p7_1[] = {
  131666. 5,
  131667. 4,
  131668. 6,
  131669. 3,
  131670. 7,
  131671. 2,
  131672. 8,
  131673. 1,
  131674. 9,
  131675. 0,
  131676. 10,
  131677. };
  131678. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131679. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131680. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131681. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131682. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131683. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131684. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131685. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131686. 10,10,10, 8, 8, 8, 8, 8, 8,
  131687. };
  131688. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131689. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131690. 3.5, 4.5,
  131691. };
  131692. static long _vq_quantmap__44c5_s_p7_1[] = {
  131693. 9, 7, 5, 3, 1, 0, 2, 4,
  131694. 6, 8, 10,
  131695. };
  131696. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131697. _vq_quantthresh__44c5_s_p7_1,
  131698. _vq_quantmap__44c5_s_p7_1,
  131699. 11,
  131700. 11
  131701. };
  131702. static static_codebook _44c5_s_p7_1 = {
  131703. 2, 121,
  131704. _vq_lengthlist__44c5_s_p7_1,
  131705. 1, -531365888, 1611661312, 4, 0,
  131706. _vq_quantlist__44c5_s_p7_1,
  131707. NULL,
  131708. &_vq_auxt__44c5_s_p7_1,
  131709. NULL,
  131710. 0
  131711. };
  131712. static long _vq_quantlist__44c5_s_p8_0[] = {
  131713. 6,
  131714. 5,
  131715. 7,
  131716. 4,
  131717. 8,
  131718. 3,
  131719. 9,
  131720. 2,
  131721. 10,
  131722. 1,
  131723. 11,
  131724. 0,
  131725. 12,
  131726. };
  131727. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131728. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131729. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131730. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131731. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131732. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131733. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131734. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131735. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131736. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131737. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131738. 0,12,12,12,12,12,12,13,13,
  131739. };
  131740. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131741. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131742. 12.5, 17.5, 22.5, 27.5,
  131743. };
  131744. static long _vq_quantmap__44c5_s_p8_0[] = {
  131745. 11, 9, 7, 5, 3, 1, 0, 2,
  131746. 4, 6, 8, 10, 12,
  131747. };
  131748. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131749. _vq_quantthresh__44c5_s_p8_0,
  131750. _vq_quantmap__44c5_s_p8_0,
  131751. 13,
  131752. 13
  131753. };
  131754. static static_codebook _44c5_s_p8_0 = {
  131755. 2, 169,
  131756. _vq_lengthlist__44c5_s_p8_0,
  131757. 1, -526516224, 1616117760, 4, 0,
  131758. _vq_quantlist__44c5_s_p8_0,
  131759. NULL,
  131760. &_vq_auxt__44c5_s_p8_0,
  131761. NULL,
  131762. 0
  131763. };
  131764. static long _vq_quantlist__44c5_s_p8_1[] = {
  131765. 2,
  131766. 1,
  131767. 3,
  131768. 0,
  131769. 4,
  131770. };
  131771. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131772. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131773. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131774. };
  131775. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131776. -1.5, -0.5, 0.5, 1.5,
  131777. };
  131778. static long _vq_quantmap__44c5_s_p8_1[] = {
  131779. 3, 1, 0, 2, 4,
  131780. };
  131781. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131782. _vq_quantthresh__44c5_s_p8_1,
  131783. _vq_quantmap__44c5_s_p8_1,
  131784. 5,
  131785. 5
  131786. };
  131787. static static_codebook _44c5_s_p8_1 = {
  131788. 2, 25,
  131789. _vq_lengthlist__44c5_s_p8_1,
  131790. 1, -533725184, 1611661312, 3, 0,
  131791. _vq_quantlist__44c5_s_p8_1,
  131792. NULL,
  131793. &_vq_auxt__44c5_s_p8_1,
  131794. NULL,
  131795. 0
  131796. };
  131797. static long _vq_quantlist__44c5_s_p9_0[] = {
  131798. 7,
  131799. 6,
  131800. 8,
  131801. 5,
  131802. 9,
  131803. 4,
  131804. 10,
  131805. 3,
  131806. 11,
  131807. 2,
  131808. 12,
  131809. 1,
  131810. 13,
  131811. 0,
  131812. 14,
  131813. };
  131814. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131815. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131816. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131817. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131818. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131819. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131820. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131821. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131822. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131823. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131824. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131825. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131826. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131827. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131828. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131829. 12,
  131830. };
  131831. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131832. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131833. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131834. };
  131835. static long _vq_quantmap__44c5_s_p9_0[] = {
  131836. 13, 11, 9, 7, 5, 3, 1, 0,
  131837. 2, 4, 6, 8, 10, 12, 14,
  131838. };
  131839. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131840. _vq_quantthresh__44c5_s_p9_0,
  131841. _vq_quantmap__44c5_s_p9_0,
  131842. 15,
  131843. 15
  131844. };
  131845. static static_codebook _44c5_s_p9_0 = {
  131846. 2, 225,
  131847. _vq_lengthlist__44c5_s_p9_0,
  131848. 1, -512522752, 1628852224, 4, 0,
  131849. _vq_quantlist__44c5_s_p9_0,
  131850. NULL,
  131851. &_vq_auxt__44c5_s_p9_0,
  131852. NULL,
  131853. 0
  131854. };
  131855. static long _vq_quantlist__44c5_s_p9_1[] = {
  131856. 8,
  131857. 7,
  131858. 9,
  131859. 6,
  131860. 10,
  131861. 5,
  131862. 11,
  131863. 4,
  131864. 12,
  131865. 3,
  131866. 13,
  131867. 2,
  131868. 14,
  131869. 1,
  131870. 15,
  131871. 0,
  131872. 16,
  131873. };
  131874. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131875. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131876. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131877. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131878. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131879. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131880. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131881. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131882. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131883. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131884. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131885. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131886. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131887. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131888. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131889. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131890. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131891. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131892. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131893. 15,
  131894. };
  131895. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131896. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131897. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131898. };
  131899. static long _vq_quantmap__44c5_s_p9_1[] = {
  131900. 15, 13, 11, 9, 7, 5, 3, 1,
  131901. 0, 2, 4, 6, 8, 10, 12, 14,
  131902. 16,
  131903. };
  131904. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131905. _vq_quantthresh__44c5_s_p9_1,
  131906. _vq_quantmap__44c5_s_p9_1,
  131907. 17,
  131908. 17
  131909. };
  131910. static static_codebook _44c5_s_p9_1 = {
  131911. 2, 289,
  131912. _vq_lengthlist__44c5_s_p9_1,
  131913. 1, -520814592, 1620377600, 5, 0,
  131914. _vq_quantlist__44c5_s_p9_1,
  131915. NULL,
  131916. &_vq_auxt__44c5_s_p9_1,
  131917. NULL,
  131918. 0
  131919. };
  131920. static long _vq_quantlist__44c5_s_p9_2[] = {
  131921. 10,
  131922. 9,
  131923. 11,
  131924. 8,
  131925. 12,
  131926. 7,
  131927. 13,
  131928. 6,
  131929. 14,
  131930. 5,
  131931. 15,
  131932. 4,
  131933. 16,
  131934. 3,
  131935. 17,
  131936. 2,
  131937. 18,
  131938. 1,
  131939. 19,
  131940. 0,
  131941. 20,
  131942. };
  131943. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131944. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131945. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131946. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131947. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131948. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131949. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131950. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131951. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131952. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131953. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131954. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131955. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131956. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131957. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131958. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131959. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131960. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131961. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131962. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131963. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131964. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131965. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131966. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131967. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131968. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131969. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131970. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131971. 10,10,10,10,10,10,10,10,10,
  131972. };
  131973. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131974. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131975. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131976. 6.5, 7.5, 8.5, 9.5,
  131977. };
  131978. static long _vq_quantmap__44c5_s_p9_2[] = {
  131979. 19, 17, 15, 13, 11, 9, 7, 5,
  131980. 3, 1, 0, 2, 4, 6, 8, 10,
  131981. 12, 14, 16, 18, 20,
  131982. };
  131983. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131984. _vq_quantthresh__44c5_s_p9_2,
  131985. _vq_quantmap__44c5_s_p9_2,
  131986. 21,
  131987. 21
  131988. };
  131989. static static_codebook _44c5_s_p9_2 = {
  131990. 2, 441,
  131991. _vq_lengthlist__44c5_s_p9_2,
  131992. 1, -529268736, 1611661312, 5, 0,
  131993. _vq_quantlist__44c5_s_p9_2,
  131994. NULL,
  131995. &_vq_auxt__44c5_s_p9_2,
  131996. NULL,
  131997. 0
  131998. };
  131999. static long _huff_lengthlist__44c5_s_short[] = {
  132000. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132001. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132002. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132003. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132004. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132005. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132006. 6, 8,11,16,
  132007. };
  132008. static static_codebook _huff_book__44c5_s_short = {
  132009. 2, 100,
  132010. _huff_lengthlist__44c5_s_short,
  132011. 0, 0, 0, 0, 0,
  132012. NULL,
  132013. NULL,
  132014. NULL,
  132015. NULL,
  132016. 0
  132017. };
  132018. static long _huff_lengthlist__44c6_s_long[] = {
  132019. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132020. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132021. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132022. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132023. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132024. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132025. 11,10,10,12,
  132026. };
  132027. static static_codebook _huff_book__44c6_s_long = {
  132028. 2, 100,
  132029. _huff_lengthlist__44c6_s_long,
  132030. 0, 0, 0, 0, 0,
  132031. NULL,
  132032. NULL,
  132033. NULL,
  132034. NULL,
  132035. 0
  132036. };
  132037. static long _vq_quantlist__44c6_s_p1_0[] = {
  132038. 1,
  132039. 0,
  132040. 2,
  132041. };
  132042. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132043. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132044. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132045. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132046. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132047. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132048. 8,
  132049. };
  132050. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132051. -0.5, 0.5,
  132052. };
  132053. static long _vq_quantmap__44c6_s_p1_0[] = {
  132054. 1, 0, 2,
  132055. };
  132056. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132057. _vq_quantthresh__44c6_s_p1_0,
  132058. _vq_quantmap__44c6_s_p1_0,
  132059. 3,
  132060. 3
  132061. };
  132062. static static_codebook _44c6_s_p1_0 = {
  132063. 4, 81,
  132064. _vq_lengthlist__44c6_s_p1_0,
  132065. 1, -535822336, 1611661312, 2, 0,
  132066. _vq_quantlist__44c6_s_p1_0,
  132067. NULL,
  132068. &_vq_auxt__44c6_s_p1_0,
  132069. NULL,
  132070. 0
  132071. };
  132072. static long _vq_quantlist__44c6_s_p2_0[] = {
  132073. 2,
  132074. 1,
  132075. 3,
  132076. 0,
  132077. 4,
  132078. };
  132079. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132080. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132081. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132082. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132083. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132084. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132085. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132086. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132087. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132089. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132090. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132091. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132092. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132093. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132094. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132095. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132098. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132099. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132100. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132101. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132102. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132103. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132105. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132106. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132107. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132108. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132109. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132110. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132111. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132116. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132117. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132118. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132119. 13,
  132120. };
  132121. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132122. -1.5, -0.5, 0.5, 1.5,
  132123. };
  132124. static long _vq_quantmap__44c6_s_p2_0[] = {
  132125. 3, 1, 0, 2, 4,
  132126. };
  132127. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132128. _vq_quantthresh__44c6_s_p2_0,
  132129. _vq_quantmap__44c6_s_p2_0,
  132130. 5,
  132131. 5
  132132. };
  132133. static static_codebook _44c6_s_p2_0 = {
  132134. 4, 625,
  132135. _vq_lengthlist__44c6_s_p2_0,
  132136. 1, -533725184, 1611661312, 3, 0,
  132137. _vq_quantlist__44c6_s_p2_0,
  132138. NULL,
  132139. &_vq_auxt__44c6_s_p2_0,
  132140. NULL,
  132141. 0
  132142. };
  132143. static long _vq_quantlist__44c6_s_p3_0[] = {
  132144. 4,
  132145. 3,
  132146. 5,
  132147. 2,
  132148. 6,
  132149. 1,
  132150. 7,
  132151. 0,
  132152. 8,
  132153. };
  132154. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132155. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132156. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132157. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132158. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132160. 0,
  132161. };
  132162. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132163. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132164. };
  132165. static long _vq_quantmap__44c6_s_p3_0[] = {
  132166. 7, 5, 3, 1, 0, 2, 4, 6,
  132167. 8,
  132168. };
  132169. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132170. _vq_quantthresh__44c6_s_p3_0,
  132171. _vq_quantmap__44c6_s_p3_0,
  132172. 9,
  132173. 9
  132174. };
  132175. static static_codebook _44c6_s_p3_0 = {
  132176. 2, 81,
  132177. _vq_lengthlist__44c6_s_p3_0,
  132178. 1, -531628032, 1611661312, 4, 0,
  132179. _vq_quantlist__44c6_s_p3_0,
  132180. NULL,
  132181. &_vq_auxt__44c6_s_p3_0,
  132182. NULL,
  132183. 0
  132184. };
  132185. static long _vq_quantlist__44c6_s_p4_0[] = {
  132186. 8,
  132187. 7,
  132188. 9,
  132189. 6,
  132190. 10,
  132191. 5,
  132192. 11,
  132193. 4,
  132194. 12,
  132195. 3,
  132196. 13,
  132197. 2,
  132198. 14,
  132199. 1,
  132200. 15,
  132201. 0,
  132202. 16,
  132203. };
  132204. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132205. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132206. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132207. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132208. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132209. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132210. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132211. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132212. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132213. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132214. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 0,
  132224. };
  132225. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132226. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132227. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132228. };
  132229. static long _vq_quantmap__44c6_s_p4_0[] = {
  132230. 15, 13, 11, 9, 7, 5, 3, 1,
  132231. 0, 2, 4, 6, 8, 10, 12, 14,
  132232. 16,
  132233. };
  132234. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132235. _vq_quantthresh__44c6_s_p4_0,
  132236. _vq_quantmap__44c6_s_p4_0,
  132237. 17,
  132238. 17
  132239. };
  132240. static static_codebook _44c6_s_p4_0 = {
  132241. 2, 289,
  132242. _vq_lengthlist__44c6_s_p4_0,
  132243. 1, -529530880, 1611661312, 5, 0,
  132244. _vq_quantlist__44c6_s_p4_0,
  132245. NULL,
  132246. &_vq_auxt__44c6_s_p4_0,
  132247. NULL,
  132248. 0
  132249. };
  132250. static long _vq_quantlist__44c6_s_p5_0[] = {
  132251. 1,
  132252. 0,
  132253. 2,
  132254. };
  132255. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132256. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132257. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132258. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132259. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132260. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132261. 12,
  132262. };
  132263. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132264. -5.5, 5.5,
  132265. };
  132266. static long _vq_quantmap__44c6_s_p5_0[] = {
  132267. 1, 0, 2,
  132268. };
  132269. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132270. _vq_quantthresh__44c6_s_p5_0,
  132271. _vq_quantmap__44c6_s_p5_0,
  132272. 3,
  132273. 3
  132274. };
  132275. static static_codebook _44c6_s_p5_0 = {
  132276. 4, 81,
  132277. _vq_lengthlist__44c6_s_p5_0,
  132278. 1, -529137664, 1618345984, 2, 0,
  132279. _vq_quantlist__44c6_s_p5_0,
  132280. NULL,
  132281. &_vq_auxt__44c6_s_p5_0,
  132282. NULL,
  132283. 0
  132284. };
  132285. static long _vq_quantlist__44c6_s_p5_1[] = {
  132286. 5,
  132287. 4,
  132288. 6,
  132289. 3,
  132290. 7,
  132291. 2,
  132292. 8,
  132293. 1,
  132294. 9,
  132295. 0,
  132296. 10,
  132297. };
  132298. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132299. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132300. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132301. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132302. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132303. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132304. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132305. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132306. 11,10,10, 7, 7, 8, 8, 8, 8,
  132307. };
  132308. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132309. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132310. 3.5, 4.5,
  132311. };
  132312. static long _vq_quantmap__44c6_s_p5_1[] = {
  132313. 9, 7, 5, 3, 1, 0, 2, 4,
  132314. 6, 8, 10,
  132315. };
  132316. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132317. _vq_quantthresh__44c6_s_p5_1,
  132318. _vq_quantmap__44c6_s_p5_1,
  132319. 11,
  132320. 11
  132321. };
  132322. static static_codebook _44c6_s_p5_1 = {
  132323. 2, 121,
  132324. _vq_lengthlist__44c6_s_p5_1,
  132325. 1, -531365888, 1611661312, 4, 0,
  132326. _vq_quantlist__44c6_s_p5_1,
  132327. NULL,
  132328. &_vq_auxt__44c6_s_p5_1,
  132329. NULL,
  132330. 0
  132331. };
  132332. static long _vq_quantlist__44c6_s_p6_0[] = {
  132333. 6,
  132334. 5,
  132335. 7,
  132336. 4,
  132337. 8,
  132338. 3,
  132339. 9,
  132340. 2,
  132341. 10,
  132342. 1,
  132343. 11,
  132344. 0,
  132345. 12,
  132346. };
  132347. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132348. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132349. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132350. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132351. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132352. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132353. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132358. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132359. };
  132360. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132361. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132362. 12.5, 17.5, 22.5, 27.5,
  132363. };
  132364. static long _vq_quantmap__44c6_s_p6_0[] = {
  132365. 11, 9, 7, 5, 3, 1, 0, 2,
  132366. 4, 6, 8, 10, 12,
  132367. };
  132368. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132369. _vq_quantthresh__44c6_s_p6_0,
  132370. _vq_quantmap__44c6_s_p6_0,
  132371. 13,
  132372. 13
  132373. };
  132374. static static_codebook _44c6_s_p6_0 = {
  132375. 2, 169,
  132376. _vq_lengthlist__44c6_s_p6_0,
  132377. 1, -526516224, 1616117760, 4, 0,
  132378. _vq_quantlist__44c6_s_p6_0,
  132379. NULL,
  132380. &_vq_auxt__44c6_s_p6_0,
  132381. NULL,
  132382. 0
  132383. };
  132384. static long _vq_quantlist__44c6_s_p6_1[] = {
  132385. 2,
  132386. 1,
  132387. 3,
  132388. 0,
  132389. 4,
  132390. };
  132391. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132392. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132393. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132394. };
  132395. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132396. -1.5, -0.5, 0.5, 1.5,
  132397. };
  132398. static long _vq_quantmap__44c6_s_p6_1[] = {
  132399. 3, 1, 0, 2, 4,
  132400. };
  132401. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132402. _vq_quantthresh__44c6_s_p6_1,
  132403. _vq_quantmap__44c6_s_p6_1,
  132404. 5,
  132405. 5
  132406. };
  132407. static static_codebook _44c6_s_p6_1 = {
  132408. 2, 25,
  132409. _vq_lengthlist__44c6_s_p6_1,
  132410. 1, -533725184, 1611661312, 3, 0,
  132411. _vq_quantlist__44c6_s_p6_1,
  132412. NULL,
  132413. &_vq_auxt__44c6_s_p6_1,
  132414. NULL,
  132415. 0
  132416. };
  132417. static long _vq_quantlist__44c6_s_p7_0[] = {
  132418. 6,
  132419. 5,
  132420. 7,
  132421. 4,
  132422. 8,
  132423. 3,
  132424. 9,
  132425. 2,
  132426. 10,
  132427. 1,
  132428. 11,
  132429. 0,
  132430. 12,
  132431. };
  132432. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132433. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132434. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132435. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132436. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132437. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132438. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132439. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132440. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132441. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132442. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132443. 20,13,13,13,13,13,13,14,14,
  132444. };
  132445. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132446. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132447. 27.5, 38.5, 49.5, 60.5,
  132448. };
  132449. static long _vq_quantmap__44c6_s_p7_0[] = {
  132450. 11, 9, 7, 5, 3, 1, 0, 2,
  132451. 4, 6, 8, 10, 12,
  132452. };
  132453. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132454. _vq_quantthresh__44c6_s_p7_0,
  132455. _vq_quantmap__44c6_s_p7_0,
  132456. 13,
  132457. 13
  132458. };
  132459. static static_codebook _44c6_s_p7_0 = {
  132460. 2, 169,
  132461. _vq_lengthlist__44c6_s_p7_0,
  132462. 1, -523206656, 1618345984, 4, 0,
  132463. _vq_quantlist__44c6_s_p7_0,
  132464. NULL,
  132465. &_vq_auxt__44c6_s_p7_0,
  132466. NULL,
  132467. 0
  132468. };
  132469. static long _vq_quantlist__44c6_s_p7_1[] = {
  132470. 5,
  132471. 4,
  132472. 6,
  132473. 3,
  132474. 7,
  132475. 2,
  132476. 8,
  132477. 1,
  132478. 9,
  132479. 0,
  132480. 10,
  132481. };
  132482. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132483. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132484. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132485. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132486. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132487. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132488. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132489. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132490. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132491. };
  132492. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132493. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132494. 3.5, 4.5,
  132495. };
  132496. static long _vq_quantmap__44c6_s_p7_1[] = {
  132497. 9, 7, 5, 3, 1, 0, 2, 4,
  132498. 6, 8, 10,
  132499. };
  132500. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132501. _vq_quantthresh__44c6_s_p7_1,
  132502. _vq_quantmap__44c6_s_p7_1,
  132503. 11,
  132504. 11
  132505. };
  132506. static static_codebook _44c6_s_p7_1 = {
  132507. 2, 121,
  132508. _vq_lengthlist__44c6_s_p7_1,
  132509. 1, -531365888, 1611661312, 4, 0,
  132510. _vq_quantlist__44c6_s_p7_1,
  132511. NULL,
  132512. &_vq_auxt__44c6_s_p7_1,
  132513. NULL,
  132514. 0
  132515. };
  132516. static long _vq_quantlist__44c6_s_p8_0[] = {
  132517. 7,
  132518. 6,
  132519. 8,
  132520. 5,
  132521. 9,
  132522. 4,
  132523. 10,
  132524. 3,
  132525. 11,
  132526. 2,
  132527. 12,
  132528. 1,
  132529. 13,
  132530. 0,
  132531. 14,
  132532. };
  132533. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132534. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132535. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132536. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132537. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132538. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132539. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132540. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132541. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132542. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132543. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132544. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132545. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132546. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132547. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132548. 14,
  132549. };
  132550. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132551. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132552. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132553. };
  132554. static long _vq_quantmap__44c6_s_p8_0[] = {
  132555. 13, 11, 9, 7, 5, 3, 1, 0,
  132556. 2, 4, 6, 8, 10, 12, 14,
  132557. };
  132558. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132559. _vq_quantthresh__44c6_s_p8_0,
  132560. _vq_quantmap__44c6_s_p8_0,
  132561. 15,
  132562. 15
  132563. };
  132564. static static_codebook _44c6_s_p8_0 = {
  132565. 2, 225,
  132566. _vq_lengthlist__44c6_s_p8_0,
  132567. 1, -520986624, 1620377600, 4, 0,
  132568. _vq_quantlist__44c6_s_p8_0,
  132569. NULL,
  132570. &_vq_auxt__44c6_s_p8_0,
  132571. NULL,
  132572. 0
  132573. };
  132574. static long _vq_quantlist__44c6_s_p8_1[] = {
  132575. 10,
  132576. 9,
  132577. 11,
  132578. 8,
  132579. 12,
  132580. 7,
  132581. 13,
  132582. 6,
  132583. 14,
  132584. 5,
  132585. 15,
  132586. 4,
  132587. 16,
  132588. 3,
  132589. 17,
  132590. 2,
  132591. 18,
  132592. 1,
  132593. 19,
  132594. 0,
  132595. 20,
  132596. };
  132597. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132598. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132599. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132600. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132601. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132602. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132603. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132604. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132605. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132606. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132607. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132608. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132609. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132610. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132611. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132612. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132613. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132614. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132615. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132616. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132617. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132618. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132619. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132620. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132621. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132622. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132623. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132624. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132625. 10,10,10,10,10,10,10,10,10,
  132626. };
  132627. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132628. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132629. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132630. 6.5, 7.5, 8.5, 9.5,
  132631. };
  132632. static long _vq_quantmap__44c6_s_p8_1[] = {
  132633. 19, 17, 15, 13, 11, 9, 7, 5,
  132634. 3, 1, 0, 2, 4, 6, 8, 10,
  132635. 12, 14, 16, 18, 20,
  132636. };
  132637. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132638. _vq_quantthresh__44c6_s_p8_1,
  132639. _vq_quantmap__44c6_s_p8_1,
  132640. 21,
  132641. 21
  132642. };
  132643. static static_codebook _44c6_s_p8_1 = {
  132644. 2, 441,
  132645. _vq_lengthlist__44c6_s_p8_1,
  132646. 1, -529268736, 1611661312, 5, 0,
  132647. _vq_quantlist__44c6_s_p8_1,
  132648. NULL,
  132649. &_vq_auxt__44c6_s_p8_1,
  132650. NULL,
  132651. 0
  132652. };
  132653. static long _vq_quantlist__44c6_s_p9_0[] = {
  132654. 6,
  132655. 5,
  132656. 7,
  132657. 4,
  132658. 8,
  132659. 3,
  132660. 9,
  132661. 2,
  132662. 10,
  132663. 1,
  132664. 11,
  132665. 0,
  132666. 12,
  132667. };
  132668. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132669. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132670. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132671. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132672. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132673. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132674. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132675. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132676. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132677. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132678. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132679. 10,10,10,10,10,10,10,10,10,
  132680. };
  132681. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132682. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132683. 1592.5, 2229.5, 2866.5, 3503.5,
  132684. };
  132685. static long _vq_quantmap__44c6_s_p9_0[] = {
  132686. 11, 9, 7, 5, 3, 1, 0, 2,
  132687. 4, 6, 8, 10, 12,
  132688. };
  132689. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132690. _vq_quantthresh__44c6_s_p9_0,
  132691. _vq_quantmap__44c6_s_p9_0,
  132692. 13,
  132693. 13
  132694. };
  132695. static static_codebook _44c6_s_p9_0 = {
  132696. 2, 169,
  132697. _vq_lengthlist__44c6_s_p9_0,
  132698. 1, -511845376, 1630791680, 4, 0,
  132699. _vq_quantlist__44c6_s_p9_0,
  132700. NULL,
  132701. &_vq_auxt__44c6_s_p9_0,
  132702. NULL,
  132703. 0
  132704. };
  132705. static long _vq_quantlist__44c6_s_p9_1[] = {
  132706. 6,
  132707. 5,
  132708. 7,
  132709. 4,
  132710. 8,
  132711. 3,
  132712. 9,
  132713. 2,
  132714. 10,
  132715. 1,
  132716. 11,
  132717. 0,
  132718. 12,
  132719. };
  132720. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132721. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132722. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132723. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132724. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132725. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132726. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132727. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132728. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132729. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132730. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132731. 15,12,10,11,11,13,11,12,13,
  132732. };
  132733. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132734. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132735. 122.5, 171.5, 220.5, 269.5,
  132736. };
  132737. static long _vq_quantmap__44c6_s_p9_1[] = {
  132738. 11, 9, 7, 5, 3, 1, 0, 2,
  132739. 4, 6, 8, 10, 12,
  132740. };
  132741. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132742. _vq_quantthresh__44c6_s_p9_1,
  132743. _vq_quantmap__44c6_s_p9_1,
  132744. 13,
  132745. 13
  132746. };
  132747. static static_codebook _44c6_s_p9_1 = {
  132748. 2, 169,
  132749. _vq_lengthlist__44c6_s_p9_1,
  132750. 1, -518889472, 1622704128, 4, 0,
  132751. _vq_quantlist__44c6_s_p9_1,
  132752. NULL,
  132753. &_vq_auxt__44c6_s_p9_1,
  132754. NULL,
  132755. 0
  132756. };
  132757. static long _vq_quantlist__44c6_s_p9_2[] = {
  132758. 24,
  132759. 23,
  132760. 25,
  132761. 22,
  132762. 26,
  132763. 21,
  132764. 27,
  132765. 20,
  132766. 28,
  132767. 19,
  132768. 29,
  132769. 18,
  132770. 30,
  132771. 17,
  132772. 31,
  132773. 16,
  132774. 32,
  132775. 15,
  132776. 33,
  132777. 14,
  132778. 34,
  132779. 13,
  132780. 35,
  132781. 12,
  132782. 36,
  132783. 11,
  132784. 37,
  132785. 10,
  132786. 38,
  132787. 9,
  132788. 39,
  132789. 8,
  132790. 40,
  132791. 7,
  132792. 41,
  132793. 6,
  132794. 42,
  132795. 5,
  132796. 43,
  132797. 4,
  132798. 44,
  132799. 3,
  132800. 45,
  132801. 2,
  132802. 46,
  132803. 1,
  132804. 47,
  132805. 0,
  132806. 48,
  132807. };
  132808. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132809. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132810. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132811. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132812. 7,
  132813. };
  132814. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132815. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132816. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132817. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132818. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132819. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132820. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132821. };
  132822. static long _vq_quantmap__44c6_s_p9_2[] = {
  132823. 47, 45, 43, 41, 39, 37, 35, 33,
  132824. 31, 29, 27, 25, 23, 21, 19, 17,
  132825. 15, 13, 11, 9, 7, 5, 3, 1,
  132826. 0, 2, 4, 6, 8, 10, 12, 14,
  132827. 16, 18, 20, 22, 24, 26, 28, 30,
  132828. 32, 34, 36, 38, 40, 42, 44, 46,
  132829. 48,
  132830. };
  132831. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132832. _vq_quantthresh__44c6_s_p9_2,
  132833. _vq_quantmap__44c6_s_p9_2,
  132834. 49,
  132835. 49
  132836. };
  132837. static static_codebook _44c6_s_p9_2 = {
  132838. 1, 49,
  132839. _vq_lengthlist__44c6_s_p9_2,
  132840. 1, -526909440, 1611661312, 6, 0,
  132841. _vq_quantlist__44c6_s_p9_2,
  132842. NULL,
  132843. &_vq_auxt__44c6_s_p9_2,
  132844. NULL,
  132845. 0
  132846. };
  132847. static long _huff_lengthlist__44c6_s_short[] = {
  132848. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132849. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132850. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132851. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132852. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132853. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132854. 9,10,17,18,
  132855. };
  132856. static static_codebook _huff_book__44c6_s_short = {
  132857. 2, 100,
  132858. _huff_lengthlist__44c6_s_short,
  132859. 0, 0, 0, 0, 0,
  132860. NULL,
  132861. NULL,
  132862. NULL,
  132863. NULL,
  132864. 0
  132865. };
  132866. static long _huff_lengthlist__44c7_s_long[] = {
  132867. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132868. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132869. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132870. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132871. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132872. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132873. 11,10,10,12,
  132874. };
  132875. static static_codebook _huff_book__44c7_s_long = {
  132876. 2, 100,
  132877. _huff_lengthlist__44c7_s_long,
  132878. 0, 0, 0, 0, 0,
  132879. NULL,
  132880. NULL,
  132881. NULL,
  132882. NULL,
  132883. 0
  132884. };
  132885. static long _vq_quantlist__44c7_s_p1_0[] = {
  132886. 1,
  132887. 0,
  132888. 2,
  132889. };
  132890. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132891. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132892. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132893. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132894. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132895. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132896. 8,
  132897. };
  132898. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132899. -0.5, 0.5,
  132900. };
  132901. static long _vq_quantmap__44c7_s_p1_0[] = {
  132902. 1, 0, 2,
  132903. };
  132904. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132905. _vq_quantthresh__44c7_s_p1_0,
  132906. _vq_quantmap__44c7_s_p1_0,
  132907. 3,
  132908. 3
  132909. };
  132910. static static_codebook _44c7_s_p1_0 = {
  132911. 4, 81,
  132912. _vq_lengthlist__44c7_s_p1_0,
  132913. 1, -535822336, 1611661312, 2, 0,
  132914. _vq_quantlist__44c7_s_p1_0,
  132915. NULL,
  132916. &_vq_auxt__44c7_s_p1_0,
  132917. NULL,
  132918. 0
  132919. };
  132920. static long _vq_quantlist__44c7_s_p2_0[] = {
  132921. 2,
  132922. 1,
  132923. 3,
  132924. 0,
  132925. 4,
  132926. };
  132927. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132928. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132929. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132930. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132931. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132932. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132933. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132934. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132935. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132937. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132938. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132939. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132940. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132941. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132942. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132943. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132945. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132946. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132947. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132948. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132949. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132950. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132951. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132953. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132954. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132955. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132956. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132957. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132958. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132959. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132964. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132965. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132966. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132967. 13,
  132968. };
  132969. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132970. -1.5, -0.5, 0.5, 1.5,
  132971. };
  132972. static long _vq_quantmap__44c7_s_p2_0[] = {
  132973. 3, 1, 0, 2, 4,
  132974. };
  132975. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132976. _vq_quantthresh__44c7_s_p2_0,
  132977. _vq_quantmap__44c7_s_p2_0,
  132978. 5,
  132979. 5
  132980. };
  132981. static static_codebook _44c7_s_p2_0 = {
  132982. 4, 625,
  132983. _vq_lengthlist__44c7_s_p2_0,
  132984. 1, -533725184, 1611661312, 3, 0,
  132985. _vq_quantlist__44c7_s_p2_0,
  132986. NULL,
  132987. &_vq_auxt__44c7_s_p2_0,
  132988. NULL,
  132989. 0
  132990. };
  132991. static long _vq_quantlist__44c7_s_p3_0[] = {
  132992. 4,
  132993. 3,
  132994. 5,
  132995. 2,
  132996. 6,
  132997. 1,
  132998. 7,
  132999. 0,
  133000. 8,
  133001. };
  133002. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133003. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133004. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133005. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133006. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133008. 0,
  133009. };
  133010. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133011. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133012. };
  133013. static long _vq_quantmap__44c7_s_p3_0[] = {
  133014. 7, 5, 3, 1, 0, 2, 4, 6,
  133015. 8,
  133016. };
  133017. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133018. _vq_quantthresh__44c7_s_p3_0,
  133019. _vq_quantmap__44c7_s_p3_0,
  133020. 9,
  133021. 9
  133022. };
  133023. static static_codebook _44c7_s_p3_0 = {
  133024. 2, 81,
  133025. _vq_lengthlist__44c7_s_p3_0,
  133026. 1, -531628032, 1611661312, 4, 0,
  133027. _vq_quantlist__44c7_s_p3_0,
  133028. NULL,
  133029. &_vq_auxt__44c7_s_p3_0,
  133030. NULL,
  133031. 0
  133032. };
  133033. static long _vq_quantlist__44c7_s_p4_0[] = {
  133034. 8,
  133035. 7,
  133036. 9,
  133037. 6,
  133038. 10,
  133039. 5,
  133040. 11,
  133041. 4,
  133042. 12,
  133043. 3,
  133044. 13,
  133045. 2,
  133046. 14,
  133047. 1,
  133048. 15,
  133049. 0,
  133050. 16,
  133051. };
  133052. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133053. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133054. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133055. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133056. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133057. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133058. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133059. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133060. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133061. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133062. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 0,
  133072. };
  133073. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133074. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133075. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133076. };
  133077. static long _vq_quantmap__44c7_s_p4_0[] = {
  133078. 15, 13, 11, 9, 7, 5, 3, 1,
  133079. 0, 2, 4, 6, 8, 10, 12, 14,
  133080. 16,
  133081. };
  133082. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133083. _vq_quantthresh__44c7_s_p4_0,
  133084. _vq_quantmap__44c7_s_p4_0,
  133085. 17,
  133086. 17
  133087. };
  133088. static static_codebook _44c7_s_p4_0 = {
  133089. 2, 289,
  133090. _vq_lengthlist__44c7_s_p4_0,
  133091. 1, -529530880, 1611661312, 5, 0,
  133092. _vq_quantlist__44c7_s_p4_0,
  133093. NULL,
  133094. &_vq_auxt__44c7_s_p4_0,
  133095. NULL,
  133096. 0
  133097. };
  133098. static long _vq_quantlist__44c7_s_p5_0[] = {
  133099. 1,
  133100. 0,
  133101. 2,
  133102. };
  133103. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133104. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133105. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133106. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133107. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133108. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133109. 12,
  133110. };
  133111. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133112. -5.5, 5.5,
  133113. };
  133114. static long _vq_quantmap__44c7_s_p5_0[] = {
  133115. 1, 0, 2,
  133116. };
  133117. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133118. _vq_quantthresh__44c7_s_p5_0,
  133119. _vq_quantmap__44c7_s_p5_0,
  133120. 3,
  133121. 3
  133122. };
  133123. static static_codebook _44c7_s_p5_0 = {
  133124. 4, 81,
  133125. _vq_lengthlist__44c7_s_p5_0,
  133126. 1, -529137664, 1618345984, 2, 0,
  133127. _vq_quantlist__44c7_s_p5_0,
  133128. NULL,
  133129. &_vq_auxt__44c7_s_p5_0,
  133130. NULL,
  133131. 0
  133132. };
  133133. static long _vq_quantlist__44c7_s_p5_1[] = {
  133134. 5,
  133135. 4,
  133136. 6,
  133137. 3,
  133138. 7,
  133139. 2,
  133140. 8,
  133141. 1,
  133142. 9,
  133143. 0,
  133144. 10,
  133145. };
  133146. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133147. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133148. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133149. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133150. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133151. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133152. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133153. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133154. 11,11,11, 7, 7, 8, 8, 8, 8,
  133155. };
  133156. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133157. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133158. 3.5, 4.5,
  133159. };
  133160. static long _vq_quantmap__44c7_s_p5_1[] = {
  133161. 9, 7, 5, 3, 1, 0, 2, 4,
  133162. 6, 8, 10,
  133163. };
  133164. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133165. _vq_quantthresh__44c7_s_p5_1,
  133166. _vq_quantmap__44c7_s_p5_1,
  133167. 11,
  133168. 11
  133169. };
  133170. static static_codebook _44c7_s_p5_1 = {
  133171. 2, 121,
  133172. _vq_lengthlist__44c7_s_p5_1,
  133173. 1, -531365888, 1611661312, 4, 0,
  133174. _vq_quantlist__44c7_s_p5_1,
  133175. NULL,
  133176. &_vq_auxt__44c7_s_p5_1,
  133177. NULL,
  133178. 0
  133179. };
  133180. static long _vq_quantlist__44c7_s_p6_0[] = {
  133181. 6,
  133182. 5,
  133183. 7,
  133184. 4,
  133185. 8,
  133186. 3,
  133187. 9,
  133188. 2,
  133189. 10,
  133190. 1,
  133191. 11,
  133192. 0,
  133193. 12,
  133194. };
  133195. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133196. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133197. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133198. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133199. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133200. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133201. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133206. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133207. };
  133208. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133209. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133210. 12.5, 17.5, 22.5, 27.5,
  133211. };
  133212. static long _vq_quantmap__44c7_s_p6_0[] = {
  133213. 11, 9, 7, 5, 3, 1, 0, 2,
  133214. 4, 6, 8, 10, 12,
  133215. };
  133216. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133217. _vq_quantthresh__44c7_s_p6_0,
  133218. _vq_quantmap__44c7_s_p6_0,
  133219. 13,
  133220. 13
  133221. };
  133222. static static_codebook _44c7_s_p6_0 = {
  133223. 2, 169,
  133224. _vq_lengthlist__44c7_s_p6_0,
  133225. 1, -526516224, 1616117760, 4, 0,
  133226. _vq_quantlist__44c7_s_p6_0,
  133227. NULL,
  133228. &_vq_auxt__44c7_s_p6_0,
  133229. NULL,
  133230. 0
  133231. };
  133232. static long _vq_quantlist__44c7_s_p6_1[] = {
  133233. 2,
  133234. 1,
  133235. 3,
  133236. 0,
  133237. 4,
  133238. };
  133239. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133240. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133241. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133242. };
  133243. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133244. -1.5, -0.5, 0.5, 1.5,
  133245. };
  133246. static long _vq_quantmap__44c7_s_p6_1[] = {
  133247. 3, 1, 0, 2, 4,
  133248. };
  133249. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133250. _vq_quantthresh__44c7_s_p6_1,
  133251. _vq_quantmap__44c7_s_p6_1,
  133252. 5,
  133253. 5
  133254. };
  133255. static static_codebook _44c7_s_p6_1 = {
  133256. 2, 25,
  133257. _vq_lengthlist__44c7_s_p6_1,
  133258. 1, -533725184, 1611661312, 3, 0,
  133259. _vq_quantlist__44c7_s_p6_1,
  133260. NULL,
  133261. &_vq_auxt__44c7_s_p6_1,
  133262. NULL,
  133263. 0
  133264. };
  133265. static long _vq_quantlist__44c7_s_p7_0[] = {
  133266. 6,
  133267. 5,
  133268. 7,
  133269. 4,
  133270. 8,
  133271. 3,
  133272. 9,
  133273. 2,
  133274. 10,
  133275. 1,
  133276. 11,
  133277. 0,
  133278. 12,
  133279. };
  133280. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133281. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133282. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133283. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133284. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133285. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133286. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133287. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133288. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133289. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133290. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133291. 19,13,13,13,13,14,14,15,15,
  133292. };
  133293. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133294. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133295. 27.5, 38.5, 49.5, 60.5,
  133296. };
  133297. static long _vq_quantmap__44c7_s_p7_0[] = {
  133298. 11, 9, 7, 5, 3, 1, 0, 2,
  133299. 4, 6, 8, 10, 12,
  133300. };
  133301. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133302. _vq_quantthresh__44c7_s_p7_0,
  133303. _vq_quantmap__44c7_s_p7_0,
  133304. 13,
  133305. 13
  133306. };
  133307. static static_codebook _44c7_s_p7_0 = {
  133308. 2, 169,
  133309. _vq_lengthlist__44c7_s_p7_0,
  133310. 1, -523206656, 1618345984, 4, 0,
  133311. _vq_quantlist__44c7_s_p7_0,
  133312. NULL,
  133313. &_vq_auxt__44c7_s_p7_0,
  133314. NULL,
  133315. 0
  133316. };
  133317. static long _vq_quantlist__44c7_s_p7_1[] = {
  133318. 5,
  133319. 4,
  133320. 6,
  133321. 3,
  133322. 7,
  133323. 2,
  133324. 8,
  133325. 1,
  133326. 9,
  133327. 0,
  133328. 10,
  133329. };
  133330. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133331. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133332. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133333. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133334. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133335. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133336. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133337. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133338. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133339. };
  133340. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133341. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133342. 3.5, 4.5,
  133343. };
  133344. static long _vq_quantmap__44c7_s_p7_1[] = {
  133345. 9, 7, 5, 3, 1, 0, 2, 4,
  133346. 6, 8, 10,
  133347. };
  133348. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133349. _vq_quantthresh__44c7_s_p7_1,
  133350. _vq_quantmap__44c7_s_p7_1,
  133351. 11,
  133352. 11
  133353. };
  133354. static static_codebook _44c7_s_p7_1 = {
  133355. 2, 121,
  133356. _vq_lengthlist__44c7_s_p7_1,
  133357. 1, -531365888, 1611661312, 4, 0,
  133358. _vq_quantlist__44c7_s_p7_1,
  133359. NULL,
  133360. &_vq_auxt__44c7_s_p7_1,
  133361. NULL,
  133362. 0
  133363. };
  133364. static long _vq_quantlist__44c7_s_p8_0[] = {
  133365. 7,
  133366. 6,
  133367. 8,
  133368. 5,
  133369. 9,
  133370. 4,
  133371. 10,
  133372. 3,
  133373. 11,
  133374. 2,
  133375. 12,
  133376. 1,
  133377. 13,
  133378. 0,
  133379. 14,
  133380. };
  133381. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133382. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133383. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133384. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133385. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133386. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133387. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133388. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133389. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133390. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133391. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133392. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133393. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133394. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133395. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133396. 14,
  133397. };
  133398. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133399. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133400. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133401. };
  133402. static long _vq_quantmap__44c7_s_p8_0[] = {
  133403. 13, 11, 9, 7, 5, 3, 1, 0,
  133404. 2, 4, 6, 8, 10, 12, 14,
  133405. };
  133406. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133407. _vq_quantthresh__44c7_s_p8_0,
  133408. _vq_quantmap__44c7_s_p8_0,
  133409. 15,
  133410. 15
  133411. };
  133412. static static_codebook _44c7_s_p8_0 = {
  133413. 2, 225,
  133414. _vq_lengthlist__44c7_s_p8_0,
  133415. 1, -520986624, 1620377600, 4, 0,
  133416. _vq_quantlist__44c7_s_p8_0,
  133417. NULL,
  133418. &_vq_auxt__44c7_s_p8_0,
  133419. NULL,
  133420. 0
  133421. };
  133422. static long _vq_quantlist__44c7_s_p8_1[] = {
  133423. 10,
  133424. 9,
  133425. 11,
  133426. 8,
  133427. 12,
  133428. 7,
  133429. 13,
  133430. 6,
  133431. 14,
  133432. 5,
  133433. 15,
  133434. 4,
  133435. 16,
  133436. 3,
  133437. 17,
  133438. 2,
  133439. 18,
  133440. 1,
  133441. 19,
  133442. 0,
  133443. 20,
  133444. };
  133445. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133446. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133447. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133448. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133449. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133450. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133451. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133452. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133453. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133454. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133455. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133456. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133457. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133458. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133459. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133460. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133461. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133462. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133463. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133464. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133465. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133466. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133467. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133468. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133469. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133470. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133471. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133472. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133473. 10,10,10,10,10,10,10,10,10,
  133474. };
  133475. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133476. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133477. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133478. 6.5, 7.5, 8.5, 9.5,
  133479. };
  133480. static long _vq_quantmap__44c7_s_p8_1[] = {
  133481. 19, 17, 15, 13, 11, 9, 7, 5,
  133482. 3, 1, 0, 2, 4, 6, 8, 10,
  133483. 12, 14, 16, 18, 20,
  133484. };
  133485. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133486. _vq_quantthresh__44c7_s_p8_1,
  133487. _vq_quantmap__44c7_s_p8_1,
  133488. 21,
  133489. 21
  133490. };
  133491. static static_codebook _44c7_s_p8_1 = {
  133492. 2, 441,
  133493. _vq_lengthlist__44c7_s_p8_1,
  133494. 1, -529268736, 1611661312, 5, 0,
  133495. _vq_quantlist__44c7_s_p8_1,
  133496. NULL,
  133497. &_vq_auxt__44c7_s_p8_1,
  133498. NULL,
  133499. 0
  133500. };
  133501. static long _vq_quantlist__44c7_s_p9_0[] = {
  133502. 6,
  133503. 5,
  133504. 7,
  133505. 4,
  133506. 8,
  133507. 3,
  133508. 9,
  133509. 2,
  133510. 10,
  133511. 1,
  133512. 11,
  133513. 0,
  133514. 12,
  133515. };
  133516. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133517. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133518. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133522. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133523. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133524. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133525. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133526. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133527. 11,11,11,11,11,11,11,11,11,
  133528. };
  133529. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133530. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133531. 1592.5, 2229.5, 2866.5, 3503.5,
  133532. };
  133533. static long _vq_quantmap__44c7_s_p9_0[] = {
  133534. 11, 9, 7, 5, 3, 1, 0, 2,
  133535. 4, 6, 8, 10, 12,
  133536. };
  133537. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133538. _vq_quantthresh__44c7_s_p9_0,
  133539. _vq_quantmap__44c7_s_p9_0,
  133540. 13,
  133541. 13
  133542. };
  133543. static static_codebook _44c7_s_p9_0 = {
  133544. 2, 169,
  133545. _vq_lengthlist__44c7_s_p9_0,
  133546. 1, -511845376, 1630791680, 4, 0,
  133547. _vq_quantlist__44c7_s_p9_0,
  133548. NULL,
  133549. &_vq_auxt__44c7_s_p9_0,
  133550. NULL,
  133551. 0
  133552. };
  133553. static long _vq_quantlist__44c7_s_p9_1[] = {
  133554. 6,
  133555. 5,
  133556. 7,
  133557. 4,
  133558. 8,
  133559. 3,
  133560. 9,
  133561. 2,
  133562. 10,
  133563. 1,
  133564. 11,
  133565. 0,
  133566. 12,
  133567. };
  133568. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133569. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133570. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133571. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133572. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133573. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133574. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133575. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133576. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133577. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133578. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133579. 15,11,11,10,10,12,12,12,12,
  133580. };
  133581. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133582. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133583. 122.5, 171.5, 220.5, 269.5,
  133584. };
  133585. static long _vq_quantmap__44c7_s_p9_1[] = {
  133586. 11, 9, 7, 5, 3, 1, 0, 2,
  133587. 4, 6, 8, 10, 12,
  133588. };
  133589. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133590. _vq_quantthresh__44c7_s_p9_1,
  133591. _vq_quantmap__44c7_s_p9_1,
  133592. 13,
  133593. 13
  133594. };
  133595. static static_codebook _44c7_s_p9_1 = {
  133596. 2, 169,
  133597. _vq_lengthlist__44c7_s_p9_1,
  133598. 1, -518889472, 1622704128, 4, 0,
  133599. _vq_quantlist__44c7_s_p9_1,
  133600. NULL,
  133601. &_vq_auxt__44c7_s_p9_1,
  133602. NULL,
  133603. 0
  133604. };
  133605. static long _vq_quantlist__44c7_s_p9_2[] = {
  133606. 24,
  133607. 23,
  133608. 25,
  133609. 22,
  133610. 26,
  133611. 21,
  133612. 27,
  133613. 20,
  133614. 28,
  133615. 19,
  133616. 29,
  133617. 18,
  133618. 30,
  133619. 17,
  133620. 31,
  133621. 16,
  133622. 32,
  133623. 15,
  133624. 33,
  133625. 14,
  133626. 34,
  133627. 13,
  133628. 35,
  133629. 12,
  133630. 36,
  133631. 11,
  133632. 37,
  133633. 10,
  133634. 38,
  133635. 9,
  133636. 39,
  133637. 8,
  133638. 40,
  133639. 7,
  133640. 41,
  133641. 6,
  133642. 42,
  133643. 5,
  133644. 43,
  133645. 4,
  133646. 44,
  133647. 3,
  133648. 45,
  133649. 2,
  133650. 46,
  133651. 1,
  133652. 47,
  133653. 0,
  133654. 48,
  133655. };
  133656. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133657. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133658. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133659. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133660. 7,
  133661. };
  133662. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133663. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133664. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133665. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133666. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133667. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133668. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133669. };
  133670. static long _vq_quantmap__44c7_s_p9_2[] = {
  133671. 47, 45, 43, 41, 39, 37, 35, 33,
  133672. 31, 29, 27, 25, 23, 21, 19, 17,
  133673. 15, 13, 11, 9, 7, 5, 3, 1,
  133674. 0, 2, 4, 6, 8, 10, 12, 14,
  133675. 16, 18, 20, 22, 24, 26, 28, 30,
  133676. 32, 34, 36, 38, 40, 42, 44, 46,
  133677. 48,
  133678. };
  133679. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133680. _vq_quantthresh__44c7_s_p9_2,
  133681. _vq_quantmap__44c7_s_p9_2,
  133682. 49,
  133683. 49
  133684. };
  133685. static static_codebook _44c7_s_p9_2 = {
  133686. 1, 49,
  133687. _vq_lengthlist__44c7_s_p9_2,
  133688. 1, -526909440, 1611661312, 6, 0,
  133689. _vq_quantlist__44c7_s_p9_2,
  133690. NULL,
  133691. &_vq_auxt__44c7_s_p9_2,
  133692. NULL,
  133693. 0
  133694. };
  133695. static long _huff_lengthlist__44c7_s_short[] = {
  133696. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133697. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133698. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133699. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133700. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133701. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133702. 10, 9,11,14,
  133703. };
  133704. static static_codebook _huff_book__44c7_s_short = {
  133705. 2, 100,
  133706. _huff_lengthlist__44c7_s_short,
  133707. 0, 0, 0, 0, 0,
  133708. NULL,
  133709. NULL,
  133710. NULL,
  133711. NULL,
  133712. 0
  133713. };
  133714. static long _huff_lengthlist__44c8_s_long[] = {
  133715. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133716. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133717. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133718. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133719. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133720. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133721. 11, 9, 9,10,
  133722. };
  133723. static static_codebook _huff_book__44c8_s_long = {
  133724. 2, 100,
  133725. _huff_lengthlist__44c8_s_long,
  133726. 0, 0, 0, 0, 0,
  133727. NULL,
  133728. NULL,
  133729. NULL,
  133730. NULL,
  133731. 0
  133732. };
  133733. static long _vq_quantlist__44c8_s_p1_0[] = {
  133734. 1,
  133735. 0,
  133736. 2,
  133737. };
  133738. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133739. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133740. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133741. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133742. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133743. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133744. 8,
  133745. };
  133746. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133747. -0.5, 0.5,
  133748. };
  133749. static long _vq_quantmap__44c8_s_p1_0[] = {
  133750. 1, 0, 2,
  133751. };
  133752. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133753. _vq_quantthresh__44c8_s_p1_0,
  133754. _vq_quantmap__44c8_s_p1_0,
  133755. 3,
  133756. 3
  133757. };
  133758. static static_codebook _44c8_s_p1_0 = {
  133759. 4, 81,
  133760. _vq_lengthlist__44c8_s_p1_0,
  133761. 1, -535822336, 1611661312, 2, 0,
  133762. _vq_quantlist__44c8_s_p1_0,
  133763. NULL,
  133764. &_vq_auxt__44c8_s_p1_0,
  133765. NULL,
  133766. 0
  133767. };
  133768. static long _vq_quantlist__44c8_s_p2_0[] = {
  133769. 2,
  133770. 1,
  133771. 3,
  133772. 0,
  133773. 4,
  133774. };
  133775. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133776. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133777. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133778. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133779. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133780. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133781. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133782. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133783. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133785. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133786. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133787. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133788. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133789. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133790. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133791. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133793. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133794. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133795. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133796. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133797. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133798. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133799. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133801. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133802. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133803. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133804. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133805. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133806. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133807. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133812. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133813. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133814. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133815. 13,
  133816. };
  133817. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133818. -1.5, -0.5, 0.5, 1.5,
  133819. };
  133820. static long _vq_quantmap__44c8_s_p2_0[] = {
  133821. 3, 1, 0, 2, 4,
  133822. };
  133823. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133824. _vq_quantthresh__44c8_s_p2_0,
  133825. _vq_quantmap__44c8_s_p2_0,
  133826. 5,
  133827. 5
  133828. };
  133829. static static_codebook _44c8_s_p2_0 = {
  133830. 4, 625,
  133831. _vq_lengthlist__44c8_s_p2_0,
  133832. 1, -533725184, 1611661312, 3, 0,
  133833. _vq_quantlist__44c8_s_p2_0,
  133834. NULL,
  133835. &_vq_auxt__44c8_s_p2_0,
  133836. NULL,
  133837. 0
  133838. };
  133839. static long _vq_quantlist__44c8_s_p3_0[] = {
  133840. 4,
  133841. 3,
  133842. 5,
  133843. 2,
  133844. 6,
  133845. 1,
  133846. 7,
  133847. 0,
  133848. 8,
  133849. };
  133850. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133851. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133852. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133853. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133854. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133856. 0,
  133857. };
  133858. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133859. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133860. };
  133861. static long _vq_quantmap__44c8_s_p3_0[] = {
  133862. 7, 5, 3, 1, 0, 2, 4, 6,
  133863. 8,
  133864. };
  133865. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133866. _vq_quantthresh__44c8_s_p3_0,
  133867. _vq_quantmap__44c8_s_p3_0,
  133868. 9,
  133869. 9
  133870. };
  133871. static static_codebook _44c8_s_p3_0 = {
  133872. 2, 81,
  133873. _vq_lengthlist__44c8_s_p3_0,
  133874. 1, -531628032, 1611661312, 4, 0,
  133875. _vq_quantlist__44c8_s_p3_0,
  133876. NULL,
  133877. &_vq_auxt__44c8_s_p3_0,
  133878. NULL,
  133879. 0
  133880. };
  133881. static long _vq_quantlist__44c8_s_p4_0[] = {
  133882. 8,
  133883. 7,
  133884. 9,
  133885. 6,
  133886. 10,
  133887. 5,
  133888. 11,
  133889. 4,
  133890. 12,
  133891. 3,
  133892. 13,
  133893. 2,
  133894. 14,
  133895. 1,
  133896. 15,
  133897. 0,
  133898. 16,
  133899. };
  133900. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133901. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133902. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133903. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133904. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133905. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133906. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133907. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133908. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133909. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133910. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133919. 0,
  133920. };
  133921. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133922. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133923. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133924. };
  133925. static long _vq_quantmap__44c8_s_p4_0[] = {
  133926. 15, 13, 11, 9, 7, 5, 3, 1,
  133927. 0, 2, 4, 6, 8, 10, 12, 14,
  133928. 16,
  133929. };
  133930. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133931. _vq_quantthresh__44c8_s_p4_0,
  133932. _vq_quantmap__44c8_s_p4_0,
  133933. 17,
  133934. 17
  133935. };
  133936. static static_codebook _44c8_s_p4_0 = {
  133937. 2, 289,
  133938. _vq_lengthlist__44c8_s_p4_0,
  133939. 1, -529530880, 1611661312, 5, 0,
  133940. _vq_quantlist__44c8_s_p4_0,
  133941. NULL,
  133942. &_vq_auxt__44c8_s_p4_0,
  133943. NULL,
  133944. 0
  133945. };
  133946. static long _vq_quantlist__44c8_s_p5_0[] = {
  133947. 1,
  133948. 0,
  133949. 2,
  133950. };
  133951. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133952. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133953. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133954. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133955. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133956. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133957. 12,
  133958. };
  133959. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133960. -5.5, 5.5,
  133961. };
  133962. static long _vq_quantmap__44c8_s_p5_0[] = {
  133963. 1, 0, 2,
  133964. };
  133965. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133966. _vq_quantthresh__44c8_s_p5_0,
  133967. _vq_quantmap__44c8_s_p5_0,
  133968. 3,
  133969. 3
  133970. };
  133971. static static_codebook _44c8_s_p5_0 = {
  133972. 4, 81,
  133973. _vq_lengthlist__44c8_s_p5_0,
  133974. 1, -529137664, 1618345984, 2, 0,
  133975. _vq_quantlist__44c8_s_p5_0,
  133976. NULL,
  133977. &_vq_auxt__44c8_s_p5_0,
  133978. NULL,
  133979. 0
  133980. };
  133981. static long _vq_quantlist__44c8_s_p5_1[] = {
  133982. 5,
  133983. 4,
  133984. 6,
  133985. 3,
  133986. 7,
  133987. 2,
  133988. 8,
  133989. 1,
  133990. 9,
  133991. 0,
  133992. 10,
  133993. };
  133994. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133995. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133996. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133997. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133998. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133999. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134000. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134001. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134002. 11,11,11, 7, 7, 7, 7, 8, 8,
  134003. };
  134004. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134005. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134006. 3.5, 4.5,
  134007. };
  134008. static long _vq_quantmap__44c8_s_p5_1[] = {
  134009. 9, 7, 5, 3, 1, 0, 2, 4,
  134010. 6, 8, 10,
  134011. };
  134012. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134013. _vq_quantthresh__44c8_s_p5_1,
  134014. _vq_quantmap__44c8_s_p5_1,
  134015. 11,
  134016. 11
  134017. };
  134018. static static_codebook _44c8_s_p5_1 = {
  134019. 2, 121,
  134020. _vq_lengthlist__44c8_s_p5_1,
  134021. 1, -531365888, 1611661312, 4, 0,
  134022. _vq_quantlist__44c8_s_p5_1,
  134023. NULL,
  134024. &_vq_auxt__44c8_s_p5_1,
  134025. NULL,
  134026. 0
  134027. };
  134028. static long _vq_quantlist__44c8_s_p6_0[] = {
  134029. 6,
  134030. 5,
  134031. 7,
  134032. 4,
  134033. 8,
  134034. 3,
  134035. 9,
  134036. 2,
  134037. 10,
  134038. 1,
  134039. 11,
  134040. 0,
  134041. 12,
  134042. };
  134043. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134044. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134045. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134046. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134047. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134048. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134049. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134054. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134055. };
  134056. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134057. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134058. 12.5, 17.5, 22.5, 27.5,
  134059. };
  134060. static long _vq_quantmap__44c8_s_p6_0[] = {
  134061. 11, 9, 7, 5, 3, 1, 0, 2,
  134062. 4, 6, 8, 10, 12,
  134063. };
  134064. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134065. _vq_quantthresh__44c8_s_p6_0,
  134066. _vq_quantmap__44c8_s_p6_0,
  134067. 13,
  134068. 13
  134069. };
  134070. static static_codebook _44c8_s_p6_0 = {
  134071. 2, 169,
  134072. _vq_lengthlist__44c8_s_p6_0,
  134073. 1, -526516224, 1616117760, 4, 0,
  134074. _vq_quantlist__44c8_s_p6_0,
  134075. NULL,
  134076. &_vq_auxt__44c8_s_p6_0,
  134077. NULL,
  134078. 0
  134079. };
  134080. static long _vq_quantlist__44c8_s_p6_1[] = {
  134081. 2,
  134082. 1,
  134083. 3,
  134084. 0,
  134085. 4,
  134086. };
  134087. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134088. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134089. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134090. };
  134091. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134092. -1.5, -0.5, 0.5, 1.5,
  134093. };
  134094. static long _vq_quantmap__44c8_s_p6_1[] = {
  134095. 3, 1, 0, 2, 4,
  134096. };
  134097. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134098. _vq_quantthresh__44c8_s_p6_1,
  134099. _vq_quantmap__44c8_s_p6_1,
  134100. 5,
  134101. 5
  134102. };
  134103. static static_codebook _44c8_s_p6_1 = {
  134104. 2, 25,
  134105. _vq_lengthlist__44c8_s_p6_1,
  134106. 1, -533725184, 1611661312, 3, 0,
  134107. _vq_quantlist__44c8_s_p6_1,
  134108. NULL,
  134109. &_vq_auxt__44c8_s_p6_1,
  134110. NULL,
  134111. 0
  134112. };
  134113. static long _vq_quantlist__44c8_s_p7_0[] = {
  134114. 6,
  134115. 5,
  134116. 7,
  134117. 4,
  134118. 8,
  134119. 3,
  134120. 9,
  134121. 2,
  134122. 10,
  134123. 1,
  134124. 11,
  134125. 0,
  134126. 12,
  134127. };
  134128. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134129. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134130. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134131. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134132. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134133. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134134. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134135. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134136. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134137. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134138. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134139. 20,13,13,13,13,14,13,15,15,
  134140. };
  134141. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134142. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134143. 27.5, 38.5, 49.5, 60.5,
  134144. };
  134145. static long _vq_quantmap__44c8_s_p7_0[] = {
  134146. 11, 9, 7, 5, 3, 1, 0, 2,
  134147. 4, 6, 8, 10, 12,
  134148. };
  134149. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134150. _vq_quantthresh__44c8_s_p7_0,
  134151. _vq_quantmap__44c8_s_p7_0,
  134152. 13,
  134153. 13
  134154. };
  134155. static static_codebook _44c8_s_p7_0 = {
  134156. 2, 169,
  134157. _vq_lengthlist__44c8_s_p7_0,
  134158. 1, -523206656, 1618345984, 4, 0,
  134159. _vq_quantlist__44c8_s_p7_0,
  134160. NULL,
  134161. &_vq_auxt__44c8_s_p7_0,
  134162. NULL,
  134163. 0
  134164. };
  134165. static long _vq_quantlist__44c8_s_p7_1[] = {
  134166. 5,
  134167. 4,
  134168. 6,
  134169. 3,
  134170. 7,
  134171. 2,
  134172. 8,
  134173. 1,
  134174. 9,
  134175. 0,
  134176. 10,
  134177. };
  134178. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134179. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134180. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134181. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134182. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134183. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134184. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134185. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134186. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134187. };
  134188. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134189. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134190. 3.5, 4.5,
  134191. };
  134192. static long _vq_quantmap__44c8_s_p7_1[] = {
  134193. 9, 7, 5, 3, 1, 0, 2, 4,
  134194. 6, 8, 10,
  134195. };
  134196. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134197. _vq_quantthresh__44c8_s_p7_1,
  134198. _vq_quantmap__44c8_s_p7_1,
  134199. 11,
  134200. 11
  134201. };
  134202. static static_codebook _44c8_s_p7_1 = {
  134203. 2, 121,
  134204. _vq_lengthlist__44c8_s_p7_1,
  134205. 1, -531365888, 1611661312, 4, 0,
  134206. _vq_quantlist__44c8_s_p7_1,
  134207. NULL,
  134208. &_vq_auxt__44c8_s_p7_1,
  134209. NULL,
  134210. 0
  134211. };
  134212. static long _vq_quantlist__44c8_s_p8_0[] = {
  134213. 7,
  134214. 6,
  134215. 8,
  134216. 5,
  134217. 9,
  134218. 4,
  134219. 10,
  134220. 3,
  134221. 11,
  134222. 2,
  134223. 12,
  134224. 1,
  134225. 13,
  134226. 0,
  134227. 14,
  134228. };
  134229. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134230. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134231. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134232. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134233. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134234. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134235. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134236. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134237. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134238. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134239. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134240. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134241. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134242. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134243. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134244. 15,
  134245. };
  134246. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134247. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134248. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134249. };
  134250. static long _vq_quantmap__44c8_s_p8_0[] = {
  134251. 13, 11, 9, 7, 5, 3, 1, 0,
  134252. 2, 4, 6, 8, 10, 12, 14,
  134253. };
  134254. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134255. _vq_quantthresh__44c8_s_p8_0,
  134256. _vq_quantmap__44c8_s_p8_0,
  134257. 15,
  134258. 15
  134259. };
  134260. static static_codebook _44c8_s_p8_0 = {
  134261. 2, 225,
  134262. _vq_lengthlist__44c8_s_p8_0,
  134263. 1, -520986624, 1620377600, 4, 0,
  134264. _vq_quantlist__44c8_s_p8_0,
  134265. NULL,
  134266. &_vq_auxt__44c8_s_p8_0,
  134267. NULL,
  134268. 0
  134269. };
  134270. static long _vq_quantlist__44c8_s_p8_1[] = {
  134271. 10,
  134272. 9,
  134273. 11,
  134274. 8,
  134275. 12,
  134276. 7,
  134277. 13,
  134278. 6,
  134279. 14,
  134280. 5,
  134281. 15,
  134282. 4,
  134283. 16,
  134284. 3,
  134285. 17,
  134286. 2,
  134287. 18,
  134288. 1,
  134289. 19,
  134290. 0,
  134291. 20,
  134292. };
  134293. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134294. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134295. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134296. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134297. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134298. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134299. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134300. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134301. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134302. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134303. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134304. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134305. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134306. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134307. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134308. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134309. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134310. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134311. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134312. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134313. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134314. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134315. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134316. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134317. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134318. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134319. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134320. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134321. 10, 9, 9,10,10, 9,10, 9, 9,
  134322. };
  134323. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134324. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134325. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134326. 6.5, 7.5, 8.5, 9.5,
  134327. };
  134328. static long _vq_quantmap__44c8_s_p8_1[] = {
  134329. 19, 17, 15, 13, 11, 9, 7, 5,
  134330. 3, 1, 0, 2, 4, 6, 8, 10,
  134331. 12, 14, 16, 18, 20,
  134332. };
  134333. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134334. _vq_quantthresh__44c8_s_p8_1,
  134335. _vq_quantmap__44c8_s_p8_1,
  134336. 21,
  134337. 21
  134338. };
  134339. static static_codebook _44c8_s_p8_1 = {
  134340. 2, 441,
  134341. _vq_lengthlist__44c8_s_p8_1,
  134342. 1, -529268736, 1611661312, 5, 0,
  134343. _vq_quantlist__44c8_s_p8_1,
  134344. NULL,
  134345. &_vq_auxt__44c8_s_p8_1,
  134346. NULL,
  134347. 0
  134348. };
  134349. static long _vq_quantlist__44c8_s_p9_0[] = {
  134350. 8,
  134351. 7,
  134352. 9,
  134353. 6,
  134354. 10,
  134355. 5,
  134356. 11,
  134357. 4,
  134358. 12,
  134359. 3,
  134360. 13,
  134361. 2,
  134362. 14,
  134363. 1,
  134364. 15,
  134365. 0,
  134366. 16,
  134367. };
  134368. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134369. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134370. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134371. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134376. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134377. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134378. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134380. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134381. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134382. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134383. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134384. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134385. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134386. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134387. 10,
  134388. };
  134389. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134390. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134391. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134392. };
  134393. static long _vq_quantmap__44c8_s_p9_0[] = {
  134394. 15, 13, 11, 9, 7, 5, 3, 1,
  134395. 0, 2, 4, 6, 8, 10, 12, 14,
  134396. 16,
  134397. };
  134398. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134399. _vq_quantthresh__44c8_s_p9_0,
  134400. _vq_quantmap__44c8_s_p9_0,
  134401. 17,
  134402. 17
  134403. };
  134404. static static_codebook _44c8_s_p9_0 = {
  134405. 2, 289,
  134406. _vq_lengthlist__44c8_s_p9_0,
  134407. 1, -509798400, 1631393792, 5, 0,
  134408. _vq_quantlist__44c8_s_p9_0,
  134409. NULL,
  134410. &_vq_auxt__44c8_s_p9_0,
  134411. NULL,
  134412. 0
  134413. };
  134414. static long _vq_quantlist__44c8_s_p9_1[] = {
  134415. 9,
  134416. 8,
  134417. 10,
  134418. 7,
  134419. 11,
  134420. 6,
  134421. 12,
  134422. 5,
  134423. 13,
  134424. 4,
  134425. 14,
  134426. 3,
  134427. 15,
  134428. 2,
  134429. 16,
  134430. 1,
  134431. 17,
  134432. 0,
  134433. 18,
  134434. };
  134435. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134436. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134437. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134438. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134439. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134440. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134441. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134442. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134443. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134444. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134445. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134446. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134447. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134448. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134449. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134450. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134451. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134452. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134453. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134454. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134455. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134456. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134457. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134458. 14,13,13,14,14,15,14,15,14,
  134459. };
  134460. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134461. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134462. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134463. 367.5, 416.5,
  134464. };
  134465. static long _vq_quantmap__44c8_s_p9_1[] = {
  134466. 17, 15, 13, 11, 9, 7, 5, 3,
  134467. 1, 0, 2, 4, 6, 8, 10, 12,
  134468. 14, 16, 18,
  134469. };
  134470. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134471. _vq_quantthresh__44c8_s_p9_1,
  134472. _vq_quantmap__44c8_s_p9_1,
  134473. 19,
  134474. 19
  134475. };
  134476. static static_codebook _44c8_s_p9_1 = {
  134477. 2, 361,
  134478. _vq_lengthlist__44c8_s_p9_1,
  134479. 1, -518287360, 1622704128, 5, 0,
  134480. _vq_quantlist__44c8_s_p9_1,
  134481. NULL,
  134482. &_vq_auxt__44c8_s_p9_1,
  134483. NULL,
  134484. 0
  134485. };
  134486. static long _vq_quantlist__44c8_s_p9_2[] = {
  134487. 24,
  134488. 23,
  134489. 25,
  134490. 22,
  134491. 26,
  134492. 21,
  134493. 27,
  134494. 20,
  134495. 28,
  134496. 19,
  134497. 29,
  134498. 18,
  134499. 30,
  134500. 17,
  134501. 31,
  134502. 16,
  134503. 32,
  134504. 15,
  134505. 33,
  134506. 14,
  134507. 34,
  134508. 13,
  134509. 35,
  134510. 12,
  134511. 36,
  134512. 11,
  134513. 37,
  134514. 10,
  134515. 38,
  134516. 9,
  134517. 39,
  134518. 8,
  134519. 40,
  134520. 7,
  134521. 41,
  134522. 6,
  134523. 42,
  134524. 5,
  134525. 43,
  134526. 4,
  134527. 44,
  134528. 3,
  134529. 45,
  134530. 2,
  134531. 46,
  134532. 1,
  134533. 47,
  134534. 0,
  134535. 48,
  134536. };
  134537. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134538. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134539. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134540. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134541. 7,
  134542. };
  134543. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134544. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134545. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134546. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134547. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134548. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134549. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134550. };
  134551. static long _vq_quantmap__44c8_s_p9_2[] = {
  134552. 47, 45, 43, 41, 39, 37, 35, 33,
  134553. 31, 29, 27, 25, 23, 21, 19, 17,
  134554. 15, 13, 11, 9, 7, 5, 3, 1,
  134555. 0, 2, 4, 6, 8, 10, 12, 14,
  134556. 16, 18, 20, 22, 24, 26, 28, 30,
  134557. 32, 34, 36, 38, 40, 42, 44, 46,
  134558. 48,
  134559. };
  134560. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134561. _vq_quantthresh__44c8_s_p9_2,
  134562. _vq_quantmap__44c8_s_p9_2,
  134563. 49,
  134564. 49
  134565. };
  134566. static static_codebook _44c8_s_p9_2 = {
  134567. 1, 49,
  134568. _vq_lengthlist__44c8_s_p9_2,
  134569. 1, -526909440, 1611661312, 6, 0,
  134570. _vq_quantlist__44c8_s_p9_2,
  134571. NULL,
  134572. &_vq_auxt__44c8_s_p9_2,
  134573. NULL,
  134574. 0
  134575. };
  134576. static long _huff_lengthlist__44c8_s_short[] = {
  134577. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134578. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134579. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134580. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134581. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134582. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134583. 10, 9,11,14,
  134584. };
  134585. static static_codebook _huff_book__44c8_s_short = {
  134586. 2, 100,
  134587. _huff_lengthlist__44c8_s_short,
  134588. 0, 0, 0, 0, 0,
  134589. NULL,
  134590. NULL,
  134591. NULL,
  134592. NULL,
  134593. 0
  134594. };
  134595. static long _huff_lengthlist__44c9_s_long[] = {
  134596. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134597. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134598. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134599. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134600. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134601. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134602. 10, 9, 8, 9,
  134603. };
  134604. static static_codebook _huff_book__44c9_s_long = {
  134605. 2, 100,
  134606. _huff_lengthlist__44c9_s_long,
  134607. 0, 0, 0, 0, 0,
  134608. NULL,
  134609. NULL,
  134610. NULL,
  134611. NULL,
  134612. 0
  134613. };
  134614. static long _vq_quantlist__44c9_s_p1_0[] = {
  134615. 1,
  134616. 0,
  134617. 2,
  134618. };
  134619. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134620. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134621. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134622. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134623. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134624. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134625. 7,
  134626. };
  134627. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134628. -0.5, 0.5,
  134629. };
  134630. static long _vq_quantmap__44c9_s_p1_0[] = {
  134631. 1, 0, 2,
  134632. };
  134633. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134634. _vq_quantthresh__44c9_s_p1_0,
  134635. _vq_quantmap__44c9_s_p1_0,
  134636. 3,
  134637. 3
  134638. };
  134639. static static_codebook _44c9_s_p1_0 = {
  134640. 4, 81,
  134641. _vq_lengthlist__44c9_s_p1_0,
  134642. 1, -535822336, 1611661312, 2, 0,
  134643. _vq_quantlist__44c9_s_p1_0,
  134644. NULL,
  134645. &_vq_auxt__44c9_s_p1_0,
  134646. NULL,
  134647. 0
  134648. };
  134649. static long _vq_quantlist__44c9_s_p2_0[] = {
  134650. 2,
  134651. 1,
  134652. 3,
  134653. 0,
  134654. 4,
  134655. };
  134656. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134657. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134658. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134659. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134660. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134661. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134662. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134663. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134664. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134666. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134667. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134668. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134669. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134670. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134671. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134672. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134674. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134675. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134676. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134677. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134678. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134679. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134680. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134682. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134683. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134684. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134685. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134686. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134687. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134688. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134693. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134694. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134695. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134696. 12,
  134697. };
  134698. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134699. -1.5, -0.5, 0.5, 1.5,
  134700. };
  134701. static long _vq_quantmap__44c9_s_p2_0[] = {
  134702. 3, 1, 0, 2, 4,
  134703. };
  134704. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134705. _vq_quantthresh__44c9_s_p2_0,
  134706. _vq_quantmap__44c9_s_p2_0,
  134707. 5,
  134708. 5
  134709. };
  134710. static static_codebook _44c9_s_p2_0 = {
  134711. 4, 625,
  134712. _vq_lengthlist__44c9_s_p2_0,
  134713. 1, -533725184, 1611661312, 3, 0,
  134714. _vq_quantlist__44c9_s_p2_0,
  134715. NULL,
  134716. &_vq_auxt__44c9_s_p2_0,
  134717. NULL,
  134718. 0
  134719. };
  134720. static long _vq_quantlist__44c9_s_p3_0[] = {
  134721. 4,
  134722. 3,
  134723. 5,
  134724. 2,
  134725. 6,
  134726. 1,
  134727. 7,
  134728. 0,
  134729. 8,
  134730. };
  134731. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134732. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134733. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134734. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134735. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134737. 0,
  134738. };
  134739. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134740. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134741. };
  134742. static long _vq_quantmap__44c9_s_p3_0[] = {
  134743. 7, 5, 3, 1, 0, 2, 4, 6,
  134744. 8,
  134745. };
  134746. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134747. _vq_quantthresh__44c9_s_p3_0,
  134748. _vq_quantmap__44c9_s_p3_0,
  134749. 9,
  134750. 9
  134751. };
  134752. static static_codebook _44c9_s_p3_0 = {
  134753. 2, 81,
  134754. _vq_lengthlist__44c9_s_p3_0,
  134755. 1, -531628032, 1611661312, 4, 0,
  134756. _vq_quantlist__44c9_s_p3_0,
  134757. NULL,
  134758. &_vq_auxt__44c9_s_p3_0,
  134759. NULL,
  134760. 0
  134761. };
  134762. static long _vq_quantlist__44c9_s_p4_0[] = {
  134763. 8,
  134764. 7,
  134765. 9,
  134766. 6,
  134767. 10,
  134768. 5,
  134769. 11,
  134770. 4,
  134771. 12,
  134772. 3,
  134773. 13,
  134774. 2,
  134775. 14,
  134776. 1,
  134777. 15,
  134778. 0,
  134779. 16,
  134780. };
  134781. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134782. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134783. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134784. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134785. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134786. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134787. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134788. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134789. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134790. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134791. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0,
  134801. };
  134802. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134803. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134804. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134805. };
  134806. static long _vq_quantmap__44c9_s_p4_0[] = {
  134807. 15, 13, 11, 9, 7, 5, 3, 1,
  134808. 0, 2, 4, 6, 8, 10, 12, 14,
  134809. 16,
  134810. };
  134811. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134812. _vq_quantthresh__44c9_s_p4_0,
  134813. _vq_quantmap__44c9_s_p4_0,
  134814. 17,
  134815. 17
  134816. };
  134817. static static_codebook _44c9_s_p4_0 = {
  134818. 2, 289,
  134819. _vq_lengthlist__44c9_s_p4_0,
  134820. 1, -529530880, 1611661312, 5, 0,
  134821. _vq_quantlist__44c9_s_p4_0,
  134822. NULL,
  134823. &_vq_auxt__44c9_s_p4_0,
  134824. NULL,
  134825. 0
  134826. };
  134827. static long _vq_quantlist__44c9_s_p5_0[] = {
  134828. 1,
  134829. 0,
  134830. 2,
  134831. };
  134832. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134833. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134834. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134835. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134836. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134837. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134838. 12,
  134839. };
  134840. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134841. -5.5, 5.5,
  134842. };
  134843. static long _vq_quantmap__44c9_s_p5_0[] = {
  134844. 1, 0, 2,
  134845. };
  134846. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134847. _vq_quantthresh__44c9_s_p5_0,
  134848. _vq_quantmap__44c9_s_p5_0,
  134849. 3,
  134850. 3
  134851. };
  134852. static static_codebook _44c9_s_p5_0 = {
  134853. 4, 81,
  134854. _vq_lengthlist__44c9_s_p5_0,
  134855. 1, -529137664, 1618345984, 2, 0,
  134856. _vq_quantlist__44c9_s_p5_0,
  134857. NULL,
  134858. &_vq_auxt__44c9_s_p5_0,
  134859. NULL,
  134860. 0
  134861. };
  134862. static long _vq_quantlist__44c9_s_p5_1[] = {
  134863. 5,
  134864. 4,
  134865. 6,
  134866. 3,
  134867. 7,
  134868. 2,
  134869. 8,
  134870. 1,
  134871. 9,
  134872. 0,
  134873. 10,
  134874. };
  134875. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134876. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134877. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134878. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134879. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134880. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134881. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134882. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134883. 11,11,11, 7, 7, 7, 7, 7, 7,
  134884. };
  134885. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134886. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134887. 3.5, 4.5,
  134888. };
  134889. static long _vq_quantmap__44c9_s_p5_1[] = {
  134890. 9, 7, 5, 3, 1, 0, 2, 4,
  134891. 6, 8, 10,
  134892. };
  134893. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134894. _vq_quantthresh__44c9_s_p5_1,
  134895. _vq_quantmap__44c9_s_p5_1,
  134896. 11,
  134897. 11
  134898. };
  134899. static static_codebook _44c9_s_p5_1 = {
  134900. 2, 121,
  134901. _vq_lengthlist__44c9_s_p5_1,
  134902. 1, -531365888, 1611661312, 4, 0,
  134903. _vq_quantlist__44c9_s_p5_1,
  134904. NULL,
  134905. &_vq_auxt__44c9_s_p5_1,
  134906. NULL,
  134907. 0
  134908. };
  134909. static long _vq_quantlist__44c9_s_p6_0[] = {
  134910. 6,
  134911. 5,
  134912. 7,
  134913. 4,
  134914. 8,
  134915. 3,
  134916. 9,
  134917. 2,
  134918. 10,
  134919. 1,
  134920. 11,
  134921. 0,
  134922. 12,
  134923. };
  134924. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134925. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134926. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134927. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134928. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134929. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134930. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134935. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134936. };
  134937. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134938. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134939. 12.5, 17.5, 22.5, 27.5,
  134940. };
  134941. static long _vq_quantmap__44c9_s_p6_0[] = {
  134942. 11, 9, 7, 5, 3, 1, 0, 2,
  134943. 4, 6, 8, 10, 12,
  134944. };
  134945. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134946. _vq_quantthresh__44c9_s_p6_0,
  134947. _vq_quantmap__44c9_s_p6_0,
  134948. 13,
  134949. 13
  134950. };
  134951. static static_codebook _44c9_s_p6_0 = {
  134952. 2, 169,
  134953. _vq_lengthlist__44c9_s_p6_0,
  134954. 1, -526516224, 1616117760, 4, 0,
  134955. _vq_quantlist__44c9_s_p6_0,
  134956. NULL,
  134957. &_vq_auxt__44c9_s_p6_0,
  134958. NULL,
  134959. 0
  134960. };
  134961. static long _vq_quantlist__44c9_s_p6_1[] = {
  134962. 2,
  134963. 1,
  134964. 3,
  134965. 0,
  134966. 4,
  134967. };
  134968. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134969. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134970. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134971. };
  134972. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134973. -1.5, -0.5, 0.5, 1.5,
  134974. };
  134975. static long _vq_quantmap__44c9_s_p6_1[] = {
  134976. 3, 1, 0, 2, 4,
  134977. };
  134978. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134979. _vq_quantthresh__44c9_s_p6_1,
  134980. _vq_quantmap__44c9_s_p6_1,
  134981. 5,
  134982. 5
  134983. };
  134984. static static_codebook _44c9_s_p6_1 = {
  134985. 2, 25,
  134986. _vq_lengthlist__44c9_s_p6_1,
  134987. 1, -533725184, 1611661312, 3, 0,
  134988. _vq_quantlist__44c9_s_p6_1,
  134989. NULL,
  134990. &_vq_auxt__44c9_s_p6_1,
  134991. NULL,
  134992. 0
  134993. };
  134994. static long _vq_quantlist__44c9_s_p7_0[] = {
  134995. 6,
  134996. 5,
  134997. 7,
  134998. 4,
  134999. 8,
  135000. 3,
  135001. 9,
  135002. 2,
  135003. 10,
  135004. 1,
  135005. 11,
  135006. 0,
  135007. 12,
  135008. };
  135009. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135010. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135011. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135012. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135013. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135014. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135015. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135016. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135017. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135018. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135019. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135020. 19,12,12,12,12,13,13,14,14,
  135021. };
  135022. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135023. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135024. 27.5, 38.5, 49.5, 60.5,
  135025. };
  135026. static long _vq_quantmap__44c9_s_p7_0[] = {
  135027. 11, 9, 7, 5, 3, 1, 0, 2,
  135028. 4, 6, 8, 10, 12,
  135029. };
  135030. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135031. _vq_quantthresh__44c9_s_p7_0,
  135032. _vq_quantmap__44c9_s_p7_0,
  135033. 13,
  135034. 13
  135035. };
  135036. static static_codebook _44c9_s_p7_0 = {
  135037. 2, 169,
  135038. _vq_lengthlist__44c9_s_p7_0,
  135039. 1, -523206656, 1618345984, 4, 0,
  135040. _vq_quantlist__44c9_s_p7_0,
  135041. NULL,
  135042. &_vq_auxt__44c9_s_p7_0,
  135043. NULL,
  135044. 0
  135045. };
  135046. static long _vq_quantlist__44c9_s_p7_1[] = {
  135047. 5,
  135048. 4,
  135049. 6,
  135050. 3,
  135051. 7,
  135052. 2,
  135053. 8,
  135054. 1,
  135055. 9,
  135056. 0,
  135057. 10,
  135058. };
  135059. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135060. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135061. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135062. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135063. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135064. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135065. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135066. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135067. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135068. };
  135069. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135070. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135071. 3.5, 4.5,
  135072. };
  135073. static long _vq_quantmap__44c9_s_p7_1[] = {
  135074. 9, 7, 5, 3, 1, 0, 2, 4,
  135075. 6, 8, 10,
  135076. };
  135077. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135078. _vq_quantthresh__44c9_s_p7_1,
  135079. _vq_quantmap__44c9_s_p7_1,
  135080. 11,
  135081. 11
  135082. };
  135083. static static_codebook _44c9_s_p7_1 = {
  135084. 2, 121,
  135085. _vq_lengthlist__44c9_s_p7_1,
  135086. 1, -531365888, 1611661312, 4, 0,
  135087. _vq_quantlist__44c9_s_p7_1,
  135088. NULL,
  135089. &_vq_auxt__44c9_s_p7_1,
  135090. NULL,
  135091. 0
  135092. };
  135093. static long _vq_quantlist__44c9_s_p8_0[] = {
  135094. 7,
  135095. 6,
  135096. 8,
  135097. 5,
  135098. 9,
  135099. 4,
  135100. 10,
  135101. 3,
  135102. 11,
  135103. 2,
  135104. 12,
  135105. 1,
  135106. 13,
  135107. 0,
  135108. 14,
  135109. };
  135110. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135111. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135112. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135113. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135114. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135115. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135116. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135117. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135118. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135119. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135120. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135121. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135122. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135123. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135124. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135125. 14,
  135126. };
  135127. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135128. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135129. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135130. };
  135131. static long _vq_quantmap__44c9_s_p8_0[] = {
  135132. 13, 11, 9, 7, 5, 3, 1, 0,
  135133. 2, 4, 6, 8, 10, 12, 14,
  135134. };
  135135. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135136. _vq_quantthresh__44c9_s_p8_0,
  135137. _vq_quantmap__44c9_s_p8_0,
  135138. 15,
  135139. 15
  135140. };
  135141. static static_codebook _44c9_s_p8_0 = {
  135142. 2, 225,
  135143. _vq_lengthlist__44c9_s_p8_0,
  135144. 1, -520986624, 1620377600, 4, 0,
  135145. _vq_quantlist__44c9_s_p8_0,
  135146. NULL,
  135147. &_vq_auxt__44c9_s_p8_0,
  135148. NULL,
  135149. 0
  135150. };
  135151. static long _vq_quantlist__44c9_s_p8_1[] = {
  135152. 10,
  135153. 9,
  135154. 11,
  135155. 8,
  135156. 12,
  135157. 7,
  135158. 13,
  135159. 6,
  135160. 14,
  135161. 5,
  135162. 15,
  135163. 4,
  135164. 16,
  135165. 3,
  135166. 17,
  135167. 2,
  135168. 18,
  135169. 1,
  135170. 19,
  135171. 0,
  135172. 20,
  135173. };
  135174. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135175. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135176. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135177. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135178. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135179. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135180. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135181. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135182. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135183. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135184. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135185. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135186. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135187. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135188. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135189. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135190. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135191. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135192. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135193. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135194. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135195. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135196. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135197. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135198. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135199. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135200. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135201. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135202. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135203. };
  135204. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135205. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135206. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135207. 6.5, 7.5, 8.5, 9.5,
  135208. };
  135209. static long _vq_quantmap__44c9_s_p8_1[] = {
  135210. 19, 17, 15, 13, 11, 9, 7, 5,
  135211. 3, 1, 0, 2, 4, 6, 8, 10,
  135212. 12, 14, 16, 18, 20,
  135213. };
  135214. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135215. _vq_quantthresh__44c9_s_p8_1,
  135216. _vq_quantmap__44c9_s_p8_1,
  135217. 21,
  135218. 21
  135219. };
  135220. static static_codebook _44c9_s_p8_1 = {
  135221. 2, 441,
  135222. _vq_lengthlist__44c9_s_p8_1,
  135223. 1, -529268736, 1611661312, 5, 0,
  135224. _vq_quantlist__44c9_s_p8_1,
  135225. NULL,
  135226. &_vq_auxt__44c9_s_p8_1,
  135227. NULL,
  135228. 0
  135229. };
  135230. static long _vq_quantlist__44c9_s_p9_0[] = {
  135231. 9,
  135232. 8,
  135233. 10,
  135234. 7,
  135235. 11,
  135236. 6,
  135237. 12,
  135238. 5,
  135239. 13,
  135240. 4,
  135241. 14,
  135242. 3,
  135243. 15,
  135244. 2,
  135245. 16,
  135246. 1,
  135247. 17,
  135248. 0,
  135249. 18,
  135250. };
  135251. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135252. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135253. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135254. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135255. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135256. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135257. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135258. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135259. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135260. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135261. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135262. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135263. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135264. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135265. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135266. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135267. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135268. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135274. 11,11,11,11,11,11,11,11,11,
  135275. };
  135276. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135277. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135278. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135279. 6982.5, 7913.5,
  135280. };
  135281. static long _vq_quantmap__44c9_s_p9_0[] = {
  135282. 17, 15, 13, 11, 9, 7, 5, 3,
  135283. 1, 0, 2, 4, 6, 8, 10, 12,
  135284. 14, 16, 18,
  135285. };
  135286. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135287. _vq_quantthresh__44c9_s_p9_0,
  135288. _vq_quantmap__44c9_s_p9_0,
  135289. 19,
  135290. 19
  135291. };
  135292. static static_codebook _44c9_s_p9_0 = {
  135293. 2, 361,
  135294. _vq_lengthlist__44c9_s_p9_0,
  135295. 1, -508535424, 1631393792, 5, 0,
  135296. _vq_quantlist__44c9_s_p9_0,
  135297. NULL,
  135298. &_vq_auxt__44c9_s_p9_0,
  135299. NULL,
  135300. 0
  135301. };
  135302. static long _vq_quantlist__44c9_s_p9_1[] = {
  135303. 9,
  135304. 8,
  135305. 10,
  135306. 7,
  135307. 11,
  135308. 6,
  135309. 12,
  135310. 5,
  135311. 13,
  135312. 4,
  135313. 14,
  135314. 3,
  135315. 15,
  135316. 2,
  135317. 16,
  135318. 1,
  135319. 17,
  135320. 0,
  135321. 18,
  135322. };
  135323. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135324. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135325. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135326. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135327. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135328. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135329. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135330. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135331. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135332. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135333. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135334. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135335. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135336. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135337. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135338. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135339. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135340. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135341. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135342. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135343. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135344. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135345. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135346. 13,13,13,14,13,14,15,15,15,
  135347. };
  135348. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135349. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135350. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135351. 367.5, 416.5,
  135352. };
  135353. static long _vq_quantmap__44c9_s_p9_1[] = {
  135354. 17, 15, 13, 11, 9, 7, 5, 3,
  135355. 1, 0, 2, 4, 6, 8, 10, 12,
  135356. 14, 16, 18,
  135357. };
  135358. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135359. _vq_quantthresh__44c9_s_p9_1,
  135360. _vq_quantmap__44c9_s_p9_1,
  135361. 19,
  135362. 19
  135363. };
  135364. static static_codebook _44c9_s_p9_1 = {
  135365. 2, 361,
  135366. _vq_lengthlist__44c9_s_p9_1,
  135367. 1, -518287360, 1622704128, 5, 0,
  135368. _vq_quantlist__44c9_s_p9_1,
  135369. NULL,
  135370. &_vq_auxt__44c9_s_p9_1,
  135371. NULL,
  135372. 0
  135373. };
  135374. static long _vq_quantlist__44c9_s_p9_2[] = {
  135375. 24,
  135376. 23,
  135377. 25,
  135378. 22,
  135379. 26,
  135380. 21,
  135381. 27,
  135382. 20,
  135383. 28,
  135384. 19,
  135385. 29,
  135386. 18,
  135387. 30,
  135388. 17,
  135389. 31,
  135390. 16,
  135391. 32,
  135392. 15,
  135393. 33,
  135394. 14,
  135395. 34,
  135396. 13,
  135397. 35,
  135398. 12,
  135399. 36,
  135400. 11,
  135401. 37,
  135402. 10,
  135403. 38,
  135404. 9,
  135405. 39,
  135406. 8,
  135407. 40,
  135408. 7,
  135409. 41,
  135410. 6,
  135411. 42,
  135412. 5,
  135413. 43,
  135414. 4,
  135415. 44,
  135416. 3,
  135417. 45,
  135418. 2,
  135419. 46,
  135420. 1,
  135421. 47,
  135422. 0,
  135423. 48,
  135424. };
  135425. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135426. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135427. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135428. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135429. 7,
  135430. };
  135431. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135432. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135433. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135434. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135435. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135436. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135437. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135438. };
  135439. static long _vq_quantmap__44c9_s_p9_2[] = {
  135440. 47, 45, 43, 41, 39, 37, 35, 33,
  135441. 31, 29, 27, 25, 23, 21, 19, 17,
  135442. 15, 13, 11, 9, 7, 5, 3, 1,
  135443. 0, 2, 4, 6, 8, 10, 12, 14,
  135444. 16, 18, 20, 22, 24, 26, 28, 30,
  135445. 32, 34, 36, 38, 40, 42, 44, 46,
  135446. 48,
  135447. };
  135448. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135449. _vq_quantthresh__44c9_s_p9_2,
  135450. _vq_quantmap__44c9_s_p9_2,
  135451. 49,
  135452. 49
  135453. };
  135454. static static_codebook _44c9_s_p9_2 = {
  135455. 1, 49,
  135456. _vq_lengthlist__44c9_s_p9_2,
  135457. 1, -526909440, 1611661312, 6, 0,
  135458. _vq_quantlist__44c9_s_p9_2,
  135459. NULL,
  135460. &_vq_auxt__44c9_s_p9_2,
  135461. NULL,
  135462. 0
  135463. };
  135464. static long _huff_lengthlist__44c9_s_short[] = {
  135465. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135466. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135467. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135468. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135469. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135470. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135471. 9, 8,10,13,
  135472. };
  135473. static static_codebook _huff_book__44c9_s_short = {
  135474. 2, 100,
  135475. _huff_lengthlist__44c9_s_short,
  135476. 0, 0, 0, 0, 0,
  135477. NULL,
  135478. NULL,
  135479. NULL,
  135480. NULL,
  135481. 0
  135482. };
  135483. static long _huff_lengthlist__44c0_s_long[] = {
  135484. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135485. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135486. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135487. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135488. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135489. 12,
  135490. };
  135491. static static_codebook _huff_book__44c0_s_long = {
  135492. 2, 81,
  135493. _huff_lengthlist__44c0_s_long,
  135494. 0, 0, 0, 0, 0,
  135495. NULL,
  135496. NULL,
  135497. NULL,
  135498. NULL,
  135499. 0
  135500. };
  135501. static long _vq_quantlist__44c0_s_p1_0[] = {
  135502. 1,
  135503. 0,
  135504. 2,
  135505. };
  135506. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135507. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135508. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135513. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135518. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135553. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135558. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135563. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135599. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135604. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135609. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  135918. };
  135919. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135920. -0.5, 0.5,
  135921. };
  135922. static long _vq_quantmap__44c0_s_p1_0[] = {
  135923. 1, 0, 2,
  135924. };
  135925. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135926. _vq_quantthresh__44c0_s_p1_0,
  135927. _vq_quantmap__44c0_s_p1_0,
  135928. 3,
  135929. 3
  135930. };
  135931. static static_codebook _44c0_s_p1_0 = {
  135932. 8, 6561,
  135933. _vq_lengthlist__44c0_s_p1_0,
  135934. 1, -535822336, 1611661312, 2, 0,
  135935. _vq_quantlist__44c0_s_p1_0,
  135936. NULL,
  135937. &_vq_auxt__44c0_s_p1_0,
  135938. NULL,
  135939. 0
  135940. };
  135941. static long _vq_quantlist__44c0_s_p2_0[] = {
  135942. 2,
  135943. 1,
  135944. 3,
  135945. 0,
  135946. 4,
  135947. };
  135948. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135949. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  135989. };
  135990. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135991. -1.5, -0.5, 0.5, 1.5,
  135992. };
  135993. static long _vq_quantmap__44c0_s_p2_0[] = {
  135994. 3, 1, 0, 2, 4,
  135995. };
  135996. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135997. _vq_quantthresh__44c0_s_p2_0,
  135998. _vq_quantmap__44c0_s_p2_0,
  135999. 5,
  136000. 5
  136001. };
  136002. static static_codebook _44c0_s_p2_0 = {
  136003. 4, 625,
  136004. _vq_lengthlist__44c0_s_p2_0,
  136005. 1, -533725184, 1611661312, 3, 0,
  136006. _vq_quantlist__44c0_s_p2_0,
  136007. NULL,
  136008. &_vq_auxt__44c0_s_p2_0,
  136009. NULL,
  136010. 0
  136011. };
  136012. static long _vq_quantlist__44c0_s_p3_0[] = {
  136013. 4,
  136014. 3,
  136015. 5,
  136016. 2,
  136017. 6,
  136018. 1,
  136019. 7,
  136020. 0,
  136021. 8,
  136022. };
  136023. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136024. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136025. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136026. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136027. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136028. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0,
  136030. };
  136031. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136032. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136033. };
  136034. static long _vq_quantmap__44c0_s_p3_0[] = {
  136035. 7, 5, 3, 1, 0, 2, 4, 6,
  136036. 8,
  136037. };
  136038. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136039. _vq_quantthresh__44c0_s_p3_0,
  136040. _vq_quantmap__44c0_s_p3_0,
  136041. 9,
  136042. 9
  136043. };
  136044. static static_codebook _44c0_s_p3_0 = {
  136045. 2, 81,
  136046. _vq_lengthlist__44c0_s_p3_0,
  136047. 1, -531628032, 1611661312, 4, 0,
  136048. _vq_quantlist__44c0_s_p3_0,
  136049. NULL,
  136050. &_vq_auxt__44c0_s_p3_0,
  136051. NULL,
  136052. 0
  136053. };
  136054. static long _vq_quantlist__44c0_s_p4_0[] = {
  136055. 4,
  136056. 3,
  136057. 5,
  136058. 2,
  136059. 6,
  136060. 1,
  136061. 7,
  136062. 0,
  136063. 8,
  136064. };
  136065. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136066. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136067. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136068. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136069. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136070. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136071. 10,
  136072. };
  136073. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136074. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136075. };
  136076. static long _vq_quantmap__44c0_s_p4_0[] = {
  136077. 7, 5, 3, 1, 0, 2, 4, 6,
  136078. 8,
  136079. };
  136080. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136081. _vq_quantthresh__44c0_s_p4_0,
  136082. _vq_quantmap__44c0_s_p4_0,
  136083. 9,
  136084. 9
  136085. };
  136086. static static_codebook _44c0_s_p4_0 = {
  136087. 2, 81,
  136088. _vq_lengthlist__44c0_s_p4_0,
  136089. 1, -531628032, 1611661312, 4, 0,
  136090. _vq_quantlist__44c0_s_p4_0,
  136091. NULL,
  136092. &_vq_auxt__44c0_s_p4_0,
  136093. NULL,
  136094. 0
  136095. };
  136096. static long _vq_quantlist__44c0_s_p5_0[] = {
  136097. 8,
  136098. 7,
  136099. 9,
  136100. 6,
  136101. 10,
  136102. 5,
  136103. 11,
  136104. 4,
  136105. 12,
  136106. 3,
  136107. 13,
  136108. 2,
  136109. 14,
  136110. 1,
  136111. 15,
  136112. 0,
  136113. 16,
  136114. };
  136115. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136116. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136117. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136118. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136119. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136120. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136121. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136122. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136123. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136124. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136125. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136126. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136127. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136128. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136129. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136130. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136131. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136132. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136134. 14,
  136135. };
  136136. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136137. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136138. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136139. };
  136140. static long _vq_quantmap__44c0_s_p5_0[] = {
  136141. 15, 13, 11, 9, 7, 5, 3, 1,
  136142. 0, 2, 4, 6, 8, 10, 12, 14,
  136143. 16,
  136144. };
  136145. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136146. _vq_quantthresh__44c0_s_p5_0,
  136147. _vq_quantmap__44c0_s_p5_0,
  136148. 17,
  136149. 17
  136150. };
  136151. static static_codebook _44c0_s_p5_0 = {
  136152. 2, 289,
  136153. _vq_lengthlist__44c0_s_p5_0,
  136154. 1, -529530880, 1611661312, 5, 0,
  136155. _vq_quantlist__44c0_s_p5_0,
  136156. NULL,
  136157. &_vq_auxt__44c0_s_p5_0,
  136158. NULL,
  136159. 0
  136160. };
  136161. static long _vq_quantlist__44c0_s_p6_0[] = {
  136162. 1,
  136163. 0,
  136164. 2,
  136165. };
  136166. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136167. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136168. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136169. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136170. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136171. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136172. 10,
  136173. };
  136174. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136175. -5.5, 5.5,
  136176. };
  136177. static long _vq_quantmap__44c0_s_p6_0[] = {
  136178. 1, 0, 2,
  136179. };
  136180. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136181. _vq_quantthresh__44c0_s_p6_0,
  136182. _vq_quantmap__44c0_s_p6_0,
  136183. 3,
  136184. 3
  136185. };
  136186. static static_codebook _44c0_s_p6_0 = {
  136187. 4, 81,
  136188. _vq_lengthlist__44c0_s_p6_0,
  136189. 1, -529137664, 1618345984, 2, 0,
  136190. _vq_quantlist__44c0_s_p6_0,
  136191. NULL,
  136192. &_vq_auxt__44c0_s_p6_0,
  136193. NULL,
  136194. 0
  136195. };
  136196. static long _vq_quantlist__44c0_s_p6_1[] = {
  136197. 5,
  136198. 4,
  136199. 6,
  136200. 3,
  136201. 7,
  136202. 2,
  136203. 8,
  136204. 1,
  136205. 9,
  136206. 0,
  136207. 10,
  136208. };
  136209. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136210. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136211. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136212. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136213. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136214. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136215. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136216. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136217. 10,10,10, 8, 8, 8, 8, 8, 8,
  136218. };
  136219. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136220. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136221. 3.5, 4.5,
  136222. };
  136223. static long _vq_quantmap__44c0_s_p6_1[] = {
  136224. 9, 7, 5, 3, 1, 0, 2, 4,
  136225. 6, 8, 10,
  136226. };
  136227. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136228. _vq_quantthresh__44c0_s_p6_1,
  136229. _vq_quantmap__44c0_s_p6_1,
  136230. 11,
  136231. 11
  136232. };
  136233. static static_codebook _44c0_s_p6_1 = {
  136234. 2, 121,
  136235. _vq_lengthlist__44c0_s_p6_1,
  136236. 1, -531365888, 1611661312, 4, 0,
  136237. _vq_quantlist__44c0_s_p6_1,
  136238. NULL,
  136239. &_vq_auxt__44c0_s_p6_1,
  136240. NULL,
  136241. 0
  136242. };
  136243. static long _vq_quantlist__44c0_s_p7_0[] = {
  136244. 6,
  136245. 5,
  136246. 7,
  136247. 4,
  136248. 8,
  136249. 3,
  136250. 9,
  136251. 2,
  136252. 10,
  136253. 1,
  136254. 11,
  136255. 0,
  136256. 12,
  136257. };
  136258. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136259. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136260. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136261. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136262. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136263. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136264. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136265. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136266. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136267. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136268. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136269. 0,12,12,11,11,12,12,13,13,
  136270. };
  136271. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136272. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136273. 12.5, 17.5, 22.5, 27.5,
  136274. };
  136275. static long _vq_quantmap__44c0_s_p7_0[] = {
  136276. 11, 9, 7, 5, 3, 1, 0, 2,
  136277. 4, 6, 8, 10, 12,
  136278. };
  136279. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136280. _vq_quantthresh__44c0_s_p7_0,
  136281. _vq_quantmap__44c0_s_p7_0,
  136282. 13,
  136283. 13
  136284. };
  136285. static static_codebook _44c0_s_p7_0 = {
  136286. 2, 169,
  136287. _vq_lengthlist__44c0_s_p7_0,
  136288. 1, -526516224, 1616117760, 4, 0,
  136289. _vq_quantlist__44c0_s_p7_0,
  136290. NULL,
  136291. &_vq_auxt__44c0_s_p7_0,
  136292. NULL,
  136293. 0
  136294. };
  136295. static long _vq_quantlist__44c0_s_p7_1[] = {
  136296. 2,
  136297. 1,
  136298. 3,
  136299. 0,
  136300. 4,
  136301. };
  136302. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136303. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136304. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136305. };
  136306. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136307. -1.5, -0.5, 0.5, 1.5,
  136308. };
  136309. static long _vq_quantmap__44c0_s_p7_1[] = {
  136310. 3, 1, 0, 2, 4,
  136311. };
  136312. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136313. _vq_quantthresh__44c0_s_p7_1,
  136314. _vq_quantmap__44c0_s_p7_1,
  136315. 5,
  136316. 5
  136317. };
  136318. static static_codebook _44c0_s_p7_1 = {
  136319. 2, 25,
  136320. _vq_lengthlist__44c0_s_p7_1,
  136321. 1, -533725184, 1611661312, 3, 0,
  136322. _vq_quantlist__44c0_s_p7_1,
  136323. NULL,
  136324. &_vq_auxt__44c0_s_p7_1,
  136325. NULL,
  136326. 0
  136327. };
  136328. static long _vq_quantlist__44c0_s_p8_0[] = {
  136329. 2,
  136330. 1,
  136331. 3,
  136332. 0,
  136333. 4,
  136334. };
  136335. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136336. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136337. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136338. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136339. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136340. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136341. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136342. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136343. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136344. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136345. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136346. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136347. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136348. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136351. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136352. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136353. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136354. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136355. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136356. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136357. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136358. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136359. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136360. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136361. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136363. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136370. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136371. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136375. 11,
  136376. };
  136377. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136378. -331.5, -110.5, 110.5, 331.5,
  136379. };
  136380. static long _vq_quantmap__44c0_s_p8_0[] = {
  136381. 3, 1, 0, 2, 4,
  136382. };
  136383. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136384. _vq_quantthresh__44c0_s_p8_0,
  136385. _vq_quantmap__44c0_s_p8_0,
  136386. 5,
  136387. 5
  136388. };
  136389. static static_codebook _44c0_s_p8_0 = {
  136390. 4, 625,
  136391. _vq_lengthlist__44c0_s_p8_0,
  136392. 1, -518283264, 1627103232, 3, 0,
  136393. _vq_quantlist__44c0_s_p8_0,
  136394. NULL,
  136395. &_vq_auxt__44c0_s_p8_0,
  136396. NULL,
  136397. 0
  136398. };
  136399. static long _vq_quantlist__44c0_s_p8_1[] = {
  136400. 6,
  136401. 5,
  136402. 7,
  136403. 4,
  136404. 8,
  136405. 3,
  136406. 9,
  136407. 2,
  136408. 10,
  136409. 1,
  136410. 11,
  136411. 0,
  136412. 12,
  136413. };
  136414. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136415. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136416. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136417. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136418. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136419. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136420. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136421. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136422. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136423. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136424. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136425. 16,13,13,12,12,14,14,15,13,
  136426. };
  136427. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136428. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136429. 42.5, 59.5, 76.5, 93.5,
  136430. };
  136431. static long _vq_quantmap__44c0_s_p8_1[] = {
  136432. 11, 9, 7, 5, 3, 1, 0, 2,
  136433. 4, 6, 8, 10, 12,
  136434. };
  136435. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136436. _vq_quantthresh__44c0_s_p8_1,
  136437. _vq_quantmap__44c0_s_p8_1,
  136438. 13,
  136439. 13
  136440. };
  136441. static static_codebook _44c0_s_p8_1 = {
  136442. 2, 169,
  136443. _vq_lengthlist__44c0_s_p8_1,
  136444. 1, -522616832, 1620115456, 4, 0,
  136445. _vq_quantlist__44c0_s_p8_1,
  136446. NULL,
  136447. &_vq_auxt__44c0_s_p8_1,
  136448. NULL,
  136449. 0
  136450. };
  136451. static long _vq_quantlist__44c0_s_p8_2[] = {
  136452. 8,
  136453. 7,
  136454. 9,
  136455. 6,
  136456. 10,
  136457. 5,
  136458. 11,
  136459. 4,
  136460. 12,
  136461. 3,
  136462. 13,
  136463. 2,
  136464. 14,
  136465. 1,
  136466. 15,
  136467. 0,
  136468. 16,
  136469. };
  136470. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136471. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136472. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136473. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136474. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136475. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136476. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136477. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136478. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136479. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136480. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136481. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136482. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136483. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136484. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136485. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136486. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136487. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136488. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136489. 10,
  136490. };
  136491. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136492. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136493. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136494. };
  136495. static long _vq_quantmap__44c0_s_p8_2[] = {
  136496. 15, 13, 11, 9, 7, 5, 3, 1,
  136497. 0, 2, 4, 6, 8, 10, 12, 14,
  136498. 16,
  136499. };
  136500. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136501. _vq_quantthresh__44c0_s_p8_2,
  136502. _vq_quantmap__44c0_s_p8_2,
  136503. 17,
  136504. 17
  136505. };
  136506. static static_codebook _44c0_s_p8_2 = {
  136507. 2, 289,
  136508. _vq_lengthlist__44c0_s_p8_2,
  136509. 1, -529530880, 1611661312, 5, 0,
  136510. _vq_quantlist__44c0_s_p8_2,
  136511. NULL,
  136512. &_vq_auxt__44c0_s_p8_2,
  136513. NULL,
  136514. 0
  136515. };
  136516. static long _huff_lengthlist__44c0_s_short[] = {
  136517. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136518. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136519. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136520. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136521. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136522. 12,
  136523. };
  136524. static static_codebook _huff_book__44c0_s_short = {
  136525. 2, 81,
  136526. _huff_lengthlist__44c0_s_short,
  136527. 0, 0, 0, 0, 0,
  136528. NULL,
  136529. NULL,
  136530. NULL,
  136531. NULL,
  136532. 0
  136533. };
  136534. static long _huff_lengthlist__44c0_sm_long[] = {
  136535. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136536. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136537. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136538. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136539. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136540. 13,
  136541. };
  136542. static static_codebook _huff_book__44c0_sm_long = {
  136543. 2, 81,
  136544. _huff_lengthlist__44c0_sm_long,
  136545. 0, 0, 0, 0, 0,
  136546. NULL,
  136547. NULL,
  136548. NULL,
  136549. NULL,
  136550. 0
  136551. };
  136552. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136553. 1,
  136554. 0,
  136555. 2,
  136556. };
  136557. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136558. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136559. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136564. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136569. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136604. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136609. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136614. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136650. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136655. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136660. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  136969. };
  136970. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136971. -0.5, 0.5,
  136972. };
  136973. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136974. 1, 0, 2,
  136975. };
  136976. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136977. _vq_quantthresh__44c0_sm_p1_0,
  136978. _vq_quantmap__44c0_sm_p1_0,
  136979. 3,
  136980. 3
  136981. };
  136982. static static_codebook _44c0_sm_p1_0 = {
  136983. 8, 6561,
  136984. _vq_lengthlist__44c0_sm_p1_0,
  136985. 1, -535822336, 1611661312, 2, 0,
  136986. _vq_quantlist__44c0_sm_p1_0,
  136987. NULL,
  136988. &_vq_auxt__44c0_sm_p1_0,
  136989. NULL,
  136990. 0
  136991. };
  136992. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136993. 2,
  136994. 1,
  136995. 3,
  136996. 0,
  136997. 4,
  136998. };
  136999. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137000. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  137040. };
  137041. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137042. -1.5, -0.5, 0.5, 1.5,
  137043. };
  137044. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137045. 3, 1, 0, 2, 4,
  137046. };
  137047. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137048. _vq_quantthresh__44c0_sm_p2_0,
  137049. _vq_quantmap__44c0_sm_p2_0,
  137050. 5,
  137051. 5
  137052. };
  137053. static static_codebook _44c0_sm_p2_0 = {
  137054. 4, 625,
  137055. _vq_lengthlist__44c0_sm_p2_0,
  137056. 1, -533725184, 1611661312, 3, 0,
  137057. _vq_quantlist__44c0_sm_p2_0,
  137058. NULL,
  137059. &_vq_auxt__44c0_sm_p2_0,
  137060. NULL,
  137061. 0
  137062. };
  137063. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137064. 4,
  137065. 3,
  137066. 5,
  137067. 2,
  137068. 6,
  137069. 1,
  137070. 7,
  137071. 0,
  137072. 8,
  137073. };
  137074. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137075. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137076. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137077. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137078. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137079. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0,
  137081. };
  137082. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137083. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137084. };
  137085. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137086. 7, 5, 3, 1, 0, 2, 4, 6,
  137087. 8,
  137088. };
  137089. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137090. _vq_quantthresh__44c0_sm_p3_0,
  137091. _vq_quantmap__44c0_sm_p3_0,
  137092. 9,
  137093. 9
  137094. };
  137095. static static_codebook _44c0_sm_p3_0 = {
  137096. 2, 81,
  137097. _vq_lengthlist__44c0_sm_p3_0,
  137098. 1, -531628032, 1611661312, 4, 0,
  137099. _vq_quantlist__44c0_sm_p3_0,
  137100. NULL,
  137101. &_vq_auxt__44c0_sm_p3_0,
  137102. NULL,
  137103. 0
  137104. };
  137105. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137106. 4,
  137107. 3,
  137108. 5,
  137109. 2,
  137110. 6,
  137111. 1,
  137112. 7,
  137113. 0,
  137114. 8,
  137115. };
  137116. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137117. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137118. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137119. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137120. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137121. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137122. 11,
  137123. };
  137124. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137125. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137126. };
  137127. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137128. 7, 5, 3, 1, 0, 2, 4, 6,
  137129. 8,
  137130. };
  137131. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137132. _vq_quantthresh__44c0_sm_p4_0,
  137133. _vq_quantmap__44c0_sm_p4_0,
  137134. 9,
  137135. 9
  137136. };
  137137. static static_codebook _44c0_sm_p4_0 = {
  137138. 2, 81,
  137139. _vq_lengthlist__44c0_sm_p4_0,
  137140. 1, -531628032, 1611661312, 4, 0,
  137141. _vq_quantlist__44c0_sm_p4_0,
  137142. NULL,
  137143. &_vq_auxt__44c0_sm_p4_0,
  137144. NULL,
  137145. 0
  137146. };
  137147. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137148. 8,
  137149. 7,
  137150. 9,
  137151. 6,
  137152. 10,
  137153. 5,
  137154. 11,
  137155. 4,
  137156. 12,
  137157. 3,
  137158. 13,
  137159. 2,
  137160. 14,
  137161. 1,
  137162. 15,
  137163. 0,
  137164. 16,
  137165. };
  137166. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137167. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137168. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137169. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137170. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137171. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137172. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137173. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137174. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137175. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137176. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137177. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137178. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137179. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137180. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137181. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137182. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137183. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137185. 14,
  137186. };
  137187. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137188. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137189. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137190. };
  137191. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137192. 15, 13, 11, 9, 7, 5, 3, 1,
  137193. 0, 2, 4, 6, 8, 10, 12, 14,
  137194. 16,
  137195. };
  137196. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137197. _vq_quantthresh__44c0_sm_p5_0,
  137198. _vq_quantmap__44c0_sm_p5_0,
  137199. 17,
  137200. 17
  137201. };
  137202. static static_codebook _44c0_sm_p5_0 = {
  137203. 2, 289,
  137204. _vq_lengthlist__44c0_sm_p5_0,
  137205. 1, -529530880, 1611661312, 5, 0,
  137206. _vq_quantlist__44c0_sm_p5_0,
  137207. NULL,
  137208. &_vq_auxt__44c0_sm_p5_0,
  137209. NULL,
  137210. 0
  137211. };
  137212. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137213. 1,
  137214. 0,
  137215. 2,
  137216. };
  137217. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137218. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137219. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137220. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137221. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137222. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137223. 11,
  137224. };
  137225. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137226. -5.5, 5.5,
  137227. };
  137228. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137229. 1, 0, 2,
  137230. };
  137231. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137232. _vq_quantthresh__44c0_sm_p6_0,
  137233. _vq_quantmap__44c0_sm_p6_0,
  137234. 3,
  137235. 3
  137236. };
  137237. static static_codebook _44c0_sm_p6_0 = {
  137238. 4, 81,
  137239. _vq_lengthlist__44c0_sm_p6_0,
  137240. 1, -529137664, 1618345984, 2, 0,
  137241. _vq_quantlist__44c0_sm_p6_0,
  137242. NULL,
  137243. &_vq_auxt__44c0_sm_p6_0,
  137244. NULL,
  137245. 0
  137246. };
  137247. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137248. 5,
  137249. 4,
  137250. 6,
  137251. 3,
  137252. 7,
  137253. 2,
  137254. 8,
  137255. 1,
  137256. 9,
  137257. 0,
  137258. 10,
  137259. };
  137260. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137261. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137262. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137263. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137264. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137265. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137266. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137267. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137268. 10,10,10, 8, 8, 8, 8, 8, 8,
  137269. };
  137270. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137271. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137272. 3.5, 4.5,
  137273. };
  137274. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137275. 9, 7, 5, 3, 1, 0, 2, 4,
  137276. 6, 8, 10,
  137277. };
  137278. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137279. _vq_quantthresh__44c0_sm_p6_1,
  137280. _vq_quantmap__44c0_sm_p6_1,
  137281. 11,
  137282. 11
  137283. };
  137284. static static_codebook _44c0_sm_p6_1 = {
  137285. 2, 121,
  137286. _vq_lengthlist__44c0_sm_p6_1,
  137287. 1, -531365888, 1611661312, 4, 0,
  137288. _vq_quantlist__44c0_sm_p6_1,
  137289. NULL,
  137290. &_vq_auxt__44c0_sm_p6_1,
  137291. NULL,
  137292. 0
  137293. };
  137294. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137295. 6,
  137296. 5,
  137297. 7,
  137298. 4,
  137299. 8,
  137300. 3,
  137301. 9,
  137302. 2,
  137303. 10,
  137304. 1,
  137305. 11,
  137306. 0,
  137307. 12,
  137308. };
  137309. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137310. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137311. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137312. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137313. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137314. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137315. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137316. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137317. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137318. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137319. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137320. 0,12,12,11,11,13,12,14,14,
  137321. };
  137322. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137323. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137324. 12.5, 17.5, 22.5, 27.5,
  137325. };
  137326. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137327. 11, 9, 7, 5, 3, 1, 0, 2,
  137328. 4, 6, 8, 10, 12,
  137329. };
  137330. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137331. _vq_quantthresh__44c0_sm_p7_0,
  137332. _vq_quantmap__44c0_sm_p7_0,
  137333. 13,
  137334. 13
  137335. };
  137336. static static_codebook _44c0_sm_p7_0 = {
  137337. 2, 169,
  137338. _vq_lengthlist__44c0_sm_p7_0,
  137339. 1, -526516224, 1616117760, 4, 0,
  137340. _vq_quantlist__44c0_sm_p7_0,
  137341. NULL,
  137342. &_vq_auxt__44c0_sm_p7_0,
  137343. NULL,
  137344. 0
  137345. };
  137346. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137347. 2,
  137348. 1,
  137349. 3,
  137350. 0,
  137351. 4,
  137352. };
  137353. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137354. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137355. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137356. };
  137357. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137358. -1.5, -0.5, 0.5, 1.5,
  137359. };
  137360. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137361. 3, 1, 0, 2, 4,
  137362. };
  137363. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137364. _vq_quantthresh__44c0_sm_p7_1,
  137365. _vq_quantmap__44c0_sm_p7_1,
  137366. 5,
  137367. 5
  137368. };
  137369. static static_codebook _44c0_sm_p7_1 = {
  137370. 2, 25,
  137371. _vq_lengthlist__44c0_sm_p7_1,
  137372. 1, -533725184, 1611661312, 3, 0,
  137373. _vq_quantlist__44c0_sm_p7_1,
  137374. NULL,
  137375. &_vq_auxt__44c0_sm_p7_1,
  137376. NULL,
  137377. 0
  137378. };
  137379. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137380. 4,
  137381. 3,
  137382. 5,
  137383. 2,
  137384. 6,
  137385. 1,
  137386. 7,
  137387. 0,
  137388. 8,
  137389. };
  137390. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137391. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137392. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137394. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137395. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137396. 12,
  137397. };
  137398. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137399. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137400. };
  137401. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137402. 7, 5, 3, 1, 0, 2, 4, 6,
  137403. 8,
  137404. };
  137405. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137406. _vq_quantthresh__44c0_sm_p8_0,
  137407. _vq_quantmap__44c0_sm_p8_0,
  137408. 9,
  137409. 9
  137410. };
  137411. static static_codebook _44c0_sm_p8_0 = {
  137412. 2, 81,
  137413. _vq_lengthlist__44c0_sm_p8_0,
  137414. 1, -516186112, 1627103232, 4, 0,
  137415. _vq_quantlist__44c0_sm_p8_0,
  137416. NULL,
  137417. &_vq_auxt__44c0_sm_p8_0,
  137418. NULL,
  137419. 0
  137420. };
  137421. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137422. 6,
  137423. 5,
  137424. 7,
  137425. 4,
  137426. 8,
  137427. 3,
  137428. 9,
  137429. 2,
  137430. 10,
  137431. 1,
  137432. 11,
  137433. 0,
  137434. 12,
  137435. };
  137436. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137437. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137438. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137439. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137440. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137441. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137442. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137443. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137444. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137445. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137446. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137447. 20,13,13,12,12,16,13,15,13,
  137448. };
  137449. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137450. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137451. 42.5, 59.5, 76.5, 93.5,
  137452. };
  137453. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137454. 11, 9, 7, 5, 3, 1, 0, 2,
  137455. 4, 6, 8, 10, 12,
  137456. };
  137457. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137458. _vq_quantthresh__44c0_sm_p8_1,
  137459. _vq_quantmap__44c0_sm_p8_1,
  137460. 13,
  137461. 13
  137462. };
  137463. static static_codebook _44c0_sm_p8_1 = {
  137464. 2, 169,
  137465. _vq_lengthlist__44c0_sm_p8_1,
  137466. 1, -522616832, 1620115456, 4, 0,
  137467. _vq_quantlist__44c0_sm_p8_1,
  137468. NULL,
  137469. &_vq_auxt__44c0_sm_p8_1,
  137470. NULL,
  137471. 0
  137472. };
  137473. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137474. 8,
  137475. 7,
  137476. 9,
  137477. 6,
  137478. 10,
  137479. 5,
  137480. 11,
  137481. 4,
  137482. 12,
  137483. 3,
  137484. 13,
  137485. 2,
  137486. 14,
  137487. 1,
  137488. 15,
  137489. 0,
  137490. 16,
  137491. };
  137492. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137493. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137494. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137495. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137496. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137497. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137498. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137499. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137500. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137501. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137502. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137503. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137504. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137505. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137506. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137507. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137508. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137509. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137510. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137511. 9,
  137512. };
  137513. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137514. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137515. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137516. };
  137517. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137518. 15, 13, 11, 9, 7, 5, 3, 1,
  137519. 0, 2, 4, 6, 8, 10, 12, 14,
  137520. 16,
  137521. };
  137522. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137523. _vq_quantthresh__44c0_sm_p8_2,
  137524. _vq_quantmap__44c0_sm_p8_2,
  137525. 17,
  137526. 17
  137527. };
  137528. static static_codebook _44c0_sm_p8_2 = {
  137529. 2, 289,
  137530. _vq_lengthlist__44c0_sm_p8_2,
  137531. 1, -529530880, 1611661312, 5, 0,
  137532. _vq_quantlist__44c0_sm_p8_2,
  137533. NULL,
  137534. &_vq_auxt__44c0_sm_p8_2,
  137535. NULL,
  137536. 0
  137537. };
  137538. static long _huff_lengthlist__44c0_sm_short[] = {
  137539. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137540. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137541. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137542. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137543. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137544. 12,
  137545. };
  137546. static static_codebook _huff_book__44c0_sm_short = {
  137547. 2, 81,
  137548. _huff_lengthlist__44c0_sm_short,
  137549. 0, 0, 0, 0, 0,
  137550. NULL,
  137551. NULL,
  137552. NULL,
  137553. NULL,
  137554. 0
  137555. };
  137556. static long _huff_lengthlist__44c1_s_long[] = {
  137557. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137558. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137559. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137560. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137561. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137562. 11,
  137563. };
  137564. static static_codebook _huff_book__44c1_s_long = {
  137565. 2, 81,
  137566. _huff_lengthlist__44c1_s_long,
  137567. 0, 0, 0, 0, 0,
  137568. NULL,
  137569. NULL,
  137570. NULL,
  137571. NULL,
  137572. 0
  137573. };
  137574. static long _vq_quantlist__44c1_s_p1_0[] = {
  137575. 1,
  137576. 0,
  137577. 2,
  137578. };
  137579. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137580. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137581. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137586. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137591. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137626. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137631. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137636. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137672. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137677. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137682. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137809. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137814. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137819. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  137991. };
  137992. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137993. -0.5, 0.5,
  137994. };
  137995. static long _vq_quantmap__44c1_s_p1_0[] = {
  137996. 1, 0, 2,
  137997. };
  137998. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137999. _vq_quantthresh__44c1_s_p1_0,
  138000. _vq_quantmap__44c1_s_p1_0,
  138001. 3,
  138002. 3
  138003. };
  138004. static static_codebook _44c1_s_p1_0 = {
  138005. 8, 6561,
  138006. _vq_lengthlist__44c1_s_p1_0,
  138007. 1, -535822336, 1611661312, 2, 0,
  138008. _vq_quantlist__44c1_s_p1_0,
  138009. NULL,
  138010. &_vq_auxt__44c1_s_p1_0,
  138011. NULL,
  138012. 0
  138013. };
  138014. static long _vq_quantlist__44c1_s_p2_0[] = {
  138015. 2,
  138016. 1,
  138017. 3,
  138018. 0,
  138019. 4,
  138020. };
  138021. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138022. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  138062. };
  138063. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138064. -1.5, -0.5, 0.5, 1.5,
  138065. };
  138066. static long _vq_quantmap__44c1_s_p2_0[] = {
  138067. 3, 1, 0, 2, 4,
  138068. };
  138069. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138070. _vq_quantthresh__44c1_s_p2_0,
  138071. _vq_quantmap__44c1_s_p2_0,
  138072. 5,
  138073. 5
  138074. };
  138075. static static_codebook _44c1_s_p2_0 = {
  138076. 4, 625,
  138077. _vq_lengthlist__44c1_s_p2_0,
  138078. 1, -533725184, 1611661312, 3, 0,
  138079. _vq_quantlist__44c1_s_p2_0,
  138080. NULL,
  138081. &_vq_auxt__44c1_s_p2_0,
  138082. NULL,
  138083. 0
  138084. };
  138085. static long _vq_quantlist__44c1_s_p3_0[] = {
  138086. 4,
  138087. 3,
  138088. 5,
  138089. 2,
  138090. 6,
  138091. 1,
  138092. 7,
  138093. 0,
  138094. 8,
  138095. };
  138096. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138097. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138098. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138099. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138100. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138101. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0,
  138103. };
  138104. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138105. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138106. };
  138107. static long _vq_quantmap__44c1_s_p3_0[] = {
  138108. 7, 5, 3, 1, 0, 2, 4, 6,
  138109. 8,
  138110. };
  138111. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138112. _vq_quantthresh__44c1_s_p3_0,
  138113. _vq_quantmap__44c1_s_p3_0,
  138114. 9,
  138115. 9
  138116. };
  138117. static static_codebook _44c1_s_p3_0 = {
  138118. 2, 81,
  138119. _vq_lengthlist__44c1_s_p3_0,
  138120. 1, -531628032, 1611661312, 4, 0,
  138121. _vq_quantlist__44c1_s_p3_0,
  138122. NULL,
  138123. &_vq_auxt__44c1_s_p3_0,
  138124. NULL,
  138125. 0
  138126. };
  138127. static long _vq_quantlist__44c1_s_p4_0[] = {
  138128. 4,
  138129. 3,
  138130. 5,
  138131. 2,
  138132. 6,
  138133. 1,
  138134. 7,
  138135. 0,
  138136. 8,
  138137. };
  138138. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138139. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138140. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138141. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138142. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138143. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138144. 11,
  138145. };
  138146. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138147. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138148. };
  138149. static long _vq_quantmap__44c1_s_p4_0[] = {
  138150. 7, 5, 3, 1, 0, 2, 4, 6,
  138151. 8,
  138152. };
  138153. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138154. _vq_quantthresh__44c1_s_p4_0,
  138155. _vq_quantmap__44c1_s_p4_0,
  138156. 9,
  138157. 9
  138158. };
  138159. static static_codebook _44c1_s_p4_0 = {
  138160. 2, 81,
  138161. _vq_lengthlist__44c1_s_p4_0,
  138162. 1, -531628032, 1611661312, 4, 0,
  138163. _vq_quantlist__44c1_s_p4_0,
  138164. NULL,
  138165. &_vq_auxt__44c1_s_p4_0,
  138166. NULL,
  138167. 0
  138168. };
  138169. static long _vq_quantlist__44c1_s_p5_0[] = {
  138170. 8,
  138171. 7,
  138172. 9,
  138173. 6,
  138174. 10,
  138175. 5,
  138176. 11,
  138177. 4,
  138178. 12,
  138179. 3,
  138180. 13,
  138181. 2,
  138182. 14,
  138183. 1,
  138184. 15,
  138185. 0,
  138186. 16,
  138187. };
  138188. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138189. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138190. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138191. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138192. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138193. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138194. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138195. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138196. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138197. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138198. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138199. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138200. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138201. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138202. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138203. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138204. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138205. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138207. 14,
  138208. };
  138209. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138210. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138211. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138212. };
  138213. static long _vq_quantmap__44c1_s_p5_0[] = {
  138214. 15, 13, 11, 9, 7, 5, 3, 1,
  138215. 0, 2, 4, 6, 8, 10, 12, 14,
  138216. 16,
  138217. };
  138218. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138219. _vq_quantthresh__44c1_s_p5_0,
  138220. _vq_quantmap__44c1_s_p5_0,
  138221. 17,
  138222. 17
  138223. };
  138224. static static_codebook _44c1_s_p5_0 = {
  138225. 2, 289,
  138226. _vq_lengthlist__44c1_s_p5_0,
  138227. 1, -529530880, 1611661312, 5, 0,
  138228. _vq_quantlist__44c1_s_p5_0,
  138229. NULL,
  138230. &_vq_auxt__44c1_s_p5_0,
  138231. NULL,
  138232. 0
  138233. };
  138234. static long _vq_quantlist__44c1_s_p6_0[] = {
  138235. 1,
  138236. 0,
  138237. 2,
  138238. };
  138239. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138240. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138241. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138242. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138243. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138244. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138245. 11,
  138246. };
  138247. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138248. -5.5, 5.5,
  138249. };
  138250. static long _vq_quantmap__44c1_s_p6_0[] = {
  138251. 1, 0, 2,
  138252. };
  138253. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138254. _vq_quantthresh__44c1_s_p6_0,
  138255. _vq_quantmap__44c1_s_p6_0,
  138256. 3,
  138257. 3
  138258. };
  138259. static static_codebook _44c1_s_p6_0 = {
  138260. 4, 81,
  138261. _vq_lengthlist__44c1_s_p6_0,
  138262. 1, -529137664, 1618345984, 2, 0,
  138263. _vq_quantlist__44c1_s_p6_0,
  138264. NULL,
  138265. &_vq_auxt__44c1_s_p6_0,
  138266. NULL,
  138267. 0
  138268. };
  138269. static long _vq_quantlist__44c1_s_p6_1[] = {
  138270. 5,
  138271. 4,
  138272. 6,
  138273. 3,
  138274. 7,
  138275. 2,
  138276. 8,
  138277. 1,
  138278. 9,
  138279. 0,
  138280. 10,
  138281. };
  138282. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138283. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138284. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138285. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138286. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138287. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138288. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138289. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138290. 10,10,10, 8, 8, 8, 8, 8, 8,
  138291. };
  138292. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138293. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138294. 3.5, 4.5,
  138295. };
  138296. static long _vq_quantmap__44c1_s_p6_1[] = {
  138297. 9, 7, 5, 3, 1, 0, 2, 4,
  138298. 6, 8, 10,
  138299. };
  138300. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138301. _vq_quantthresh__44c1_s_p6_1,
  138302. _vq_quantmap__44c1_s_p6_1,
  138303. 11,
  138304. 11
  138305. };
  138306. static static_codebook _44c1_s_p6_1 = {
  138307. 2, 121,
  138308. _vq_lengthlist__44c1_s_p6_1,
  138309. 1, -531365888, 1611661312, 4, 0,
  138310. _vq_quantlist__44c1_s_p6_1,
  138311. NULL,
  138312. &_vq_auxt__44c1_s_p6_1,
  138313. NULL,
  138314. 0
  138315. };
  138316. static long _vq_quantlist__44c1_s_p7_0[] = {
  138317. 6,
  138318. 5,
  138319. 7,
  138320. 4,
  138321. 8,
  138322. 3,
  138323. 9,
  138324. 2,
  138325. 10,
  138326. 1,
  138327. 11,
  138328. 0,
  138329. 12,
  138330. };
  138331. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138332. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138333. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138334. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138335. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138336. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138337. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138338. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138339. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138340. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138341. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138342. 0,12,11,11,11,13,10,14,13,
  138343. };
  138344. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138345. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138346. 12.5, 17.5, 22.5, 27.5,
  138347. };
  138348. static long _vq_quantmap__44c1_s_p7_0[] = {
  138349. 11, 9, 7, 5, 3, 1, 0, 2,
  138350. 4, 6, 8, 10, 12,
  138351. };
  138352. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138353. _vq_quantthresh__44c1_s_p7_0,
  138354. _vq_quantmap__44c1_s_p7_0,
  138355. 13,
  138356. 13
  138357. };
  138358. static static_codebook _44c1_s_p7_0 = {
  138359. 2, 169,
  138360. _vq_lengthlist__44c1_s_p7_0,
  138361. 1, -526516224, 1616117760, 4, 0,
  138362. _vq_quantlist__44c1_s_p7_0,
  138363. NULL,
  138364. &_vq_auxt__44c1_s_p7_0,
  138365. NULL,
  138366. 0
  138367. };
  138368. static long _vq_quantlist__44c1_s_p7_1[] = {
  138369. 2,
  138370. 1,
  138371. 3,
  138372. 0,
  138373. 4,
  138374. };
  138375. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138376. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138377. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138378. };
  138379. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138380. -1.5, -0.5, 0.5, 1.5,
  138381. };
  138382. static long _vq_quantmap__44c1_s_p7_1[] = {
  138383. 3, 1, 0, 2, 4,
  138384. };
  138385. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138386. _vq_quantthresh__44c1_s_p7_1,
  138387. _vq_quantmap__44c1_s_p7_1,
  138388. 5,
  138389. 5
  138390. };
  138391. static static_codebook _44c1_s_p7_1 = {
  138392. 2, 25,
  138393. _vq_lengthlist__44c1_s_p7_1,
  138394. 1, -533725184, 1611661312, 3, 0,
  138395. _vq_quantlist__44c1_s_p7_1,
  138396. NULL,
  138397. &_vq_auxt__44c1_s_p7_1,
  138398. NULL,
  138399. 0
  138400. };
  138401. static long _vq_quantlist__44c1_s_p8_0[] = {
  138402. 6,
  138403. 5,
  138404. 7,
  138405. 4,
  138406. 8,
  138407. 3,
  138408. 9,
  138409. 2,
  138410. 10,
  138411. 1,
  138412. 11,
  138413. 0,
  138414. 12,
  138415. };
  138416. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138417. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138418. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138419. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138420. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138421. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138422. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138423. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138424. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138425. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138426. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138427. 10,10,10,10,10,10,10,10,10,
  138428. };
  138429. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138430. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138431. 552.5, 773.5, 994.5, 1215.5,
  138432. };
  138433. static long _vq_quantmap__44c1_s_p8_0[] = {
  138434. 11, 9, 7, 5, 3, 1, 0, 2,
  138435. 4, 6, 8, 10, 12,
  138436. };
  138437. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138438. _vq_quantthresh__44c1_s_p8_0,
  138439. _vq_quantmap__44c1_s_p8_0,
  138440. 13,
  138441. 13
  138442. };
  138443. static static_codebook _44c1_s_p8_0 = {
  138444. 2, 169,
  138445. _vq_lengthlist__44c1_s_p8_0,
  138446. 1, -514541568, 1627103232, 4, 0,
  138447. _vq_quantlist__44c1_s_p8_0,
  138448. NULL,
  138449. &_vq_auxt__44c1_s_p8_0,
  138450. NULL,
  138451. 0
  138452. };
  138453. static long _vq_quantlist__44c1_s_p8_1[] = {
  138454. 6,
  138455. 5,
  138456. 7,
  138457. 4,
  138458. 8,
  138459. 3,
  138460. 9,
  138461. 2,
  138462. 10,
  138463. 1,
  138464. 11,
  138465. 0,
  138466. 12,
  138467. };
  138468. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138469. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138470. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138471. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138472. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138473. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138474. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138475. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138476. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138477. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138478. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138479. 16,13,12,12,11,14,12,15,13,
  138480. };
  138481. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138482. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138483. 42.5, 59.5, 76.5, 93.5,
  138484. };
  138485. static long _vq_quantmap__44c1_s_p8_1[] = {
  138486. 11, 9, 7, 5, 3, 1, 0, 2,
  138487. 4, 6, 8, 10, 12,
  138488. };
  138489. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138490. _vq_quantthresh__44c1_s_p8_1,
  138491. _vq_quantmap__44c1_s_p8_1,
  138492. 13,
  138493. 13
  138494. };
  138495. static static_codebook _44c1_s_p8_1 = {
  138496. 2, 169,
  138497. _vq_lengthlist__44c1_s_p8_1,
  138498. 1, -522616832, 1620115456, 4, 0,
  138499. _vq_quantlist__44c1_s_p8_1,
  138500. NULL,
  138501. &_vq_auxt__44c1_s_p8_1,
  138502. NULL,
  138503. 0
  138504. };
  138505. static long _vq_quantlist__44c1_s_p8_2[] = {
  138506. 8,
  138507. 7,
  138508. 9,
  138509. 6,
  138510. 10,
  138511. 5,
  138512. 11,
  138513. 4,
  138514. 12,
  138515. 3,
  138516. 13,
  138517. 2,
  138518. 14,
  138519. 1,
  138520. 15,
  138521. 0,
  138522. 16,
  138523. };
  138524. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138525. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138526. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138527. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138528. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138529. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138530. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138531. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138532. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138533. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138534. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138535. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138536. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138537. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138538. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138539. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138540. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138541. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138542. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138543. 9,
  138544. };
  138545. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138546. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138547. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138548. };
  138549. static long _vq_quantmap__44c1_s_p8_2[] = {
  138550. 15, 13, 11, 9, 7, 5, 3, 1,
  138551. 0, 2, 4, 6, 8, 10, 12, 14,
  138552. 16,
  138553. };
  138554. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138555. _vq_quantthresh__44c1_s_p8_2,
  138556. _vq_quantmap__44c1_s_p8_2,
  138557. 17,
  138558. 17
  138559. };
  138560. static static_codebook _44c1_s_p8_2 = {
  138561. 2, 289,
  138562. _vq_lengthlist__44c1_s_p8_2,
  138563. 1, -529530880, 1611661312, 5, 0,
  138564. _vq_quantlist__44c1_s_p8_2,
  138565. NULL,
  138566. &_vq_auxt__44c1_s_p8_2,
  138567. NULL,
  138568. 0
  138569. };
  138570. static long _huff_lengthlist__44c1_s_short[] = {
  138571. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138572. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138573. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138574. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138575. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138576. 11,
  138577. };
  138578. static static_codebook _huff_book__44c1_s_short = {
  138579. 2, 81,
  138580. _huff_lengthlist__44c1_s_short,
  138581. 0, 0, 0, 0, 0,
  138582. NULL,
  138583. NULL,
  138584. NULL,
  138585. NULL,
  138586. 0
  138587. };
  138588. static long _huff_lengthlist__44c1_sm_long[] = {
  138589. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138590. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138591. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138592. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138593. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138594. 11,
  138595. };
  138596. static static_codebook _huff_book__44c1_sm_long = {
  138597. 2, 81,
  138598. _huff_lengthlist__44c1_sm_long,
  138599. 0, 0, 0, 0, 0,
  138600. NULL,
  138601. NULL,
  138602. NULL,
  138603. NULL,
  138604. 0
  138605. };
  138606. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138607. 1,
  138608. 0,
  138609. 2,
  138610. };
  138611. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138612. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138613. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138617. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138618. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138623. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138658. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138663. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138668. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138704. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138709. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138714. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138841. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138846. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138851. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  138886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  138891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  138896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  139023. };
  139024. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139025. -0.5, 0.5,
  139026. };
  139027. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139028. 1, 0, 2,
  139029. };
  139030. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139031. _vq_quantthresh__44c1_sm_p1_0,
  139032. _vq_quantmap__44c1_sm_p1_0,
  139033. 3,
  139034. 3
  139035. };
  139036. static static_codebook _44c1_sm_p1_0 = {
  139037. 8, 6561,
  139038. _vq_lengthlist__44c1_sm_p1_0,
  139039. 1, -535822336, 1611661312, 2, 0,
  139040. _vq_quantlist__44c1_sm_p1_0,
  139041. NULL,
  139042. &_vq_auxt__44c1_sm_p1_0,
  139043. NULL,
  139044. 0
  139045. };
  139046. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139047. 2,
  139048. 1,
  139049. 3,
  139050. 0,
  139051. 4,
  139052. };
  139053. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139054. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  139094. };
  139095. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139096. -1.5, -0.5, 0.5, 1.5,
  139097. };
  139098. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139099. 3, 1, 0, 2, 4,
  139100. };
  139101. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139102. _vq_quantthresh__44c1_sm_p2_0,
  139103. _vq_quantmap__44c1_sm_p2_0,
  139104. 5,
  139105. 5
  139106. };
  139107. static static_codebook _44c1_sm_p2_0 = {
  139108. 4, 625,
  139109. _vq_lengthlist__44c1_sm_p2_0,
  139110. 1, -533725184, 1611661312, 3, 0,
  139111. _vq_quantlist__44c1_sm_p2_0,
  139112. NULL,
  139113. &_vq_auxt__44c1_sm_p2_0,
  139114. NULL,
  139115. 0
  139116. };
  139117. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139118. 4,
  139119. 3,
  139120. 5,
  139121. 2,
  139122. 6,
  139123. 1,
  139124. 7,
  139125. 0,
  139126. 8,
  139127. };
  139128. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139129. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139130. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139131. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139132. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139133. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0,
  139135. };
  139136. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139137. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139138. };
  139139. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139140. 7, 5, 3, 1, 0, 2, 4, 6,
  139141. 8,
  139142. };
  139143. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139144. _vq_quantthresh__44c1_sm_p3_0,
  139145. _vq_quantmap__44c1_sm_p3_0,
  139146. 9,
  139147. 9
  139148. };
  139149. static static_codebook _44c1_sm_p3_0 = {
  139150. 2, 81,
  139151. _vq_lengthlist__44c1_sm_p3_0,
  139152. 1, -531628032, 1611661312, 4, 0,
  139153. _vq_quantlist__44c1_sm_p3_0,
  139154. NULL,
  139155. &_vq_auxt__44c1_sm_p3_0,
  139156. NULL,
  139157. 0
  139158. };
  139159. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139160. 4,
  139161. 3,
  139162. 5,
  139163. 2,
  139164. 6,
  139165. 1,
  139166. 7,
  139167. 0,
  139168. 8,
  139169. };
  139170. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139171. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139172. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139173. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139174. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139175. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139176. 11,
  139177. };
  139178. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139179. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139180. };
  139181. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139182. 7, 5, 3, 1, 0, 2, 4, 6,
  139183. 8,
  139184. };
  139185. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139186. _vq_quantthresh__44c1_sm_p4_0,
  139187. _vq_quantmap__44c1_sm_p4_0,
  139188. 9,
  139189. 9
  139190. };
  139191. static static_codebook _44c1_sm_p4_0 = {
  139192. 2, 81,
  139193. _vq_lengthlist__44c1_sm_p4_0,
  139194. 1, -531628032, 1611661312, 4, 0,
  139195. _vq_quantlist__44c1_sm_p4_0,
  139196. NULL,
  139197. &_vq_auxt__44c1_sm_p4_0,
  139198. NULL,
  139199. 0
  139200. };
  139201. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139202. 8,
  139203. 7,
  139204. 9,
  139205. 6,
  139206. 10,
  139207. 5,
  139208. 11,
  139209. 4,
  139210. 12,
  139211. 3,
  139212. 13,
  139213. 2,
  139214. 14,
  139215. 1,
  139216. 15,
  139217. 0,
  139218. 16,
  139219. };
  139220. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139221. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139222. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139223. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139224. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139225. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139226. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139227. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139228. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139229. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139230. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139231. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139232. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139233. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139234. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139235. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139236. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139237. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139239. 14,
  139240. };
  139241. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139242. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139243. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139244. };
  139245. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139246. 15, 13, 11, 9, 7, 5, 3, 1,
  139247. 0, 2, 4, 6, 8, 10, 12, 14,
  139248. 16,
  139249. };
  139250. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139251. _vq_quantthresh__44c1_sm_p5_0,
  139252. _vq_quantmap__44c1_sm_p5_0,
  139253. 17,
  139254. 17
  139255. };
  139256. static static_codebook _44c1_sm_p5_0 = {
  139257. 2, 289,
  139258. _vq_lengthlist__44c1_sm_p5_0,
  139259. 1, -529530880, 1611661312, 5, 0,
  139260. _vq_quantlist__44c1_sm_p5_0,
  139261. NULL,
  139262. &_vq_auxt__44c1_sm_p5_0,
  139263. NULL,
  139264. 0
  139265. };
  139266. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139267. 1,
  139268. 0,
  139269. 2,
  139270. };
  139271. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139272. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139273. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139274. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139275. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139276. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139277. 11,
  139278. };
  139279. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139280. -5.5, 5.5,
  139281. };
  139282. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139283. 1, 0, 2,
  139284. };
  139285. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139286. _vq_quantthresh__44c1_sm_p6_0,
  139287. _vq_quantmap__44c1_sm_p6_0,
  139288. 3,
  139289. 3
  139290. };
  139291. static static_codebook _44c1_sm_p6_0 = {
  139292. 4, 81,
  139293. _vq_lengthlist__44c1_sm_p6_0,
  139294. 1, -529137664, 1618345984, 2, 0,
  139295. _vq_quantlist__44c1_sm_p6_0,
  139296. NULL,
  139297. &_vq_auxt__44c1_sm_p6_0,
  139298. NULL,
  139299. 0
  139300. };
  139301. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139302. 5,
  139303. 4,
  139304. 6,
  139305. 3,
  139306. 7,
  139307. 2,
  139308. 8,
  139309. 1,
  139310. 9,
  139311. 0,
  139312. 10,
  139313. };
  139314. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139315. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139316. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139317. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139318. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139319. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139320. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139321. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139322. 10,10,10, 8, 8, 8, 8, 8, 8,
  139323. };
  139324. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139325. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139326. 3.5, 4.5,
  139327. };
  139328. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139329. 9, 7, 5, 3, 1, 0, 2, 4,
  139330. 6, 8, 10,
  139331. };
  139332. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139333. _vq_quantthresh__44c1_sm_p6_1,
  139334. _vq_quantmap__44c1_sm_p6_1,
  139335. 11,
  139336. 11
  139337. };
  139338. static static_codebook _44c1_sm_p6_1 = {
  139339. 2, 121,
  139340. _vq_lengthlist__44c1_sm_p6_1,
  139341. 1, -531365888, 1611661312, 4, 0,
  139342. _vq_quantlist__44c1_sm_p6_1,
  139343. NULL,
  139344. &_vq_auxt__44c1_sm_p6_1,
  139345. NULL,
  139346. 0
  139347. };
  139348. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139349. 6,
  139350. 5,
  139351. 7,
  139352. 4,
  139353. 8,
  139354. 3,
  139355. 9,
  139356. 2,
  139357. 10,
  139358. 1,
  139359. 11,
  139360. 0,
  139361. 12,
  139362. };
  139363. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139364. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139365. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139366. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139367. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139368. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139369. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139370. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139371. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139372. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139373. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139374. 0,12,12,11,11,13,12,14,13,
  139375. };
  139376. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139377. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139378. 12.5, 17.5, 22.5, 27.5,
  139379. };
  139380. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139381. 11, 9, 7, 5, 3, 1, 0, 2,
  139382. 4, 6, 8, 10, 12,
  139383. };
  139384. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139385. _vq_quantthresh__44c1_sm_p7_0,
  139386. _vq_quantmap__44c1_sm_p7_0,
  139387. 13,
  139388. 13
  139389. };
  139390. static static_codebook _44c1_sm_p7_0 = {
  139391. 2, 169,
  139392. _vq_lengthlist__44c1_sm_p7_0,
  139393. 1, -526516224, 1616117760, 4, 0,
  139394. _vq_quantlist__44c1_sm_p7_0,
  139395. NULL,
  139396. &_vq_auxt__44c1_sm_p7_0,
  139397. NULL,
  139398. 0
  139399. };
  139400. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139401. 2,
  139402. 1,
  139403. 3,
  139404. 0,
  139405. 4,
  139406. };
  139407. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139408. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139409. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139410. };
  139411. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139412. -1.5, -0.5, 0.5, 1.5,
  139413. };
  139414. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139415. 3, 1, 0, 2, 4,
  139416. };
  139417. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139418. _vq_quantthresh__44c1_sm_p7_1,
  139419. _vq_quantmap__44c1_sm_p7_1,
  139420. 5,
  139421. 5
  139422. };
  139423. static static_codebook _44c1_sm_p7_1 = {
  139424. 2, 25,
  139425. _vq_lengthlist__44c1_sm_p7_1,
  139426. 1, -533725184, 1611661312, 3, 0,
  139427. _vq_quantlist__44c1_sm_p7_1,
  139428. NULL,
  139429. &_vq_auxt__44c1_sm_p7_1,
  139430. NULL,
  139431. 0
  139432. };
  139433. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139434. 6,
  139435. 5,
  139436. 7,
  139437. 4,
  139438. 8,
  139439. 3,
  139440. 9,
  139441. 2,
  139442. 10,
  139443. 1,
  139444. 11,
  139445. 0,
  139446. 12,
  139447. };
  139448. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139449. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139450. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139451. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139452. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139453. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139454. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139455. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139456. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139457. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139458. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139459. 13,13,13,13,13,13,13,13,13,
  139460. };
  139461. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139462. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139463. 552.5, 773.5, 994.5, 1215.5,
  139464. };
  139465. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139466. 11, 9, 7, 5, 3, 1, 0, 2,
  139467. 4, 6, 8, 10, 12,
  139468. };
  139469. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139470. _vq_quantthresh__44c1_sm_p8_0,
  139471. _vq_quantmap__44c1_sm_p8_0,
  139472. 13,
  139473. 13
  139474. };
  139475. static static_codebook _44c1_sm_p8_0 = {
  139476. 2, 169,
  139477. _vq_lengthlist__44c1_sm_p8_0,
  139478. 1, -514541568, 1627103232, 4, 0,
  139479. _vq_quantlist__44c1_sm_p8_0,
  139480. NULL,
  139481. &_vq_auxt__44c1_sm_p8_0,
  139482. NULL,
  139483. 0
  139484. };
  139485. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139486. 6,
  139487. 5,
  139488. 7,
  139489. 4,
  139490. 8,
  139491. 3,
  139492. 9,
  139493. 2,
  139494. 10,
  139495. 1,
  139496. 11,
  139497. 0,
  139498. 12,
  139499. };
  139500. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139501. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139502. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139503. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139504. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139505. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139506. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139507. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139508. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139509. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139510. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139511. 20,13,12,12,12,14,12,14,13,
  139512. };
  139513. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139514. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139515. 42.5, 59.5, 76.5, 93.5,
  139516. };
  139517. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139518. 11, 9, 7, 5, 3, 1, 0, 2,
  139519. 4, 6, 8, 10, 12,
  139520. };
  139521. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139522. _vq_quantthresh__44c1_sm_p8_1,
  139523. _vq_quantmap__44c1_sm_p8_1,
  139524. 13,
  139525. 13
  139526. };
  139527. static static_codebook _44c1_sm_p8_1 = {
  139528. 2, 169,
  139529. _vq_lengthlist__44c1_sm_p8_1,
  139530. 1, -522616832, 1620115456, 4, 0,
  139531. _vq_quantlist__44c1_sm_p8_1,
  139532. NULL,
  139533. &_vq_auxt__44c1_sm_p8_1,
  139534. NULL,
  139535. 0
  139536. };
  139537. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139538. 8,
  139539. 7,
  139540. 9,
  139541. 6,
  139542. 10,
  139543. 5,
  139544. 11,
  139545. 4,
  139546. 12,
  139547. 3,
  139548. 13,
  139549. 2,
  139550. 14,
  139551. 1,
  139552. 15,
  139553. 0,
  139554. 16,
  139555. };
  139556. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139557. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139558. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139559. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139560. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139561. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139562. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139563. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139564. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139565. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139566. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139567. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139568. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139569. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139570. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139571. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139572. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139573. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139574. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139575. 9,
  139576. };
  139577. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139578. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139579. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139580. };
  139581. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139582. 15, 13, 11, 9, 7, 5, 3, 1,
  139583. 0, 2, 4, 6, 8, 10, 12, 14,
  139584. 16,
  139585. };
  139586. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139587. _vq_quantthresh__44c1_sm_p8_2,
  139588. _vq_quantmap__44c1_sm_p8_2,
  139589. 17,
  139590. 17
  139591. };
  139592. static static_codebook _44c1_sm_p8_2 = {
  139593. 2, 289,
  139594. _vq_lengthlist__44c1_sm_p8_2,
  139595. 1, -529530880, 1611661312, 5, 0,
  139596. _vq_quantlist__44c1_sm_p8_2,
  139597. NULL,
  139598. &_vq_auxt__44c1_sm_p8_2,
  139599. NULL,
  139600. 0
  139601. };
  139602. static long _huff_lengthlist__44c1_sm_short[] = {
  139603. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139604. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139605. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139606. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139607. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139608. 11,
  139609. };
  139610. static static_codebook _huff_book__44c1_sm_short = {
  139611. 2, 81,
  139612. _huff_lengthlist__44c1_sm_short,
  139613. 0, 0, 0, 0, 0,
  139614. NULL,
  139615. NULL,
  139616. NULL,
  139617. NULL,
  139618. 0
  139619. };
  139620. static long _huff_lengthlist__44cn1_s_long[] = {
  139621. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139622. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139623. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139624. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139625. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139626. 20,
  139627. };
  139628. static static_codebook _huff_book__44cn1_s_long = {
  139629. 2, 81,
  139630. _huff_lengthlist__44cn1_s_long,
  139631. 0, 0, 0, 0, 0,
  139632. NULL,
  139633. NULL,
  139634. NULL,
  139635. NULL,
  139636. 0
  139637. };
  139638. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139639. 1,
  139640. 0,
  139641. 2,
  139642. };
  139643. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139644. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139645. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139649. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139650. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139655. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139690. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139695. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139700. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139736. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139741. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139746. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139873. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139878. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139883. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  139918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  139923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  139928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  140055. };
  140056. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140057. -0.5, 0.5,
  140058. };
  140059. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140060. 1, 0, 2,
  140061. };
  140062. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140063. _vq_quantthresh__44cn1_s_p1_0,
  140064. _vq_quantmap__44cn1_s_p1_0,
  140065. 3,
  140066. 3
  140067. };
  140068. static static_codebook _44cn1_s_p1_0 = {
  140069. 8, 6561,
  140070. _vq_lengthlist__44cn1_s_p1_0,
  140071. 1, -535822336, 1611661312, 2, 0,
  140072. _vq_quantlist__44cn1_s_p1_0,
  140073. NULL,
  140074. &_vq_auxt__44cn1_s_p1_0,
  140075. NULL,
  140076. 0
  140077. };
  140078. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140079. 2,
  140080. 1,
  140081. 3,
  140082. 0,
  140083. 4,
  140084. };
  140085. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140086. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  140126. };
  140127. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140128. -1.5, -0.5, 0.5, 1.5,
  140129. };
  140130. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140131. 3, 1, 0, 2, 4,
  140132. };
  140133. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140134. _vq_quantthresh__44cn1_s_p2_0,
  140135. _vq_quantmap__44cn1_s_p2_0,
  140136. 5,
  140137. 5
  140138. };
  140139. static static_codebook _44cn1_s_p2_0 = {
  140140. 4, 625,
  140141. _vq_lengthlist__44cn1_s_p2_0,
  140142. 1, -533725184, 1611661312, 3, 0,
  140143. _vq_quantlist__44cn1_s_p2_0,
  140144. NULL,
  140145. &_vq_auxt__44cn1_s_p2_0,
  140146. NULL,
  140147. 0
  140148. };
  140149. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140150. 4,
  140151. 3,
  140152. 5,
  140153. 2,
  140154. 6,
  140155. 1,
  140156. 7,
  140157. 0,
  140158. 8,
  140159. };
  140160. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140161. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140162. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140163. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140164. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140165. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0,
  140167. };
  140168. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140169. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140170. };
  140171. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140172. 7, 5, 3, 1, 0, 2, 4, 6,
  140173. 8,
  140174. };
  140175. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140176. _vq_quantthresh__44cn1_s_p3_0,
  140177. _vq_quantmap__44cn1_s_p3_0,
  140178. 9,
  140179. 9
  140180. };
  140181. static static_codebook _44cn1_s_p3_0 = {
  140182. 2, 81,
  140183. _vq_lengthlist__44cn1_s_p3_0,
  140184. 1, -531628032, 1611661312, 4, 0,
  140185. _vq_quantlist__44cn1_s_p3_0,
  140186. NULL,
  140187. &_vq_auxt__44cn1_s_p3_0,
  140188. NULL,
  140189. 0
  140190. };
  140191. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140192. 4,
  140193. 3,
  140194. 5,
  140195. 2,
  140196. 6,
  140197. 1,
  140198. 7,
  140199. 0,
  140200. 8,
  140201. };
  140202. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140203. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140204. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140205. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140206. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140207. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140208. 11,
  140209. };
  140210. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140211. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140212. };
  140213. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140214. 7, 5, 3, 1, 0, 2, 4, 6,
  140215. 8,
  140216. };
  140217. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140218. _vq_quantthresh__44cn1_s_p4_0,
  140219. _vq_quantmap__44cn1_s_p4_0,
  140220. 9,
  140221. 9
  140222. };
  140223. static static_codebook _44cn1_s_p4_0 = {
  140224. 2, 81,
  140225. _vq_lengthlist__44cn1_s_p4_0,
  140226. 1, -531628032, 1611661312, 4, 0,
  140227. _vq_quantlist__44cn1_s_p4_0,
  140228. NULL,
  140229. &_vq_auxt__44cn1_s_p4_0,
  140230. NULL,
  140231. 0
  140232. };
  140233. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140234. 8,
  140235. 7,
  140236. 9,
  140237. 6,
  140238. 10,
  140239. 5,
  140240. 11,
  140241. 4,
  140242. 12,
  140243. 3,
  140244. 13,
  140245. 2,
  140246. 14,
  140247. 1,
  140248. 15,
  140249. 0,
  140250. 16,
  140251. };
  140252. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140253. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140254. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140255. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140256. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140257. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140258. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140259. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140260. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140261. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140262. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140263. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140264. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140265. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140266. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140267. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140268. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140269. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140271. 14,
  140272. };
  140273. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140274. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140275. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140276. };
  140277. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140278. 15, 13, 11, 9, 7, 5, 3, 1,
  140279. 0, 2, 4, 6, 8, 10, 12, 14,
  140280. 16,
  140281. };
  140282. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140283. _vq_quantthresh__44cn1_s_p5_0,
  140284. _vq_quantmap__44cn1_s_p5_0,
  140285. 17,
  140286. 17
  140287. };
  140288. static static_codebook _44cn1_s_p5_0 = {
  140289. 2, 289,
  140290. _vq_lengthlist__44cn1_s_p5_0,
  140291. 1, -529530880, 1611661312, 5, 0,
  140292. _vq_quantlist__44cn1_s_p5_0,
  140293. NULL,
  140294. &_vq_auxt__44cn1_s_p5_0,
  140295. NULL,
  140296. 0
  140297. };
  140298. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140299. 1,
  140300. 0,
  140301. 2,
  140302. };
  140303. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140304. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140305. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140306. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140307. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140308. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140309. 10,
  140310. };
  140311. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140312. -5.5, 5.5,
  140313. };
  140314. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140315. 1, 0, 2,
  140316. };
  140317. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140318. _vq_quantthresh__44cn1_s_p6_0,
  140319. _vq_quantmap__44cn1_s_p6_0,
  140320. 3,
  140321. 3
  140322. };
  140323. static static_codebook _44cn1_s_p6_0 = {
  140324. 4, 81,
  140325. _vq_lengthlist__44cn1_s_p6_0,
  140326. 1, -529137664, 1618345984, 2, 0,
  140327. _vq_quantlist__44cn1_s_p6_0,
  140328. NULL,
  140329. &_vq_auxt__44cn1_s_p6_0,
  140330. NULL,
  140331. 0
  140332. };
  140333. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140334. 5,
  140335. 4,
  140336. 6,
  140337. 3,
  140338. 7,
  140339. 2,
  140340. 8,
  140341. 1,
  140342. 9,
  140343. 0,
  140344. 10,
  140345. };
  140346. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140347. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140348. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140349. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140350. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140351. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140352. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140353. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140354. 10,10,10, 9, 9, 9, 9, 9, 9,
  140355. };
  140356. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140357. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140358. 3.5, 4.5,
  140359. };
  140360. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140361. 9, 7, 5, 3, 1, 0, 2, 4,
  140362. 6, 8, 10,
  140363. };
  140364. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140365. _vq_quantthresh__44cn1_s_p6_1,
  140366. _vq_quantmap__44cn1_s_p6_1,
  140367. 11,
  140368. 11
  140369. };
  140370. static static_codebook _44cn1_s_p6_1 = {
  140371. 2, 121,
  140372. _vq_lengthlist__44cn1_s_p6_1,
  140373. 1, -531365888, 1611661312, 4, 0,
  140374. _vq_quantlist__44cn1_s_p6_1,
  140375. NULL,
  140376. &_vq_auxt__44cn1_s_p6_1,
  140377. NULL,
  140378. 0
  140379. };
  140380. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140381. 6,
  140382. 5,
  140383. 7,
  140384. 4,
  140385. 8,
  140386. 3,
  140387. 9,
  140388. 2,
  140389. 10,
  140390. 1,
  140391. 11,
  140392. 0,
  140393. 12,
  140394. };
  140395. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140396. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140397. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140398. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140399. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140400. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140401. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140402. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140403. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140404. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140405. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140406. 0,13,13,12,12,13,13,13,14,
  140407. };
  140408. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140409. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140410. 12.5, 17.5, 22.5, 27.5,
  140411. };
  140412. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140413. 11, 9, 7, 5, 3, 1, 0, 2,
  140414. 4, 6, 8, 10, 12,
  140415. };
  140416. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140417. _vq_quantthresh__44cn1_s_p7_0,
  140418. _vq_quantmap__44cn1_s_p7_0,
  140419. 13,
  140420. 13
  140421. };
  140422. static static_codebook _44cn1_s_p7_0 = {
  140423. 2, 169,
  140424. _vq_lengthlist__44cn1_s_p7_0,
  140425. 1, -526516224, 1616117760, 4, 0,
  140426. _vq_quantlist__44cn1_s_p7_0,
  140427. NULL,
  140428. &_vq_auxt__44cn1_s_p7_0,
  140429. NULL,
  140430. 0
  140431. };
  140432. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140433. 2,
  140434. 1,
  140435. 3,
  140436. 0,
  140437. 4,
  140438. };
  140439. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140440. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140441. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140442. };
  140443. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140444. -1.5, -0.5, 0.5, 1.5,
  140445. };
  140446. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140447. 3, 1, 0, 2, 4,
  140448. };
  140449. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140450. _vq_quantthresh__44cn1_s_p7_1,
  140451. _vq_quantmap__44cn1_s_p7_1,
  140452. 5,
  140453. 5
  140454. };
  140455. static static_codebook _44cn1_s_p7_1 = {
  140456. 2, 25,
  140457. _vq_lengthlist__44cn1_s_p7_1,
  140458. 1, -533725184, 1611661312, 3, 0,
  140459. _vq_quantlist__44cn1_s_p7_1,
  140460. NULL,
  140461. &_vq_auxt__44cn1_s_p7_1,
  140462. NULL,
  140463. 0
  140464. };
  140465. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140466. 2,
  140467. 1,
  140468. 3,
  140469. 0,
  140470. 4,
  140471. };
  140472. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140473. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140474. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140476. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140479. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140480. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140481. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140482. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140488. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140498. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140499. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140500. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140501. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140502. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140503. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140504. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140505. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140506. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140507. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140508. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140509. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140510. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140511. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140512. 12,
  140513. };
  140514. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140515. -331.5, -110.5, 110.5, 331.5,
  140516. };
  140517. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140518. 3, 1, 0, 2, 4,
  140519. };
  140520. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140521. _vq_quantthresh__44cn1_s_p8_0,
  140522. _vq_quantmap__44cn1_s_p8_0,
  140523. 5,
  140524. 5
  140525. };
  140526. static static_codebook _44cn1_s_p8_0 = {
  140527. 4, 625,
  140528. _vq_lengthlist__44cn1_s_p8_0,
  140529. 1, -518283264, 1627103232, 3, 0,
  140530. _vq_quantlist__44cn1_s_p8_0,
  140531. NULL,
  140532. &_vq_auxt__44cn1_s_p8_0,
  140533. NULL,
  140534. 0
  140535. };
  140536. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140537. 6,
  140538. 5,
  140539. 7,
  140540. 4,
  140541. 8,
  140542. 3,
  140543. 9,
  140544. 2,
  140545. 10,
  140546. 1,
  140547. 11,
  140548. 0,
  140549. 12,
  140550. };
  140551. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140552. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140553. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140554. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140555. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140556. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140557. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140558. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140559. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140560. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140561. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140562. 15,12,12,11,11,14,12,13,14,
  140563. };
  140564. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140565. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140566. 42.5, 59.5, 76.5, 93.5,
  140567. };
  140568. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140569. 11, 9, 7, 5, 3, 1, 0, 2,
  140570. 4, 6, 8, 10, 12,
  140571. };
  140572. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140573. _vq_quantthresh__44cn1_s_p8_1,
  140574. _vq_quantmap__44cn1_s_p8_1,
  140575. 13,
  140576. 13
  140577. };
  140578. static static_codebook _44cn1_s_p8_1 = {
  140579. 2, 169,
  140580. _vq_lengthlist__44cn1_s_p8_1,
  140581. 1, -522616832, 1620115456, 4, 0,
  140582. _vq_quantlist__44cn1_s_p8_1,
  140583. NULL,
  140584. &_vq_auxt__44cn1_s_p8_1,
  140585. NULL,
  140586. 0
  140587. };
  140588. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140589. 8,
  140590. 7,
  140591. 9,
  140592. 6,
  140593. 10,
  140594. 5,
  140595. 11,
  140596. 4,
  140597. 12,
  140598. 3,
  140599. 13,
  140600. 2,
  140601. 14,
  140602. 1,
  140603. 15,
  140604. 0,
  140605. 16,
  140606. };
  140607. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140608. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140609. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140610. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140611. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140612. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140613. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140614. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140615. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140616. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140617. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140618. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140619. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140620. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140621. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140622. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140623. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140624. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140625. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140626. 9,
  140627. };
  140628. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140629. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140630. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140631. };
  140632. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140633. 15, 13, 11, 9, 7, 5, 3, 1,
  140634. 0, 2, 4, 6, 8, 10, 12, 14,
  140635. 16,
  140636. };
  140637. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140638. _vq_quantthresh__44cn1_s_p8_2,
  140639. _vq_quantmap__44cn1_s_p8_2,
  140640. 17,
  140641. 17
  140642. };
  140643. static static_codebook _44cn1_s_p8_2 = {
  140644. 2, 289,
  140645. _vq_lengthlist__44cn1_s_p8_2,
  140646. 1, -529530880, 1611661312, 5, 0,
  140647. _vq_quantlist__44cn1_s_p8_2,
  140648. NULL,
  140649. &_vq_auxt__44cn1_s_p8_2,
  140650. NULL,
  140651. 0
  140652. };
  140653. static long _huff_lengthlist__44cn1_s_short[] = {
  140654. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140655. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140656. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140657. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140658. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140659. 10,
  140660. };
  140661. static static_codebook _huff_book__44cn1_s_short = {
  140662. 2, 81,
  140663. _huff_lengthlist__44cn1_s_short,
  140664. 0, 0, 0, 0, 0,
  140665. NULL,
  140666. NULL,
  140667. NULL,
  140668. NULL,
  140669. 0
  140670. };
  140671. static long _huff_lengthlist__44cn1_sm_long[] = {
  140672. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140673. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140674. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140675. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140676. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140677. 17,
  140678. };
  140679. static static_codebook _huff_book__44cn1_sm_long = {
  140680. 2, 81,
  140681. _huff_lengthlist__44cn1_sm_long,
  140682. 0, 0, 0, 0, 0,
  140683. NULL,
  140684. NULL,
  140685. NULL,
  140686. NULL,
  140687. 0
  140688. };
  140689. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140690. 1,
  140691. 0,
  140692. 2,
  140693. };
  140694. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140695. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140696. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140701. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140706. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140741. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140746. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140751. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140787. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140792. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140797. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140924. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140929. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140934. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  140969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  140974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  140979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  141106. };
  141107. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141108. -0.5, 0.5,
  141109. };
  141110. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141111. 1, 0, 2,
  141112. };
  141113. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141114. _vq_quantthresh__44cn1_sm_p1_0,
  141115. _vq_quantmap__44cn1_sm_p1_0,
  141116. 3,
  141117. 3
  141118. };
  141119. static static_codebook _44cn1_sm_p1_0 = {
  141120. 8, 6561,
  141121. _vq_lengthlist__44cn1_sm_p1_0,
  141122. 1, -535822336, 1611661312, 2, 0,
  141123. _vq_quantlist__44cn1_sm_p1_0,
  141124. NULL,
  141125. &_vq_auxt__44cn1_sm_p1_0,
  141126. NULL,
  141127. 0
  141128. };
  141129. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141130. 2,
  141131. 1,
  141132. 3,
  141133. 0,
  141134. 4,
  141135. };
  141136. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141137. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  141177. };
  141178. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141179. -1.5, -0.5, 0.5, 1.5,
  141180. };
  141181. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141182. 3, 1, 0, 2, 4,
  141183. };
  141184. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141185. _vq_quantthresh__44cn1_sm_p2_0,
  141186. _vq_quantmap__44cn1_sm_p2_0,
  141187. 5,
  141188. 5
  141189. };
  141190. static static_codebook _44cn1_sm_p2_0 = {
  141191. 4, 625,
  141192. _vq_lengthlist__44cn1_sm_p2_0,
  141193. 1, -533725184, 1611661312, 3, 0,
  141194. _vq_quantlist__44cn1_sm_p2_0,
  141195. NULL,
  141196. &_vq_auxt__44cn1_sm_p2_0,
  141197. NULL,
  141198. 0
  141199. };
  141200. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141201. 4,
  141202. 3,
  141203. 5,
  141204. 2,
  141205. 6,
  141206. 1,
  141207. 7,
  141208. 0,
  141209. 8,
  141210. };
  141211. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141212. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141213. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141214. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141215. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141216. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0,
  141218. };
  141219. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141220. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141221. };
  141222. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141223. 7, 5, 3, 1, 0, 2, 4, 6,
  141224. 8,
  141225. };
  141226. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141227. _vq_quantthresh__44cn1_sm_p3_0,
  141228. _vq_quantmap__44cn1_sm_p3_0,
  141229. 9,
  141230. 9
  141231. };
  141232. static static_codebook _44cn1_sm_p3_0 = {
  141233. 2, 81,
  141234. _vq_lengthlist__44cn1_sm_p3_0,
  141235. 1, -531628032, 1611661312, 4, 0,
  141236. _vq_quantlist__44cn1_sm_p3_0,
  141237. NULL,
  141238. &_vq_auxt__44cn1_sm_p3_0,
  141239. NULL,
  141240. 0
  141241. };
  141242. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141243. 4,
  141244. 3,
  141245. 5,
  141246. 2,
  141247. 6,
  141248. 1,
  141249. 7,
  141250. 0,
  141251. 8,
  141252. };
  141253. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141254. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141255. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141256. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141257. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141258. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141259. 11,
  141260. };
  141261. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141262. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141263. };
  141264. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141265. 7, 5, 3, 1, 0, 2, 4, 6,
  141266. 8,
  141267. };
  141268. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141269. _vq_quantthresh__44cn1_sm_p4_0,
  141270. _vq_quantmap__44cn1_sm_p4_0,
  141271. 9,
  141272. 9
  141273. };
  141274. static static_codebook _44cn1_sm_p4_0 = {
  141275. 2, 81,
  141276. _vq_lengthlist__44cn1_sm_p4_0,
  141277. 1, -531628032, 1611661312, 4, 0,
  141278. _vq_quantlist__44cn1_sm_p4_0,
  141279. NULL,
  141280. &_vq_auxt__44cn1_sm_p4_0,
  141281. NULL,
  141282. 0
  141283. };
  141284. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141285. 8,
  141286. 7,
  141287. 9,
  141288. 6,
  141289. 10,
  141290. 5,
  141291. 11,
  141292. 4,
  141293. 12,
  141294. 3,
  141295. 13,
  141296. 2,
  141297. 14,
  141298. 1,
  141299. 15,
  141300. 0,
  141301. 16,
  141302. };
  141303. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141304. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141305. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141306. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141307. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141308. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141309. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141310. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141311. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141312. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141313. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141314. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141315. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141316. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141317. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141318. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141319. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141320. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141322. 14,
  141323. };
  141324. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141325. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141326. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141327. };
  141328. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141329. 15, 13, 11, 9, 7, 5, 3, 1,
  141330. 0, 2, 4, 6, 8, 10, 12, 14,
  141331. 16,
  141332. };
  141333. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141334. _vq_quantthresh__44cn1_sm_p5_0,
  141335. _vq_quantmap__44cn1_sm_p5_0,
  141336. 17,
  141337. 17
  141338. };
  141339. static static_codebook _44cn1_sm_p5_0 = {
  141340. 2, 289,
  141341. _vq_lengthlist__44cn1_sm_p5_0,
  141342. 1, -529530880, 1611661312, 5, 0,
  141343. _vq_quantlist__44cn1_sm_p5_0,
  141344. NULL,
  141345. &_vq_auxt__44cn1_sm_p5_0,
  141346. NULL,
  141347. 0
  141348. };
  141349. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141350. 1,
  141351. 0,
  141352. 2,
  141353. };
  141354. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141355. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141356. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141357. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141358. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141359. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141360. 10,
  141361. };
  141362. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141363. -5.5, 5.5,
  141364. };
  141365. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141366. 1, 0, 2,
  141367. };
  141368. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141369. _vq_quantthresh__44cn1_sm_p6_0,
  141370. _vq_quantmap__44cn1_sm_p6_0,
  141371. 3,
  141372. 3
  141373. };
  141374. static static_codebook _44cn1_sm_p6_0 = {
  141375. 4, 81,
  141376. _vq_lengthlist__44cn1_sm_p6_0,
  141377. 1, -529137664, 1618345984, 2, 0,
  141378. _vq_quantlist__44cn1_sm_p6_0,
  141379. NULL,
  141380. &_vq_auxt__44cn1_sm_p6_0,
  141381. NULL,
  141382. 0
  141383. };
  141384. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141385. 5,
  141386. 4,
  141387. 6,
  141388. 3,
  141389. 7,
  141390. 2,
  141391. 8,
  141392. 1,
  141393. 9,
  141394. 0,
  141395. 10,
  141396. };
  141397. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141398. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141399. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141400. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141401. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141402. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141403. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141404. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141405. 10,10,10, 8, 9, 8, 8, 9, 8,
  141406. };
  141407. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141408. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141409. 3.5, 4.5,
  141410. };
  141411. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141412. 9, 7, 5, 3, 1, 0, 2, 4,
  141413. 6, 8, 10,
  141414. };
  141415. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141416. _vq_quantthresh__44cn1_sm_p6_1,
  141417. _vq_quantmap__44cn1_sm_p6_1,
  141418. 11,
  141419. 11
  141420. };
  141421. static static_codebook _44cn1_sm_p6_1 = {
  141422. 2, 121,
  141423. _vq_lengthlist__44cn1_sm_p6_1,
  141424. 1, -531365888, 1611661312, 4, 0,
  141425. _vq_quantlist__44cn1_sm_p6_1,
  141426. NULL,
  141427. &_vq_auxt__44cn1_sm_p6_1,
  141428. NULL,
  141429. 0
  141430. };
  141431. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141432. 6,
  141433. 5,
  141434. 7,
  141435. 4,
  141436. 8,
  141437. 3,
  141438. 9,
  141439. 2,
  141440. 10,
  141441. 1,
  141442. 11,
  141443. 0,
  141444. 12,
  141445. };
  141446. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141447. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141448. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141449. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141450. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141451. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141452. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141453. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141454. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141455. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141456. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141457. 0,13,12,12,12,13,13,13,14,
  141458. };
  141459. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141460. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141461. 12.5, 17.5, 22.5, 27.5,
  141462. };
  141463. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141464. 11, 9, 7, 5, 3, 1, 0, 2,
  141465. 4, 6, 8, 10, 12,
  141466. };
  141467. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141468. _vq_quantthresh__44cn1_sm_p7_0,
  141469. _vq_quantmap__44cn1_sm_p7_0,
  141470. 13,
  141471. 13
  141472. };
  141473. static static_codebook _44cn1_sm_p7_0 = {
  141474. 2, 169,
  141475. _vq_lengthlist__44cn1_sm_p7_0,
  141476. 1, -526516224, 1616117760, 4, 0,
  141477. _vq_quantlist__44cn1_sm_p7_0,
  141478. NULL,
  141479. &_vq_auxt__44cn1_sm_p7_0,
  141480. NULL,
  141481. 0
  141482. };
  141483. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141484. 2,
  141485. 1,
  141486. 3,
  141487. 0,
  141488. 4,
  141489. };
  141490. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141491. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141492. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141493. };
  141494. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141495. -1.5, -0.5, 0.5, 1.5,
  141496. };
  141497. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141498. 3, 1, 0, 2, 4,
  141499. };
  141500. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141501. _vq_quantthresh__44cn1_sm_p7_1,
  141502. _vq_quantmap__44cn1_sm_p7_1,
  141503. 5,
  141504. 5
  141505. };
  141506. static static_codebook _44cn1_sm_p7_1 = {
  141507. 2, 25,
  141508. _vq_lengthlist__44cn1_sm_p7_1,
  141509. 1, -533725184, 1611661312, 3, 0,
  141510. _vq_quantlist__44cn1_sm_p7_1,
  141511. NULL,
  141512. &_vq_auxt__44cn1_sm_p7_1,
  141513. NULL,
  141514. 0
  141515. };
  141516. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141517. 4,
  141518. 3,
  141519. 5,
  141520. 2,
  141521. 6,
  141522. 1,
  141523. 7,
  141524. 0,
  141525. 8,
  141526. };
  141527. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141528. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141529. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141530. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141531. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141532. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141533. 14,
  141534. };
  141535. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141536. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141537. };
  141538. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141539. 7, 5, 3, 1, 0, 2, 4, 6,
  141540. 8,
  141541. };
  141542. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141543. _vq_quantthresh__44cn1_sm_p8_0,
  141544. _vq_quantmap__44cn1_sm_p8_0,
  141545. 9,
  141546. 9
  141547. };
  141548. static static_codebook _44cn1_sm_p8_0 = {
  141549. 2, 81,
  141550. _vq_lengthlist__44cn1_sm_p8_0,
  141551. 1, -516186112, 1627103232, 4, 0,
  141552. _vq_quantlist__44cn1_sm_p8_0,
  141553. NULL,
  141554. &_vq_auxt__44cn1_sm_p8_0,
  141555. NULL,
  141556. 0
  141557. };
  141558. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141559. 6,
  141560. 5,
  141561. 7,
  141562. 4,
  141563. 8,
  141564. 3,
  141565. 9,
  141566. 2,
  141567. 10,
  141568. 1,
  141569. 11,
  141570. 0,
  141571. 12,
  141572. };
  141573. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141574. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141575. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141576. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141577. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141578. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141579. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141580. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141581. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141582. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141583. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141584. 17,12,12,11,10,13,11,13,13,
  141585. };
  141586. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141587. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141588. 42.5, 59.5, 76.5, 93.5,
  141589. };
  141590. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141591. 11, 9, 7, 5, 3, 1, 0, 2,
  141592. 4, 6, 8, 10, 12,
  141593. };
  141594. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141595. _vq_quantthresh__44cn1_sm_p8_1,
  141596. _vq_quantmap__44cn1_sm_p8_1,
  141597. 13,
  141598. 13
  141599. };
  141600. static static_codebook _44cn1_sm_p8_1 = {
  141601. 2, 169,
  141602. _vq_lengthlist__44cn1_sm_p8_1,
  141603. 1, -522616832, 1620115456, 4, 0,
  141604. _vq_quantlist__44cn1_sm_p8_1,
  141605. NULL,
  141606. &_vq_auxt__44cn1_sm_p8_1,
  141607. NULL,
  141608. 0
  141609. };
  141610. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141611. 8,
  141612. 7,
  141613. 9,
  141614. 6,
  141615. 10,
  141616. 5,
  141617. 11,
  141618. 4,
  141619. 12,
  141620. 3,
  141621. 13,
  141622. 2,
  141623. 14,
  141624. 1,
  141625. 15,
  141626. 0,
  141627. 16,
  141628. };
  141629. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141630. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141631. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141632. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141633. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141634. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141635. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141636. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141637. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141638. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141639. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141640. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141641. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141642. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141643. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141644. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141645. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141646. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141647. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141648. 9,
  141649. };
  141650. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141651. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141652. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141653. };
  141654. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141655. 15, 13, 11, 9, 7, 5, 3, 1,
  141656. 0, 2, 4, 6, 8, 10, 12, 14,
  141657. 16,
  141658. };
  141659. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141660. _vq_quantthresh__44cn1_sm_p8_2,
  141661. _vq_quantmap__44cn1_sm_p8_2,
  141662. 17,
  141663. 17
  141664. };
  141665. static static_codebook _44cn1_sm_p8_2 = {
  141666. 2, 289,
  141667. _vq_lengthlist__44cn1_sm_p8_2,
  141668. 1, -529530880, 1611661312, 5, 0,
  141669. _vq_quantlist__44cn1_sm_p8_2,
  141670. NULL,
  141671. &_vq_auxt__44cn1_sm_p8_2,
  141672. NULL,
  141673. 0
  141674. };
  141675. static long _huff_lengthlist__44cn1_sm_short[] = {
  141676. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141677. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141678. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141679. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141680. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141681. 9,
  141682. };
  141683. static static_codebook _huff_book__44cn1_sm_short = {
  141684. 2, 81,
  141685. _huff_lengthlist__44cn1_sm_short,
  141686. 0, 0, 0, 0, 0,
  141687. NULL,
  141688. NULL,
  141689. NULL,
  141690. NULL,
  141691. 0
  141692. };
  141693. /*** End of inlined file: res_books_stereo.h ***/
  141694. /***** residue backends *********************************************/
  141695. static vorbis_info_residue0 _residue_44_low={
  141696. 0,-1, -1, 9,-1,
  141697. /* 0 1 2 3 4 5 6 7 */
  141698. {0},
  141699. {-1},
  141700. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141701. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141702. };
  141703. static vorbis_info_residue0 _residue_44_mid={
  141704. 0,-1, -1, 10,-1,
  141705. /* 0 1 2 3 4 5 6 7 8 */
  141706. {0},
  141707. {-1},
  141708. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141709. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141710. };
  141711. static vorbis_info_residue0 _residue_44_high={
  141712. 0,-1, -1, 10,-1,
  141713. /* 0 1 2 3 4 5 6 7 8 */
  141714. {0},
  141715. {-1},
  141716. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141717. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141718. };
  141719. static static_bookblock _resbook_44s_n1={
  141720. {
  141721. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141722. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141723. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141724. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141725. }
  141726. };
  141727. static static_bookblock _resbook_44sm_n1={
  141728. {
  141729. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141730. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141731. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141732. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141733. }
  141734. };
  141735. static static_bookblock _resbook_44s_0={
  141736. {
  141737. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141738. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141739. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141740. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141741. }
  141742. };
  141743. static static_bookblock _resbook_44sm_0={
  141744. {
  141745. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141746. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141747. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141748. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141749. }
  141750. };
  141751. static static_bookblock _resbook_44s_1={
  141752. {
  141753. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141754. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141755. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141756. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141757. }
  141758. };
  141759. static static_bookblock _resbook_44sm_1={
  141760. {
  141761. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141762. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141763. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141764. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141765. }
  141766. };
  141767. static static_bookblock _resbook_44s_2={
  141768. {
  141769. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141770. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141771. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141772. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141773. }
  141774. };
  141775. static static_bookblock _resbook_44s_3={
  141776. {
  141777. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141778. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141779. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141780. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141781. }
  141782. };
  141783. static static_bookblock _resbook_44s_4={
  141784. {
  141785. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141786. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141787. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141788. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141789. }
  141790. };
  141791. static static_bookblock _resbook_44s_5={
  141792. {
  141793. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141794. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141795. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141796. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141797. }
  141798. };
  141799. static static_bookblock _resbook_44s_6={
  141800. {
  141801. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141802. {0,0,&_44c6_s_p4_0},
  141803. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141804. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141805. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141806. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141807. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141808. }
  141809. };
  141810. static static_bookblock _resbook_44s_7={
  141811. {
  141812. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141813. {0,0,&_44c7_s_p4_0},
  141814. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141815. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141816. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141817. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141818. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141819. }
  141820. };
  141821. static static_bookblock _resbook_44s_8={
  141822. {
  141823. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141824. {0,0,&_44c8_s_p4_0},
  141825. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141826. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141827. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141828. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141829. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141830. }
  141831. };
  141832. static static_bookblock _resbook_44s_9={
  141833. {
  141834. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141835. {0,0,&_44c9_s_p4_0},
  141836. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141837. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141838. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141839. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141840. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141841. }
  141842. };
  141843. static vorbis_residue_template _res_44s_n1[]={
  141844. {2,0, &_residue_44_low,
  141845. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141846. &_resbook_44s_n1,&_resbook_44sm_n1},
  141847. {2,0, &_residue_44_low,
  141848. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141849. &_resbook_44s_n1,&_resbook_44sm_n1}
  141850. };
  141851. static vorbis_residue_template _res_44s_0[]={
  141852. {2,0, &_residue_44_low,
  141853. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141854. &_resbook_44s_0,&_resbook_44sm_0},
  141855. {2,0, &_residue_44_low,
  141856. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141857. &_resbook_44s_0,&_resbook_44sm_0}
  141858. };
  141859. static vorbis_residue_template _res_44s_1[]={
  141860. {2,0, &_residue_44_low,
  141861. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141862. &_resbook_44s_1,&_resbook_44sm_1},
  141863. {2,0, &_residue_44_low,
  141864. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141865. &_resbook_44s_1,&_resbook_44sm_1}
  141866. };
  141867. static vorbis_residue_template _res_44s_2[]={
  141868. {2,0, &_residue_44_mid,
  141869. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141870. &_resbook_44s_2,&_resbook_44s_2},
  141871. {2,0, &_residue_44_mid,
  141872. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141873. &_resbook_44s_2,&_resbook_44s_2}
  141874. };
  141875. static vorbis_residue_template _res_44s_3[]={
  141876. {2,0, &_residue_44_mid,
  141877. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141878. &_resbook_44s_3,&_resbook_44s_3},
  141879. {2,0, &_residue_44_mid,
  141880. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141881. &_resbook_44s_3,&_resbook_44s_3}
  141882. };
  141883. static vorbis_residue_template _res_44s_4[]={
  141884. {2,0, &_residue_44_mid,
  141885. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141886. &_resbook_44s_4,&_resbook_44s_4},
  141887. {2,0, &_residue_44_mid,
  141888. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141889. &_resbook_44s_4,&_resbook_44s_4}
  141890. };
  141891. static vorbis_residue_template _res_44s_5[]={
  141892. {2,0, &_residue_44_mid,
  141893. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141894. &_resbook_44s_5,&_resbook_44s_5},
  141895. {2,0, &_residue_44_mid,
  141896. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141897. &_resbook_44s_5,&_resbook_44s_5}
  141898. };
  141899. static vorbis_residue_template _res_44s_6[]={
  141900. {2,0, &_residue_44_high,
  141901. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141902. &_resbook_44s_6,&_resbook_44s_6},
  141903. {2,0, &_residue_44_high,
  141904. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141905. &_resbook_44s_6,&_resbook_44s_6}
  141906. };
  141907. static vorbis_residue_template _res_44s_7[]={
  141908. {2,0, &_residue_44_high,
  141909. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141910. &_resbook_44s_7,&_resbook_44s_7},
  141911. {2,0, &_residue_44_high,
  141912. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141913. &_resbook_44s_7,&_resbook_44s_7}
  141914. };
  141915. static vorbis_residue_template _res_44s_8[]={
  141916. {2,0, &_residue_44_high,
  141917. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141918. &_resbook_44s_8,&_resbook_44s_8},
  141919. {2,0, &_residue_44_high,
  141920. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141921. &_resbook_44s_8,&_resbook_44s_8}
  141922. };
  141923. static vorbis_residue_template _res_44s_9[]={
  141924. {2,0, &_residue_44_high,
  141925. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141926. &_resbook_44s_9,&_resbook_44s_9},
  141927. {2,0, &_residue_44_high,
  141928. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141929. &_resbook_44s_9,&_resbook_44s_9}
  141930. };
  141931. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141932. { _map_nominal, _res_44s_n1 }, /* -1 */
  141933. { _map_nominal, _res_44s_0 }, /* 0 */
  141934. { _map_nominal, _res_44s_1 }, /* 1 */
  141935. { _map_nominal, _res_44s_2 }, /* 2 */
  141936. { _map_nominal, _res_44s_3 }, /* 3 */
  141937. { _map_nominal, _res_44s_4 }, /* 4 */
  141938. { _map_nominal, _res_44s_5 }, /* 5 */
  141939. { _map_nominal, _res_44s_6 }, /* 6 */
  141940. { _map_nominal, _res_44s_7 }, /* 7 */
  141941. { _map_nominal, _res_44s_8 }, /* 8 */
  141942. { _map_nominal, _res_44s_9 }, /* 9 */
  141943. };
  141944. /*** End of inlined file: residue_44.h ***/
  141945. /*** Start of inlined file: psych_44.h ***/
  141946. /* preecho trigger settings *****************************************/
  141947. static vorbis_info_psy_global _psy_global_44[5]={
  141948. {8, /* lines per eighth octave */
  141949. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141950. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141951. -6.f,
  141952. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141953. },
  141954. {8, /* lines per eighth octave */
  141955. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141956. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141957. -6.f,
  141958. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141959. },
  141960. {8, /* lines per eighth octave */
  141961. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141962. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141963. -6.f,
  141964. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141965. },
  141966. {8, /* lines per eighth octave */
  141967. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141968. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141969. -6.f,
  141970. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141971. },
  141972. {8, /* lines per eighth octave */
  141973. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141974. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141975. -6.f,
  141976. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141977. },
  141978. };
  141979. /* noise compander lookups * low, mid, high quality ****************/
  141980. static compandblock _psy_compand_44[6]={
  141981. /* sub-mode Z short */
  141982. {{
  141983. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141984. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141985. 16,17,18,19,20,21,22, 23, /* 23dB */
  141986. 24,25,26,27,28,29,30, 31, /* 31dB */
  141987. 32,33,34,35,36,37,38, 39, /* 39dB */
  141988. }},
  141989. /* mode_Z nominal short */
  141990. {{
  141991. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141992. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141993. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141994. 15,16,17,17,17,18,18, 19, /* 31dB */
  141995. 19,19,20,21,22,23,24, 25, /* 39dB */
  141996. }},
  141997. /* mode A short */
  141998. {{
  141999. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142000. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142001. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142002. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142003. 11,12,13,14,15,16,17, 18, /* 39dB */
  142004. }},
  142005. /* sub-mode Z long */
  142006. {{
  142007. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142008. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142009. 16,17,18,19,20,21,22, 23, /* 23dB */
  142010. 24,25,26,27,28,29,30, 31, /* 31dB */
  142011. 32,33,34,35,36,37,38, 39, /* 39dB */
  142012. }},
  142013. /* mode_Z nominal long */
  142014. {{
  142015. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142016. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142017. 13,14,14,14,15,15,15, 15, /* 23dB */
  142018. 16,16,17,17,17,18,18, 19, /* 31dB */
  142019. 19,19,20,21,22,23,24, 25, /* 39dB */
  142020. }},
  142021. /* mode A long */
  142022. {{
  142023. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142024. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142025. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142026. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142027. 11,12,13,14,15,16,17, 18, /* 39dB */
  142028. }}
  142029. };
  142030. /* tonal masking curve level adjustments *************************/
  142031. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142032. /* 63 125 250 500 1 2 4 8 16 */
  142033. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142034. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142035. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142036. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142037. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142038. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142039. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142040. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142041. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142042. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142043. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142044. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142045. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142046. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142047. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142048. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142049. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142050. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142051. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142052. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142053. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142054. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142055. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142056. };
  142057. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142058. /* 63 125 250 500 1 2 4 8 16 */
  142059. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142060. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142061. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142062. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142063. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142064. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142065. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142066. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142067. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142068. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142069. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142070. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142071. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142072. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142073. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142074. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142075. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142076. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142077. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142078. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142079. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142080. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142081. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142082. };
  142083. /* noise bias (transition block) */
  142084. static noise3 _psy_noisebias_trans[12]={
  142085. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142086. /* -1 */
  142087. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142088. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142089. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142090. /* 0
  142091. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142092. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142093. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142094. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142095. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142096. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142097. /* 1
  142098. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142099. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142100. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142101. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142102. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142103. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142104. /* 2
  142105. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142106. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142107. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142108. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142109. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142110. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142111. /* 3
  142112. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142113. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142114. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142115. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142116. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142117. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142118. /* 4
  142119. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142120. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142121. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142122. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142123. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142124. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142125. /* 5
  142126. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142127. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142128. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142129. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142130. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142131. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142132. /* 6
  142133. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142134. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142135. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142136. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142137. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142138. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142139. /* 7
  142140. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142141. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142142. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142143. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142144. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142145. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142146. /* 8
  142147. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142148. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142149. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142150. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142151. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142152. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142153. /* 9
  142154. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142155. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142156. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142157. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142158. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142159. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142160. /* 10 */
  142161. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142162. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142163. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142164. };
  142165. /* noise bias (long block) */
  142166. static noise3 _psy_noisebias_long[12]={
  142167. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142168. /* -1 */
  142169. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142170. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142171. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142172. /* 0 */
  142173. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142174. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142175. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142176. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142177. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142178. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142179. /* 1 */
  142180. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142181. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142182. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142183. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142184. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142185. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142186. /* 2 */
  142187. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142188. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142189. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142190. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142191. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142192. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142193. /* 3 */
  142194. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142195. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142196. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142197. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142198. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142199. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142200. /* 4 */
  142201. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142202. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142203. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142204. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142205. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142206. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142207. /* 5 */
  142208. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142209. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142210. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142211. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142212. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142213. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142214. /* 6 */
  142215. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142216. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142217. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142218. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142219. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142220. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142221. /* 7 */
  142222. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142223. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142224. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142225. /* 8 */
  142226. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142227. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142228. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142229. /* 9 */
  142230. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142231. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142232. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142233. /* 10 */
  142234. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142235. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142236. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142237. };
  142238. /* noise bias (impulse block) */
  142239. static noise3 _psy_noisebias_impulse[12]={
  142240. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142241. /* -1 */
  142242. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142243. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142244. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142245. /* 0 */
  142246. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142247. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142248. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142249. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142250. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142251. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142252. /* 1 */
  142253. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142254. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142255. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142256. /* 2 */
  142257. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142258. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142259. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142260. /* 3 */
  142261. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142262. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142263. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142264. /* 4 */
  142265. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142266. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142267. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142268. /* 5 */
  142269. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142270. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142271. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142272. /* 6
  142273. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142274. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142275. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142276. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142277. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142278. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142279. /* 7 */
  142280. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142281. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142282. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142283. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142284. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142285. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142286. /* 8 */
  142287. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142288. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142289. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142290. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142291. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142292. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142293. /* 9 */
  142294. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142295. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142296. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142297. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142298. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142299. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142300. /* 10 */
  142301. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142302. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142303. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142304. };
  142305. /* noise bias (padding block) */
  142306. static noise3 _psy_noisebias_padding[12]={
  142307. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142308. /* -1 */
  142309. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142310. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142311. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142312. /* 0 */
  142313. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142314. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142315. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142316. /* 1 */
  142317. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142318. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142319. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142320. /* 2 */
  142321. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142322. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142323. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142324. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142325. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142326. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142327. /* 3 */
  142328. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142329. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142330. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142331. /* 4 */
  142332. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142333. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142334. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142335. /* 5 */
  142336. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142337. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142338. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142339. /* 6 */
  142340. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142341. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142342. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142343. /* 7 */
  142344. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142345. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142346. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142347. /* 8 */
  142348. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142349. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142350. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142351. /* 9 */
  142352. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142353. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142354. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142355. /* 10 */
  142356. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142357. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142358. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142359. };
  142360. static noiseguard _psy_noiseguards_44[4]={
  142361. {3,3,15},
  142362. {3,3,15},
  142363. {10,10,100},
  142364. {10,10,100},
  142365. };
  142366. static int _psy_tone_suppress[12]={
  142367. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142368. };
  142369. static int _psy_tone_0dB[12]={
  142370. 90,90,95,95,95,95,105,105,105,105,105,105,
  142371. };
  142372. static int _psy_noise_suppress[12]={
  142373. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142374. };
  142375. static vorbis_info_psy _psy_info_template={
  142376. /* blockflag */
  142377. -1,
  142378. /* ath_adjatt, ath_maxatt */
  142379. -140.,-140.,
  142380. /* tonemask att boost/decay,suppr,curves */
  142381. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142382. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142383. 1, -0.f, .5f, .5f, 0,0,0,
  142384. /* noiseoffset*3, noisecompand, max_curve_dB */
  142385. {{-1},{-1},{-1}},{-1},105.f,
  142386. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142387. 0,0,-1,-1,0.,
  142388. };
  142389. /* ath ****************/
  142390. static int _psy_ath_floater[12]={
  142391. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142392. };
  142393. static int _psy_ath_abs[12]={
  142394. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142395. };
  142396. /* stereo setup. These don't map directly to quality level, there's
  142397. an additional indirection as several of the below may be used in a
  142398. single bitmanaged stream
  142399. ****************/
  142400. /* various stereo possibilities */
  142401. /* stereo mode by base quality level */
  142402. static adj_stereo _psy_stereo_modes_44[12]={
  142403. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142404. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142405. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142406. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142407. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142408. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142409. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142410. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142411. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142412. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142413. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142414. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142415. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142416. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142417. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142418. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142419. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142420. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142421. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142422. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142423. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142424. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142425. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142426. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142427. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142428. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142429. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142430. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142431. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142432. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142433. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142434. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142435. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142436. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142437. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142438. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142439. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142440. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142441. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142442. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142443. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142444. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142445. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142446. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142447. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142448. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142449. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142450. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142451. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142452. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142453. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142454. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142455. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142456. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142457. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142458. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142459. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142460. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142461. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142462. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142463. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142464. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142465. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142466. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142467. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142468. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142469. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142470. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142471. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142472. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142473. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142474. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142475. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142476. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142477. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142478. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142479. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142480. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142481. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142482. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142483. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142484. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142485. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142486. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142487. };
  142488. /* tone master attenuation by base quality mode and bitrate tweak */
  142489. static att3 _psy_tone_masteratt_44[12]={
  142490. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142491. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142492. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142493. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142494. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142495. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142496. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142497. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142498. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142499. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142500. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142501. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142502. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142503. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142504. };
  142505. /* lowpass by mode **************/
  142506. static double _psy_lowpass_44[12]={
  142507. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142508. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142509. };
  142510. /* noise normalization **********/
  142511. static int _noise_start_short_44[11]={
  142512. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142513. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142514. };
  142515. static int _noise_start_long_44[11]={
  142516. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142517. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142518. };
  142519. static int _noise_part_short_44[11]={
  142520. 8,8,8,8,8,8,8,8,8,8,8
  142521. };
  142522. static int _noise_part_long_44[11]={
  142523. 32,32,32,32,32,32,32,32,32,32,32
  142524. };
  142525. static double _noise_thresh_44[11]={
  142526. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142527. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142528. };
  142529. static double _noise_thresh_5only[2]={
  142530. .5,.5,
  142531. };
  142532. /*** End of inlined file: psych_44.h ***/
  142533. static double rate_mapping_44_stereo[12]={
  142534. 22500.,32000.,40000.,48000.,56000.,64000.,
  142535. 80000.,96000.,112000.,128000.,160000.,250001.
  142536. };
  142537. static double quality_mapping_44[12]={
  142538. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142539. };
  142540. static int blocksize_short_44[11]={
  142541. 512,256,256,256,256,256,256,256,256,256,256
  142542. };
  142543. static int blocksize_long_44[11]={
  142544. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142545. };
  142546. static double _psy_compand_short_mapping[12]={
  142547. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142548. };
  142549. static double _psy_compand_long_mapping[12]={
  142550. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142551. };
  142552. static double _global_mapping_44[12]={
  142553. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142554. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142555. };
  142556. static int _floor_short_mapping_44[11]={
  142557. 1,0,0,2,2,4,5,5,5,5,5
  142558. };
  142559. static int _floor_long_mapping_44[11]={
  142560. 8,7,7,7,7,7,7,7,7,7,7
  142561. };
  142562. ve_setup_data_template ve_setup_44_stereo={
  142563. 11,
  142564. rate_mapping_44_stereo,
  142565. quality_mapping_44,
  142566. 2,
  142567. 40000,
  142568. 50000,
  142569. blocksize_short_44,
  142570. blocksize_long_44,
  142571. _psy_tone_masteratt_44,
  142572. _psy_tone_0dB,
  142573. _psy_tone_suppress,
  142574. _vp_tonemask_adj_otherblock,
  142575. _vp_tonemask_adj_longblock,
  142576. _vp_tonemask_adj_otherblock,
  142577. _psy_noiseguards_44,
  142578. _psy_noisebias_impulse,
  142579. _psy_noisebias_padding,
  142580. _psy_noisebias_trans,
  142581. _psy_noisebias_long,
  142582. _psy_noise_suppress,
  142583. _psy_compand_44,
  142584. _psy_compand_short_mapping,
  142585. _psy_compand_long_mapping,
  142586. {_noise_start_short_44,_noise_start_long_44},
  142587. {_noise_part_short_44,_noise_part_long_44},
  142588. _noise_thresh_44,
  142589. _psy_ath_floater,
  142590. _psy_ath_abs,
  142591. _psy_lowpass_44,
  142592. _psy_global_44,
  142593. _global_mapping_44,
  142594. _psy_stereo_modes_44,
  142595. _floor_books,
  142596. _floor,
  142597. _floor_short_mapping_44,
  142598. _floor_long_mapping_44,
  142599. _mapres_template_44_stereo
  142600. };
  142601. /*** End of inlined file: setup_44.h ***/
  142602. /*** Start of inlined file: setup_44u.h ***/
  142603. /*** Start of inlined file: residue_44u.h ***/
  142604. /*** Start of inlined file: res_books_uncoupled.h ***/
  142605. static long _vq_quantlist__16u0__p1_0[] = {
  142606. 1,
  142607. 0,
  142608. 2,
  142609. };
  142610. static long _vq_lengthlist__16u0__p1_0[] = {
  142611. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142612. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142613. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142614. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142615. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142616. 12,
  142617. };
  142618. static float _vq_quantthresh__16u0__p1_0[] = {
  142619. -0.5, 0.5,
  142620. };
  142621. static long _vq_quantmap__16u0__p1_0[] = {
  142622. 1, 0, 2,
  142623. };
  142624. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142625. _vq_quantthresh__16u0__p1_0,
  142626. _vq_quantmap__16u0__p1_0,
  142627. 3,
  142628. 3
  142629. };
  142630. static static_codebook _16u0__p1_0 = {
  142631. 4, 81,
  142632. _vq_lengthlist__16u0__p1_0,
  142633. 1, -535822336, 1611661312, 2, 0,
  142634. _vq_quantlist__16u0__p1_0,
  142635. NULL,
  142636. &_vq_auxt__16u0__p1_0,
  142637. NULL,
  142638. 0
  142639. };
  142640. static long _vq_quantlist__16u0__p2_0[] = {
  142641. 1,
  142642. 0,
  142643. 2,
  142644. };
  142645. static long _vq_lengthlist__16u0__p2_0[] = {
  142646. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142647. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142648. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142649. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142650. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142651. 8,
  142652. };
  142653. static float _vq_quantthresh__16u0__p2_0[] = {
  142654. -0.5, 0.5,
  142655. };
  142656. static long _vq_quantmap__16u0__p2_0[] = {
  142657. 1, 0, 2,
  142658. };
  142659. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142660. _vq_quantthresh__16u0__p2_0,
  142661. _vq_quantmap__16u0__p2_0,
  142662. 3,
  142663. 3
  142664. };
  142665. static static_codebook _16u0__p2_0 = {
  142666. 4, 81,
  142667. _vq_lengthlist__16u0__p2_0,
  142668. 1, -535822336, 1611661312, 2, 0,
  142669. _vq_quantlist__16u0__p2_0,
  142670. NULL,
  142671. &_vq_auxt__16u0__p2_0,
  142672. NULL,
  142673. 0
  142674. };
  142675. static long _vq_quantlist__16u0__p3_0[] = {
  142676. 2,
  142677. 1,
  142678. 3,
  142679. 0,
  142680. 4,
  142681. };
  142682. static long _vq_lengthlist__16u0__p3_0[] = {
  142683. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142684. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142685. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142686. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142687. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142688. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142689. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142690. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142691. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142692. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142693. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142694. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142695. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142696. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142697. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142698. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142699. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142700. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142701. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142702. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142703. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142704. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142705. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142706. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142707. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142708. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142709. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142710. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142711. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142712. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142713. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142714. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142715. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142716. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142717. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142718. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142719. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142720. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142721. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142722. 18,
  142723. };
  142724. static float _vq_quantthresh__16u0__p3_0[] = {
  142725. -1.5, -0.5, 0.5, 1.5,
  142726. };
  142727. static long _vq_quantmap__16u0__p3_0[] = {
  142728. 3, 1, 0, 2, 4,
  142729. };
  142730. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142731. _vq_quantthresh__16u0__p3_0,
  142732. _vq_quantmap__16u0__p3_0,
  142733. 5,
  142734. 5
  142735. };
  142736. static static_codebook _16u0__p3_0 = {
  142737. 4, 625,
  142738. _vq_lengthlist__16u0__p3_0,
  142739. 1, -533725184, 1611661312, 3, 0,
  142740. _vq_quantlist__16u0__p3_0,
  142741. NULL,
  142742. &_vq_auxt__16u0__p3_0,
  142743. NULL,
  142744. 0
  142745. };
  142746. static long _vq_quantlist__16u0__p4_0[] = {
  142747. 2,
  142748. 1,
  142749. 3,
  142750. 0,
  142751. 4,
  142752. };
  142753. static long _vq_lengthlist__16u0__p4_0[] = {
  142754. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142755. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142756. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142757. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142758. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142759. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142760. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142761. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142762. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142763. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142764. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142765. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142766. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142767. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142768. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142769. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142770. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142771. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142772. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142773. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142774. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142775. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142776. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142777. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142778. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142779. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142780. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142781. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142782. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142783. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142784. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142785. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142786. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142787. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142788. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142789. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142790. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142791. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142792. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142793. 11,
  142794. };
  142795. static float _vq_quantthresh__16u0__p4_0[] = {
  142796. -1.5, -0.5, 0.5, 1.5,
  142797. };
  142798. static long _vq_quantmap__16u0__p4_0[] = {
  142799. 3, 1, 0, 2, 4,
  142800. };
  142801. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142802. _vq_quantthresh__16u0__p4_0,
  142803. _vq_quantmap__16u0__p4_0,
  142804. 5,
  142805. 5
  142806. };
  142807. static static_codebook _16u0__p4_0 = {
  142808. 4, 625,
  142809. _vq_lengthlist__16u0__p4_0,
  142810. 1, -533725184, 1611661312, 3, 0,
  142811. _vq_quantlist__16u0__p4_0,
  142812. NULL,
  142813. &_vq_auxt__16u0__p4_0,
  142814. NULL,
  142815. 0
  142816. };
  142817. static long _vq_quantlist__16u0__p5_0[] = {
  142818. 4,
  142819. 3,
  142820. 5,
  142821. 2,
  142822. 6,
  142823. 1,
  142824. 7,
  142825. 0,
  142826. 8,
  142827. };
  142828. static long _vq_lengthlist__16u0__p5_0[] = {
  142829. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142830. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142831. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142832. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142833. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142834. 12,
  142835. };
  142836. static float _vq_quantthresh__16u0__p5_0[] = {
  142837. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142838. };
  142839. static long _vq_quantmap__16u0__p5_0[] = {
  142840. 7, 5, 3, 1, 0, 2, 4, 6,
  142841. 8,
  142842. };
  142843. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142844. _vq_quantthresh__16u0__p5_0,
  142845. _vq_quantmap__16u0__p5_0,
  142846. 9,
  142847. 9
  142848. };
  142849. static static_codebook _16u0__p5_0 = {
  142850. 2, 81,
  142851. _vq_lengthlist__16u0__p5_0,
  142852. 1, -531628032, 1611661312, 4, 0,
  142853. _vq_quantlist__16u0__p5_0,
  142854. NULL,
  142855. &_vq_auxt__16u0__p5_0,
  142856. NULL,
  142857. 0
  142858. };
  142859. static long _vq_quantlist__16u0__p6_0[] = {
  142860. 6,
  142861. 5,
  142862. 7,
  142863. 4,
  142864. 8,
  142865. 3,
  142866. 9,
  142867. 2,
  142868. 10,
  142869. 1,
  142870. 11,
  142871. 0,
  142872. 12,
  142873. };
  142874. static long _vq_lengthlist__16u0__p6_0[] = {
  142875. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142876. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142877. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142878. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142879. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142880. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142881. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142882. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142883. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142884. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142885. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142886. };
  142887. static float _vq_quantthresh__16u0__p6_0[] = {
  142888. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142889. 12.5, 17.5, 22.5, 27.5,
  142890. };
  142891. static long _vq_quantmap__16u0__p6_0[] = {
  142892. 11, 9, 7, 5, 3, 1, 0, 2,
  142893. 4, 6, 8, 10, 12,
  142894. };
  142895. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142896. _vq_quantthresh__16u0__p6_0,
  142897. _vq_quantmap__16u0__p6_0,
  142898. 13,
  142899. 13
  142900. };
  142901. static static_codebook _16u0__p6_0 = {
  142902. 2, 169,
  142903. _vq_lengthlist__16u0__p6_0,
  142904. 1, -526516224, 1616117760, 4, 0,
  142905. _vq_quantlist__16u0__p6_0,
  142906. NULL,
  142907. &_vq_auxt__16u0__p6_0,
  142908. NULL,
  142909. 0
  142910. };
  142911. static long _vq_quantlist__16u0__p6_1[] = {
  142912. 2,
  142913. 1,
  142914. 3,
  142915. 0,
  142916. 4,
  142917. };
  142918. static long _vq_lengthlist__16u0__p6_1[] = {
  142919. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142920. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142921. };
  142922. static float _vq_quantthresh__16u0__p6_1[] = {
  142923. -1.5, -0.5, 0.5, 1.5,
  142924. };
  142925. static long _vq_quantmap__16u0__p6_1[] = {
  142926. 3, 1, 0, 2, 4,
  142927. };
  142928. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142929. _vq_quantthresh__16u0__p6_1,
  142930. _vq_quantmap__16u0__p6_1,
  142931. 5,
  142932. 5
  142933. };
  142934. static static_codebook _16u0__p6_1 = {
  142935. 2, 25,
  142936. _vq_lengthlist__16u0__p6_1,
  142937. 1, -533725184, 1611661312, 3, 0,
  142938. _vq_quantlist__16u0__p6_1,
  142939. NULL,
  142940. &_vq_auxt__16u0__p6_1,
  142941. NULL,
  142942. 0
  142943. };
  142944. static long _vq_quantlist__16u0__p7_0[] = {
  142945. 1,
  142946. 0,
  142947. 2,
  142948. };
  142949. static long _vq_lengthlist__16u0__p7_0[] = {
  142950. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142951. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142952. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142953. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142954. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142955. 7,
  142956. };
  142957. static float _vq_quantthresh__16u0__p7_0[] = {
  142958. -157.5, 157.5,
  142959. };
  142960. static long _vq_quantmap__16u0__p7_0[] = {
  142961. 1, 0, 2,
  142962. };
  142963. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142964. _vq_quantthresh__16u0__p7_0,
  142965. _vq_quantmap__16u0__p7_0,
  142966. 3,
  142967. 3
  142968. };
  142969. static static_codebook _16u0__p7_0 = {
  142970. 4, 81,
  142971. _vq_lengthlist__16u0__p7_0,
  142972. 1, -518803456, 1628680192, 2, 0,
  142973. _vq_quantlist__16u0__p7_0,
  142974. NULL,
  142975. &_vq_auxt__16u0__p7_0,
  142976. NULL,
  142977. 0
  142978. };
  142979. static long _vq_quantlist__16u0__p7_1[] = {
  142980. 7,
  142981. 6,
  142982. 8,
  142983. 5,
  142984. 9,
  142985. 4,
  142986. 10,
  142987. 3,
  142988. 11,
  142989. 2,
  142990. 12,
  142991. 1,
  142992. 13,
  142993. 0,
  142994. 14,
  142995. };
  142996. static long _vq_lengthlist__16u0__p7_1[] = {
  142997. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142998. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142999. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143000. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143001. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143002. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143003. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143004. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143005. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143006. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143007. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143008. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143009. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143011. 10,
  143012. };
  143013. static float _vq_quantthresh__16u0__p7_1[] = {
  143014. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143015. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143016. };
  143017. static long _vq_quantmap__16u0__p7_1[] = {
  143018. 13, 11, 9, 7, 5, 3, 1, 0,
  143019. 2, 4, 6, 8, 10, 12, 14,
  143020. };
  143021. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143022. _vq_quantthresh__16u0__p7_1,
  143023. _vq_quantmap__16u0__p7_1,
  143024. 15,
  143025. 15
  143026. };
  143027. static static_codebook _16u0__p7_1 = {
  143028. 2, 225,
  143029. _vq_lengthlist__16u0__p7_1,
  143030. 1, -520986624, 1620377600, 4, 0,
  143031. _vq_quantlist__16u0__p7_1,
  143032. NULL,
  143033. &_vq_auxt__16u0__p7_1,
  143034. NULL,
  143035. 0
  143036. };
  143037. static long _vq_quantlist__16u0__p7_2[] = {
  143038. 10,
  143039. 9,
  143040. 11,
  143041. 8,
  143042. 12,
  143043. 7,
  143044. 13,
  143045. 6,
  143046. 14,
  143047. 5,
  143048. 15,
  143049. 4,
  143050. 16,
  143051. 3,
  143052. 17,
  143053. 2,
  143054. 18,
  143055. 1,
  143056. 19,
  143057. 0,
  143058. 20,
  143059. };
  143060. static long _vq_lengthlist__16u0__p7_2[] = {
  143061. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143062. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143063. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143064. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143065. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143066. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143067. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143068. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143069. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143070. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143071. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143072. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143073. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143074. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143075. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143076. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143077. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143078. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143079. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143080. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143081. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143082. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143083. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143084. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143085. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143086. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143087. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143088. 10,10,12,11,10,11,11,11,10,
  143089. };
  143090. static float _vq_quantthresh__16u0__p7_2[] = {
  143091. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143092. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143093. 6.5, 7.5, 8.5, 9.5,
  143094. };
  143095. static long _vq_quantmap__16u0__p7_2[] = {
  143096. 19, 17, 15, 13, 11, 9, 7, 5,
  143097. 3, 1, 0, 2, 4, 6, 8, 10,
  143098. 12, 14, 16, 18, 20,
  143099. };
  143100. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143101. _vq_quantthresh__16u0__p7_2,
  143102. _vq_quantmap__16u0__p7_2,
  143103. 21,
  143104. 21
  143105. };
  143106. static static_codebook _16u0__p7_2 = {
  143107. 2, 441,
  143108. _vq_lengthlist__16u0__p7_2,
  143109. 1, -529268736, 1611661312, 5, 0,
  143110. _vq_quantlist__16u0__p7_2,
  143111. NULL,
  143112. &_vq_auxt__16u0__p7_2,
  143113. NULL,
  143114. 0
  143115. };
  143116. static long _huff_lengthlist__16u0__single[] = {
  143117. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143118. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143119. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143120. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143121. };
  143122. static static_codebook _huff_book__16u0__single = {
  143123. 2, 64,
  143124. _huff_lengthlist__16u0__single,
  143125. 0, 0, 0, 0, 0,
  143126. NULL,
  143127. NULL,
  143128. NULL,
  143129. NULL,
  143130. 0
  143131. };
  143132. static long _huff_lengthlist__16u1__long[] = {
  143133. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143134. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143135. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143136. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143137. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143138. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143139. 16,13,16,18,
  143140. };
  143141. static static_codebook _huff_book__16u1__long = {
  143142. 2, 100,
  143143. _huff_lengthlist__16u1__long,
  143144. 0, 0, 0, 0, 0,
  143145. NULL,
  143146. NULL,
  143147. NULL,
  143148. NULL,
  143149. 0
  143150. };
  143151. static long _vq_quantlist__16u1__p1_0[] = {
  143152. 1,
  143153. 0,
  143154. 2,
  143155. };
  143156. static long _vq_lengthlist__16u1__p1_0[] = {
  143157. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143158. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143159. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143160. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143161. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143162. 11,
  143163. };
  143164. static float _vq_quantthresh__16u1__p1_0[] = {
  143165. -0.5, 0.5,
  143166. };
  143167. static long _vq_quantmap__16u1__p1_0[] = {
  143168. 1, 0, 2,
  143169. };
  143170. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143171. _vq_quantthresh__16u1__p1_0,
  143172. _vq_quantmap__16u1__p1_0,
  143173. 3,
  143174. 3
  143175. };
  143176. static static_codebook _16u1__p1_0 = {
  143177. 4, 81,
  143178. _vq_lengthlist__16u1__p1_0,
  143179. 1, -535822336, 1611661312, 2, 0,
  143180. _vq_quantlist__16u1__p1_0,
  143181. NULL,
  143182. &_vq_auxt__16u1__p1_0,
  143183. NULL,
  143184. 0
  143185. };
  143186. static long _vq_quantlist__16u1__p2_0[] = {
  143187. 1,
  143188. 0,
  143189. 2,
  143190. };
  143191. static long _vq_lengthlist__16u1__p2_0[] = {
  143192. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143193. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143194. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143195. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143196. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143197. 8,
  143198. };
  143199. static float _vq_quantthresh__16u1__p2_0[] = {
  143200. -0.5, 0.5,
  143201. };
  143202. static long _vq_quantmap__16u1__p2_0[] = {
  143203. 1, 0, 2,
  143204. };
  143205. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143206. _vq_quantthresh__16u1__p2_0,
  143207. _vq_quantmap__16u1__p2_0,
  143208. 3,
  143209. 3
  143210. };
  143211. static static_codebook _16u1__p2_0 = {
  143212. 4, 81,
  143213. _vq_lengthlist__16u1__p2_0,
  143214. 1, -535822336, 1611661312, 2, 0,
  143215. _vq_quantlist__16u1__p2_0,
  143216. NULL,
  143217. &_vq_auxt__16u1__p2_0,
  143218. NULL,
  143219. 0
  143220. };
  143221. static long _vq_quantlist__16u1__p3_0[] = {
  143222. 2,
  143223. 1,
  143224. 3,
  143225. 0,
  143226. 4,
  143227. };
  143228. static long _vq_lengthlist__16u1__p3_0[] = {
  143229. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143230. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143231. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143232. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143233. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143234. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143235. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143236. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143237. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143238. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143239. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143240. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143241. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143242. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143243. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143244. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143245. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143246. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143247. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143248. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143249. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143250. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143251. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143252. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143253. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143254. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143255. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143256. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143257. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143258. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143259. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143260. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143261. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143262. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143263. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143264. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143265. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143266. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143267. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143268. 16,
  143269. };
  143270. static float _vq_quantthresh__16u1__p3_0[] = {
  143271. -1.5, -0.5, 0.5, 1.5,
  143272. };
  143273. static long _vq_quantmap__16u1__p3_0[] = {
  143274. 3, 1, 0, 2, 4,
  143275. };
  143276. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143277. _vq_quantthresh__16u1__p3_0,
  143278. _vq_quantmap__16u1__p3_0,
  143279. 5,
  143280. 5
  143281. };
  143282. static static_codebook _16u1__p3_0 = {
  143283. 4, 625,
  143284. _vq_lengthlist__16u1__p3_0,
  143285. 1, -533725184, 1611661312, 3, 0,
  143286. _vq_quantlist__16u1__p3_0,
  143287. NULL,
  143288. &_vq_auxt__16u1__p3_0,
  143289. NULL,
  143290. 0
  143291. };
  143292. static long _vq_quantlist__16u1__p4_0[] = {
  143293. 2,
  143294. 1,
  143295. 3,
  143296. 0,
  143297. 4,
  143298. };
  143299. static long _vq_lengthlist__16u1__p4_0[] = {
  143300. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143301. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143302. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143303. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143304. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143305. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143306. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143307. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143308. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143309. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143310. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143311. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143312. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143313. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143314. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143315. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143316. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143317. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143318. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143319. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143320. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143321. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143322. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143323. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143324. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143325. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143326. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143327. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143328. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143329. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143330. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143331. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143332. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143333. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143334. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143335. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143336. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143337. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143338. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143339. 11,
  143340. };
  143341. static float _vq_quantthresh__16u1__p4_0[] = {
  143342. -1.5, -0.5, 0.5, 1.5,
  143343. };
  143344. static long _vq_quantmap__16u1__p4_0[] = {
  143345. 3, 1, 0, 2, 4,
  143346. };
  143347. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143348. _vq_quantthresh__16u1__p4_0,
  143349. _vq_quantmap__16u1__p4_0,
  143350. 5,
  143351. 5
  143352. };
  143353. static static_codebook _16u1__p4_0 = {
  143354. 4, 625,
  143355. _vq_lengthlist__16u1__p4_0,
  143356. 1, -533725184, 1611661312, 3, 0,
  143357. _vq_quantlist__16u1__p4_0,
  143358. NULL,
  143359. &_vq_auxt__16u1__p4_0,
  143360. NULL,
  143361. 0
  143362. };
  143363. static long _vq_quantlist__16u1__p5_0[] = {
  143364. 4,
  143365. 3,
  143366. 5,
  143367. 2,
  143368. 6,
  143369. 1,
  143370. 7,
  143371. 0,
  143372. 8,
  143373. };
  143374. static long _vq_lengthlist__16u1__p5_0[] = {
  143375. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143376. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143377. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143378. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143379. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143380. 13,
  143381. };
  143382. static float _vq_quantthresh__16u1__p5_0[] = {
  143383. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143384. };
  143385. static long _vq_quantmap__16u1__p5_0[] = {
  143386. 7, 5, 3, 1, 0, 2, 4, 6,
  143387. 8,
  143388. };
  143389. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143390. _vq_quantthresh__16u1__p5_0,
  143391. _vq_quantmap__16u1__p5_0,
  143392. 9,
  143393. 9
  143394. };
  143395. static static_codebook _16u1__p5_0 = {
  143396. 2, 81,
  143397. _vq_lengthlist__16u1__p5_0,
  143398. 1, -531628032, 1611661312, 4, 0,
  143399. _vq_quantlist__16u1__p5_0,
  143400. NULL,
  143401. &_vq_auxt__16u1__p5_0,
  143402. NULL,
  143403. 0
  143404. };
  143405. static long _vq_quantlist__16u1__p6_0[] = {
  143406. 4,
  143407. 3,
  143408. 5,
  143409. 2,
  143410. 6,
  143411. 1,
  143412. 7,
  143413. 0,
  143414. 8,
  143415. };
  143416. static long _vq_lengthlist__16u1__p6_0[] = {
  143417. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143418. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143419. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143420. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143421. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143422. 11,
  143423. };
  143424. static float _vq_quantthresh__16u1__p6_0[] = {
  143425. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143426. };
  143427. static long _vq_quantmap__16u1__p6_0[] = {
  143428. 7, 5, 3, 1, 0, 2, 4, 6,
  143429. 8,
  143430. };
  143431. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143432. _vq_quantthresh__16u1__p6_0,
  143433. _vq_quantmap__16u1__p6_0,
  143434. 9,
  143435. 9
  143436. };
  143437. static static_codebook _16u1__p6_0 = {
  143438. 2, 81,
  143439. _vq_lengthlist__16u1__p6_0,
  143440. 1, -531628032, 1611661312, 4, 0,
  143441. _vq_quantlist__16u1__p6_0,
  143442. NULL,
  143443. &_vq_auxt__16u1__p6_0,
  143444. NULL,
  143445. 0
  143446. };
  143447. static long _vq_quantlist__16u1__p7_0[] = {
  143448. 1,
  143449. 0,
  143450. 2,
  143451. };
  143452. static long _vq_lengthlist__16u1__p7_0[] = {
  143453. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143454. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143455. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143456. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143457. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143458. 13,
  143459. };
  143460. static float _vq_quantthresh__16u1__p7_0[] = {
  143461. -5.5, 5.5,
  143462. };
  143463. static long _vq_quantmap__16u1__p7_0[] = {
  143464. 1, 0, 2,
  143465. };
  143466. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143467. _vq_quantthresh__16u1__p7_0,
  143468. _vq_quantmap__16u1__p7_0,
  143469. 3,
  143470. 3
  143471. };
  143472. static static_codebook _16u1__p7_0 = {
  143473. 4, 81,
  143474. _vq_lengthlist__16u1__p7_0,
  143475. 1, -529137664, 1618345984, 2, 0,
  143476. _vq_quantlist__16u1__p7_0,
  143477. NULL,
  143478. &_vq_auxt__16u1__p7_0,
  143479. NULL,
  143480. 0
  143481. };
  143482. static long _vq_quantlist__16u1__p7_1[] = {
  143483. 5,
  143484. 4,
  143485. 6,
  143486. 3,
  143487. 7,
  143488. 2,
  143489. 8,
  143490. 1,
  143491. 9,
  143492. 0,
  143493. 10,
  143494. };
  143495. static long _vq_lengthlist__16u1__p7_1[] = {
  143496. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143497. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143498. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143499. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143500. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143501. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143502. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143503. 8, 9, 9,10,10,10,10,10,10,
  143504. };
  143505. static float _vq_quantthresh__16u1__p7_1[] = {
  143506. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143507. 3.5, 4.5,
  143508. };
  143509. static long _vq_quantmap__16u1__p7_1[] = {
  143510. 9, 7, 5, 3, 1, 0, 2, 4,
  143511. 6, 8, 10,
  143512. };
  143513. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143514. _vq_quantthresh__16u1__p7_1,
  143515. _vq_quantmap__16u1__p7_1,
  143516. 11,
  143517. 11
  143518. };
  143519. static static_codebook _16u1__p7_1 = {
  143520. 2, 121,
  143521. _vq_lengthlist__16u1__p7_1,
  143522. 1, -531365888, 1611661312, 4, 0,
  143523. _vq_quantlist__16u1__p7_1,
  143524. NULL,
  143525. &_vq_auxt__16u1__p7_1,
  143526. NULL,
  143527. 0
  143528. };
  143529. static long _vq_quantlist__16u1__p8_0[] = {
  143530. 5,
  143531. 4,
  143532. 6,
  143533. 3,
  143534. 7,
  143535. 2,
  143536. 8,
  143537. 1,
  143538. 9,
  143539. 0,
  143540. 10,
  143541. };
  143542. static long _vq_lengthlist__16u1__p8_0[] = {
  143543. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143544. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143545. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143546. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143547. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143548. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143549. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143550. 13,14,14,15,15,16,16,15,16,
  143551. };
  143552. static float _vq_quantthresh__16u1__p8_0[] = {
  143553. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143554. 38.5, 49.5,
  143555. };
  143556. static long _vq_quantmap__16u1__p8_0[] = {
  143557. 9, 7, 5, 3, 1, 0, 2, 4,
  143558. 6, 8, 10,
  143559. };
  143560. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143561. _vq_quantthresh__16u1__p8_0,
  143562. _vq_quantmap__16u1__p8_0,
  143563. 11,
  143564. 11
  143565. };
  143566. static static_codebook _16u1__p8_0 = {
  143567. 2, 121,
  143568. _vq_lengthlist__16u1__p8_0,
  143569. 1, -524582912, 1618345984, 4, 0,
  143570. _vq_quantlist__16u1__p8_0,
  143571. NULL,
  143572. &_vq_auxt__16u1__p8_0,
  143573. NULL,
  143574. 0
  143575. };
  143576. static long _vq_quantlist__16u1__p8_1[] = {
  143577. 5,
  143578. 4,
  143579. 6,
  143580. 3,
  143581. 7,
  143582. 2,
  143583. 8,
  143584. 1,
  143585. 9,
  143586. 0,
  143587. 10,
  143588. };
  143589. static long _vq_lengthlist__16u1__p8_1[] = {
  143590. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143591. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143592. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143593. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143594. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143595. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143596. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143597. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143598. };
  143599. static float _vq_quantthresh__16u1__p8_1[] = {
  143600. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143601. 3.5, 4.5,
  143602. };
  143603. static long _vq_quantmap__16u1__p8_1[] = {
  143604. 9, 7, 5, 3, 1, 0, 2, 4,
  143605. 6, 8, 10,
  143606. };
  143607. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143608. _vq_quantthresh__16u1__p8_1,
  143609. _vq_quantmap__16u1__p8_1,
  143610. 11,
  143611. 11
  143612. };
  143613. static static_codebook _16u1__p8_1 = {
  143614. 2, 121,
  143615. _vq_lengthlist__16u1__p8_1,
  143616. 1, -531365888, 1611661312, 4, 0,
  143617. _vq_quantlist__16u1__p8_1,
  143618. NULL,
  143619. &_vq_auxt__16u1__p8_1,
  143620. NULL,
  143621. 0
  143622. };
  143623. static long _vq_quantlist__16u1__p9_0[] = {
  143624. 7,
  143625. 6,
  143626. 8,
  143627. 5,
  143628. 9,
  143629. 4,
  143630. 10,
  143631. 3,
  143632. 11,
  143633. 2,
  143634. 12,
  143635. 1,
  143636. 13,
  143637. 0,
  143638. 14,
  143639. };
  143640. static long _vq_lengthlist__16u1__p9_0[] = {
  143641. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143642. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143643. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143644. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143645. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143646. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143647. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143648. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143649. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143650. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143651. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143652. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143653. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143654. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143655. 8,
  143656. };
  143657. static float _vq_quantthresh__16u1__p9_0[] = {
  143658. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143659. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143660. };
  143661. static long _vq_quantmap__16u1__p9_0[] = {
  143662. 13, 11, 9, 7, 5, 3, 1, 0,
  143663. 2, 4, 6, 8, 10, 12, 14,
  143664. };
  143665. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143666. _vq_quantthresh__16u1__p9_0,
  143667. _vq_quantmap__16u1__p9_0,
  143668. 15,
  143669. 15
  143670. };
  143671. static static_codebook _16u1__p9_0 = {
  143672. 2, 225,
  143673. _vq_lengthlist__16u1__p9_0,
  143674. 1, -514071552, 1627381760, 4, 0,
  143675. _vq_quantlist__16u1__p9_0,
  143676. NULL,
  143677. &_vq_auxt__16u1__p9_0,
  143678. NULL,
  143679. 0
  143680. };
  143681. static long _vq_quantlist__16u1__p9_1[] = {
  143682. 7,
  143683. 6,
  143684. 8,
  143685. 5,
  143686. 9,
  143687. 4,
  143688. 10,
  143689. 3,
  143690. 11,
  143691. 2,
  143692. 12,
  143693. 1,
  143694. 13,
  143695. 0,
  143696. 14,
  143697. };
  143698. static long _vq_lengthlist__16u1__p9_1[] = {
  143699. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143700. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143701. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143702. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143703. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143704. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143705. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143706. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143707. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143708. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143709. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143710. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143711. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143712. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143713. 9,
  143714. };
  143715. static float _vq_quantthresh__16u1__p9_1[] = {
  143716. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143717. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143718. };
  143719. static long _vq_quantmap__16u1__p9_1[] = {
  143720. 13, 11, 9, 7, 5, 3, 1, 0,
  143721. 2, 4, 6, 8, 10, 12, 14,
  143722. };
  143723. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143724. _vq_quantthresh__16u1__p9_1,
  143725. _vq_quantmap__16u1__p9_1,
  143726. 15,
  143727. 15
  143728. };
  143729. static static_codebook _16u1__p9_1 = {
  143730. 2, 225,
  143731. _vq_lengthlist__16u1__p9_1,
  143732. 1, -522338304, 1620115456, 4, 0,
  143733. _vq_quantlist__16u1__p9_1,
  143734. NULL,
  143735. &_vq_auxt__16u1__p9_1,
  143736. NULL,
  143737. 0
  143738. };
  143739. static long _vq_quantlist__16u1__p9_2[] = {
  143740. 8,
  143741. 7,
  143742. 9,
  143743. 6,
  143744. 10,
  143745. 5,
  143746. 11,
  143747. 4,
  143748. 12,
  143749. 3,
  143750. 13,
  143751. 2,
  143752. 14,
  143753. 1,
  143754. 15,
  143755. 0,
  143756. 16,
  143757. };
  143758. static long _vq_lengthlist__16u1__p9_2[] = {
  143759. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143760. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143761. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143762. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143763. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143764. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143765. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143766. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143767. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143768. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143769. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143770. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143771. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143772. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143773. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143774. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143775. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143776. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143777. 10,
  143778. };
  143779. static float _vq_quantthresh__16u1__p9_2[] = {
  143780. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143781. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143782. };
  143783. static long _vq_quantmap__16u1__p9_2[] = {
  143784. 15, 13, 11, 9, 7, 5, 3, 1,
  143785. 0, 2, 4, 6, 8, 10, 12, 14,
  143786. 16,
  143787. };
  143788. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143789. _vq_quantthresh__16u1__p9_2,
  143790. _vq_quantmap__16u1__p9_2,
  143791. 17,
  143792. 17
  143793. };
  143794. static static_codebook _16u1__p9_2 = {
  143795. 2, 289,
  143796. _vq_lengthlist__16u1__p9_2,
  143797. 1, -529530880, 1611661312, 5, 0,
  143798. _vq_quantlist__16u1__p9_2,
  143799. NULL,
  143800. &_vq_auxt__16u1__p9_2,
  143801. NULL,
  143802. 0
  143803. };
  143804. static long _huff_lengthlist__16u1__short[] = {
  143805. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143806. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143807. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143808. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143809. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143810. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143811. 16,16,16,16,
  143812. };
  143813. static static_codebook _huff_book__16u1__short = {
  143814. 2, 100,
  143815. _huff_lengthlist__16u1__short,
  143816. 0, 0, 0, 0, 0,
  143817. NULL,
  143818. NULL,
  143819. NULL,
  143820. NULL,
  143821. 0
  143822. };
  143823. static long _huff_lengthlist__16u2__long[] = {
  143824. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143825. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143826. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143827. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143828. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143829. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143830. 13,14,18,18,
  143831. };
  143832. static static_codebook _huff_book__16u2__long = {
  143833. 2, 100,
  143834. _huff_lengthlist__16u2__long,
  143835. 0, 0, 0, 0, 0,
  143836. NULL,
  143837. NULL,
  143838. NULL,
  143839. NULL,
  143840. 0
  143841. };
  143842. static long _huff_lengthlist__16u2__short[] = {
  143843. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143844. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143845. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143846. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143847. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143848. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143849. 16,16,16,16,
  143850. };
  143851. static static_codebook _huff_book__16u2__short = {
  143852. 2, 100,
  143853. _huff_lengthlist__16u2__short,
  143854. 0, 0, 0, 0, 0,
  143855. NULL,
  143856. NULL,
  143857. NULL,
  143858. NULL,
  143859. 0
  143860. };
  143861. static long _vq_quantlist__16u2_p1_0[] = {
  143862. 1,
  143863. 0,
  143864. 2,
  143865. };
  143866. static long _vq_lengthlist__16u2_p1_0[] = {
  143867. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143868. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143869. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143870. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143871. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143872. 10,
  143873. };
  143874. static float _vq_quantthresh__16u2_p1_0[] = {
  143875. -0.5, 0.5,
  143876. };
  143877. static long _vq_quantmap__16u2_p1_0[] = {
  143878. 1, 0, 2,
  143879. };
  143880. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143881. _vq_quantthresh__16u2_p1_0,
  143882. _vq_quantmap__16u2_p1_0,
  143883. 3,
  143884. 3
  143885. };
  143886. static static_codebook _16u2_p1_0 = {
  143887. 4, 81,
  143888. _vq_lengthlist__16u2_p1_0,
  143889. 1, -535822336, 1611661312, 2, 0,
  143890. _vq_quantlist__16u2_p1_0,
  143891. NULL,
  143892. &_vq_auxt__16u2_p1_0,
  143893. NULL,
  143894. 0
  143895. };
  143896. static long _vq_quantlist__16u2_p2_0[] = {
  143897. 2,
  143898. 1,
  143899. 3,
  143900. 0,
  143901. 4,
  143902. };
  143903. static long _vq_lengthlist__16u2_p2_0[] = {
  143904. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143905. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143906. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143907. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143908. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143909. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143910. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143911. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143912. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143913. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143914. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143915. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143916. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143917. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143918. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143919. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143920. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143921. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143922. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143923. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143924. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143925. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143926. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143927. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143928. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143929. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143930. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143931. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143932. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143933. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143934. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143935. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143936. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143937. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143938. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143939. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143940. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143941. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143942. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143943. 13,
  143944. };
  143945. static float _vq_quantthresh__16u2_p2_0[] = {
  143946. -1.5, -0.5, 0.5, 1.5,
  143947. };
  143948. static long _vq_quantmap__16u2_p2_0[] = {
  143949. 3, 1, 0, 2, 4,
  143950. };
  143951. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143952. _vq_quantthresh__16u2_p2_0,
  143953. _vq_quantmap__16u2_p2_0,
  143954. 5,
  143955. 5
  143956. };
  143957. static static_codebook _16u2_p2_0 = {
  143958. 4, 625,
  143959. _vq_lengthlist__16u2_p2_0,
  143960. 1, -533725184, 1611661312, 3, 0,
  143961. _vq_quantlist__16u2_p2_0,
  143962. NULL,
  143963. &_vq_auxt__16u2_p2_0,
  143964. NULL,
  143965. 0
  143966. };
  143967. static long _vq_quantlist__16u2_p3_0[] = {
  143968. 4,
  143969. 3,
  143970. 5,
  143971. 2,
  143972. 6,
  143973. 1,
  143974. 7,
  143975. 0,
  143976. 8,
  143977. };
  143978. static long _vq_lengthlist__16u2_p3_0[] = {
  143979. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143980. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143981. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143982. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143983. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143984. 11,
  143985. };
  143986. static float _vq_quantthresh__16u2_p3_0[] = {
  143987. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143988. };
  143989. static long _vq_quantmap__16u2_p3_0[] = {
  143990. 7, 5, 3, 1, 0, 2, 4, 6,
  143991. 8,
  143992. };
  143993. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143994. _vq_quantthresh__16u2_p3_0,
  143995. _vq_quantmap__16u2_p3_0,
  143996. 9,
  143997. 9
  143998. };
  143999. static static_codebook _16u2_p3_0 = {
  144000. 2, 81,
  144001. _vq_lengthlist__16u2_p3_0,
  144002. 1, -531628032, 1611661312, 4, 0,
  144003. _vq_quantlist__16u2_p3_0,
  144004. NULL,
  144005. &_vq_auxt__16u2_p3_0,
  144006. NULL,
  144007. 0
  144008. };
  144009. static long _vq_quantlist__16u2_p4_0[] = {
  144010. 8,
  144011. 7,
  144012. 9,
  144013. 6,
  144014. 10,
  144015. 5,
  144016. 11,
  144017. 4,
  144018. 12,
  144019. 3,
  144020. 13,
  144021. 2,
  144022. 14,
  144023. 1,
  144024. 15,
  144025. 0,
  144026. 16,
  144027. };
  144028. static long _vq_lengthlist__16u2_p4_0[] = {
  144029. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144030. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144031. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144032. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144033. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144034. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144035. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144036. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144037. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144038. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144039. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144040. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144041. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144042. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144043. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144044. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144045. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144046. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144047. 14,
  144048. };
  144049. static float _vq_quantthresh__16u2_p4_0[] = {
  144050. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144051. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144052. };
  144053. static long _vq_quantmap__16u2_p4_0[] = {
  144054. 15, 13, 11, 9, 7, 5, 3, 1,
  144055. 0, 2, 4, 6, 8, 10, 12, 14,
  144056. 16,
  144057. };
  144058. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144059. _vq_quantthresh__16u2_p4_0,
  144060. _vq_quantmap__16u2_p4_0,
  144061. 17,
  144062. 17
  144063. };
  144064. static static_codebook _16u2_p4_0 = {
  144065. 2, 289,
  144066. _vq_lengthlist__16u2_p4_0,
  144067. 1, -529530880, 1611661312, 5, 0,
  144068. _vq_quantlist__16u2_p4_0,
  144069. NULL,
  144070. &_vq_auxt__16u2_p4_0,
  144071. NULL,
  144072. 0
  144073. };
  144074. static long _vq_quantlist__16u2_p5_0[] = {
  144075. 1,
  144076. 0,
  144077. 2,
  144078. };
  144079. static long _vq_lengthlist__16u2_p5_0[] = {
  144080. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144081. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144082. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144083. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144084. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144085. 10,
  144086. };
  144087. static float _vq_quantthresh__16u2_p5_0[] = {
  144088. -5.5, 5.5,
  144089. };
  144090. static long _vq_quantmap__16u2_p5_0[] = {
  144091. 1, 0, 2,
  144092. };
  144093. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144094. _vq_quantthresh__16u2_p5_0,
  144095. _vq_quantmap__16u2_p5_0,
  144096. 3,
  144097. 3
  144098. };
  144099. static static_codebook _16u2_p5_0 = {
  144100. 4, 81,
  144101. _vq_lengthlist__16u2_p5_0,
  144102. 1, -529137664, 1618345984, 2, 0,
  144103. _vq_quantlist__16u2_p5_0,
  144104. NULL,
  144105. &_vq_auxt__16u2_p5_0,
  144106. NULL,
  144107. 0
  144108. };
  144109. static long _vq_quantlist__16u2_p5_1[] = {
  144110. 5,
  144111. 4,
  144112. 6,
  144113. 3,
  144114. 7,
  144115. 2,
  144116. 8,
  144117. 1,
  144118. 9,
  144119. 0,
  144120. 10,
  144121. };
  144122. static long _vq_lengthlist__16u2_p5_1[] = {
  144123. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144124. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144125. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144126. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144127. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144128. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144129. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144130. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144131. };
  144132. static float _vq_quantthresh__16u2_p5_1[] = {
  144133. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144134. 3.5, 4.5,
  144135. };
  144136. static long _vq_quantmap__16u2_p5_1[] = {
  144137. 9, 7, 5, 3, 1, 0, 2, 4,
  144138. 6, 8, 10,
  144139. };
  144140. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144141. _vq_quantthresh__16u2_p5_1,
  144142. _vq_quantmap__16u2_p5_1,
  144143. 11,
  144144. 11
  144145. };
  144146. static static_codebook _16u2_p5_1 = {
  144147. 2, 121,
  144148. _vq_lengthlist__16u2_p5_1,
  144149. 1, -531365888, 1611661312, 4, 0,
  144150. _vq_quantlist__16u2_p5_1,
  144151. NULL,
  144152. &_vq_auxt__16u2_p5_1,
  144153. NULL,
  144154. 0
  144155. };
  144156. static long _vq_quantlist__16u2_p6_0[] = {
  144157. 6,
  144158. 5,
  144159. 7,
  144160. 4,
  144161. 8,
  144162. 3,
  144163. 9,
  144164. 2,
  144165. 10,
  144166. 1,
  144167. 11,
  144168. 0,
  144169. 12,
  144170. };
  144171. static long _vq_lengthlist__16u2_p6_0[] = {
  144172. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144173. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144174. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144175. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144176. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144177. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144178. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144179. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144180. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144181. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144182. 12,13,13,14,14,14,14,15,15,
  144183. };
  144184. static float _vq_quantthresh__16u2_p6_0[] = {
  144185. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144186. 12.5, 17.5, 22.5, 27.5,
  144187. };
  144188. static long _vq_quantmap__16u2_p6_0[] = {
  144189. 11, 9, 7, 5, 3, 1, 0, 2,
  144190. 4, 6, 8, 10, 12,
  144191. };
  144192. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144193. _vq_quantthresh__16u2_p6_0,
  144194. _vq_quantmap__16u2_p6_0,
  144195. 13,
  144196. 13
  144197. };
  144198. static static_codebook _16u2_p6_0 = {
  144199. 2, 169,
  144200. _vq_lengthlist__16u2_p6_0,
  144201. 1, -526516224, 1616117760, 4, 0,
  144202. _vq_quantlist__16u2_p6_0,
  144203. NULL,
  144204. &_vq_auxt__16u2_p6_0,
  144205. NULL,
  144206. 0
  144207. };
  144208. static long _vq_quantlist__16u2_p6_1[] = {
  144209. 2,
  144210. 1,
  144211. 3,
  144212. 0,
  144213. 4,
  144214. };
  144215. static long _vq_lengthlist__16u2_p6_1[] = {
  144216. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144217. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144218. };
  144219. static float _vq_quantthresh__16u2_p6_1[] = {
  144220. -1.5, -0.5, 0.5, 1.5,
  144221. };
  144222. static long _vq_quantmap__16u2_p6_1[] = {
  144223. 3, 1, 0, 2, 4,
  144224. };
  144225. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144226. _vq_quantthresh__16u2_p6_1,
  144227. _vq_quantmap__16u2_p6_1,
  144228. 5,
  144229. 5
  144230. };
  144231. static static_codebook _16u2_p6_1 = {
  144232. 2, 25,
  144233. _vq_lengthlist__16u2_p6_1,
  144234. 1, -533725184, 1611661312, 3, 0,
  144235. _vq_quantlist__16u2_p6_1,
  144236. NULL,
  144237. &_vq_auxt__16u2_p6_1,
  144238. NULL,
  144239. 0
  144240. };
  144241. static long _vq_quantlist__16u2_p7_0[] = {
  144242. 6,
  144243. 5,
  144244. 7,
  144245. 4,
  144246. 8,
  144247. 3,
  144248. 9,
  144249. 2,
  144250. 10,
  144251. 1,
  144252. 11,
  144253. 0,
  144254. 12,
  144255. };
  144256. static long _vq_lengthlist__16u2_p7_0[] = {
  144257. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144258. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144259. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144260. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144261. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144262. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144263. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144264. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144265. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144266. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144267. 12,13,13,13,14,14,14,15,14,
  144268. };
  144269. static float _vq_quantthresh__16u2_p7_0[] = {
  144270. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144271. 27.5, 38.5, 49.5, 60.5,
  144272. };
  144273. static long _vq_quantmap__16u2_p7_0[] = {
  144274. 11, 9, 7, 5, 3, 1, 0, 2,
  144275. 4, 6, 8, 10, 12,
  144276. };
  144277. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144278. _vq_quantthresh__16u2_p7_0,
  144279. _vq_quantmap__16u2_p7_0,
  144280. 13,
  144281. 13
  144282. };
  144283. static static_codebook _16u2_p7_0 = {
  144284. 2, 169,
  144285. _vq_lengthlist__16u2_p7_0,
  144286. 1, -523206656, 1618345984, 4, 0,
  144287. _vq_quantlist__16u2_p7_0,
  144288. NULL,
  144289. &_vq_auxt__16u2_p7_0,
  144290. NULL,
  144291. 0
  144292. };
  144293. static long _vq_quantlist__16u2_p7_1[] = {
  144294. 5,
  144295. 4,
  144296. 6,
  144297. 3,
  144298. 7,
  144299. 2,
  144300. 8,
  144301. 1,
  144302. 9,
  144303. 0,
  144304. 10,
  144305. };
  144306. static long _vq_lengthlist__16u2_p7_1[] = {
  144307. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144308. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144309. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144310. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144311. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144312. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144313. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144314. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144315. };
  144316. static float _vq_quantthresh__16u2_p7_1[] = {
  144317. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144318. 3.5, 4.5,
  144319. };
  144320. static long _vq_quantmap__16u2_p7_1[] = {
  144321. 9, 7, 5, 3, 1, 0, 2, 4,
  144322. 6, 8, 10,
  144323. };
  144324. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144325. _vq_quantthresh__16u2_p7_1,
  144326. _vq_quantmap__16u2_p7_1,
  144327. 11,
  144328. 11
  144329. };
  144330. static static_codebook _16u2_p7_1 = {
  144331. 2, 121,
  144332. _vq_lengthlist__16u2_p7_1,
  144333. 1, -531365888, 1611661312, 4, 0,
  144334. _vq_quantlist__16u2_p7_1,
  144335. NULL,
  144336. &_vq_auxt__16u2_p7_1,
  144337. NULL,
  144338. 0
  144339. };
  144340. static long _vq_quantlist__16u2_p8_0[] = {
  144341. 7,
  144342. 6,
  144343. 8,
  144344. 5,
  144345. 9,
  144346. 4,
  144347. 10,
  144348. 3,
  144349. 11,
  144350. 2,
  144351. 12,
  144352. 1,
  144353. 13,
  144354. 0,
  144355. 14,
  144356. };
  144357. static long _vq_lengthlist__16u2_p8_0[] = {
  144358. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144359. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144360. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144361. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144362. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144363. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144364. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144365. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144366. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144367. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144368. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144369. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144370. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144371. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144372. 14,
  144373. };
  144374. static float _vq_quantthresh__16u2_p8_0[] = {
  144375. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144376. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144377. };
  144378. static long _vq_quantmap__16u2_p8_0[] = {
  144379. 13, 11, 9, 7, 5, 3, 1, 0,
  144380. 2, 4, 6, 8, 10, 12, 14,
  144381. };
  144382. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144383. _vq_quantthresh__16u2_p8_0,
  144384. _vq_quantmap__16u2_p8_0,
  144385. 15,
  144386. 15
  144387. };
  144388. static static_codebook _16u2_p8_0 = {
  144389. 2, 225,
  144390. _vq_lengthlist__16u2_p8_0,
  144391. 1, -520986624, 1620377600, 4, 0,
  144392. _vq_quantlist__16u2_p8_0,
  144393. NULL,
  144394. &_vq_auxt__16u2_p8_0,
  144395. NULL,
  144396. 0
  144397. };
  144398. static long _vq_quantlist__16u2_p8_1[] = {
  144399. 10,
  144400. 9,
  144401. 11,
  144402. 8,
  144403. 12,
  144404. 7,
  144405. 13,
  144406. 6,
  144407. 14,
  144408. 5,
  144409. 15,
  144410. 4,
  144411. 16,
  144412. 3,
  144413. 17,
  144414. 2,
  144415. 18,
  144416. 1,
  144417. 19,
  144418. 0,
  144419. 20,
  144420. };
  144421. static long _vq_lengthlist__16u2_p8_1[] = {
  144422. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144423. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144424. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144425. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144426. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144427. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144428. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144429. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144430. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144431. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144432. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144433. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144434. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144435. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144436. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144437. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144438. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144439. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144440. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144441. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144442. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144443. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144444. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144445. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144446. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144447. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144448. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144449. 11,11,10,11,11,11,10,11,11,
  144450. };
  144451. static float _vq_quantthresh__16u2_p8_1[] = {
  144452. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144453. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144454. 6.5, 7.5, 8.5, 9.5,
  144455. };
  144456. static long _vq_quantmap__16u2_p8_1[] = {
  144457. 19, 17, 15, 13, 11, 9, 7, 5,
  144458. 3, 1, 0, 2, 4, 6, 8, 10,
  144459. 12, 14, 16, 18, 20,
  144460. };
  144461. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144462. _vq_quantthresh__16u2_p8_1,
  144463. _vq_quantmap__16u2_p8_1,
  144464. 21,
  144465. 21
  144466. };
  144467. static static_codebook _16u2_p8_1 = {
  144468. 2, 441,
  144469. _vq_lengthlist__16u2_p8_1,
  144470. 1, -529268736, 1611661312, 5, 0,
  144471. _vq_quantlist__16u2_p8_1,
  144472. NULL,
  144473. &_vq_auxt__16u2_p8_1,
  144474. NULL,
  144475. 0
  144476. };
  144477. static long _vq_quantlist__16u2_p9_0[] = {
  144478. 5586,
  144479. 4655,
  144480. 6517,
  144481. 3724,
  144482. 7448,
  144483. 2793,
  144484. 8379,
  144485. 1862,
  144486. 9310,
  144487. 931,
  144488. 10241,
  144489. 0,
  144490. 11172,
  144491. 5521,
  144492. 5651,
  144493. };
  144494. static long _vq_lengthlist__16u2_p9_0[] = {
  144495. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144496. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144497. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144499. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144500. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144501. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144502. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144503. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144504. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144505. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144506. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144507. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144508. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144509. 5,
  144510. };
  144511. static float _vq_quantthresh__16u2_p9_0[] = {
  144512. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144513. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144514. };
  144515. static long _vq_quantmap__16u2_p9_0[] = {
  144516. 11, 9, 7, 5, 3, 1, 13, 0,
  144517. 14, 2, 4, 6, 8, 10, 12,
  144518. };
  144519. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144520. _vq_quantthresh__16u2_p9_0,
  144521. _vq_quantmap__16u2_p9_0,
  144522. 15,
  144523. 15
  144524. };
  144525. static static_codebook _16u2_p9_0 = {
  144526. 2, 225,
  144527. _vq_lengthlist__16u2_p9_0,
  144528. 1, -510275072, 1611661312, 14, 0,
  144529. _vq_quantlist__16u2_p9_0,
  144530. NULL,
  144531. &_vq_auxt__16u2_p9_0,
  144532. NULL,
  144533. 0
  144534. };
  144535. static long _vq_quantlist__16u2_p9_1[] = {
  144536. 392,
  144537. 343,
  144538. 441,
  144539. 294,
  144540. 490,
  144541. 245,
  144542. 539,
  144543. 196,
  144544. 588,
  144545. 147,
  144546. 637,
  144547. 98,
  144548. 686,
  144549. 49,
  144550. 735,
  144551. 0,
  144552. 784,
  144553. 388,
  144554. 396,
  144555. };
  144556. static long _vq_lengthlist__16u2_p9_1[] = {
  144557. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144558. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144559. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144560. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144561. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144562. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144563. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144564. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144565. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144566. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144567. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144568. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144569. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144570. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144571. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144572. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144577. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144578. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144579. 11,11,11,11,11,11,11, 5, 4,
  144580. };
  144581. static float _vq_quantthresh__16u2_p9_1[] = {
  144582. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144583. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144584. 318.5, 367.5,
  144585. };
  144586. static long _vq_quantmap__16u2_p9_1[] = {
  144587. 15, 13, 11, 9, 7, 5, 3, 1,
  144588. 17, 0, 18, 2, 4, 6, 8, 10,
  144589. 12, 14, 16,
  144590. };
  144591. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144592. _vq_quantthresh__16u2_p9_1,
  144593. _vq_quantmap__16u2_p9_1,
  144594. 19,
  144595. 19
  144596. };
  144597. static static_codebook _16u2_p9_1 = {
  144598. 2, 361,
  144599. _vq_lengthlist__16u2_p9_1,
  144600. 1, -518488064, 1611661312, 10, 0,
  144601. _vq_quantlist__16u2_p9_1,
  144602. NULL,
  144603. &_vq_auxt__16u2_p9_1,
  144604. NULL,
  144605. 0
  144606. };
  144607. static long _vq_quantlist__16u2_p9_2[] = {
  144608. 24,
  144609. 23,
  144610. 25,
  144611. 22,
  144612. 26,
  144613. 21,
  144614. 27,
  144615. 20,
  144616. 28,
  144617. 19,
  144618. 29,
  144619. 18,
  144620. 30,
  144621. 17,
  144622. 31,
  144623. 16,
  144624. 32,
  144625. 15,
  144626. 33,
  144627. 14,
  144628. 34,
  144629. 13,
  144630. 35,
  144631. 12,
  144632. 36,
  144633. 11,
  144634. 37,
  144635. 10,
  144636. 38,
  144637. 9,
  144638. 39,
  144639. 8,
  144640. 40,
  144641. 7,
  144642. 41,
  144643. 6,
  144644. 42,
  144645. 5,
  144646. 43,
  144647. 4,
  144648. 44,
  144649. 3,
  144650. 45,
  144651. 2,
  144652. 46,
  144653. 1,
  144654. 47,
  144655. 0,
  144656. 48,
  144657. };
  144658. static long _vq_lengthlist__16u2_p9_2[] = {
  144659. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144660. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144661. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144662. 11,
  144663. };
  144664. static float _vq_quantthresh__16u2_p9_2[] = {
  144665. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144666. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144667. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144668. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144669. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144670. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144671. };
  144672. static long _vq_quantmap__16u2_p9_2[] = {
  144673. 47, 45, 43, 41, 39, 37, 35, 33,
  144674. 31, 29, 27, 25, 23, 21, 19, 17,
  144675. 15, 13, 11, 9, 7, 5, 3, 1,
  144676. 0, 2, 4, 6, 8, 10, 12, 14,
  144677. 16, 18, 20, 22, 24, 26, 28, 30,
  144678. 32, 34, 36, 38, 40, 42, 44, 46,
  144679. 48,
  144680. };
  144681. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144682. _vq_quantthresh__16u2_p9_2,
  144683. _vq_quantmap__16u2_p9_2,
  144684. 49,
  144685. 49
  144686. };
  144687. static static_codebook _16u2_p9_2 = {
  144688. 1, 49,
  144689. _vq_lengthlist__16u2_p9_2,
  144690. 1, -526909440, 1611661312, 6, 0,
  144691. _vq_quantlist__16u2_p9_2,
  144692. NULL,
  144693. &_vq_auxt__16u2_p9_2,
  144694. NULL,
  144695. 0
  144696. };
  144697. static long _vq_quantlist__8u0__p1_0[] = {
  144698. 1,
  144699. 0,
  144700. 2,
  144701. };
  144702. static long _vq_lengthlist__8u0__p1_0[] = {
  144703. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144704. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144705. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144706. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144707. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144708. 11,
  144709. };
  144710. static float _vq_quantthresh__8u0__p1_0[] = {
  144711. -0.5, 0.5,
  144712. };
  144713. static long _vq_quantmap__8u0__p1_0[] = {
  144714. 1, 0, 2,
  144715. };
  144716. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144717. _vq_quantthresh__8u0__p1_0,
  144718. _vq_quantmap__8u0__p1_0,
  144719. 3,
  144720. 3
  144721. };
  144722. static static_codebook _8u0__p1_0 = {
  144723. 4, 81,
  144724. _vq_lengthlist__8u0__p1_0,
  144725. 1, -535822336, 1611661312, 2, 0,
  144726. _vq_quantlist__8u0__p1_0,
  144727. NULL,
  144728. &_vq_auxt__8u0__p1_0,
  144729. NULL,
  144730. 0
  144731. };
  144732. static long _vq_quantlist__8u0__p2_0[] = {
  144733. 1,
  144734. 0,
  144735. 2,
  144736. };
  144737. static long _vq_lengthlist__8u0__p2_0[] = {
  144738. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144739. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144740. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144741. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144742. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144743. 8,
  144744. };
  144745. static float _vq_quantthresh__8u0__p2_0[] = {
  144746. -0.5, 0.5,
  144747. };
  144748. static long _vq_quantmap__8u0__p2_0[] = {
  144749. 1, 0, 2,
  144750. };
  144751. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144752. _vq_quantthresh__8u0__p2_0,
  144753. _vq_quantmap__8u0__p2_0,
  144754. 3,
  144755. 3
  144756. };
  144757. static static_codebook _8u0__p2_0 = {
  144758. 4, 81,
  144759. _vq_lengthlist__8u0__p2_0,
  144760. 1, -535822336, 1611661312, 2, 0,
  144761. _vq_quantlist__8u0__p2_0,
  144762. NULL,
  144763. &_vq_auxt__8u0__p2_0,
  144764. NULL,
  144765. 0
  144766. };
  144767. static long _vq_quantlist__8u0__p3_0[] = {
  144768. 2,
  144769. 1,
  144770. 3,
  144771. 0,
  144772. 4,
  144773. };
  144774. static long _vq_lengthlist__8u0__p3_0[] = {
  144775. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144776. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144777. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144778. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144779. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144780. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144781. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144782. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144783. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144784. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144785. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144786. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144787. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144788. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144789. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144790. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144791. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144792. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144793. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144794. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144795. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144796. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144797. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144798. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144799. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144800. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144801. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144802. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144803. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144804. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144805. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144806. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144807. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144808. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144809. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144810. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144811. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144812. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144813. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144814. 16,
  144815. };
  144816. static float _vq_quantthresh__8u0__p3_0[] = {
  144817. -1.5, -0.5, 0.5, 1.5,
  144818. };
  144819. static long _vq_quantmap__8u0__p3_0[] = {
  144820. 3, 1, 0, 2, 4,
  144821. };
  144822. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144823. _vq_quantthresh__8u0__p3_0,
  144824. _vq_quantmap__8u0__p3_0,
  144825. 5,
  144826. 5
  144827. };
  144828. static static_codebook _8u0__p3_0 = {
  144829. 4, 625,
  144830. _vq_lengthlist__8u0__p3_0,
  144831. 1, -533725184, 1611661312, 3, 0,
  144832. _vq_quantlist__8u0__p3_0,
  144833. NULL,
  144834. &_vq_auxt__8u0__p3_0,
  144835. NULL,
  144836. 0
  144837. };
  144838. static long _vq_quantlist__8u0__p4_0[] = {
  144839. 2,
  144840. 1,
  144841. 3,
  144842. 0,
  144843. 4,
  144844. };
  144845. static long _vq_lengthlist__8u0__p4_0[] = {
  144846. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144847. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144848. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144849. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144850. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144851. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144852. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144853. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144854. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144855. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144856. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144857. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144858. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144859. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144860. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144861. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144862. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144863. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144864. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144865. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144866. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144867. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144868. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144869. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144870. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144871. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144872. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144873. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144874. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144875. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144876. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144877. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144878. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144879. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144880. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144881. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144882. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144883. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144884. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144885. 12,
  144886. };
  144887. static float _vq_quantthresh__8u0__p4_0[] = {
  144888. -1.5, -0.5, 0.5, 1.5,
  144889. };
  144890. static long _vq_quantmap__8u0__p4_0[] = {
  144891. 3, 1, 0, 2, 4,
  144892. };
  144893. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144894. _vq_quantthresh__8u0__p4_0,
  144895. _vq_quantmap__8u0__p4_0,
  144896. 5,
  144897. 5
  144898. };
  144899. static static_codebook _8u0__p4_0 = {
  144900. 4, 625,
  144901. _vq_lengthlist__8u0__p4_0,
  144902. 1, -533725184, 1611661312, 3, 0,
  144903. _vq_quantlist__8u0__p4_0,
  144904. NULL,
  144905. &_vq_auxt__8u0__p4_0,
  144906. NULL,
  144907. 0
  144908. };
  144909. static long _vq_quantlist__8u0__p5_0[] = {
  144910. 4,
  144911. 3,
  144912. 5,
  144913. 2,
  144914. 6,
  144915. 1,
  144916. 7,
  144917. 0,
  144918. 8,
  144919. };
  144920. static long _vq_lengthlist__8u0__p5_0[] = {
  144921. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144922. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144923. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144924. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144925. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144926. 12,
  144927. };
  144928. static float _vq_quantthresh__8u0__p5_0[] = {
  144929. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144930. };
  144931. static long _vq_quantmap__8u0__p5_0[] = {
  144932. 7, 5, 3, 1, 0, 2, 4, 6,
  144933. 8,
  144934. };
  144935. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144936. _vq_quantthresh__8u0__p5_0,
  144937. _vq_quantmap__8u0__p5_0,
  144938. 9,
  144939. 9
  144940. };
  144941. static static_codebook _8u0__p5_0 = {
  144942. 2, 81,
  144943. _vq_lengthlist__8u0__p5_0,
  144944. 1, -531628032, 1611661312, 4, 0,
  144945. _vq_quantlist__8u0__p5_0,
  144946. NULL,
  144947. &_vq_auxt__8u0__p5_0,
  144948. NULL,
  144949. 0
  144950. };
  144951. static long _vq_quantlist__8u0__p6_0[] = {
  144952. 6,
  144953. 5,
  144954. 7,
  144955. 4,
  144956. 8,
  144957. 3,
  144958. 9,
  144959. 2,
  144960. 10,
  144961. 1,
  144962. 11,
  144963. 0,
  144964. 12,
  144965. };
  144966. static long _vq_lengthlist__8u0__p6_0[] = {
  144967. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144968. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144969. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144970. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144971. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144972. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144973. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144974. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144975. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144976. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144977. 16, 0,15, 0,17, 0, 0, 0, 0,
  144978. };
  144979. static float _vq_quantthresh__8u0__p6_0[] = {
  144980. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144981. 12.5, 17.5, 22.5, 27.5,
  144982. };
  144983. static long _vq_quantmap__8u0__p6_0[] = {
  144984. 11, 9, 7, 5, 3, 1, 0, 2,
  144985. 4, 6, 8, 10, 12,
  144986. };
  144987. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144988. _vq_quantthresh__8u0__p6_0,
  144989. _vq_quantmap__8u0__p6_0,
  144990. 13,
  144991. 13
  144992. };
  144993. static static_codebook _8u0__p6_0 = {
  144994. 2, 169,
  144995. _vq_lengthlist__8u0__p6_0,
  144996. 1, -526516224, 1616117760, 4, 0,
  144997. _vq_quantlist__8u0__p6_0,
  144998. NULL,
  144999. &_vq_auxt__8u0__p6_0,
  145000. NULL,
  145001. 0
  145002. };
  145003. static long _vq_quantlist__8u0__p6_1[] = {
  145004. 2,
  145005. 1,
  145006. 3,
  145007. 0,
  145008. 4,
  145009. };
  145010. static long _vq_lengthlist__8u0__p6_1[] = {
  145011. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145012. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145013. };
  145014. static float _vq_quantthresh__8u0__p6_1[] = {
  145015. -1.5, -0.5, 0.5, 1.5,
  145016. };
  145017. static long _vq_quantmap__8u0__p6_1[] = {
  145018. 3, 1, 0, 2, 4,
  145019. };
  145020. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145021. _vq_quantthresh__8u0__p6_1,
  145022. _vq_quantmap__8u0__p6_1,
  145023. 5,
  145024. 5
  145025. };
  145026. static static_codebook _8u0__p6_1 = {
  145027. 2, 25,
  145028. _vq_lengthlist__8u0__p6_1,
  145029. 1, -533725184, 1611661312, 3, 0,
  145030. _vq_quantlist__8u0__p6_1,
  145031. NULL,
  145032. &_vq_auxt__8u0__p6_1,
  145033. NULL,
  145034. 0
  145035. };
  145036. static long _vq_quantlist__8u0__p7_0[] = {
  145037. 1,
  145038. 0,
  145039. 2,
  145040. };
  145041. static long _vq_lengthlist__8u0__p7_0[] = {
  145042. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145043. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145044. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145045. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145046. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145047. 7,
  145048. };
  145049. static float _vq_quantthresh__8u0__p7_0[] = {
  145050. -157.5, 157.5,
  145051. };
  145052. static long _vq_quantmap__8u0__p7_0[] = {
  145053. 1, 0, 2,
  145054. };
  145055. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145056. _vq_quantthresh__8u0__p7_0,
  145057. _vq_quantmap__8u0__p7_0,
  145058. 3,
  145059. 3
  145060. };
  145061. static static_codebook _8u0__p7_0 = {
  145062. 4, 81,
  145063. _vq_lengthlist__8u0__p7_0,
  145064. 1, -518803456, 1628680192, 2, 0,
  145065. _vq_quantlist__8u0__p7_0,
  145066. NULL,
  145067. &_vq_auxt__8u0__p7_0,
  145068. NULL,
  145069. 0
  145070. };
  145071. static long _vq_quantlist__8u0__p7_1[] = {
  145072. 7,
  145073. 6,
  145074. 8,
  145075. 5,
  145076. 9,
  145077. 4,
  145078. 10,
  145079. 3,
  145080. 11,
  145081. 2,
  145082. 12,
  145083. 1,
  145084. 13,
  145085. 0,
  145086. 14,
  145087. };
  145088. static long _vq_lengthlist__8u0__p7_1[] = {
  145089. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145090. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145091. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145092. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145093. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145094. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145101. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145102. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145103. 10,
  145104. };
  145105. static float _vq_quantthresh__8u0__p7_1[] = {
  145106. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145107. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145108. };
  145109. static long _vq_quantmap__8u0__p7_1[] = {
  145110. 13, 11, 9, 7, 5, 3, 1, 0,
  145111. 2, 4, 6, 8, 10, 12, 14,
  145112. };
  145113. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145114. _vq_quantthresh__8u0__p7_1,
  145115. _vq_quantmap__8u0__p7_1,
  145116. 15,
  145117. 15
  145118. };
  145119. static static_codebook _8u0__p7_1 = {
  145120. 2, 225,
  145121. _vq_lengthlist__8u0__p7_1,
  145122. 1, -520986624, 1620377600, 4, 0,
  145123. _vq_quantlist__8u0__p7_1,
  145124. NULL,
  145125. &_vq_auxt__8u0__p7_1,
  145126. NULL,
  145127. 0
  145128. };
  145129. static long _vq_quantlist__8u0__p7_2[] = {
  145130. 10,
  145131. 9,
  145132. 11,
  145133. 8,
  145134. 12,
  145135. 7,
  145136. 13,
  145137. 6,
  145138. 14,
  145139. 5,
  145140. 15,
  145141. 4,
  145142. 16,
  145143. 3,
  145144. 17,
  145145. 2,
  145146. 18,
  145147. 1,
  145148. 19,
  145149. 0,
  145150. 20,
  145151. };
  145152. static long _vq_lengthlist__8u0__p7_2[] = {
  145153. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145154. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145155. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145156. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145157. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145158. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145159. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145160. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145161. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145162. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145163. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145164. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145165. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145166. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145167. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145168. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145169. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145170. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145171. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145172. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145173. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145174. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145175. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145176. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145177. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145178. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145179. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145180. 11,12,11,11,11,10,10,11,11,
  145181. };
  145182. static float _vq_quantthresh__8u0__p7_2[] = {
  145183. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145184. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145185. 6.5, 7.5, 8.5, 9.5,
  145186. };
  145187. static long _vq_quantmap__8u0__p7_2[] = {
  145188. 19, 17, 15, 13, 11, 9, 7, 5,
  145189. 3, 1, 0, 2, 4, 6, 8, 10,
  145190. 12, 14, 16, 18, 20,
  145191. };
  145192. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145193. _vq_quantthresh__8u0__p7_2,
  145194. _vq_quantmap__8u0__p7_2,
  145195. 21,
  145196. 21
  145197. };
  145198. static static_codebook _8u0__p7_2 = {
  145199. 2, 441,
  145200. _vq_lengthlist__8u0__p7_2,
  145201. 1, -529268736, 1611661312, 5, 0,
  145202. _vq_quantlist__8u0__p7_2,
  145203. NULL,
  145204. &_vq_auxt__8u0__p7_2,
  145205. NULL,
  145206. 0
  145207. };
  145208. static long _huff_lengthlist__8u0__single[] = {
  145209. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145210. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145211. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145212. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145213. };
  145214. static static_codebook _huff_book__8u0__single = {
  145215. 2, 64,
  145216. _huff_lengthlist__8u0__single,
  145217. 0, 0, 0, 0, 0,
  145218. NULL,
  145219. NULL,
  145220. NULL,
  145221. NULL,
  145222. 0
  145223. };
  145224. static long _vq_quantlist__8u1__p1_0[] = {
  145225. 1,
  145226. 0,
  145227. 2,
  145228. };
  145229. static long _vq_lengthlist__8u1__p1_0[] = {
  145230. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145231. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145232. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145233. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145234. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145235. 10,
  145236. };
  145237. static float _vq_quantthresh__8u1__p1_0[] = {
  145238. -0.5, 0.5,
  145239. };
  145240. static long _vq_quantmap__8u1__p1_0[] = {
  145241. 1, 0, 2,
  145242. };
  145243. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145244. _vq_quantthresh__8u1__p1_0,
  145245. _vq_quantmap__8u1__p1_0,
  145246. 3,
  145247. 3
  145248. };
  145249. static static_codebook _8u1__p1_0 = {
  145250. 4, 81,
  145251. _vq_lengthlist__8u1__p1_0,
  145252. 1, -535822336, 1611661312, 2, 0,
  145253. _vq_quantlist__8u1__p1_0,
  145254. NULL,
  145255. &_vq_auxt__8u1__p1_0,
  145256. NULL,
  145257. 0
  145258. };
  145259. static long _vq_quantlist__8u1__p2_0[] = {
  145260. 1,
  145261. 0,
  145262. 2,
  145263. };
  145264. static long _vq_lengthlist__8u1__p2_0[] = {
  145265. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145266. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145267. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145268. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145269. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145270. 7,
  145271. };
  145272. static float _vq_quantthresh__8u1__p2_0[] = {
  145273. -0.5, 0.5,
  145274. };
  145275. static long _vq_quantmap__8u1__p2_0[] = {
  145276. 1, 0, 2,
  145277. };
  145278. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145279. _vq_quantthresh__8u1__p2_0,
  145280. _vq_quantmap__8u1__p2_0,
  145281. 3,
  145282. 3
  145283. };
  145284. static static_codebook _8u1__p2_0 = {
  145285. 4, 81,
  145286. _vq_lengthlist__8u1__p2_0,
  145287. 1, -535822336, 1611661312, 2, 0,
  145288. _vq_quantlist__8u1__p2_0,
  145289. NULL,
  145290. &_vq_auxt__8u1__p2_0,
  145291. NULL,
  145292. 0
  145293. };
  145294. static long _vq_quantlist__8u1__p3_0[] = {
  145295. 2,
  145296. 1,
  145297. 3,
  145298. 0,
  145299. 4,
  145300. };
  145301. static long _vq_lengthlist__8u1__p3_0[] = {
  145302. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145303. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145304. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145305. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145306. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145307. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145308. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145309. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145310. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145311. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145312. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145313. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145314. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145315. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145316. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145317. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145318. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145319. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145320. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145321. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145322. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145323. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145324. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145325. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145326. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145327. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145328. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145329. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145330. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145331. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145332. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145333. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145334. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145335. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145336. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145337. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145338. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145339. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145340. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145341. 16,
  145342. };
  145343. static float _vq_quantthresh__8u1__p3_0[] = {
  145344. -1.5, -0.5, 0.5, 1.5,
  145345. };
  145346. static long _vq_quantmap__8u1__p3_0[] = {
  145347. 3, 1, 0, 2, 4,
  145348. };
  145349. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145350. _vq_quantthresh__8u1__p3_0,
  145351. _vq_quantmap__8u1__p3_0,
  145352. 5,
  145353. 5
  145354. };
  145355. static static_codebook _8u1__p3_0 = {
  145356. 4, 625,
  145357. _vq_lengthlist__8u1__p3_0,
  145358. 1, -533725184, 1611661312, 3, 0,
  145359. _vq_quantlist__8u1__p3_0,
  145360. NULL,
  145361. &_vq_auxt__8u1__p3_0,
  145362. NULL,
  145363. 0
  145364. };
  145365. static long _vq_quantlist__8u1__p4_0[] = {
  145366. 2,
  145367. 1,
  145368. 3,
  145369. 0,
  145370. 4,
  145371. };
  145372. static long _vq_lengthlist__8u1__p4_0[] = {
  145373. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145374. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145375. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145376. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145377. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145378. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145379. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145380. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145381. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145382. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145383. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145384. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145385. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145386. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145387. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145388. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145389. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145390. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145391. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145392. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145393. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145394. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145395. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145396. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145397. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145398. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145399. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145400. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145401. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145402. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145403. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145404. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145405. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145406. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145407. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145408. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145409. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145410. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145411. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145412. 10,
  145413. };
  145414. static float _vq_quantthresh__8u1__p4_0[] = {
  145415. -1.5, -0.5, 0.5, 1.5,
  145416. };
  145417. static long _vq_quantmap__8u1__p4_0[] = {
  145418. 3, 1, 0, 2, 4,
  145419. };
  145420. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145421. _vq_quantthresh__8u1__p4_0,
  145422. _vq_quantmap__8u1__p4_0,
  145423. 5,
  145424. 5
  145425. };
  145426. static static_codebook _8u1__p4_0 = {
  145427. 4, 625,
  145428. _vq_lengthlist__8u1__p4_0,
  145429. 1, -533725184, 1611661312, 3, 0,
  145430. _vq_quantlist__8u1__p4_0,
  145431. NULL,
  145432. &_vq_auxt__8u1__p4_0,
  145433. NULL,
  145434. 0
  145435. };
  145436. static long _vq_quantlist__8u1__p5_0[] = {
  145437. 4,
  145438. 3,
  145439. 5,
  145440. 2,
  145441. 6,
  145442. 1,
  145443. 7,
  145444. 0,
  145445. 8,
  145446. };
  145447. static long _vq_lengthlist__8u1__p5_0[] = {
  145448. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145449. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145450. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145451. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145452. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145453. 13,
  145454. };
  145455. static float _vq_quantthresh__8u1__p5_0[] = {
  145456. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145457. };
  145458. static long _vq_quantmap__8u1__p5_0[] = {
  145459. 7, 5, 3, 1, 0, 2, 4, 6,
  145460. 8,
  145461. };
  145462. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145463. _vq_quantthresh__8u1__p5_0,
  145464. _vq_quantmap__8u1__p5_0,
  145465. 9,
  145466. 9
  145467. };
  145468. static static_codebook _8u1__p5_0 = {
  145469. 2, 81,
  145470. _vq_lengthlist__8u1__p5_0,
  145471. 1, -531628032, 1611661312, 4, 0,
  145472. _vq_quantlist__8u1__p5_0,
  145473. NULL,
  145474. &_vq_auxt__8u1__p5_0,
  145475. NULL,
  145476. 0
  145477. };
  145478. static long _vq_quantlist__8u1__p6_0[] = {
  145479. 4,
  145480. 3,
  145481. 5,
  145482. 2,
  145483. 6,
  145484. 1,
  145485. 7,
  145486. 0,
  145487. 8,
  145488. };
  145489. static long _vq_lengthlist__8u1__p6_0[] = {
  145490. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145491. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145492. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145493. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145494. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145495. 10,
  145496. };
  145497. static float _vq_quantthresh__8u1__p6_0[] = {
  145498. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145499. };
  145500. static long _vq_quantmap__8u1__p6_0[] = {
  145501. 7, 5, 3, 1, 0, 2, 4, 6,
  145502. 8,
  145503. };
  145504. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145505. _vq_quantthresh__8u1__p6_0,
  145506. _vq_quantmap__8u1__p6_0,
  145507. 9,
  145508. 9
  145509. };
  145510. static static_codebook _8u1__p6_0 = {
  145511. 2, 81,
  145512. _vq_lengthlist__8u1__p6_0,
  145513. 1, -531628032, 1611661312, 4, 0,
  145514. _vq_quantlist__8u1__p6_0,
  145515. NULL,
  145516. &_vq_auxt__8u1__p6_0,
  145517. NULL,
  145518. 0
  145519. };
  145520. static long _vq_quantlist__8u1__p7_0[] = {
  145521. 1,
  145522. 0,
  145523. 2,
  145524. };
  145525. static long _vq_lengthlist__8u1__p7_0[] = {
  145526. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145527. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145528. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145529. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145530. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145531. 11,
  145532. };
  145533. static float _vq_quantthresh__8u1__p7_0[] = {
  145534. -5.5, 5.5,
  145535. };
  145536. static long _vq_quantmap__8u1__p7_0[] = {
  145537. 1, 0, 2,
  145538. };
  145539. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145540. _vq_quantthresh__8u1__p7_0,
  145541. _vq_quantmap__8u1__p7_0,
  145542. 3,
  145543. 3
  145544. };
  145545. static static_codebook _8u1__p7_0 = {
  145546. 4, 81,
  145547. _vq_lengthlist__8u1__p7_0,
  145548. 1, -529137664, 1618345984, 2, 0,
  145549. _vq_quantlist__8u1__p7_0,
  145550. NULL,
  145551. &_vq_auxt__8u1__p7_0,
  145552. NULL,
  145553. 0
  145554. };
  145555. static long _vq_quantlist__8u1__p7_1[] = {
  145556. 5,
  145557. 4,
  145558. 6,
  145559. 3,
  145560. 7,
  145561. 2,
  145562. 8,
  145563. 1,
  145564. 9,
  145565. 0,
  145566. 10,
  145567. };
  145568. static long _vq_lengthlist__8u1__p7_1[] = {
  145569. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145570. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145571. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145572. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145573. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145574. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145575. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145576. 9, 9, 9, 9, 9,10,10,10,10,
  145577. };
  145578. static float _vq_quantthresh__8u1__p7_1[] = {
  145579. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145580. 3.5, 4.5,
  145581. };
  145582. static long _vq_quantmap__8u1__p7_1[] = {
  145583. 9, 7, 5, 3, 1, 0, 2, 4,
  145584. 6, 8, 10,
  145585. };
  145586. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145587. _vq_quantthresh__8u1__p7_1,
  145588. _vq_quantmap__8u1__p7_1,
  145589. 11,
  145590. 11
  145591. };
  145592. static static_codebook _8u1__p7_1 = {
  145593. 2, 121,
  145594. _vq_lengthlist__8u1__p7_1,
  145595. 1, -531365888, 1611661312, 4, 0,
  145596. _vq_quantlist__8u1__p7_1,
  145597. NULL,
  145598. &_vq_auxt__8u1__p7_1,
  145599. NULL,
  145600. 0
  145601. };
  145602. static long _vq_quantlist__8u1__p8_0[] = {
  145603. 5,
  145604. 4,
  145605. 6,
  145606. 3,
  145607. 7,
  145608. 2,
  145609. 8,
  145610. 1,
  145611. 9,
  145612. 0,
  145613. 10,
  145614. };
  145615. static long _vq_lengthlist__8u1__p8_0[] = {
  145616. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145617. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145618. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145619. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145620. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145621. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145622. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145623. 12,13,13,14,14,15,15,15,15,
  145624. };
  145625. static float _vq_quantthresh__8u1__p8_0[] = {
  145626. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145627. 38.5, 49.5,
  145628. };
  145629. static long _vq_quantmap__8u1__p8_0[] = {
  145630. 9, 7, 5, 3, 1, 0, 2, 4,
  145631. 6, 8, 10,
  145632. };
  145633. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145634. _vq_quantthresh__8u1__p8_0,
  145635. _vq_quantmap__8u1__p8_0,
  145636. 11,
  145637. 11
  145638. };
  145639. static static_codebook _8u1__p8_0 = {
  145640. 2, 121,
  145641. _vq_lengthlist__8u1__p8_0,
  145642. 1, -524582912, 1618345984, 4, 0,
  145643. _vq_quantlist__8u1__p8_0,
  145644. NULL,
  145645. &_vq_auxt__8u1__p8_0,
  145646. NULL,
  145647. 0
  145648. };
  145649. static long _vq_quantlist__8u1__p8_1[] = {
  145650. 5,
  145651. 4,
  145652. 6,
  145653. 3,
  145654. 7,
  145655. 2,
  145656. 8,
  145657. 1,
  145658. 9,
  145659. 0,
  145660. 10,
  145661. };
  145662. static long _vq_lengthlist__8u1__p8_1[] = {
  145663. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145664. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145665. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145666. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145667. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145668. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145669. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145670. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145671. };
  145672. static float _vq_quantthresh__8u1__p8_1[] = {
  145673. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145674. 3.5, 4.5,
  145675. };
  145676. static long _vq_quantmap__8u1__p8_1[] = {
  145677. 9, 7, 5, 3, 1, 0, 2, 4,
  145678. 6, 8, 10,
  145679. };
  145680. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145681. _vq_quantthresh__8u1__p8_1,
  145682. _vq_quantmap__8u1__p8_1,
  145683. 11,
  145684. 11
  145685. };
  145686. static static_codebook _8u1__p8_1 = {
  145687. 2, 121,
  145688. _vq_lengthlist__8u1__p8_1,
  145689. 1, -531365888, 1611661312, 4, 0,
  145690. _vq_quantlist__8u1__p8_1,
  145691. NULL,
  145692. &_vq_auxt__8u1__p8_1,
  145693. NULL,
  145694. 0
  145695. };
  145696. static long _vq_quantlist__8u1__p9_0[] = {
  145697. 7,
  145698. 6,
  145699. 8,
  145700. 5,
  145701. 9,
  145702. 4,
  145703. 10,
  145704. 3,
  145705. 11,
  145706. 2,
  145707. 12,
  145708. 1,
  145709. 13,
  145710. 0,
  145711. 14,
  145712. };
  145713. static long _vq_lengthlist__8u1__p9_0[] = {
  145714. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145715. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145716. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145726. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145727. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145728. 10,
  145729. };
  145730. static float _vq_quantthresh__8u1__p9_0[] = {
  145731. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145732. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145733. };
  145734. static long _vq_quantmap__8u1__p9_0[] = {
  145735. 13, 11, 9, 7, 5, 3, 1, 0,
  145736. 2, 4, 6, 8, 10, 12, 14,
  145737. };
  145738. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145739. _vq_quantthresh__8u1__p9_0,
  145740. _vq_quantmap__8u1__p9_0,
  145741. 15,
  145742. 15
  145743. };
  145744. static static_codebook _8u1__p9_0 = {
  145745. 2, 225,
  145746. _vq_lengthlist__8u1__p9_0,
  145747. 1, -514071552, 1627381760, 4, 0,
  145748. _vq_quantlist__8u1__p9_0,
  145749. NULL,
  145750. &_vq_auxt__8u1__p9_0,
  145751. NULL,
  145752. 0
  145753. };
  145754. static long _vq_quantlist__8u1__p9_1[] = {
  145755. 7,
  145756. 6,
  145757. 8,
  145758. 5,
  145759. 9,
  145760. 4,
  145761. 10,
  145762. 3,
  145763. 11,
  145764. 2,
  145765. 12,
  145766. 1,
  145767. 13,
  145768. 0,
  145769. 14,
  145770. };
  145771. static long _vq_lengthlist__8u1__p9_1[] = {
  145772. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145773. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145774. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145775. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145776. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145777. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145778. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145779. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145780. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145781. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145782. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145783. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145784. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145785. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145786. 13,
  145787. };
  145788. static float _vq_quantthresh__8u1__p9_1[] = {
  145789. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145790. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145791. };
  145792. static long _vq_quantmap__8u1__p9_1[] = {
  145793. 13, 11, 9, 7, 5, 3, 1, 0,
  145794. 2, 4, 6, 8, 10, 12, 14,
  145795. };
  145796. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145797. _vq_quantthresh__8u1__p9_1,
  145798. _vq_quantmap__8u1__p9_1,
  145799. 15,
  145800. 15
  145801. };
  145802. static static_codebook _8u1__p9_1 = {
  145803. 2, 225,
  145804. _vq_lengthlist__8u1__p9_1,
  145805. 1, -522338304, 1620115456, 4, 0,
  145806. _vq_quantlist__8u1__p9_1,
  145807. NULL,
  145808. &_vq_auxt__8u1__p9_1,
  145809. NULL,
  145810. 0
  145811. };
  145812. static long _vq_quantlist__8u1__p9_2[] = {
  145813. 8,
  145814. 7,
  145815. 9,
  145816. 6,
  145817. 10,
  145818. 5,
  145819. 11,
  145820. 4,
  145821. 12,
  145822. 3,
  145823. 13,
  145824. 2,
  145825. 14,
  145826. 1,
  145827. 15,
  145828. 0,
  145829. 16,
  145830. };
  145831. static long _vq_lengthlist__8u1__p9_2[] = {
  145832. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145833. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145834. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145835. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145836. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145837. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145838. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145839. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145840. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145841. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145842. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145843. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145844. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145845. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145846. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145847. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145848. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145849. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145850. 10,
  145851. };
  145852. static float _vq_quantthresh__8u1__p9_2[] = {
  145853. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145854. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145855. };
  145856. static long _vq_quantmap__8u1__p9_2[] = {
  145857. 15, 13, 11, 9, 7, 5, 3, 1,
  145858. 0, 2, 4, 6, 8, 10, 12, 14,
  145859. 16,
  145860. };
  145861. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145862. _vq_quantthresh__8u1__p9_2,
  145863. _vq_quantmap__8u1__p9_2,
  145864. 17,
  145865. 17
  145866. };
  145867. static static_codebook _8u1__p9_2 = {
  145868. 2, 289,
  145869. _vq_lengthlist__8u1__p9_2,
  145870. 1, -529530880, 1611661312, 5, 0,
  145871. _vq_quantlist__8u1__p9_2,
  145872. NULL,
  145873. &_vq_auxt__8u1__p9_2,
  145874. NULL,
  145875. 0
  145876. };
  145877. static long _huff_lengthlist__8u1__single[] = {
  145878. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145879. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145880. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145881. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145882. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145883. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145884. 13, 8, 8,15,
  145885. };
  145886. static static_codebook _huff_book__8u1__single = {
  145887. 2, 100,
  145888. _huff_lengthlist__8u1__single,
  145889. 0, 0, 0, 0, 0,
  145890. NULL,
  145891. NULL,
  145892. NULL,
  145893. NULL,
  145894. 0
  145895. };
  145896. static long _huff_lengthlist__44u0__long[] = {
  145897. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145898. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145899. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145900. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145901. };
  145902. static static_codebook _huff_book__44u0__long = {
  145903. 2, 64,
  145904. _huff_lengthlist__44u0__long,
  145905. 0, 0, 0, 0, 0,
  145906. NULL,
  145907. NULL,
  145908. NULL,
  145909. NULL,
  145910. 0
  145911. };
  145912. static long _vq_quantlist__44u0__p1_0[] = {
  145913. 1,
  145914. 0,
  145915. 2,
  145916. };
  145917. static long _vq_lengthlist__44u0__p1_0[] = {
  145918. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145919. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145920. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145921. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145922. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145923. 13,
  145924. };
  145925. static float _vq_quantthresh__44u0__p1_0[] = {
  145926. -0.5, 0.5,
  145927. };
  145928. static long _vq_quantmap__44u0__p1_0[] = {
  145929. 1, 0, 2,
  145930. };
  145931. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145932. _vq_quantthresh__44u0__p1_0,
  145933. _vq_quantmap__44u0__p1_0,
  145934. 3,
  145935. 3
  145936. };
  145937. static static_codebook _44u0__p1_0 = {
  145938. 4, 81,
  145939. _vq_lengthlist__44u0__p1_0,
  145940. 1, -535822336, 1611661312, 2, 0,
  145941. _vq_quantlist__44u0__p1_0,
  145942. NULL,
  145943. &_vq_auxt__44u0__p1_0,
  145944. NULL,
  145945. 0
  145946. };
  145947. static long _vq_quantlist__44u0__p2_0[] = {
  145948. 1,
  145949. 0,
  145950. 2,
  145951. };
  145952. static long _vq_lengthlist__44u0__p2_0[] = {
  145953. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145954. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145955. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145956. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145957. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145958. 9,
  145959. };
  145960. static float _vq_quantthresh__44u0__p2_0[] = {
  145961. -0.5, 0.5,
  145962. };
  145963. static long _vq_quantmap__44u0__p2_0[] = {
  145964. 1, 0, 2,
  145965. };
  145966. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145967. _vq_quantthresh__44u0__p2_0,
  145968. _vq_quantmap__44u0__p2_0,
  145969. 3,
  145970. 3
  145971. };
  145972. static static_codebook _44u0__p2_0 = {
  145973. 4, 81,
  145974. _vq_lengthlist__44u0__p2_0,
  145975. 1, -535822336, 1611661312, 2, 0,
  145976. _vq_quantlist__44u0__p2_0,
  145977. NULL,
  145978. &_vq_auxt__44u0__p2_0,
  145979. NULL,
  145980. 0
  145981. };
  145982. static long _vq_quantlist__44u0__p3_0[] = {
  145983. 2,
  145984. 1,
  145985. 3,
  145986. 0,
  145987. 4,
  145988. };
  145989. static long _vq_lengthlist__44u0__p3_0[] = {
  145990. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145991. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145992. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145993. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145994. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145995. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145996. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145997. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145998. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145999. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146000. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146001. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146002. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146003. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146004. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146005. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146006. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146007. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146008. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146009. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146010. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146011. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146012. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146013. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146014. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146015. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146016. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146017. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146018. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146019. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146020. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146021. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146022. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146023. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146024. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146025. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146026. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146027. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146028. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146029. 19,
  146030. };
  146031. static float _vq_quantthresh__44u0__p3_0[] = {
  146032. -1.5, -0.5, 0.5, 1.5,
  146033. };
  146034. static long _vq_quantmap__44u0__p3_0[] = {
  146035. 3, 1, 0, 2, 4,
  146036. };
  146037. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146038. _vq_quantthresh__44u0__p3_0,
  146039. _vq_quantmap__44u0__p3_0,
  146040. 5,
  146041. 5
  146042. };
  146043. static static_codebook _44u0__p3_0 = {
  146044. 4, 625,
  146045. _vq_lengthlist__44u0__p3_0,
  146046. 1, -533725184, 1611661312, 3, 0,
  146047. _vq_quantlist__44u0__p3_0,
  146048. NULL,
  146049. &_vq_auxt__44u0__p3_0,
  146050. NULL,
  146051. 0
  146052. };
  146053. static long _vq_quantlist__44u0__p4_0[] = {
  146054. 2,
  146055. 1,
  146056. 3,
  146057. 0,
  146058. 4,
  146059. };
  146060. static long _vq_lengthlist__44u0__p4_0[] = {
  146061. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146062. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146063. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146064. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146065. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146066. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146067. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146068. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146069. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146070. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146071. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146072. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146073. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146074. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146075. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146076. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146077. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146078. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146079. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146080. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146081. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146082. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146083. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146084. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146085. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146086. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146087. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146088. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146089. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146090. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146091. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146092. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146093. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146094. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146095. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146096. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146097. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146098. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146099. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146100. 12,
  146101. };
  146102. static float _vq_quantthresh__44u0__p4_0[] = {
  146103. -1.5, -0.5, 0.5, 1.5,
  146104. };
  146105. static long _vq_quantmap__44u0__p4_0[] = {
  146106. 3, 1, 0, 2, 4,
  146107. };
  146108. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146109. _vq_quantthresh__44u0__p4_0,
  146110. _vq_quantmap__44u0__p4_0,
  146111. 5,
  146112. 5
  146113. };
  146114. static static_codebook _44u0__p4_0 = {
  146115. 4, 625,
  146116. _vq_lengthlist__44u0__p4_0,
  146117. 1, -533725184, 1611661312, 3, 0,
  146118. _vq_quantlist__44u0__p4_0,
  146119. NULL,
  146120. &_vq_auxt__44u0__p4_0,
  146121. NULL,
  146122. 0
  146123. };
  146124. static long _vq_quantlist__44u0__p5_0[] = {
  146125. 4,
  146126. 3,
  146127. 5,
  146128. 2,
  146129. 6,
  146130. 1,
  146131. 7,
  146132. 0,
  146133. 8,
  146134. };
  146135. static long _vq_lengthlist__44u0__p5_0[] = {
  146136. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146137. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146138. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146139. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146140. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146141. 12,
  146142. };
  146143. static float _vq_quantthresh__44u0__p5_0[] = {
  146144. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146145. };
  146146. static long _vq_quantmap__44u0__p5_0[] = {
  146147. 7, 5, 3, 1, 0, 2, 4, 6,
  146148. 8,
  146149. };
  146150. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146151. _vq_quantthresh__44u0__p5_0,
  146152. _vq_quantmap__44u0__p5_0,
  146153. 9,
  146154. 9
  146155. };
  146156. static static_codebook _44u0__p5_0 = {
  146157. 2, 81,
  146158. _vq_lengthlist__44u0__p5_0,
  146159. 1, -531628032, 1611661312, 4, 0,
  146160. _vq_quantlist__44u0__p5_0,
  146161. NULL,
  146162. &_vq_auxt__44u0__p5_0,
  146163. NULL,
  146164. 0
  146165. };
  146166. static long _vq_quantlist__44u0__p6_0[] = {
  146167. 6,
  146168. 5,
  146169. 7,
  146170. 4,
  146171. 8,
  146172. 3,
  146173. 9,
  146174. 2,
  146175. 10,
  146176. 1,
  146177. 11,
  146178. 0,
  146179. 12,
  146180. };
  146181. static long _vq_lengthlist__44u0__p6_0[] = {
  146182. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146183. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146184. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146185. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146186. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146187. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146188. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146189. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146190. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146191. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146192. 15,17,16,17,18,17,17,18, 0,
  146193. };
  146194. static float _vq_quantthresh__44u0__p6_0[] = {
  146195. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146196. 12.5, 17.5, 22.5, 27.5,
  146197. };
  146198. static long _vq_quantmap__44u0__p6_0[] = {
  146199. 11, 9, 7, 5, 3, 1, 0, 2,
  146200. 4, 6, 8, 10, 12,
  146201. };
  146202. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146203. _vq_quantthresh__44u0__p6_0,
  146204. _vq_quantmap__44u0__p6_0,
  146205. 13,
  146206. 13
  146207. };
  146208. static static_codebook _44u0__p6_0 = {
  146209. 2, 169,
  146210. _vq_lengthlist__44u0__p6_0,
  146211. 1, -526516224, 1616117760, 4, 0,
  146212. _vq_quantlist__44u0__p6_0,
  146213. NULL,
  146214. &_vq_auxt__44u0__p6_0,
  146215. NULL,
  146216. 0
  146217. };
  146218. static long _vq_quantlist__44u0__p6_1[] = {
  146219. 2,
  146220. 1,
  146221. 3,
  146222. 0,
  146223. 4,
  146224. };
  146225. static long _vq_lengthlist__44u0__p6_1[] = {
  146226. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146227. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146228. };
  146229. static float _vq_quantthresh__44u0__p6_1[] = {
  146230. -1.5, -0.5, 0.5, 1.5,
  146231. };
  146232. static long _vq_quantmap__44u0__p6_1[] = {
  146233. 3, 1, 0, 2, 4,
  146234. };
  146235. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146236. _vq_quantthresh__44u0__p6_1,
  146237. _vq_quantmap__44u0__p6_1,
  146238. 5,
  146239. 5
  146240. };
  146241. static static_codebook _44u0__p6_1 = {
  146242. 2, 25,
  146243. _vq_lengthlist__44u0__p6_1,
  146244. 1, -533725184, 1611661312, 3, 0,
  146245. _vq_quantlist__44u0__p6_1,
  146246. NULL,
  146247. &_vq_auxt__44u0__p6_1,
  146248. NULL,
  146249. 0
  146250. };
  146251. static long _vq_quantlist__44u0__p7_0[] = {
  146252. 2,
  146253. 1,
  146254. 3,
  146255. 0,
  146256. 4,
  146257. };
  146258. static long _vq_lengthlist__44u0__p7_0[] = {
  146259. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146262. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146266. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146281. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146282. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146283. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146284. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146285. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146286. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146287. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146288. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146289. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146290. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146291. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146292. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146293. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146294. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146295. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146296. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146297. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146298. 10,
  146299. };
  146300. static float _vq_quantthresh__44u0__p7_0[] = {
  146301. -253.5, -84.5, 84.5, 253.5,
  146302. };
  146303. static long _vq_quantmap__44u0__p7_0[] = {
  146304. 3, 1, 0, 2, 4,
  146305. };
  146306. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146307. _vq_quantthresh__44u0__p7_0,
  146308. _vq_quantmap__44u0__p7_0,
  146309. 5,
  146310. 5
  146311. };
  146312. static static_codebook _44u0__p7_0 = {
  146313. 4, 625,
  146314. _vq_lengthlist__44u0__p7_0,
  146315. 1, -518709248, 1626677248, 3, 0,
  146316. _vq_quantlist__44u0__p7_0,
  146317. NULL,
  146318. &_vq_auxt__44u0__p7_0,
  146319. NULL,
  146320. 0
  146321. };
  146322. static long _vq_quantlist__44u0__p7_1[] = {
  146323. 6,
  146324. 5,
  146325. 7,
  146326. 4,
  146327. 8,
  146328. 3,
  146329. 9,
  146330. 2,
  146331. 10,
  146332. 1,
  146333. 11,
  146334. 0,
  146335. 12,
  146336. };
  146337. static long _vq_lengthlist__44u0__p7_1[] = {
  146338. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146339. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146340. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146341. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146342. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146343. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146344. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146345. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146346. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146347. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146348. 15,15,15,15,15,15,15,15,15,
  146349. };
  146350. static float _vq_quantthresh__44u0__p7_1[] = {
  146351. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146352. 32.5, 45.5, 58.5, 71.5,
  146353. };
  146354. static long _vq_quantmap__44u0__p7_1[] = {
  146355. 11, 9, 7, 5, 3, 1, 0, 2,
  146356. 4, 6, 8, 10, 12,
  146357. };
  146358. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146359. _vq_quantthresh__44u0__p7_1,
  146360. _vq_quantmap__44u0__p7_1,
  146361. 13,
  146362. 13
  146363. };
  146364. static static_codebook _44u0__p7_1 = {
  146365. 2, 169,
  146366. _vq_lengthlist__44u0__p7_1,
  146367. 1, -523010048, 1618608128, 4, 0,
  146368. _vq_quantlist__44u0__p7_1,
  146369. NULL,
  146370. &_vq_auxt__44u0__p7_1,
  146371. NULL,
  146372. 0
  146373. };
  146374. static long _vq_quantlist__44u0__p7_2[] = {
  146375. 6,
  146376. 5,
  146377. 7,
  146378. 4,
  146379. 8,
  146380. 3,
  146381. 9,
  146382. 2,
  146383. 10,
  146384. 1,
  146385. 11,
  146386. 0,
  146387. 12,
  146388. };
  146389. static long _vq_lengthlist__44u0__p7_2[] = {
  146390. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146391. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146392. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146393. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146394. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146395. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146396. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146397. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146398. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146399. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146400. 9, 9, 9,10, 9, 9,10,10, 9,
  146401. };
  146402. static float _vq_quantthresh__44u0__p7_2[] = {
  146403. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146404. 2.5, 3.5, 4.5, 5.5,
  146405. };
  146406. static long _vq_quantmap__44u0__p7_2[] = {
  146407. 11, 9, 7, 5, 3, 1, 0, 2,
  146408. 4, 6, 8, 10, 12,
  146409. };
  146410. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146411. _vq_quantthresh__44u0__p7_2,
  146412. _vq_quantmap__44u0__p7_2,
  146413. 13,
  146414. 13
  146415. };
  146416. static static_codebook _44u0__p7_2 = {
  146417. 2, 169,
  146418. _vq_lengthlist__44u0__p7_2,
  146419. 1, -531103744, 1611661312, 4, 0,
  146420. _vq_quantlist__44u0__p7_2,
  146421. NULL,
  146422. &_vq_auxt__44u0__p7_2,
  146423. NULL,
  146424. 0
  146425. };
  146426. static long _huff_lengthlist__44u0__short[] = {
  146427. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146428. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146429. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146430. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146431. };
  146432. static static_codebook _huff_book__44u0__short = {
  146433. 2, 64,
  146434. _huff_lengthlist__44u0__short,
  146435. 0, 0, 0, 0, 0,
  146436. NULL,
  146437. NULL,
  146438. NULL,
  146439. NULL,
  146440. 0
  146441. };
  146442. static long _huff_lengthlist__44u1__long[] = {
  146443. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146444. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146445. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146446. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146447. };
  146448. static static_codebook _huff_book__44u1__long = {
  146449. 2, 64,
  146450. _huff_lengthlist__44u1__long,
  146451. 0, 0, 0, 0, 0,
  146452. NULL,
  146453. NULL,
  146454. NULL,
  146455. NULL,
  146456. 0
  146457. };
  146458. static long _vq_quantlist__44u1__p1_0[] = {
  146459. 1,
  146460. 0,
  146461. 2,
  146462. };
  146463. static long _vq_lengthlist__44u1__p1_0[] = {
  146464. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146465. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146466. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146467. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146468. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146469. 13,
  146470. };
  146471. static float _vq_quantthresh__44u1__p1_0[] = {
  146472. -0.5, 0.5,
  146473. };
  146474. static long _vq_quantmap__44u1__p1_0[] = {
  146475. 1, 0, 2,
  146476. };
  146477. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146478. _vq_quantthresh__44u1__p1_0,
  146479. _vq_quantmap__44u1__p1_0,
  146480. 3,
  146481. 3
  146482. };
  146483. static static_codebook _44u1__p1_0 = {
  146484. 4, 81,
  146485. _vq_lengthlist__44u1__p1_0,
  146486. 1, -535822336, 1611661312, 2, 0,
  146487. _vq_quantlist__44u1__p1_0,
  146488. NULL,
  146489. &_vq_auxt__44u1__p1_0,
  146490. NULL,
  146491. 0
  146492. };
  146493. static long _vq_quantlist__44u1__p2_0[] = {
  146494. 1,
  146495. 0,
  146496. 2,
  146497. };
  146498. static long _vq_lengthlist__44u1__p2_0[] = {
  146499. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146500. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146501. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146502. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146503. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146504. 9,
  146505. };
  146506. static float _vq_quantthresh__44u1__p2_0[] = {
  146507. -0.5, 0.5,
  146508. };
  146509. static long _vq_quantmap__44u1__p2_0[] = {
  146510. 1, 0, 2,
  146511. };
  146512. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146513. _vq_quantthresh__44u1__p2_0,
  146514. _vq_quantmap__44u1__p2_0,
  146515. 3,
  146516. 3
  146517. };
  146518. static static_codebook _44u1__p2_0 = {
  146519. 4, 81,
  146520. _vq_lengthlist__44u1__p2_0,
  146521. 1, -535822336, 1611661312, 2, 0,
  146522. _vq_quantlist__44u1__p2_0,
  146523. NULL,
  146524. &_vq_auxt__44u1__p2_0,
  146525. NULL,
  146526. 0
  146527. };
  146528. static long _vq_quantlist__44u1__p3_0[] = {
  146529. 2,
  146530. 1,
  146531. 3,
  146532. 0,
  146533. 4,
  146534. };
  146535. static long _vq_lengthlist__44u1__p3_0[] = {
  146536. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146537. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146538. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146539. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146540. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146541. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146542. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146543. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146544. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146545. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146546. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146547. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146548. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146549. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146550. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146551. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146552. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146553. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146554. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146555. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146556. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146557. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146558. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146559. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146560. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146561. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146562. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146563. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146564. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146565. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146566. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146567. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146568. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146569. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146570. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146571. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146572. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146573. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146574. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146575. 19,
  146576. };
  146577. static float _vq_quantthresh__44u1__p3_0[] = {
  146578. -1.5, -0.5, 0.5, 1.5,
  146579. };
  146580. static long _vq_quantmap__44u1__p3_0[] = {
  146581. 3, 1, 0, 2, 4,
  146582. };
  146583. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146584. _vq_quantthresh__44u1__p3_0,
  146585. _vq_quantmap__44u1__p3_0,
  146586. 5,
  146587. 5
  146588. };
  146589. static static_codebook _44u1__p3_0 = {
  146590. 4, 625,
  146591. _vq_lengthlist__44u1__p3_0,
  146592. 1, -533725184, 1611661312, 3, 0,
  146593. _vq_quantlist__44u1__p3_0,
  146594. NULL,
  146595. &_vq_auxt__44u1__p3_0,
  146596. NULL,
  146597. 0
  146598. };
  146599. static long _vq_quantlist__44u1__p4_0[] = {
  146600. 2,
  146601. 1,
  146602. 3,
  146603. 0,
  146604. 4,
  146605. };
  146606. static long _vq_lengthlist__44u1__p4_0[] = {
  146607. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146608. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146609. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146610. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146611. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146612. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146613. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146614. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146615. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146616. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146617. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146618. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146619. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146620. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146621. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146622. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146623. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146624. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146625. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146626. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146627. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146628. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146629. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146630. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146631. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146632. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146633. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146634. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146635. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146636. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146637. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146638. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146639. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146640. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146641. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146642. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146643. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146644. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146645. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146646. 12,
  146647. };
  146648. static float _vq_quantthresh__44u1__p4_0[] = {
  146649. -1.5, -0.5, 0.5, 1.5,
  146650. };
  146651. static long _vq_quantmap__44u1__p4_0[] = {
  146652. 3, 1, 0, 2, 4,
  146653. };
  146654. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146655. _vq_quantthresh__44u1__p4_0,
  146656. _vq_quantmap__44u1__p4_0,
  146657. 5,
  146658. 5
  146659. };
  146660. static static_codebook _44u1__p4_0 = {
  146661. 4, 625,
  146662. _vq_lengthlist__44u1__p4_0,
  146663. 1, -533725184, 1611661312, 3, 0,
  146664. _vq_quantlist__44u1__p4_0,
  146665. NULL,
  146666. &_vq_auxt__44u1__p4_0,
  146667. NULL,
  146668. 0
  146669. };
  146670. static long _vq_quantlist__44u1__p5_0[] = {
  146671. 4,
  146672. 3,
  146673. 5,
  146674. 2,
  146675. 6,
  146676. 1,
  146677. 7,
  146678. 0,
  146679. 8,
  146680. };
  146681. static long _vq_lengthlist__44u1__p5_0[] = {
  146682. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146683. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146684. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146685. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146686. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146687. 12,
  146688. };
  146689. static float _vq_quantthresh__44u1__p5_0[] = {
  146690. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146691. };
  146692. static long _vq_quantmap__44u1__p5_0[] = {
  146693. 7, 5, 3, 1, 0, 2, 4, 6,
  146694. 8,
  146695. };
  146696. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146697. _vq_quantthresh__44u1__p5_0,
  146698. _vq_quantmap__44u1__p5_0,
  146699. 9,
  146700. 9
  146701. };
  146702. static static_codebook _44u1__p5_0 = {
  146703. 2, 81,
  146704. _vq_lengthlist__44u1__p5_0,
  146705. 1, -531628032, 1611661312, 4, 0,
  146706. _vq_quantlist__44u1__p5_0,
  146707. NULL,
  146708. &_vq_auxt__44u1__p5_0,
  146709. NULL,
  146710. 0
  146711. };
  146712. static long _vq_quantlist__44u1__p6_0[] = {
  146713. 6,
  146714. 5,
  146715. 7,
  146716. 4,
  146717. 8,
  146718. 3,
  146719. 9,
  146720. 2,
  146721. 10,
  146722. 1,
  146723. 11,
  146724. 0,
  146725. 12,
  146726. };
  146727. static long _vq_lengthlist__44u1__p6_0[] = {
  146728. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146729. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146730. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146731. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146732. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146733. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146734. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146735. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146736. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146737. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146738. 15,17,16,17,18,17,17,18, 0,
  146739. };
  146740. static float _vq_quantthresh__44u1__p6_0[] = {
  146741. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146742. 12.5, 17.5, 22.5, 27.5,
  146743. };
  146744. static long _vq_quantmap__44u1__p6_0[] = {
  146745. 11, 9, 7, 5, 3, 1, 0, 2,
  146746. 4, 6, 8, 10, 12,
  146747. };
  146748. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146749. _vq_quantthresh__44u1__p6_0,
  146750. _vq_quantmap__44u1__p6_0,
  146751. 13,
  146752. 13
  146753. };
  146754. static static_codebook _44u1__p6_0 = {
  146755. 2, 169,
  146756. _vq_lengthlist__44u1__p6_0,
  146757. 1, -526516224, 1616117760, 4, 0,
  146758. _vq_quantlist__44u1__p6_0,
  146759. NULL,
  146760. &_vq_auxt__44u1__p6_0,
  146761. NULL,
  146762. 0
  146763. };
  146764. static long _vq_quantlist__44u1__p6_1[] = {
  146765. 2,
  146766. 1,
  146767. 3,
  146768. 0,
  146769. 4,
  146770. };
  146771. static long _vq_lengthlist__44u1__p6_1[] = {
  146772. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146773. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146774. };
  146775. static float _vq_quantthresh__44u1__p6_1[] = {
  146776. -1.5, -0.5, 0.5, 1.5,
  146777. };
  146778. static long _vq_quantmap__44u1__p6_1[] = {
  146779. 3, 1, 0, 2, 4,
  146780. };
  146781. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146782. _vq_quantthresh__44u1__p6_1,
  146783. _vq_quantmap__44u1__p6_1,
  146784. 5,
  146785. 5
  146786. };
  146787. static static_codebook _44u1__p6_1 = {
  146788. 2, 25,
  146789. _vq_lengthlist__44u1__p6_1,
  146790. 1, -533725184, 1611661312, 3, 0,
  146791. _vq_quantlist__44u1__p6_1,
  146792. NULL,
  146793. &_vq_auxt__44u1__p6_1,
  146794. NULL,
  146795. 0
  146796. };
  146797. static long _vq_quantlist__44u1__p7_0[] = {
  146798. 3,
  146799. 2,
  146800. 4,
  146801. 1,
  146802. 5,
  146803. 0,
  146804. 6,
  146805. };
  146806. static long _vq_lengthlist__44u1__p7_0[] = {
  146807. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146808. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146809. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146810. 8,
  146811. };
  146812. static float _vq_quantthresh__44u1__p7_0[] = {
  146813. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146814. };
  146815. static long _vq_quantmap__44u1__p7_0[] = {
  146816. 5, 3, 1, 0, 2, 4, 6,
  146817. };
  146818. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146819. _vq_quantthresh__44u1__p7_0,
  146820. _vq_quantmap__44u1__p7_0,
  146821. 7,
  146822. 7
  146823. };
  146824. static static_codebook _44u1__p7_0 = {
  146825. 2, 49,
  146826. _vq_lengthlist__44u1__p7_0,
  146827. 1, -518017024, 1626677248, 3, 0,
  146828. _vq_quantlist__44u1__p7_0,
  146829. NULL,
  146830. &_vq_auxt__44u1__p7_0,
  146831. NULL,
  146832. 0
  146833. };
  146834. static long _vq_quantlist__44u1__p7_1[] = {
  146835. 6,
  146836. 5,
  146837. 7,
  146838. 4,
  146839. 8,
  146840. 3,
  146841. 9,
  146842. 2,
  146843. 10,
  146844. 1,
  146845. 11,
  146846. 0,
  146847. 12,
  146848. };
  146849. static long _vq_lengthlist__44u1__p7_1[] = {
  146850. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146851. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146852. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146853. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146854. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146855. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146856. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146857. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146858. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146859. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146860. 15,15,15,15,15,15,15,15,15,
  146861. };
  146862. static float _vq_quantthresh__44u1__p7_1[] = {
  146863. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146864. 32.5, 45.5, 58.5, 71.5,
  146865. };
  146866. static long _vq_quantmap__44u1__p7_1[] = {
  146867. 11, 9, 7, 5, 3, 1, 0, 2,
  146868. 4, 6, 8, 10, 12,
  146869. };
  146870. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146871. _vq_quantthresh__44u1__p7_1,
  146872. _vq_quantmap__44u1__p7_1,
  146873. 13,
  146874. 13
  146875. };
  146876. static static_codebook _44u1__p7_1 = {
  146877. 2, 169,
  146878. _vq_lengthlist__44u1__p7_1,
  146879. 1, -523010048, 1618608128, 4, 0,
  146880. _vq_quantlist__44u1__p7_1,
  146881. NULL,
  146882. &_vq_auxt__44u1__p7_1,
  146883. NULL,
  146884. 0
  146885. };
  146886. static long _vq_quantlist__44u1__p7_2[] = {
  146887. 6,
  146888. 5,
  146889. 7,
  146890. 4,
  146891. 8,
  146892. 3,
  146893. 9,
  146894. 2,
  146895. 10,
  146896. 1,
  146897. 11,
  146898. 0,
  146899. 12,
  146900. };
  146901. static long _vq_lengthlist__44u1__p7_2[] = {
  146902. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146903. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146904. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146905. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146906. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146907. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146908. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146909. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146910. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146911. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146912. 9, 9, 9,10, 9, 9,10,10, 9,
  146913. };
  146914. static float _vq_quantthresh__44u1__p7_2[] = {
  146915. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146916. 2.5, 3.5, 4.5, 5.5,
  146917. };
  146918. static long _vq_quantmap__44u1__p7_2[] = {
  146919. 11, 9, 7, 5, 3, 1, 0, 2,
  146920. 4, 6, 8, 10, 12,
  146921. };
  146922. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146923. _vq_quantthresh__44u1__p7_2,
  146924. _vq_quantmap__44u1__p7_2,
  146925. 13,
  146926. 13
  146927. };
  146928. static static_codebook _44u1__p7_2 = {
  146929. 2, 169,
  146930. _vq_lengthlist__44u1__p7_2,
  146931. 1, -531103744, 1611661312, 4, 0,
  146932. _vq_quantlist__44u1__p7_2,
  146933. NULL,
  146934. &_vq_auxt__44u1__p7_2,
  146935. NULL,
  146936. 0
  146937. };
  146938. static long _huff_lengthlist__44u1__short[] = {
  146939. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146940. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146941. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146942. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146943. };
  146944. static static_codebook _huff_book__44u1__short = {
  146945. 2, 64,
  146946. _huff_lengthlist__44u1__short,
  146947. 0, 0, 0, 0, 0,
  146948. NULL,
  146949. NULL,
  146950. NULL,
  146951. NULL,
  146952. 0
  146953. };
  146954. static long _huff_lengthlist__44u2__long[] = {
  146955. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146956. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146957. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146958. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146959. };
  146960. static static_codebook _huff_book__44u2__long = {
  146961. 2, 64,
  146962. _huff_lengthlist__44u2__long,
  146963. 0, 0, 0, 0, 0,
  146964. NULL,
  146965. NULL,
  146966. NULL,
  146967. NULL,
  146968. 0
  146969. };
  146970. static long _vq_quantlist__44u2__p1_0[] = {
  146971. 1,
  146972. 0,
  146973. 2,
  146974. };
  146975. static long _vq_lengthlist__44u2__p1_0[] = {
  146976. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146977. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146978. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146979. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146980. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146981. 13,
  146982. };
  146983. static float _vq_quantthresh__44u2__p1_0[] = {
  146984. -0.5, 0.5,
  146985. };
  146986. static long _vq_quantmap__44u2__p1_0[] = {
  146987. 1, 0, 2,
  146988. };
  146989. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146990. _vq_quantthresh__44u2__p1_0,
  146991. _vq_quantmap__44u2__p1_0,
  146992. 3,
  146993. 3
  146994. };
  146995. static static_codebook _44u2__p1_0 = {
  146996. 4, 81,
  146997. _vq_lengthlist__44u2__p1_0,
  146998. 1, -535822336, 1611661312, 2, 0,
  146999. _vq_quantlist__44u2__p1_0,
  147000. NULL,
  147001. &_vq_auxt__44u2__p1_0,
  147002. NULL,
  147003. 0
  147004. };
  147005. static long _vq_quantlist__44u2__p2_0[] = {
  147006. 1,
  147007. 0,
  147008. 2,
  147009. };
  147010. static long _vq_lengthlist__44u2__p2_0[] = {
  147011. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147012. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147013. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147014. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147015. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147016. 9,
  147017. };
  147018. static float _vq_quantthresh__44u2__p2_0[] = {
  147019. -0.5, 0.5,
  147020. };
  147021. static long _vq_quantmap__44u2__p2_0[] = {
  147022. 1, 0, 2,
  147023. };
  147024. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147025. _vq_quantthresh__44u2__p2_0,
  147026. _vq_quantmap__44u2__p2_0,
  147027. 3,
  147028. 3
  147029. };
  147030. static static_codebook _44u2__p2_0 = {
  147031. 4, 81,
  147032. _vq_lengthlist__44u2__p2_0,
  147033. 1, -535822336, 1611661312, 2, 0,
  147034. _vq_quantlist__44u2__p2_0,
  147035. NULL,
  147036. &_vq_auxt__44u2__p2_0,
  147037. NULL,
  147038. 0
  147039. };
  147040. static long _vq_quantlist__44u2__p3_0[] = {
  147041. 2,
  147042. 1,
  147043. 3,
  147044. 0,
  147045. 4,
  147046. };
  147047. static long _vq_lengthlist__44u2__p3_0[] = {
  147048. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147049. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147050. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147051. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147052. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147053. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147054. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147055. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147056. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147057. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147058. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147059. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147060. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147061. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147062. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147063. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147064. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147065. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147066. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147067. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147068. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147069. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147070. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147071. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147072. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147073. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147074. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147075. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147076. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147077. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147078. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147079. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147080. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147081. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147082. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147083. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147084. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147085. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147086. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147087. 0,
  147088. };
  147089. static float _vq_quantthresh__44u2__p3_0[] = {
  147090. -1.5, -0.5, 0.5, 1.5,
  147091. };
  147092. static long _vq_quantmap__44u2__p3_0[] = {
  147093. 3, 1, 0, 2, 4,
  147094. };
  147095. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147096. _vq_quantthresh__44u2__p3_0,
  147097. _vq_quantmap__44u2__p3_0,
  147098. 5,
  147099. 5
  147100. };
  147101. static static_codebook _44u2__p3_0 = {
  147102. 4, 625,
  147103. _vq_lengthlist__44u2__p3_0,
  147104. 1, -533725184, 1611661312, 3, 0,
  147105. _vq_quantlist__44u2__p3_0,
  147106. NULL,
  147107. &_vq_auxt__44u2__p3_0,
  147108. NULL,
  147109. 0
  147110. };
  147111. static long _vq_quantlist__44u2__p4_0[] = {
  147112. 2,
  147113. 1,
  147114. 3,
  147115. 0,
  147116. 4,
  147117. };
  147118. static long _vq_lengthlist__44u2__p4_0[] = {
  147119. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147120. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147121. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147122. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147123. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147124. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147125. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147126. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147127. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147128. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147129. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147130. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147131. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147132. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147133. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147134. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147135. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147136. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147137. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147138. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147139. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147140. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147141. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147142. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147143. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147144. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147145. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147146. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147147. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147148. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147149. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147150. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147151. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147152. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147153. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147154. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147155. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147156. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147157. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147158. 13,
  147159. };
  147160. static float _vq_quantthresh__44u2__p4_0[] = {
  147161. -1.5, -0.5, 0.5, 1.5,
  147162. };
  147163. static long _vq_quantmap__44u2__p4_0[] = {
  147164. 3, 1, 0, 2, 4,
  147165. };
  147166. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147167. _vq_quantthresh__44u2__p4_0,
  147168. _vq_quantmap__44u2__p4_0,
  147169. 5,
  147170. 5
  147171. };
  147172. static static_codebook _44u2__p4_0 = {
  147173. 4, 625,
  147174. _vq_lengthlist__44u2__p4_0,
  147175. 1, -533725184, 1611661312, 3, 0,
  147176. _vq_quantlist__44u2__p4_0,
  147177. NULL,
  147178. &_vq_auxt__44u2__p4_0,
  147179. NULL,
  147180. 0
  147181. };
  147182. static long _vq_quantlist__44u2__p5_0[] = {
  147183. 4,
  147184. 3,
  147185. 5,
  147186. 2,
  147187. 6,
  147188. 1,
  147189. 7,
  147190. 0,
  147191. 8,
  147192. };
  147193. static long _vq_lengthlist__44u2__p5_0[] = {
  147194. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147195. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147196. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147197. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147198. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147199. 13,
  147200. };
  147201. static float _vq_quantthresh__44u2__p5_0[] = {
  147202. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147203. };
  147204. static long _vq_quantmap__44u2__p5_0[] = {
  147205. 7, 5, 3, 1, 0, 2, 4, 6,
  147206. 8,
  147207. };
  147208. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147209. _vq_quantthresh__44u2__p5_0,
  147210. _vq_quantmap__44u2__p5_0,
  147211. 9,
  147212. 9
  147213. };
  147214. static static_codebook _44u2__p5_0 = {
  147215. 2, 81,
  147216. _vq_lengthlist__44u2__p5_0,
  147217. 1, -531628032, 1611661312, 4, 0,
  147218. _vq_quantlist__44u2__p5_0,
  147219. NULL,
  147220. &_vq_auxt__44u2__p5_0,
  147221. NULL,
  147222. 0
  147223. };
  147224. static long _vq_quantlist__44u2__p6_0[] = {
  147225. 6,
  147226. 5,
  147227. 7,
  147228. 4,
  147229. 8,
  147230. 3,
  147231. 9,
  147232. 2,
  147233. 10,
  147234. 1,
  147235. 11,
  147236. 0,
  147237. 12,
  147238. };
  147239. static long _vq_lengthlist__44u2__p6_0[] = {
  147240. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147241. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147242. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147243. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147244. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147245. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147246. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147247. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147248. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147249. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147250. 15,17,17,16,18,17,18, 0, 0,
  147251. };
  147252. static float _vq_quantthresh__44u2__p6_0[] = {
  147253. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147254. 12.5, 17.5, 22.5, 27.5,
  147255. };
  147256. static long _vq_quantmap__44u2__p6_0[] = {
  147257. 11, 9, 7, 5, 3, 1, 0, 2,
  147258. 4, 6, 8, 10, 12,
  147259. };
  147260. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147261. _vq_quantthresh__44u2__p6_0,
  147262. _vq_quantmap__44u2__p6_0,
  147263. 13,
  147264. 13
  147265. };
  147266. static static_codebook _44u2__p6_0 = {
  147267. 2, 169,
  147268. _vq_lengthlist__44u2__p6_0,
  147269. 1, -526516224, 1616117760, 4, 0,
  147270. _vq_quantlist__44u2__p6_0,
  147271. NULL,
  147272. &_vq_auxt__44u2__p6_0,
  147273. NULL,
  147274. 0
  147275. };
  147276. static long _vq_quantlist__44u2__p6_1[] = {
  147277. 2,
  147278. 1,
  147279. 3,
  147280. 0,
  147281. 4,
  147282. };
  147283. static long _vq_lengthlist__44u2__p6_1[] = {
  147284. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147285. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147286. };
  147287. static float _vq_quantthresh__44u2__p6_1[] = {
  147288. -1.5, -0.5, 0.5, 1.5,
  147289. };
  147290. static long _vq_quantmap__44u2__p6_1[] = {
  147291. 3, 1, 0, 2, 4,
  147292. };
  147293. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147294. _vq_quantthresh__44u2__p6_1,
  147295. _vq_quantmap__44u2__p6_1,
  147296. 5,
  147297. 5
  147298. };
  147299. static static_codebook _44u2__p6_1 = {
  147300. 2, 25,
  147301. _vq_lengthlist__44u2__p6_1,
  147302. 1, -533725184, 1611661312, 3, 0,
  147303. _vq_quantlist__44u2__p6_1,
  147304. NULL,
  147305. &_vq_auxt__44u2__p6_1,
  147306. NULL,
  147307. 0
  147308. };
  147309. static long _vq_quantlist__44u2__p7_0[] = {
  147310. 4,
  147311. 3,
  147312. 5,
  147313. 2,
  147314. 6,
  147315. 1,
  147316. 7,
  147317. 0,
  147318. 8,
  147319. };
  147320. static long _vq_lengthlist__44u2__p7_0[] = {
  147321. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147322. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147323. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147324. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147325. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147326. 11,
  147327. };
  147328. static float _vq_quantthresh__44u2__p7_0[] = {
  147329. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147330. };
  147331. static long _vq_quantmap__44u2__p7_0[] = {
  147332. 7, 5, 3, 1, 0, 2, 4, 6,
  147333. 8,
  147334. };
  147335. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147336. _vq_quantthresh__44u2__p7_0,
  147337. _vq_quantmap__44u2__p7_0,
  147338. 9,
  147339. 9
  147340. };
  147341. static static_codebook _44u2__p7_0 = {
  147342. 2, 81,
  147343. _vq_lengthlist__44u2__p7_0,
  147344. 1, -516612096, 1626677248, 4, 0,
  147345. _vq_quantlist__44u2__p7_0,
  147346. NULL,
  147347. &_vq_auxt__44u2__p7_0,
  147348. NULL,
  147349. 0
  147350. };
  147351. static long _vq_quantlist__44u2__p7_1[] = {
  147352. 6,
  147353. 5,
  147354. 7,
  147355. 4,
  147356. 8,
  147357. 3,
  147358. 9,
  147359. 2,
  147360. 10,
  147361. 1,
  147362. 11,
  147363. 0,
  147364. 12,
  147365. };
  147366. static long _vq_lengthlist__44u2__p7_1[] = {
  147367. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147368. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147369. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147370. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147371. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147372. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147373. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147374. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147375. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147376. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147377. 14,14,14,17,15,17,17,17,17,
  147378. };
  147379. static float _vq_quantthresh__44u2__p7_1[] = {
  147380. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147381. 32.5, 45.5, 58.5, 71.5,
  147382. };
  147383. static long _vq_quantmap__44u2__p7_1[] = {
  147384. 11, 9, 7, 5, 3, 1, 0, 2,
  147385. 4, 6, 8, 10, 12,
  147386. };
  147387. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147388. _vq_quantthresh__44u2__p7_1,
  147389. _vq_quantmap__44u2__p7_1,
  147390. 13,
  147391. 13
  147392. };
  147393. static static_codebook _44u2__p7_1 = {
  147394. 2, 169,
  147395. _vq_lengthlist__44u2__p7_1,
  147396. 1, -523010048, 1618608128, 4, 0,
  147397. _vq_quantlist__44u2__p7_1,
  147398. NULL,
  147399. &_vq_auxt__44u2__p7_1,
  147400. NULL,
  147401. 0
  147402. };
  147403. static long _vq_quantlist__44u2__p7_2[] = {
  147404. 6,
  147405. 5,
  147406. 7,
  147407. 4,
  147408. 8,
  147409. 3,
  147410. 9,
  147411. 2,
  147412. 10,
  147413. 1,
  147414. 11,
  147415. 0,
  147416. 12,
  147417. };
  147418. static long _vq_lengthlist__44u2__p7_2[] = {
  147419. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147420. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147421. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147422. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147423. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147424. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147425. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147426. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147427. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147428. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147429. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147430. };
  147431. static float _vq_quantthresh__44u2__p7_2[] = {
  147432. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147433. 2.5, 3.5, 4.5, 5.5,
  147434. };
  147435. static long _vq_quantmap__44u2__p7_2[] = {
  147436. 11, 9, 7, 5, 3, 1, 0, 2,
  147437. 4, 6, 8, 10, 12,
  147438. };
  147439. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147440. _vq_quantthresh__44u2__p7_2,
  147441. _vq_quantmap__44u2__p7_2,
  147442. 13,
  147443. 13
  147444. };
  147445. static static_codebook _44u2__p7_2 = {
  147446. 2, 169,
  147447. _vq_lengthlist__44u2__p7_2,
  147448. 1, -531103744, 1611661312, 4, 0,
  147449. _vq_quantlist__44u2__p7_2,
  147450. NULL,
  147451. &_vq_auxt__44u2__p7_2,
  147452. NULL,
  147453. 0
  147454. };
  147455. static long _huff_lengthlist__44u2__short[] = {
  147456. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147457. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147458. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147459. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147460. };
  147461. static static_codebook _huff_book__44u2__short = {
  147462. 2, 64,
  147463. _huff_lengthlist__44u2__short,
  147464. 0, 0, 0, 0, 0,
  147465. NULL,
  147466. NULL,
  147467. NULL,
  147468. NULL,
  147469. 0
  147470. };
  147471. static long _huff_lengthlist__44u3__long[] = {
  147472. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147473. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147474. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147475. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147476. };
  147477. static static_codebook _huff_book__44u3__long = {
  147478. 2, 64,
  147479. _huff_lengthlist__44u3__long,
  147480. 0, 0, 0, 0, 0,
  147481. NULL,
  147482. NULL,
  147483. NULL,
  147484. NULL,
  147485. 0
  147486. };
  147487. static long _vq_quantlist__44u3__p1_0[] = {
  147488. 1,
  147489. 0,
  147490. 2,
  147491. };
  147492. static long _vq_lengthlist__44u3__p1_0[] = {
  147493. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147494. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147495. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147496. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147497. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147498. 13,
  147499. };
  147500. static float _vq_quantthresh__44u3__p1_0[] = {
  147501. -0.5, 0.5,
  147502. };
  147503. static long _vq_quantmap__44u3__p1_0[] = {
  147504. 1, 0, 2,
  147505. };
  147506. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147507. _vq_quantthresh__44u3__p1_0,
  147508. _vq_quantmap__44u3__p1_0,
  147509. 3,
  147510. 3
  147511. };
  147512. static static_codebook _44u3__p1_0 = {
  147513. 4, 81,
  147514. _vq_lengthlist__44u3__p1_0,
  147515. 1, -535822336, 1611661312, 2, 0,
  147516. _vq_quantlist__44u3__p1_0,
  147517. NULL,
  147518. &_vq_auxt__44u3__p1_0,
  147519. NULL,
  147520. 0
  147521. };
  147522. static long _vq_quantlist__44u3__p2_0[] = {
  147523. 1,
  147524. 0,
  147525. 2,
  147526. };
  147527. static long _vq_lengthlist__44u3__p2_0[] = {
  147528. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147529. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147530. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147531. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147532. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147533. 9,
  147534. };
  147535. static float _vq_quantthresh__44u3__p2_0[] = {
  147536. -0.5, 0.5,
  147537. };
  147538. static long _vq_quantmap__44u3__p2_0[] = {
  147539. 1, 0, 2,
  147540. };
  147541. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147542. _vq_quantthresh__44u3__p2_0,
  147543. _vq_quantmap__44u3__p2_0,
  147544. 3,
  147545. 3
  147546. };
  147547. static static_codebook _44u3__p2_0 = {
  147548. 4, 81,
  147549. _vq_lengthlist__44u3__p2_0,
  147550. 1, -535822336, 1611661312, 2, 0,
  147551. _vq_quantlist__44u3__p2_0,
  147552. NULL,
  147553. &_vq_auxt__44u3__p2_0,
  147554. NULL,
  147555. 0
  147556. };
  147557. static long _vq_quantlist__44u3__p3_0[] = {
  147558. 2,
  147559. 1,
  147560. 3,
  147561. 0,
  147562. 4,
  147563. };
  147564. static long _vq_lengthlist__44u3__p3_0[] = {
  147565. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147566. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147567. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147568. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147569. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147570. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147571. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147572. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147573. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147574. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147575. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147576. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147577. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147578. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147579. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147580. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147581. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147582. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147583. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147584. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147585. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147586. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147587. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147588. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147589. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147590. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147591. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147592. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147593. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147594. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147595. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147596. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147597. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147598. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147599. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147600. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147601. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147602. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147603. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147604. 0,
  147605. };
  147606. static float _vq_quantthresh__44u3__p3_0[] = {
  147607. -1.5, -0.5, 0.5, 1.5,
  147608. };
  147609. static long _vq_quantmap__44u3__p3_0[] = {
  147610. 3, 1, 0, 2, 4,
  147611. };
  147612. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147613. _vq_quantthresh__44u3__p3_0,
  147614. _vq_quantmap__44u3__p3_0,
  147615. 5,
  147616. 5
  147617. };
  147618. static static_codebook _44u3__p3_0 = {
  147619. 4, 625,
  147620. _vq_lengthlist__44u3__p3_0,
  147621. 1, -533725184, 1611661312, 3, 0,
  147622. _vq_quantlist__44u3__p3_0,
  147623. NULL,
  147624. &_vq_auxt__44u3__p3_0,
  147625. NULL,
  147626. 0
  147627. };
  147628. static long _vq_quantlist__44u3__p4_0[] = {
  147629. 2,
  147630. 1,
  147631. 3,
  147632. 0,
  147633. 4,
  147634. };
  147635. static long _vq_lengthlist__44u3__p4_0[] = {
  147636. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147637. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147638. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147639. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147640. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147641. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147642. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147643. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147644. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147645. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147646. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147647. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147648. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147649. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147650. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147651. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147652. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147653. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147654. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147655. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147656. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147657. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147658. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147659. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147660. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147661. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147662. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147663. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147664. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147665. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147666. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147667. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147668. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147669. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147670. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147671. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147672. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147673. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147674. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147675. 13,
  147676. };
  147677. static float _vq_quantthresh__44u3__p4_0[] = {
  147678. -1.5, -0.5, 0.5, 1.5,
  147679. };
  147680. static long _vq_quantmap__44u3__p4_0[] = {
  147681. 3, 1, 0, 2, 4,
  147682. };
  147683. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147684. _vq_quantthresh__44u3__p4_0,
  147685. _vq_quantmap__44u3__p4_0,
  147686. 5,
  147687. 5
  147688. };
  147689. static static_codebook _44u3__p4_0 = {
  147690. 4, 625,
  147691. _vq_lengthlist__44u3__p4_0,
  147692. 1, -533725184, 1611661312, 3, 0,
  147693. _vq_quantlist__44u3__p4_0,
  147694. NULL,
  147695. &_vq_auxt__44u3__p4_0,
  147696. NULL,
  147697. 0
  147698. };
  147699. static long _vq_quantlist__44u3__p5_0[] = {
  147700. 4,
  147701. 3,
  147702. 5,
  147703. 2,
  147704. 6,
  147705. 1,
  147706. 7,
  147707. 0,
  147708. 8,
  147709. };
  147710. static long _vq_lengthlist__44u3__p5_0[] = {
  147711. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147712. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147713. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147714. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147715. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147716. 12,
  147717. };
  147718. static float _vq_quantthresh__44u3__p5_0[] = {
  147719. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147720. };
  147721. static long _vq_quantmap__44u3__p5_0[] = {
  147722. 7, 5, 3, 1, 0, 2, 4, 6,
  147723. 8,
  147724. };
  147725. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147726. _vq_quantthresh__44u3__p5_0,
  147727. _vq_quantmap__44u3__p5_0,
  147728. 9,
  147729. 9
  147730. };
  147731. static static_codebook _44u3__p5_0 = {
  147732. 2, 81,
  147733. _vq_lengthlist__44u3__p5_0,
  147734. 1, -531628032, 1611661312, 4, 0,
  147735. _vq_quantlist__44u3__p5_0,
  147736. NULL,
  147737. &_vq_auxt__44u3__p5_0,
  147738. NULL,
  147739. 0
  147740. };
  147741. static long _vq_quantlist__44u3__p6_0[] = {
  147742. 6,
  147743. 5,
  147744. 7,
  147745. 4,
  147746. 8,
  147747. 3,
  147748. 9,
  147749. 2,
  147750. 10,
  147751. 1,
  147752. 11,
  147753. 0,
  147754. 12,
  147755. };
  147756. static long _vq_lengthlist__44u3__p6_0[] = {
  147757. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147758. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147759. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147760. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147761. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147762. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147763. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147764. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147765. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147766. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147767. 15,16,16,16,17,18,16,20,18,
  147768. };
  147769. static float _vq_quantthresh__44u3__p6_0[] = {
  147770. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147771. 12.5, 17.5, 22.5, 27.5,
  147772. };
  147773. static long _vq_quantmap__44u3__p6_0[] = {
  147774. 11, 9, 7, 5, 3, 1, 0, 2,
  147775. 4, 6, 8, 10, 12,
  147776. };
  147777. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147778. _vq_quantthresh__44u3__p6_0,
  147779. _vq_quantmap__44u3__p6_0,
  147780. 13,
  147781. 13
  147782. };
  147783. static static_codebook _44u3__p6_0 = {
  147784. 2, 169,
  147785. _vq_lengthlist__44u3__p6_0,
  147786. 1, -526516224, 1616117760, 4, 0,
  147787. _vq_quantlist__44u3__p6_0,
  147788. NULL,
  147789. &_vq_auxt__44u3__p6_0,
  147790. NULL,
  147791. 0
  147792. };
  147793. static long _vq_quantlist__44u3__p6_1[] = {
  147794. 2,
  147795. 1,
  147796. 3,
  147797. 0,
  147798. 4,
  147799. };
  147800. static long _vq_lengthlist__44u3__p6_1[] = {
  147801. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147802. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147803. };
  147804. static float _vq_quantthresh__44u3__p6_1[] = {
  147805. -1.5, -0.5, 0.5, 1.5,
  147806. };
  147807. static long _vq_quantmap__44u3__p6_1[] = {
  147808. 3, 1, 0, 2, 4,
  147809. };
  147810. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147811. _vq_quantthresh__44u3__p6_1,
  147812. _vq_quantmap__44u3__p6_1,
  147813. 5,
  147814. 5
  147815. };
  147816. static static_codebook _44u3__p6_1 = {
  147817. 2, 25,
  147818. _vq_lengthlist__44u3__p6_1,
  147819. 1, -533725184, 1611661312, 3, 0,
  147820. _vq_quantlist__44u3__p6_1,
  147821. NULL,
  147822. &_vq_auxt__44u3__p6_1,
  147823. NULL,
  147824. 0
  147825. };
  147826. static long _vq_quantlist__44u3__p7_0[] = {
  147827. 4,
  147828. 3,
  147829. 5,
  147830. 2,
  147831. 6,
  147832. 1,
  147833. 7,
  147834. 0,
  147835. 8,
  147836. };
  147837. static long _vq_lengthlist__44u3__p7_0[] = {
  147838. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147839. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147840. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147841. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147842. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147843. 9,
  147844. };
  147845. static float _vq_quantthresh__44u3__p7_0[] = {
  147846. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147847. };
  147848. static long _vq_quantmap__44u3__p7_0[] = {
  147849. 7, 5, 3, 1, 0, 2, 4, 6,
  147850. 8,
  147851. };
  147852. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147853. _vq_quantthresh__44u3__p7_0,
  147854. _vq_quantmap__44u3__p7_0,
  147855. 9,
  147856. 9
  147857. };
  147858. static static_codebook _44u3__p7_0 = {
  147859. 2, 81,
  147860. _vq_lengthlist__44u3__p7_0,
  147861. 1, -515907584, 1627381760, 4, 0,
  147862. _vq_quantlist__44u3__p7_0,
  147863. NULL,
  147864. &_vq_auxt__44u3__p7_0,
  147865. NULL,
  147866. 0
  147867. };
  147868. static long _vq_quantlist__44u3__p7_1[] = {
  147869. 7,
  147870. 6,
  147871. 8,
  147872. 5,
  147873. 9,
  147874. 4,
  147875. 10,
  147876. 3,
  147877. 11,
  147878. 2,
  147879. 12,
  147880. 1,
  147881. 13,
  147882. 0,
  147883. 14,
  147884. };
  147885. static long _vq_lengthlist__44u3__p7_1[] = {
  147886. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147887. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147888. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147889. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147890. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147891. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147892. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147893. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147894. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147895. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147896. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147897. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147898. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147899. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147900. 17,
  147901. };
  147902. static float _vq_quantthresh__44u3__p7_1[] = {
  147903. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147904. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147905. };
  147906. static long _vq_quantmap__44u3__p7_1[] = {
  147907. 13, 11, 9, 7, 5, 3, 1, 0,
  147908. 2, 4, 6, 8, 10, 12, 14,
  147909. };
  147910. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147911. _vq_quantthresh__44u3__p7_1,
  147912. _vq_quantmap__44u3__p7_1,
  147913. 15,
  147914. 15
  147915. };
  147916. static static_codebook _44u3__p7_1 = {
  147917. 2, 225,
  147918. _vq_lengthlist__44u3__p7_1,
  147919. 1, -522338304, 1620115456, 4, 0,
  147920. _vq_quantlist__44u3__p7_1,
  147921. NULL,
  147922. &_vq_auxt__44u3__p7_1,
  147923. NULL,
  147924. 0
  147925. };
  147926. static long _vq_quantlist__44u3__p7_2[] = {
  147927. 8,
  147928. 7,
  147929. 9,
  147930. 6,
  147931. 10,
  147932. 5,
  147933. 11,
  147934. 4,
  147935. 12,
  147936. 3,
  147937. 13,
  147938. 2,
  147939. 14,
  147940. 1,
  147941. 15,
  147942. 0,
  147943. 16,
  147944. };
  147945. static long _vq_lengthlist__44u3__p7_2[] = {
  147946. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147947. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147948. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147949. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147950. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147951. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147952. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147953. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147954. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147955. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147956. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147957. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147958. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147959. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147960. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147961. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147962. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147963. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147964. 11,
  147965. };
  147966. static float _vq_quantthresh__44u3__p7_2[] = {
  147967. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147968. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147969. };
  147970. static long _vq_quantmap__44u3__p7_2[] = {
  147971. 15, 13, 11, 9, 7, 5, 3, 1,
  147972. 0, 2, 4, 6, 8, 10, 12, 14,
  147973. 16,
  147974. };
  147975. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147976. _vq_quantthresh__44u3__p7_2,
  147977. _vq_quantmap__44u3__p7_2,
  147978. 17,
  147979. 17
  147980. };
  147981. static static_codebook _44u3__p7_2 = {
  147982. 2, 289,
  147983. _vq_lengthlist__44u3__p7_2,
  147984. 1, -529530880, 1611661312, 5, 0,
  147985. _vq_quantlist__44u3__p7_2,
  147986. NULL,
  147987. &_vq_auxt__44u3__p7_2,
  147988. NULL,
  147989. 0
  147990. };
  147991. static long _huff_lengthlist__44u3__short[] = {
  147992. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147993. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147994. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147995. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147996. };
  147997. static static_codebook _huff_book__44u3__short = {
  147998. 2, 64,
  147999. _huff_lengthlist__44u3__short,
  148000. 0, 0, 0, 0, 0,
  148001. NULL,
  148002. NULL,
  148003. NULL,
  148004. NULL,
  148005. 0
  148006. };
  148007. static long _huff_lengthlist__44u4__long[] = {
  148008. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148009. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148010. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148011. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148012. };
  148013. static static_codebook _huff_book__44u4__long = {
  148014. 2, 64,
  148015. _huff_lengthlist__44u4__long,
  148016. 0, 0, 0, 0, 0,
  148017. NULL,
  148018. NULL,
  148019. NULL,
  148020. NULL,
  148021. 0
  148022. };
  148023. static long _vq_quantlist__44u4__p1_0[] = {
  148024. 1,
  148025. 0,
  148026. 2,
  148027. };
  148028. static long _vq_lengthlist__44u4__p1_0[] = {
  148029. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148030. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148031. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148032. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148033. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148034. 13,
  148035. };
  148036. static float _vq_quantthresh__44u4__p1_0[] = {
  148037. -0.5, 0.5,
  148038. };
  148039. static long _vq_quantmap__44u4__p1_0[] = {
  148040. 1, 0, 2,
  148041. };
  148042. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148043. _vq_quantthresh__44u4__p1_0,
  148044. _vq_quantmap__44u4__p1_0,
  148045. 3,
  148046. 3
  148047. };
  148048. static static_codebook _44u4__p1_0 = {
  148049. 4, 81,
  148050. _vq_lengthlist__44u4__p1_0,
  148051. 1, -535822336, 1611661312, 2, 0,
  148052. _vq_quantlist__44u4__p1_0,
  148053. NULL,
  148054. &_vq_auxt__44u4__p1_0,
  148055. NULL,
  148056. 0
  148057. };
  148058. static long _vq_quantlist__44u4__p2_0[] = {
  148059. 1,
  148060. 0,
  148061. 2,
  148062. };
  148063. static long _vq_lengthlist__44u4__p2_0[] = {
  148064. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148065. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148066. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148067. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148068. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148069. 9,
  148070. };
  148071. static float _vq_quantthresh__44u4__p2_0[] = {
  148072. -0.5, 0.5,
  148073. };
  148074. static long _vq_quantmap__44u4__p2_0[] = {
  148075. 1, 0, 2,
  148076. };
  148077. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148078. _vq_quantthresh__44u4__p2_0,
  148079. _vq_quantmap__44u4__p2_0,
  148080. 3,
  148081. 3
  148082. };
  148083. static static_codebook _44u4__p2_0 = {
  148084. 4, 81,
  148085. _vq_lengthlist__44u4__p2_0,
  148086. 1, -535822336, 1611661312, 2, 0,
  148087. _vq_quantlist__44u4__p2_0,
  148088. NULL,
  148089. &_vq_auxt__44u4__p2_0,
  148090. NULL,
  148091. 0
  148092. };
  148093. static long _vq_quantlist__44u4__p3_0[] = {
  148094. 2,
  148095. 1,
  148096. 3,
  148097. 0,
  148098. 4,
  148099. };
  148100. static long _vq_lengthlist__44u4__p3_0[] = {
  148101. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148102. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148103. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148104. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148105. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148106. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148107. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148108. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148109. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148110. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148111. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148112. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148113. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148114. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148115. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148116. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148117. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148118. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148119. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148120. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148121. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148122. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148123. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148124. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148125. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148126. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148127. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148128. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148129. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148130. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148131. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148132. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148133. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148134. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148135. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148136. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148137. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148138. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148139. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148140. 0,
  148141. };
  148142. static float _vq_quantthresh__44u4__p3_0[] = {
  148143. -1.5, -0.5, 0.5, 1.5,
  148144. };
  148145. static long _vq_quantmap__44u4__p3_0[] = {
  148146. 3, 1, 0, 2, 4,
  148147. };
  148148. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148149. _vq_quantthresh__44u4__p3_0,
  148150. _vq_quantmap__44u4__p3_0,
  148151. 5,
  148152. 5
  148153. };
  148154. static static_codebook _44u4__p3_0 = {
  148155. 4, 625,
  148156. _vq_lengthlist__44u4__p3_0,
  148157. 1, -533725184, 1611661312, 3, 0,
  148158. _vq_quantlist__44u4__p3_0,
  148159. NULL,
  148160. &_vq_auxt__44u4__p3_0,
  148161. NULL,
  148162. 0
  148163. };
  148164. static long _vq_quantlist__44u4__p4_0[] = {
  148165. 2,
  148166. 1,
  148167. 3,
  148168. 0,
  148169. 4,
  148170. };
  148171. static long _vq_lengthlist__44u4__p4_0[] = {
  148172. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148173. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148174. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148175. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148176. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148177. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148178. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148179. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148180. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148181. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148182. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148183. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148184. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148185. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148186. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148187. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148188. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148189. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148190. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148191. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148192. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148193. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148194. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148195. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148196. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148197. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148198. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148199. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148200. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148201. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148202. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148203. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148204. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148205. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148206. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148207. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148208. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148209. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148210. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148211. 13,
  148212. };
  148213. static float _vq_quantthresh__44u4__p4_0[] = {
  148214. -1.5, -0.5, 0.5, 1.5,
  148215. };
  148216. static long _vq_quantmap__44u4__p4_0[] = {
  148217. 3, 1, 0, 2, 4,
  148218. };
  148219. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148220. _vq_quantthresh__44u4__p4_0,
  148221. _vq_quantmap__44u4__p4_0,
  148222. 5,
  148223. 5
  148224. };
  148225. static static_codebook _44u4__p4_0 = {
  148226. 4, 625,
  148227. _vq_lengthlist__44u4__p4_0,
  148228. 1, -533725184, 1611661312, 3, 0,
  148229. _vq_quantlist__44u4__p4_0,
  148230. NULL,
  148231. &_vq_auxt__44u4__p4_0,
  148232. NULL,
  148233. 0
  148234. };
  148235. static long _vq_quantlist__44u4__p5_0[] = {
  148236. 4,
  148237. 3,
  148238. 5,
  148239. 2,
  148240. 6,
  148241. 1,
  148242. 7,
  148243. 0,
  148244. 8,
  148245. };
  148246. static long _vq_lengthlist__44u4__p5_0[] = {
  148247. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148248. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148249. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148250. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148251. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148252. 12,
  148253. };
  148254. static float _vq_quantthresh__44u4__p5_0[] = {
  148255. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148256. };
  148257. static long _vq_quantmap__44u4__p5_0[] = {
  148258. 7, 5, 3, 1, 0, 2, 4, 6,
  148259. 8,
  148260. };
  148261. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148262. _vq_quantthresh__44u4__p5_0,
  148263. _vq_quantmap__44u4__p5_0,
  148264. 9,
  148265. 9
  148266. };
  148267. static static_codebook _44u4__p5_0 = {
  148268. 2, 81,
  148269. _vq_lengthlist__44u4__p5_0,
  148270. 1, -531628032, 1611661312, 4, 0,
  148271. _vq_quantlist__44u4__p5_0,
  148272. NULL,
  148273. &_vq_auxt__44u4__p5_0,
  148274. NULL,
  148275. 0
  148276. };
  148277. static long _vq_quantlist__44u4__p6_0[] = {
  148278. 6,
  148279. 5,
  148280. 7,
  148281. 4,
  148282. 8,
  148283. 3,
  148284. 9,
  148285. 2,
  148286. 10,
  148287. 1,
  148288. 11,
  148289. 0,
  148290. 12,
  148291. };
  148292. static long _vq_lengthlist__44u4__p6_0[] = {
  148293. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148294. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148295. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148296. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148297. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148298. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148299. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148300. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148301. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148302. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148303. 16,16,16,17,17,18,17,20,21,
  148304. };
  148305. static float _vq_quantthresh__44u4__p6_0[] = {
  148306. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148307. 12.5, 17.5, 22.5, 27.5,
  148308. };
  148309. static long _vq_quantmap__44u4__p6_0[] = {
  148310. 11, 9, 7, 5, 3, 1, 0, 2,
  148311. 4, 6, 8, 10, 12,
  148312. };
  148313. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148314. _vq_quantthresh__44u4__p6_0,
  148315. _vq_quantmap__44u4__p6_0,
  148316. 13,
  148317. 13
  148318. };
  148319. static static_codebook _44u4__p6_0 = {
  148320. 2, 169,
  148321. _vq_lengthlist__44u4__p6_0,
  148322. 1, -526516224, 1616117760, 4, 0,
  148323. _vq_quantlist__44u4__p6_0,
  148324. NULL,
  148325. &_vq_auxt__44u4__p6_0,
  148326. NULL,
  148327. 0
  148328. };
  148329. static long _vq_quantlist__44u4__p6_1[] = {
  148330. 2,
  148331. 1,
  148332. 3,
  148333. 0,
  148334. 4,
  148335. };
  148336. static long _vq_lengthlist__44u4__p6_1[] = {
  148337. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148338. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148339. };
  148340. static float _vq_quantthresh__44u4__p6_1[] = {
  148341. -1.5, -0.5, 0.5, 1.5,
  148342. };
  148343. static long _vq_quantmap__44u4__p6_1[] = {
  148344. 3, 1, 0, 2, 4,
  148345. };
  148346. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148347. _vq_quantthresh__44u4__p6_1,
  148348. _vq_quantmap__44u4__p6_1,
  148349. 5,
  148350. 5
  148351. };
  148352. static static_codebook _44u4__p6_1 = {
  148353. 2, 25,
  148354. _vq_lengthlist__44u4__p6_1,
  148355. 1, -533725184, 1611661312, 3, 0,
  148356. _vq_quantlist__44u4__p6_1,
  148357. NULL,
  148358. &_vq_auxt__44u4__p6_1,
  148359. NULL,
  148360. 0
  148361. };
  148362. static long _vq_quantlist__44u4__p7_0[] = {
  148363. 6,
  148364. 5,
  148365. 7,
  148366. 4,
  148367. 8,
  148368. 3,
  148369. 9,
  148370. 2,
  148371. 10,
  148372. 1,
  148373. 11,
  148374. 0,
  148375. 12,
  148376. };
  148377. static long _vq_lengthlist__44u4__p7_0[] = {
  148378. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148379. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148380. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148381. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148382. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148383. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148384. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148388. 11,11,11,11,11,11,11,11,11,
  148389. };
  148390. static float _vq_quantthresh__44u4__p7_0[] = {
  148391. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148392. 637.5, 892.5, 1147.5, 1402.5,
  148393. };
  148394. static long _vq_quantmap__44u4__p7_0[] = {
  148395. 11, 9, 7, 5, 3, 1, 0, 2,
  148396. 4, 6, 8, 10, 12,
  148397. };
  148398. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148399. _vq_quantthresh__44u4__p7_0,
  148400. _vq_quantmap__44u4__p7_0,
  148401. 13,
  148402. 13
  148403. };
  148404. static static_codebook _44u4__p7_0 = {
  148405. 2, 169,
  148406. _vq_lengthlist__44u4__p7_0,
  148407. 1, -514332672, 1627381760, 4, 0,
  148408. _vq_quantlist__44u4__p7_0,
  148409. NULL,
  148410. &_vq_auxt__44u4__p7_0,
  148411. NULL,
  148412. 0
  148413. };
  148414. static long _vq_quantlist__44u4__p7_1[] = {
  148415. 7,
  148416. 6,
  148417. 8,
  148418. 5,
  148419. 9,
  148420. 4,
  148421. 10,
  148422. 3,
  148423. 11,
  148424. 2,
  148425. 12,
  148426. 1,
  148427. 13,
  148428. 0,
  148429. 14,
  148430. };
  148431. static long _vq_lengthlist__44u4__p7_1[] = {
  148432. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148433. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148434. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148435. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148436. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148437. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148438. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148439. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148440. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148441. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148442. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148443. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148444. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148445. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148446. 16,
  148447. };
  148448. static float _vq_quantthresh__44u4__p7_1[] = {
  148449. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148450. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148451. };
  148452. static long _vq_quantmap__44u4__p7_1[] = {
  148453. 13, 11, 9, 7, 5, 3, 1, 0,
  148454. 2, 4, 6, 8, 10, 12, 14,
  148455. };
  148456. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148457. _vq_quantthresh__44u4__p7_1,
  148458. _vq_quantmap__44u4__p7_1,
  148459. 15,
  148460. 15
  148461. };
  148462. static static_codebook _44u4__p7_1 = {
  148463. 2, 225,
  148464. _vq_lengthlist__44u4__p7_1,
  148465. 1, -522338304, 1620115456, 4, 0,
  148466. _vq_quantlist__44u4__p7_1,
  148467. NULL,
  148468. &_vq_auxt__44u4__p7_1,
  148469. NULL,
  148470. 0
  148471. };
  148472. static long _vq_quantlist__44u4__p7_2[] = {
  148473. 8,
  148474. 7,
  148475. 9,
  148476. 6,
  148477. 10,
  148478. 5,
  148479. 11,
  148480. 4,
  148481. 12,
  148482. 3,
  148483. 13,
  148484. 2,
  148485. 14,
  148486. 1,
  148487. 15,
  148488. 0,
  148489. 16,
  148490. };
  148491. static long _vq_lengthlist__44u4__p7_2[] = {
  148492. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148493. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148494. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148495. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148496. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148497. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148498. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148499. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148500. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148501. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148502. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148503. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148504. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148505. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148506. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148507. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148508. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148509. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148510. 10,
  148511. };
  148512. static float _vq_quantthresh__44u4__p7_2[] = {
  148513. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148514. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148515. };
  148516. static long _vq_quantmap__44u4__p7_2[] = {
  148517. 15, 13, 11, 9, 7, 5, 3, 1,
  148518. 0, 2, 4, 6, 8, 10, 12, 14,
  148519. 16,
  148520. };
  148521. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148522. _vq_quantthresh__44u4__p7_2,
  148523. _vq_quantmap__44u4__p7_2,
  148524. 17,
  148525. 17
  148526. };
  148527. static static_codebook _44u4__p7_2 = {
  148528. 2, 289,
  148529. _vq_lengthlist__44u4__p7_2,
  148530. 1, -529530880, 1611661312, 5, 0,
  148531. _vq_quantlist__44u4__p7_2,
  148532. NULL,
  148533. &_vq_auxt__44u4__p7_2,
  148534. NULL,
  148535. 0
  148536. };
  148537. static long _huff_lengthlist__44u4__short[] = {
  148538. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148539. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148540. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148541. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148542. };
  148543. static static_codebook _huff_book__44u4__short = {
  148544. 2, 64,
  148545. _huff_lengthlist__44u4__short,
  148546. 0, 0, 0, 0, 0,
  148547. NULL,
  148548. NULL,
  148549. NULL,
  148550. NULL,
  148551. 0
  148552. };
  148553. static long _huff_lengthlist__44u5__long[] = {
  148554. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148555. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148556. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148557. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148558. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148559. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148560. 14, 8, 7, 8,
  148561. };
  148562. static static_codebook _huff_book__44u5__long = {
  148563. 2, 100,
  148564. _huff_lengthlist__44u5__long,
  148565. 0, 0, 0, 0, 0,
  148566. NULL,
  148567. NULL,
  148568. NULL,
  148569. NULL,
  148570. 0
  148571. };
  148572. static long _vq_quantlist__44u5__p1_0[] = {
  148573. 1,
  148574. 0,
  148575. 2,
  148576. };
  148577. static long _vq_lengthlist__44u5__p1_0[] = {
  148578. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148579. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148580. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148581. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148582. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148583. 12,
  148584. };
  148585. static float _vq_quantthresh__44u5__p1_0[] = {
  148586. -0.5, 0.5,
  148587. };
  148588. static long _vq_quantmap__44u5__p1_0[] = {
  148589. 1, 0, 2,
  148590. };
  148591. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148592. _vq_quantthresh__44u5__p1_0,
  148593. _vq_quantmap__44u5__p1_0,
  148594. 3,
  148595. 3
  148596. };
  148597. static static_codebook _44u5__p1_0 = {
  148598. 4, 81,
  148599. _vq_lengthlist__44u5__p1_0,
  148600. 1, -535822336, 1611661312, 2, 0,
  148601. _vq_quantlist__44u5__p1_0,
  148602. NULL,
  148603. &_vq_auxt__44u5__p1_0,
  148604. NULL,
  148605. 0
  148606. };
  148607. static long _vq_quantlist__44u5__p2_0[] = {
  148608. 1,
  148609. 0,
  148610. 2,
  148611. };
  148612. static long _vq_lengthlist__44u5__p2_0[] = {
  148613. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148614. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148615. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148616. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148617. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148618. 9,
  148619. };
  148620. static float _vq_quantthresh__44u5__p2_0[] = {
  148621. -0.5, 0.5,
  148622. };
  148623. static long _vq_quantmap__44u5__p2_0[] = {
  148624. 1, 0, 2,
  148625. };
  148626. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148627. _vq_quantthresh__44u5__p2_0,
  148628. _vq_quantmap__44u5__p2_0,
  148629. 3,
  148630. 3
  148631. };
  148632. static static_codebook _44u5__p2_0 = {
  148633. 4, 81,
  148634. _vq_lengthlist__44u5__p2_0,
  148635. 1, -535822336, 1611661312, 2, 0,
  148636. _vq_quantlist__44u5__p2_0,
  148637. NULL,
  148638. &_vq_auxt__44u5__p2_0,
  148639. NULL,
  148640. 0
  148641. };
  148642. static long _vq_quantlist__44u5__p3_0[] = {
  148643. 2,
  148644. 1,
  148645. 3,
  148646. 0,
  148647. 4,
  148648. };
  148649. static long _vq_lengthlist__44u5__p3_0[] = {
  148650. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148651. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148652. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148653. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148654. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148655. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148656. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148657. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148658. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148659. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148660. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148661. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148662. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148663. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148664. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148665. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148666. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148667. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148668. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148669. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148670. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148671. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148672. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148673. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148674. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148675. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148676. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148677. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148678. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148679. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148680. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148681. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148682. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148683. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148684. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148685. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148686. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148687. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148688. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148689. 0,
  148690. };
  148691. static float _vq_quantthresh__44u5__p3_0[] = {
  148692. -1.5, -0.5, 0.5, 1.5,
  148693. };
  148694. static long _vq_quantmap__44u5__p3_0[] = {
  148695. 3, 1, 0, 2, 4,
  148696. };
  148697. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148698. _vq_quantthresh__44u5__p3_0,
  148699. _vq_quantmap__44u5__p3_0,
  148700. 5,
  148701. 5
  148702. };
  148703. static static_codebook _44u5__p3_0 = {
  148704. 4, 625,
  148705. _vq_lengthlist__44u5__p3_0,
  148706. 1, -533725184, 1611661312, 3, 0,
  148707. _vq_quantlist__44u5__p3_0,
  148708. NULL,
  148709. &_vq_auxt__44u5__p3_0,
  148710. NULL,
  148711. 0
  148712. };
  148713. static long _vq_quantlist__44u5__p4_0[] = {
  148714. 2,
  148715. 1,
  148716. 3,
  148717. 0,
  148718. 4,
  148719. };
  148720. static long _vq_lengthlist__44u5__p4_0[] = {
  148721. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148722. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148723. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148724. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148725. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148726. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148727. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148728. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148729. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148730. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148731. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148732. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148733. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148734. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148735. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148736. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148737. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148738. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148739. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148740. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148741. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148742. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148743. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148744. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148745. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148746. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148747. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148748. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148749. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148750. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148751. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148752. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148753. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148754. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148755. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148756. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148757. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148758. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148759. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148760. 12,
  148761. };
  148762. static float _vq_quantthresh__44u5__p4_0[] = {
  148763. -1.5, -0.5, 0.5, 1.5,
  148764. };
  148765. static long _vq_quantmap__44u5__p4_0[] = {
  148766. 3, 1, 0, 2, 4,
  148767. };
  148768. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148769. _vq_quantthresh__44u5__p4_0,
  148770. _vq_quantmap__44u5__p4_0,
  148771. 5,
  148772. 5
  148773. };
  148774. static static_codebook _44u5__p4_0 = {
  148775. 4, 625,
  148776. _vq_lengthlist__44u5__p4_0,
  148777. 1, -533725184, 1611661312, 3, 0,
  148778. _vq_quantlist__44u5__p4_0,
  148779. NULL,
  148780. &_vq_auxt__44u5__p4_0,
  148781. NULL,
  148782. 0
  148783. };
  148784. static long _vq_quantlist__44u5__p5_0[] = {
  148785. 4,
  148786. 3,
  148787. 5,
  148788. 2,
  148789. 6,
  148790. 1,
  148791. 7,
  148792. 0,
  148793. 8,
  148794. };
  148795. static long _vq_lengthlist__44u5__p5_0[] = {
  148796. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148797. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148798. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148799. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148800. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148801. 14,
  148802. };
  148803. static float _vq_quantthresh__44u5__p5_0[] = {
  148804. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148805. };
  148806. static long _vq_quantmap__44u5__p5_0[] = {
  148807. 7, 5, 3, 1, 0, 2, 4, 6,
  148808. 8,
  148809. };
  148810. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148811. _vq_quantthresh__44u5__p5_0,
  148812. _vq_quantmap__44u5__p5_0,
  148813. 9,
  148814. 9
  148815. };
  148816. static static_codebook _44u5__p5_0 = {
  148817. 2, 81,
  148818. _vq_lengthlist__44u5__p5_0,
  148819. 1, -531628032, 1611661312, 4, 0,
  148820. _vq_quantlist__44u5__p5_0,
  148821. NULL,
  148822. &_vq_auxt__44u5__p5_0,
  148823. NULL,
  148824. 0
  148825. };
  148826. static long _vq_quantlist__44u5__p6_0[] = {
  148827. 4,
  148828. 3,
  148829. 5,
  148830. 2,
  148831. 6,
  148832. 1,
  148833. 7,
  148834. 0,
  148835. 8,
  148836. };
  148837. static long _vq_lengthlist__44u5__p6_0[] = {
  148838. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148839. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148840. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148841. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148842. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148843. 11,
  148844. };
  148845. static float _vq_quantthresh__44u5__p6_0[] = {
  148846. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148847. };
  148848. static long _vq_quantmap__44u5__p6_0[] = {
  148849. 7, 5, 3, 1, 0, 2, 4, 6,
  148850. 8,
  148851. };
  148852. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148853. _vq_quantthresh__44u5__p6_0,
  148854. _vq_quantmap__44u5__p6_0,
  148855. 9,
  148856. 9
  148857. };
  148858. static static_codebook _44u5__p6_0 = {
  148859. 2, 81,
  148860. _vq_lengthlist__44u5__p6_0,
  148861. 1, -531628032, 1611661312, 4, 0,
  148862. _vq_quantlist__44u5__p6_0,
  148863. NULL,
  148864. &_vq_auxt__44u5__p6_0,
  148865. NULL,
  148866. 0
  148867. };
  148868. static long _vq_quantlist__44u5__p7_0[] = {
  148869. 1,
  148870. 0,
  148871. 2,
  148872. };
  148873. static long _vq_lengthlist__44u5__p7_0[] = {
  148874. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148875. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148876. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148877. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148878. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148879. 12,
  148880. };
  148881. static float _vq_quantthresh__44u5__p7_0[] = {
  148882. -5.5, 5.5,
  148883. };
  148884. static long _vq_quantmap__44u5__p7_0[] = {
  148885. 1, 0, 2,
  148886. };
  148887. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148888. _vq_quantthresh__44u5__p7_0,
  148889. _vq_quantmap__44u5__p7_0,
  148890. 3,
  148891. 3
  148892. };
  148893. static static_codebook _44u5__p7_0 = {
  148894. 4, 81,
  148895. _vq_lengthlist__44u5__p7_0,
  148896. 1, -529137664, 1618345984, 2, 0,
  148897. _vq_quantlist__44u5__p7_0,
  148898. NULL,
  148899. &_vq_auxt__44u5__p7_0,
  148900. NULL,
  148901. 0
  148902. };
  148903. static long _vq_quantlist__44u5__p7_1[] = {
  148904. 5,
  148905. 4,
  148906. 6,
  148907. 3,
  148908. 7,
  148909. 2,
  148910. 8,
  148911. 1,
  148912. 9,
  148913. 0,
  148914. 10,
  148915. };
  148916. static long _vq_lengthlist__44u5__p7_1[] = {
  148917. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148918. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148919. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148920. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148921. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148922. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148923. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148924. 9, 9, 9, 9, 9,10,10,10,10,
  148925. };
  148926. static float _vq_quantthresh__44u5__p7_1[] = {
  148927. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148928. 3.5, 4.5,
  148929. };
  148930. static long _vq_quantmap__44u5__p7_1[] = {
  148931. 9, 7, 5, 3, 1, 0, 2, 4,
  148932. 6, 8, 10,
  148933. };
  148934. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148935. _vq_quantthresh__44u5__p7_1,
  148936. _vq_quantmap__44u5__p7_1,
  148937. 11,
  148938. 11
  148939. };
  148940. static static_codebook _44u5__p7_1 = {
  148941. 2, 121,
  148942. _vq_lengthlist__44u5__p7_1,
  148943. 1, -531365888, 1611661312, 4, 0,
  148944. _vq_quantlist__44u5__p7_1,
  148945. NULL,
  148946. &_vq_auxt__44u5__p7_1,
  148947. NULL,
  148948. 0
  148949. };
  148950. static long _vq_quantlist__44u5__p8_0[] = {
  148951. 5,
  148952. 4,
  148953. 6,
  148954. 3,
  148955. 7,
  148956. 2,
  148957. 8,
  148958. 1,
  148959. 9,
  148960. 0,
  148961. 10,
  148962. };
  148963. static long _vq_lengthlist__44u5__p8_0[] = {
  148964. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148965. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148966. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148967. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148968. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148969. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148970. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148971. 12,13,13,14,14,14,14,15,15,
  148972. };
  148973. static float _vq_quantthresh__44u5__p8_0[] = {
  148974. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148975. 38.5, 49.5,
  148976. };
  148977. static long _vq_quantmap__44u5__p8_0[] = {
  148978. 9, 7, 5, 3, 1, 0, 2, 4,
  148979. 6, 8, 10,
  148980. };
  148981. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148982. _vq_quantthresh__44u5__p8_0,
  148983. _vq_quantmap__44u5__p8_0,
  148984. 11,
  148985. 11
  148986. };
  148987. static static_codebook _44u5__p8_0 = {
  148988. 2, 121,
  148989. _vq_lengthlist__44u5__p8_0,
  148990. 1, -524582912, 1618345984, 4, 0,
  148991. _vq_quantlist__44u5__p8_0,
  148992. NULL,
  148993. &_vq_auxt__44u5__p8_0,
  148994. NULL,
  148995. 0
  148996. };
  148997. static long _vq_quantlist__44u5__p8_1[] = {
  148998. 5,
  148999. 4,
  149000. 6,
  149001. 3,
  149002. 7,
  149003. 2,
  149004. 8,
  149005. 1,
  149006. 9,
  149007. 0,
  149008. 10,
  149009. };
  149010. static long _vq_lengthlist__44u5__p8_1[] = {
  149011. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149012. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149013. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149014. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149015. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149016. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149017. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149018. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149019. };
  149020. static float _vq_quantthresh__44u5__p8_1[] = {
  149021. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149022. 3.5, 4.5,
  149023. };
  149024. static long _vq_quantmap__44u5__p8_1[] = {
  149025. 9, 7, 5, 3, 1, 0, 2, 4,
  149026. 6, 8, 10,
  149027. };
  149028. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149029. _vq_quantthresh__44u5__p8_1,
  149030. _vq_quantmap__44u5__p8_1,
  149031. 11,
  149032. 11
  149033. };
  149034. static static_codebook _44u5__p8_1 = {
  149035. 2, 121,
  149036. _vq_lengthlist__44u5__p8_1,
  149037. 1, -531365888, 1611661312, 4, 0,
  149038. _vq_quantlist__44u5__p8_1,
  149039. NULL,
  149040. &_vq_auxt__44u5__p8_1,
  149041. NULL,
  149042. 0
  149043. };
  149044. static long _vq_quantlist__44u5__p9_0[] = {
  149045. 6,
  149046. 5,
  149047. 7,
  149048. 4,
  149049. 8,
  149050. 3,
  149051. 9,
  149052. 2,
  149053. 10,
  149054. 1,
  149055. 11,
  149056. 0,
  149057. 12,
  149058. };
  149059. static long _vq_lengthlist__44u5__p9_0[] = {
  149060. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149061. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149062. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149063. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149064. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149065. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149066. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149067. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149068. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149069. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149070. 12,12,12,12,12,12,12,12,12,
  149071. };
  149072. static float _vq_quantthresh__44u5__p9_0[] = {
  149073. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149074. 637.5, 892.5, 1147.5, 1402.5,
  149075. };
  149076. static long _vq_quantmap__44u5__p9_0[] = {
  149077. 11, 9, 7, 5, 3, 1, 0, 2,
  149078. 4, 6, 8, 10, 12,
  149079. };
  149080. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149081. _vq_quantthresh__44u5__p9_0,
  149082. _vq_quantmap__44u5__p9_0,
  149083. 13,
  149084. 13
  149085. };
  149086. static static_codebook _44u5__p9_0 = {
  149087. 2, 169,
  149088. _vq_lengthlist__44u5__p9_0,
  149089. 1, -514332672, 1627381760, 4, 0,
  149090. _vq_quantlist__44u5__p9_0,
  149091. NULL,
  149092. &_vq_auxt__44u5__p9_0,
  149093. NULL,
  149094. 0
  149095. };
  149096. static long _vq_quantlist__44u5__p9_1[] = {
  149097. 7,
  149098. 6,
  149099. 8,
  149100. 5,
  149101. 9,
  149102. 4,
  149103. 10,
  149104. 3,
  149105. 11,
  149106. 2,
  149107. 12,
  149108. 1,
  149109. 13,
  149110. 0,
  149111. 14,
  149112. };
  149113. static long _vq_lengthlist__44u5__p9_1[] = {
  149114. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149115. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149116. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149117. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149118. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149119. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149120. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149121. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149122. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149123. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149124. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149125. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149126. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149127. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149128. 14,
  149129. };
  149130. static float _vq_quantthresh__44u5__p9_1[] = {
  149131. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149132. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149133. };
  149134. static long _vq_quantmap__44u5__p9_1[] = {
  149135. 13, 11, 9, 7, 5, 3, 1, 0,
  149136. 2, 4, 6, 8, 10, 12, 14,
  149137. };
  149138. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149139. _vq_quantthresh__44u5__p9_1,
  149140. _vq_quantmap__44u5__p9_1,
  149141. 15,
  149142. 15
  149143. };
  149144. static static_codebook _44u5__p9_1 = {
  149145. 2, 225,
  149146. _vq_lengthlist__44u5__p9_1,
  149147. 1, -522338304, 1620115456, 4, 0,
  149148. _vq_quantlist__44u5__p9_1,
  149149. NULL,
  149150. &_vq_auxt__44u5__p9_1,
  149151. NULL,
  149152. 0
  149153. };
  149154. static long _vq_quantlist__44u5__p9_2[] = {
  149155. 8,
  149156. 7,
  149157. 9,
  149158. 6,
  149159. 10,
  149160. 5,
  149161. 11,
  149162. 4,
  149163. 12,
  149164. 3,
  149165. 13,
  149166. 2,
  149167. 14,
  149168. 1,
  149169. 15,
  149170. 0,
  149171. 16,
  149172. };
  149173. static long _vq_lengthlist__44u5__p9_2[] = {
  149174. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149175. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149176. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149177. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149178. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149179. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149180. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149181. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149182. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149183. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149184. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149185. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149186. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149187. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149188. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149189. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149190. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149191. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149192. 10,
  149193. };
  149194. static float _vq_quantthresh__44u5__p9_2[] = {
  149195. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149196. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149197. };
  149198. static long _vq_quantmap__44u5__p9_2[] = {
  149199. 15, 13, 11, 9, 7, 5, 3, 1,
  149200. 0, 2, 4, 6, 8, 10, 12, 14,
  149201. 16,
  149202. };
  149203. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149204. _vq_quantthresh__44u5__p9_2,
  149205. _vq_quantmap__44u5__p9_2,
  149206. 17,
  149207. 17
  149208. };
  149209. static static_codebook _44u5__p9_2 = {
  149210. 2, 289,
  149211. _vq_lengthlist__44u5__p9_2,
  149212. 1, -529530880, 1611661312, 5, 0,
  149213. _vq_quantlist__44u5__p9_2,
  149214. NULL,
  149215. &_vq_auxt__44u5__p9_2,
  149216. NULL,
  149217. 0
  149218. };
  149219. static long _huff_lengthlist__44u5__short[] = {
  149220. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149221. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149222. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149223. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149224. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149225. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149226. 6, 8,15,17,
  149227. };
  149228. static static_codebook _huff_book__44u5__short = {
  149229. 2, 100,
  149230. _huff_lengthlist__44u5__short,
  149231. 0, 0, 0, 0, 0,
  149232. NULL,
  149233. NULL,
  149234. NULL,
  149235. NULL,
  149236. 0
  149237. };
  149238. static long _huff_lengthlist__44u6__long[] = {
  149239. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149240. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149241. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149242. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149243. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149244. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149245. 13, 8, 7, 7,
  149246. };
  149247. static static_codebook _huff_book__44u6__long = {
  149248. 2, 100,
  149249. _huff_lengthlist__44u6__long,
  149250. 0, 0, 0, 0, 0,
  149251. NULL,
  149252. NULL,
  149253. NULL,
  149254. NULL,
  149255. 0
  149256. };
  149257. static long _vq_quantlist__44u6__p1_0[] = {
  149258. 1,
  149259. 0,
  149260. 2,
  149261. };
  149262. static long _vq_lengthlist__44u6__p1_0[] = {
  149263. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149264. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149265. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149266. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149267. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149268. 12,
  149269. };
  149270. static float _vq_quantthresh__44u6__p1_0[] = {
  149271. -0.5, 0.5,
  149272. };
  149273. static long _vq_quantmap__44u6__p1_0[] = {
  149274. 1, 0, 2,
  149275. };
  149276. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149277. _vq_quantthresh__44u6__p1_0,
  149278. _vq_quantmap__44u6__p1_0,
  149279. 3,
  149280. 3
  149281. };
  149282. static static_codebook _44u6__p1_0 = {
  149283. 4, 81,
  149284. _vq_lengthlist__44u6__p1_0,
  149285. 1, -535822336, 1611661312, 2, 0,
  149286. _vq_quantlist__44u6__p1_0,
  149287. NULL,
  149288. &_vq_auxt__44u6__p1_0,
  149289. NULL,
  149290. 0
  149291. };
  149292. static long _vq_quantlist__44u6__p2_0[] = {
  149293. 1,
  149294. 0,
  149295. 2,
  149296. };
  149297. static long _vq_lengthlist__44u6__p2_0[] = {
  149298. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149299. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149300. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149301. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149302. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149303. 9,
  149304. };
  149305. static float _vq_quantthresh__44u6__p2_0[] = {
  149306. -0.5, 0.5,
  149307. };
  149308. static long _vq_quantmap__44u6__p2_0[] = {
  149309. 1, 0, 2,
  149310. };
  149311. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149312. _vq_quantthresh__44u6__p2_0,
  149313. _vq_quantmap__44u6__p2_0,
  149314. 3,
  149315. 3
  149316. };
  149317. static static_codebook _44u6__p2_0 = {
  149318. 4, 81,
  149319. _vq_lengthlist__44u6__p2_0,
  149320. 1, -535822336, 1611661312, 2, 0,
  149321. _vq_quantlist__44u6__p2_0,
  149322. NULL,
  149323. &_vq_auxt__44u6__p2_0,
  149324. NULL,
  149325. 0
  149326. };
  149327. static long _vq_quantlist__44u6__p3_0[] = {
  149328. 2,
  149329. 1,
  149330. 3,
  149331. 0,
  149332. 4,
  149333. };
  149334. static long _vq_lengthlist__44u6__p3_0[] = {
  149335. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149336. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149337. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149338. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149339. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149340. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149341. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149342. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149343. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149344. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149345. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149346. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149347. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149348. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149349. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149350. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149351. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149352. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149353. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149354. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149355. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149356. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149357. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149358. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149359. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149360. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149361. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149362. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149363. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149364. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149365. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149366. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149367. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149368. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149369. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149370. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149371. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149372. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149373. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149374. 19,
  149375. };
  149376. static float _vq_quantthresh__44u6__p3_0[] = {
  149377. -1.5, -0.5, 0.5, 1.5,
  149378. };
  149379. static long _vq_quantmap__44u6__p3_0[] = {
  149380. 3, 1, 0, 2, 4,
  149381. };
  149382. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149383. _vq_quantthresh__44u6__p3_0,
  149384. _vq_quantmap__44u6__p3_0,
  149385. 5,
  149386. 5
  149387. };
  149388. static static_codebook _44u6__p3_0 = {
  149389. 4, 625,
  149390. _vq_lengthlist__44u6__p3_0,
  149391. 1, -533725184, 1611661312, 3, 0,
  149392. _vq_quantlist__44u6__p3_0,
  149393. NULL,
  149394. &_vq_auxt__44u6__p3_0,
  149395. NULL,
  149396. 0
  149397. };
  149398. static long _vq_quantlist__44u6__p4_0[] = {
  149399. 2,
  149400. 1,
  149401. 3,
  149402. 0,
  149403. 4,
  149404. };
  149405. static long _vq_lengthlist__44u6__p4_0[] = {
  149406. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149407. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149408. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149409. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149410. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149411. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149412. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149413. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149414. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149415. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149416. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149417. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149418. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149419. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149420. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149421. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149422. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149423. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149424. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149425. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149426. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149427. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149428. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149429. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149430. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149431. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149432. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149433. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149434. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149435. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149436. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149437. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149438. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149439. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149440. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149441. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149442. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149443. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149444. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149445. 13,
  149446. };
  149447. static float _vq_quantthresh__44u6__p4_0[] = {
  149448. -1.5, -0.5, 0.5, 1.5,
  149449. };
  149450. static long _vq_quantmap__44u6__p4_0[] = {
  149451. 3, 1, 0, 2, 4,
  149452. };
  149453. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149454. _vq_quantthresh__44u6__p4_0,
  149455. _vq_quantmap__44u6__p4_0,
  149456. 5,
  149457. 5
  149458. };
  149459. static static_codebook _44u6__p4_0 = {
  149460. 4, 625,
  149461. _vq_lengthlist__44u6__p4_0,
  149462. 1, -533725184, 1611661312, 3, 0,
  149463. _vq_quantlist__44u6__p4_0,
  149464. NULL,
  149465. &_vq_auxt__44u6__p4_0,
  149466. NULL,
  149467. 0
  149468. };
  149469. static long _vq_quantlist__44u6__p5_0[] = {
  149470. 4,
  149471. 3,
  149472. 5,
  149473. 2,
  149474. 6,
  149475. 1,
  149476. 7,
  149477. 0,
  149478. 8,
  149479. };
  149480. static long _vq_lengthlist__44u6__p5_0[] = {
  149481. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149482. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149483. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149484. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149485. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149486. 14,
  149487. };
  149488. static float _vq_quantthresh__44u6__p5_0[] = {
  149489. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149490. };
  149491. static long _vq_quantmap__44u6__p5_0[] = {
  149492. 7, 5, 3, 1, 0, 2, 4, 6,
  149493. 8,
  149494. };
  149495. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149496. _vq_quantthresh__44u6__p5_0,
  149497. _vq_quantmap__44u6__p5_0,
  149498. 9,
  149499. 9
  149500. };
  149501. static static_codebook _44u6__p5_0 = {
  149502. 2, 81,
  149503. _vq_lengthlist__44u6__p5_0,
  149504. 1, -531628032, 1611661312, 4, 0,
  149505. _vq_quantlist__44u6__p5_0,
  149506. NULL,
  149507. &_vq_auxt__44u6__p5_0,
  149508. NULL,
  149509. 0
  149510. };
  149511. static long _vq_quantlist__44u6__p6_0[] = {
  149512. 4,
  149513. 3,
  149514. 5,
  149515. 2,
  149516. 6,
  149517. 1,
  149518. 7,
  149519. 0,
  149520. 8,
  149521. };
  149522. static long _vq_lengthlist__44u6__p6_0[] = {
  149523. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149524. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149525. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149526. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149527. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149528. 12,
  149529. };
  149530. static float _vq_quantthresh__44u6__p6_0[] = {
  149531. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149532. };
  149533. static long _vq_quantmap__44u6__p6_0[] = {
  149534. 7, 5, 3, 1, 0, 2, 4, 6,
  149535. 8,
  149536. };
  149537. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149538. _vq_quantthresh__44u6__p6_0,
  149539. _vq_quantmap__44u6__p6_0,
  149540. 9,
  149541. 9
  149542. };
  149543. static static_codebook _44u6__p6_0 = {
  149544. 2, 81,
  149545. _vq_lengthlist__44u6__p6_0,
  149546. 1, -531628032, 1611661312, 4, 0,
  149547. _vq_quantlist__44u6__p6_0,
  149548. NULL,
  149549. &_vq_auxt__44u6__p6_0,
  149550. NULL,
  149551. 0
  149552. };
  149553. static long _vq_quantlist__44u6__p7_0[] = {
  149554. 1,
  149555. 0,
  149556. 2,
  149557. };
  149558. static long _vq_lengthlist__44u6__p7_0[] = {
  149559. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149560. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149561. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149562. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149563. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149564. 10,
  149565. };
  149566. static float _vq_quantthresh__44u6__p7_0[] = {
  149567. -5.5, 5.5,
  149568. };
  149569. static long _vq_quantmap__44u6__p7_0[] = {
  149570. 1, 0, 2,
  149571. };
  149572. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149573. _vq_quantthresh__44u6__p7_0,
  149574. _vq_quantmap__44u6__p7_0,
  149575. 3,
  149576. 3
  149577. };
  149578. static static_codebook _44u6__p7_0 = {
  149579. 4, 81,
  149580. _vq_lengthlist__44u6__p7_0,
  149581. 1, -529137664, 1618345984, 2, 0,
  149582. _vq_quantlist__44u6__p7_0,
  149583. NULL,
  149584. &_vq_auxt__44u6__p7_0,
  149585. NULL,
  149586. 0
  149587. };
  149588. static long _vq_quantlist__44u6__p7_1[] = {
  149589. 5,
  149590. 4,
  149591. 6,
  149592. 3,
  149593. 7,
  149594. 2,
  149595. 8,
  149596. 1,
  149597. 9,
  149598. 0,
  149599. 10,
  149600. };
  149601. static long _vq_lengthlist__44u6__p7_1[] = {
  149602. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149603. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149604. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149605. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149606. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149607. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149608. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149609. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149610. };
  149611. static float _vq_quantthresh__44u6__p7_1[] = {
  149612. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149613. 3.5, 4.5,
  149614. };
  149615. static long _vq_quantmap__44u6__p7_1[] = {
  149616. 9, 7, 5, 3, 1, 0, 2, 4,
  149617. 6, 8, 10,
  149618. };
  149619. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149620. _vq_quantthresh__44u6__p7_1,
  149621. _vq_quantmap__44u6__p7_1,
  149622. 11,
  149623. 11
  149624. };
  149625. static static_codebook _44u6__p7_1 = {
  149626. 2, 121,
  149627. _vq_lengthlist__44u6__p7_1,
  149628. 1, -531365888, 1611661312, 4, 0,
  149629. _vq_quantlist__44u6__p7_1,
  149630. NULL,
  149631. &_vq_auxt__44u6__p7_1,
  149632. NULL,
  149633. 0
  149634. };
  149635. static long _vq_quantlist__44u6__p8_0[] = {
  149636. 5,
  149637. 4,
  149638. 6,
  149639. 3,
  149640. 7,
  149641. 2,
  149642. 8,
  149643. 1,
  149644. 9,
  149645. 0,
  149646. 10,
  149647. };
  149648. static long _vq_lengthlist__44u6__p8_0[] = {
  149649. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149650. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149651. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149652. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149653. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149654. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149655. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149656. 12,13,13,14,14,14,15,15,15,
  149657. };
  149658. static float _vq_quantthresh__44u6__p8_0[] = {
  149659. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149660. 38.5, 49.5,
  149661. };
  149662. static long _vq_quantmap__44u6__p8_0[] = {
  149663. 9, 7, 5, 3, 1, 0, 2, 4,
  149664. 6, 8, 10,
  149665. };
  149666. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149667. _vq_quantthresh__44u6__p8_0,
  149668. _vq_quantmap__44u6__p8_0,
  149669. 11,
  149670. 11
  149671. };
  149672. static static_codebook _44u6__p8_0 = {
  149673. 2, 121,
  149674. _vq_lengthlist__44u6__p8_0,
  149675. 1, -524582912, 1618345984, 4, 0,
  149676. _vq_quantlist__44u6__p8_0,
  149677. NULL,
  149678. &_vq_auxt__44u6__p8_0,
  149679. NULL,
  149680. 0
  149681. };
  149682. static long _vq_quantlist__44u6__p8_1[] = {
  149683. 5,
  149684. 4,
  149685. 6,
  149686. 3,
  149687. 7,
  149688. 2,
  149689. 8,
  149690. 1,
  149691. 9,
  149692. 0,
  149693. 10,
  149694. };
  149695. static long _vq_lengthlist__44u6__p8_1[] = {
  149696. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149697. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149698. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149699. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149700. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149701. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149702. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149703. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149704. };
  149705. static float _vq_quantthresh__44u6__p8_1[] = {
  149706. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149707. 3.5, 4.5,
  149708. };
  149709. static long _vq_quantmap__44u6__p8_1[] = {
  149710. 9, 7, 5, 3, 1, 0, 2, 4,
  149711. 6, 8, 10,
  149712. };
  149713. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149714. _vq_quantthresh__44u6__p8_1,
  149715. _vq_quantmap__44u6__p8_1,
  149716. 11,
  149717. 11
  149718. };
  149719. static static_codebook _44u6__p8_1 = {
  149720. 2, 121,
  149721. _vq_lengthlist__44u6__p8_1,
  149722. 1, -531365888, 1611661312, 4, 0,
  149723. _vq_quantlist__44u6__p8_1,
  149724. NULL,
  149725. &_vq_auxt__44u6__p8_1,
  149726. NULL,
  149727. 0
  149728. };
  149729. static long _vq_quantlist__44u6__p9_0[] = {
  149730. 7,
  149731. 6,
  149732. 8,
  149733. 5,
  149734. 9,
  149735. 4,
  149736. 10,
  149737. 3,
  149738. 11,
  149739. 2,
  149740. 12,
  149741. 1,
  149742. 13,
  149743. 0,
  149744. 14,
  149745. };
  149746. static long _vq_lengthlist__44u6__p9_0[] = {
  149747. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149748. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149749. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149750. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149751. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149752. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149753. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149754. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149755. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149756. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149757. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149758. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149759. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149760. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149761. 14,
  149762. };
  149763. static float _vq_quantthresh__44u6__p9_0[] = {
  149764. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149765. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149766. };
  149767. static long _vq_quantmap__44u6__p9_0[] = {
  149768. 13, 11, 9, 7, 5, 3, 1, 0,
  149769. 2, 4, 6, 8, 10, 12, 14,
  149770. };
  149771. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149772. _vq_quantthresh__44u6__p9_0,
  149773. _vq_quantmap__44u6__p9_0,
  149774. 15,
  149775. 15
  149776. };
  149777. static static_codebook _44u6__p9_0 = {
  149778. 2, 225,
  149779. _vq_lengthlist__44u6__p9_0,
  149780. 1, -514071552, 1627381760, 4, 0,
  149781. _vq_quantlist__44u6__p9_0,
  149782. NULL,
  149783. &_vq_auxt__44u6__p9_0,
  149784. NULL,
  149785. 0
  149786. };
  149787. static long _vq_quantlist__44u6__p9_1[] = {
  149788. 7,
  149789. 6,
  149790. 8,
  149791. 5,
  149792. 9,
  149793. 4,
  149794. 10,
  149795. 3,
  149796. 11,
  149797. 2,
  149798. 12,
  149799. 1,
  149800. 13,
  149801. 0,
  149802. 14,
  149803. };
  149804. static long _vq_lengthlist__44u6__p9_1[] = {
  149805. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149806. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149807. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149808. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149809. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149810. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149811. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149812. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149813. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149814. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149815. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149816. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149817. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149818. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149819. 13,
  149820. };
  149821. static float _vq_quantthresh__44u6__p9_1[] = {
  149822. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149823. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149824. };
  149825. static long _vq_quantmap__44u6__p9_1[] = {
  149826. 13, 11, 9, 7, 5, 3, 1, 0,
  149827. 2, 4, 6, 8, 10, 12, 14,
  149828. };
  149829. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149830. _vq_quantthresh__44u6__p9_1,
  149831. _vq_quantmap__44u6__p9_1,
  149832. 15,
  149833. 15
  149834. };
  149835. static static_codebook _44u6__p9_1 = {
  149836. 2, 225,
  149837. _vq_lengthlist__44u6__p9_1,
  149838. 1, -522338304, 1620115456, 4, 0,
  149839. _vq_quantlist__44u6__p9_1,
  149840. NULL,
  149841. &_vq_auxt__44u6__p9_1,
  149842. NULL,
  149843. 0
  149844. };
  149845. static long _vq_quantlist__44u6__p9_2[] = {
  149846. 8,
  149847. 7,
  149848. 9,
  149849. 6,
  149850. 10,
  149851. 5,
  149852. 11,
  149853. 4,
  149854. 12,
  149855. 3,
  149856. 13,
  149857. 2,
  149858. 14,
  149859. 1,
  149860. 15,
  149861. 0,
  149862. 16,
  149863. };
  149864. static long _vq_lengthlist__44u6__p9_2[] = {
  149865. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149866. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149867. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149868. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149869. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149870. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149871. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149872. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149873. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149874. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149875. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149876. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149877. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149878. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149879. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149880. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149881. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149882. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149883. 10,
  149884. };
  149885. static float _vq_quantthresh__44u6__p9_2[] = {
  149886. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149887. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149888. };
  149889. static long _vq_quantmap__44u6__p9_2[] = {
  149890. 15, 13, 11, 9, 7, 5, 3, 1,
  149891. 0, 2, 4, 6, 8, 10, 12, 14,
  149892. 16,
  149893. };
  149894. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149895. _vq_quantthresh__44u6__p9_2,
  149896. _vq_quantmap__44u6__p9_2,
  149897. 17,
  149898. 17
  149899. };
  149900. static static_codebook _44u6__p9_2 = {
  149901. 2, 289,
  149902. _vq_lengthlist__44u6__p9_2,
  149903. 1, -529530880, 1611661312, 5, 0,
  149904. _vq_quantlist__44u6__p9_2,
  149905. NULL,
  149906. &_vq_auxt__44u6__p9_2,
  149907. NULL,
  149908. 0
  149909. };
  149910. static long _huff_lengthlist__44u6__short[] = {
  149911. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149912. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149913. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149914. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149915. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149916. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149917. 7, 6, 9,16,
  149918. };
  149919. static static_codebook _huff_book__44u6__short = {
  149920. 2, 100,
  149921. _huff_lengthlist__44u6__short,
  149922. 0, 0, 0, 0, 0,
  149923. NULL,
  149924. NULL,
  149925. NULL,
  149926. NULL,
  149927. 0
  149928. };
  149929. static long _huff_lengthlist__44u7__long[] = {
  149930. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149931. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149932. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149933. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149934. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149935. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149936. 12, 8, 6, 7,
  149937. };
  149938. static static_codebook _huff_book__44u7__long = {
  149939. 2, 100,
  149940. _huff_lengthlist__44u7__long,
  149941. 0, 0, 0, 0, 0,
  149942. NULL,
  149943. NULL,
  149944. NULL,
  149945. NULL,
  149946. 0
  149947. };
  149948. static long _vq_quantlist__44u7__p1_0[] = {
  149949. 1,
  149950. 0,
  149951. 2,
  149952. };
  149953. static long _vq_lengthlist__44u7__p1_0[] = {
  149954. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149955. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149956. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149957. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149958. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149959. 12,
  149960. };
  149961. static float _vq_quantthresh__44u7__p1_0[] = {
  149962. -0.5, 0.5,
  149963. };
  149964. static long _vq_quantmap__44u7__p1_0[] = {
  149965. 1, 0, 2,
  149966. };
  149967. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149968. _vq_quantthresh__44u7__p1_0,
  149969. _vq_quantmap__44u7__p1_0,
  149970. 3,
  149971. 3
  149972. };
  149973. static static_codebook _44u7__p1_0 = {
  149974. 4, 81,
  149975. _vq_lengthlist__44u7__p1_0,
  149976. 1, -535822336, 1611661312, 2, 0,
  149977. _vq_quantlist__44u7__p1_0,
  149978. NULL,
  149979. &_vq_auxt__44u7__p1_0,
  149980. NULL,
  149981. 0
  149982. };
  149983. static long _vq_quantlist__44u7__p2_0[] = {
  149984. 1,
  149985. 0,
  149986. 2,
  149987. };
  149988. static long _vq_lengthlist__44u7__p2_0[] = {
  149989. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149990. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149991. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149992. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149993. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149994. 9,
  149995. };
  149996. static float _vq_quantthresh__44u7__p2_0[] = {
  149997. -0.5, 0.5,
  149998. };
  149999. static long _vq_quantmap__44u7__p2_0[] = {
  150000. 1, 0, 2,
  150001. };
  150002. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150003. _vq_quantthresh__44u7__p2_0,
  150004. _vq_quantmap__44u7__p2_0,
  150005. 3,
  150006. 3
  150007. };
  150008. static static_codebook _44u7__p2_0 = {
  150009. 4, 81,
  150010. _vq_lengthlist__44u7__p2_0,
  150011. 1, -535822336, 1611661312, 2, 0,
  150012. _vq_quantlist__44u7__p2_0,
  150013. NULL,
  150014. &_vq_auxt__44u7__p2_0,
  150015. NULL,
  150016. 0
  150017. };
  150018. static long _vq_quantlist__44u7__p3_0[] = {
  150019. 2,
  150020. 1,
  150021. 3,
  150022. 0,
  150023. 4,
  150024. };
  150025. static long _vq_lengthlist__44u7__p3_0[] = {
  150026. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150027. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150028. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150029. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150030. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150031. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150032. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150033. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150034. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150035. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150036. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150037. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150038. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150039. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150040. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150041. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150042. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150043. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150044. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150045. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150046. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150047. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150048. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150049. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150050. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150051. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150052. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150053. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150054. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150055. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150056. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150057. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150058. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150059. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150060. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150061. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150062. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150063. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150064. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150065. 0,
  150066. };
  150067. static float _vq_quantthresh__44u7__p3_0[] = {
  150068. -1.5, -0.5, 0.5, 1.5,
  150069. };
  150070. static long _vq_quantmap__44u7__p3_0[] = {
  150071. 3, 1, 0, 2, 4,
  150072. };
  150073. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150074. _vq_quantthresh__44u7__p3_0,
  150075. _vq_quantmap__44u7__p3_0,
  150076. 5,
  150077. 5
  150078. };
  150079. static static_codebook _44u7__p3_0 = {
  150080. 4, 625,
  150081. _vq_lengthlist__44u7__p3_0,
  150082. 1, -533725184, 1611661312, 3, 0,
  150083. _vq_quantlist__44u7__p3_0,
  150084. NULL,
  150085. &_vq_auxt__44u7__p3_0,
  150086. NULL,
  150087. 0
  150088. };
  150089. static long _vq_quantlist__44u7__p4_0[] = {
  150090. 2,
  150091. 1,
  150092. 3,
  150093. 0,
  150094. 4,
  150095. };
  150096. static long _vq_lengthlist__44u7__p4_0[] = {
  150097. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150098. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150099. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150100. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150101. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150102. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150103. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150104. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150105. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150106. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150107. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150108. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150109. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150110. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150111. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150112. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150113. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150114. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150115. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150116. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150117. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150118. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150119. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150120. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150121. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150122. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150123. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150124. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150125. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150126. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150127. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150128. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150129. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150130. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150131. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150132. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150133. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150134. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150135. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150136. 14,
  150137. };
  150138. static float _vq_quantthresh__44u7__p4_0[] = {
  150139. -1.5, -0.5, 0.5, 1.5,
  150140. };
  150141. static long _vq_quantmap__44u7__p4_0[] = {
  150142. 3, 1, 0, 2, 4,
  150143. };
  150144. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150145. _vq_quantthresh__44u7__p4_0,
  150146. _vq_quantmap__44u7__p4_0,
  150147. 5,
  150148. 5
  150149. };
  150150. static static_codebook _44u7__p4_0 = {
  150151. 4, 625,
  150152. _vq_lengthlist__44u7__p4_0,
  150153. 1, -533725184, 1611661312, 3, 0,
  150154. _vq_quantlist__44u7__p4_0,
  150155. NULL,
  150156. &_vq_auxt__44u7__p4_0,
  150157. NULL,
  150158. 0
  150159. };
  150160. static long _vq_quantlist__44u7__p5_0[] = {
  150161. 4,
  150162. 3,
  150163. 5,
  150164. 2,
  150165. 6,
  150166. 1,
  150167. 7,
  150168. 0,
  150169. 8,
  150170. };
  150171. static long _vq_lengthlist__44u7__p5_0[] = {
  150172. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150173. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150174. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150175. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150176. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150177. 14,
  150178. };
  150179. static float _vq_quantthresh__44u7__p5_0[] = {
  150180. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150181. };
  150182. static long _vq_quantmap__44u7__p5_0[] = {
  150183. 7, 5, 3, 1, 0, 2, 4, 6,
  150184. 8,
  150185. };
  150186. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150187. _vq_quantthresh__44u7__p5_0,
  150188. _vq_quantmap__44u7__p5_0,
  150189. 9,
  150190. 9
  150191. };
  150192. static static_codebook _44u7__p5_0 = {
  150193. 2, 81,
  150194. _vq_lengthlist__44u7__p5_0,
  150195. 1, -531628032, 1611661312, 4, 0,
  150196. _vq_quantlist__44u7__p5_0,
  150197. NULL,
  150198. &_vq_auxt__44u7__p5_0,
  150199. NULL,
  150200. 0
  150201. };
  150202. static long _vq_quantlist__44u7__p6_0[] = {
  150203. 4,
  150204. 3,
  150205. 5,
  150206. 2,
  150207. 6,
  150208. 1,
  150209. 7,
  150210. 0,
  150211. 8,
  150212. };
  150213. static long _vq_lengthlist__44u7__p6_0[] = {
  150214. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150215. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150216. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150217. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150218. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150219. 12,
  150220. };
  150221. static float _vq_quantthresh__44u7__p6_0[] = {
  150222. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150223. };
  150224. static long _vq_quantmap__44u7__p6_0[] = {
  150225. 7, 5, 3, 1, 0, 2, 4, 6,
  150226. 8,
  150227. };
  150228. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150229. _vq_quantthresh__44u7__p6_0,
  150230. _vq_quantmap__44u7__p6_0,
  150231. 9,
  150232. 9
  150233. };
  150234. static static_codebook _44u7__p6_0 = {
  150235. 2, 81,
  150236. _vq_lengthlist__44u7__p6_0,
  150237. 1, -531628032, 1611661312, 4, 0,
  150238. _vq_quantlist__44u7__p6_0,
  150239. NULL,
  150240. &_vq_auxt__44u7__p6_0,
  150241. NULL,
  150242. 0
  150243. };
  150244. static long _vq_quantlist__44u7__p7_0[] = {
  150245. 1,
  150246. 0,
  150247. 2,
  150248. };
  150249. static long _vq_lengthlist__44u7__p7_0[] = {
  150250. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150251. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150252. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150253. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150254. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150255. 10,
  150256. };
  150257. static float _vq_quantthresh__44u7__p7_0[] = {
  150258. -5.5, 5.5,
  150259. };
  150260. static long _vq_quantmap__44u7__p7_0[] = {
  150261. 1, 0, 2,
  150262. };
  150263. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150264. _vq_quantthresh__44u7__p7_0,
  150265. _vq_quantmap__44u7__p7_0,
  150266. 3,
  150267. 3
  150268. };
  150269. static static_codebook _44u7__p7_0 = {
  150270. 4, 81,
  150271. _vq_lengthlist__44u7__p7_0,
  150272. 1, -529137664, 1618345984, 2, 0,
  150273. _vq_quantlist__44u7__p7_0,
  150274. NULL,
  150275. &_vq_auxt__44u7__p7_0,
  150276. NULL,
  150277. 0
  150278. };
  150279. static long _vq_quantlist__44u7__p7_1[] = {
  150280. 5,
  150281. 4,
  150282. 6,
  150283. 3,
  150284. 7,
  150285. 2,
  150286. 8,
  150287. 1,
  150288. 9,
  150289. 0,
  150290. 10,
  150291. };
  150292. static long _vq_lengthlist__44u7__p7_1[] = {
  150293. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150294. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150295. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150296. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150297. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150298. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150299. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150300. 8, 9, 9, 9, 9, 9,10,10,10,
  150301. };
  150302. static float _vq_quantthresh__44u7__p7_1[] = {
  150303. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150304. 3.5, 4.5,
  150305. };
  150306. static long _vq_quantmap__44u7__p7_1[] = {
  150307. 9, 7, 5, 3, 1, 0, 2, 4,
  150308. 6, 8, 10,
  150309. };
  150310. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150311. _vq_quantthresh__44u7__p7_1,
  150312. _vq_quantmap__44u7__p7_1,
  150313. 11,
  150314. 11
  150315. };
  150316. static static_codebook _44u7__p7_1 = {
  150317. 2, 121,
  150318. _vq_lengthlist__44u7__p7_1,
  150319. 1, -531365888, 1611661312, 4, 0,
  150320. _vq_quantlist__44u7__p7_1,
  150321. NULL,
  150322. &_vq_auxt__44u7__p7_1,
  150323. NULL,
  150324. 0
  150325. };
  150326. static long _vq_quantlist__44u7__p8_0[] = {
  150327. 5,
  150328. 4,
  150329. 6,
  150330. 3,
  150331. 7,
  150332. 2,
  150333. 8,
  150334. 1,
  150335. 9,
  150336. 0,
  150337. 10,
  150338. };
  150339. static long _vq_lengthlist__44u7__p8_0[] = {
  150340. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150341. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150342. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150343. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150344. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150345. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150346. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150347. 12,13,13,14,14,15,15,15,16,
  150348. };
  150349. static float _vq_quantthresh__44u7__p8_0[] = {
  150350. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150351. 38.5, 49.5,
  150352. };
  150353. static long _vq_quantmap__44u7__p8_0[] = {
  150354. 9, 7, 5, 3, 1, 0, 2, 4,
  150355. 6, 8, 10,
  150356. };
  150357. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150358. _vq_quantthresh__44u7__p8_0,
  150359. _vq_quantmap__44u7__p8_0,
  150360. 11,
  150361. 11
  150362. };
  150363. static static_codebook _44u7__p8_0 = {
  150364. 2, 121,
  150365. _vq_lengthlist__44u7__p8_0,
  150366. 1, -524582912, 1618345984, 4, 0,
  150367. _vq_quantlist__44u7__p8_0,
  150368. NULL,
  150369. &_vq_auxt__44u7__p8_0,
  150370. NULL,
  150371. 0
  150372. };
  150373. static long _vq_quantlist__44u7__p8_1[] = {
  150374. 5,
  150375. 4,
  150376. 6,
  150377. 3,
  150378. 7,
  150379. 2,
  150380. 8,
  150381. 1,
  150382. 9,
  150383. 0,
  150384. 10,
  150385. };
  150386. static long _vq_lengthlist__44u7__p8_1[] = {
  150387. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150388. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150389. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150390. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150391. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150392. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150393. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150394. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150395. };
  150396. static float _vq_quantthresh__44u7__p8_1[] = {
  150397. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150398. 3.5, 4.5,
  150399. };
  150400. static long _vq_quantmap__44u7__p8_1[] = {
  150401. 9, 7, 5, 3, 1, 0, 2, 4,
  150402. 6, 8, 10,
  150403. };
  150404. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150405. _vq_quantthresh__44u7__p8_1,
  150406. _vq_quantmap__44u7__p8_1,
  150407. 11,
  150408. 11
  150409. };
  150410. static static_codebook _44u7__p8_1 = {
  150411. 2, 121,
  150412. _vq_lengthlist__44u7__p8_1,
  150413. 1, -531365888, 1611661312, 4, 0,
  150414. _vq_quantlist__44u7__p8_1,
  150415. NULL,
  150416. &_vq_auxt__44u7__p8_1,
  150417. NULL,
  150418. 0
  150419. };
  150420. static long _vq_quantlist__44u7__p9_0[] = {
  150421. 5,
  150422. 4,
  150423. 6,
  150424. 3,
  150425. 7,
  150426. 2,
  150427. 8,
  150428. 1,
  150429. 9,
  150430. 0,
  150431. 10,
  150432. };
  150433. static long _vq_lengthlist__44u7__p9_0[] = {
  150434. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150435. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150436. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150437. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150438. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150440. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150441. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150442. };
  150443. static float _vq_quantthresh__44u7__p9_0[] = {
  150444. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150445. 2229.5, 2866.5,
  150446. };
  150447. static long _vq_quantmap__44u7__p9_0[] = {
  150448. 9, 7, 5, 3, 1, 0, 2, 4,
  150449. 6, 8, 10,
  150450. };
  150451. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150452. _vq_quantthresh__44u7__p9_0,
  150453. _vq_quantmap__44u7__p9_0,
  150454. 11,
  150455. 11
  150456. };
  150457. static static_codebook _44u7__p9_0 = {
  150458. 2, 121,
  150459. _vq_lengthlist__44u7__p9_0,
  150460. 1, -512171520, 1630791680, 4, 0,
  150461. _vq_quantlist__44u7__p9_0,
  150462. NULL,
  150463. &_vq_auxt__44u7__p9_0,
  150464. NULL,
  150465. 0
  150466. };
  150467. static long _vq_quantlist__44u7__p9_1[] = {
  150468. 6,
  150469. 5,
  150470. 7,
  150471. 4,
  150472. 8,
  150473. 3,
  150474. 9,
  150475. 2,
  150476. 10,
  150477. 1,
  150478. 11,
  150479. 0,
  150480. 12,
  150481. };
  150482. static long _vq_lengthlist__44u7__p9_1[] = {
  150483. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150484. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150485. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150486. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150487. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150488. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150489. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150490. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150491. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150492. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150493. 15,15,15,15,17,17,16,17,16,
  150494. };
  150495. static float _vq_quantthresh__44u7__p9_1[] = {
  150496. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150497. 122.5, 171.5, 220.5, 269.5,
  150498. };
  150499. static long _vq_quantmap__44u7__p9_1[] = {
  150500. 11, 9, 7, 5, 3, 1, 0, 2,
  150501. 4, 6, 8, 10, 12,
  150502. };
  150503. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150504. _vq_quantthresh__44u7__p9_1,
  150505. _vq_quantmap__44u7__p9_1,
  150506. 13,
  150507. 13
  150508. };
  150509. static static_codebook _44u7__p9_1 = {
  150510. 2, 169,
  150511. _vq_lengthlist__44u7__p9_1,
  150512. 1, -518889472, 1622704128, 4, 0,
  150513. _vq_quantlist__44u7__p9_1,
  150514. NULL,
  150515. &_vq_auxt__44u7__p9_1,
  150516. NULL,
  150517. 0
  150518. };
  150519. static long _vq_quantlist__44u7__p9_2[] = {
  150520. 24,
  150521. 23,
  150522. 25,
  150523. 22,
  150524. 26,
  150525. 21,
  150526. 27,
  150527. 20,
  150528. 28,
  150529. 19,
  150530. 29,
  150531. 18,
  150532. 30,
  150533. 17,
  150534. 31,
  150535. 16,
  150536. 32,
  150537. 15,
  150538. 33,
  150539. 14,
  150540. 34,
  150541. 13,
  150542. 35,
  150543. 12,
  150544. 36,
  150545. 11,
  150546. 37,
  150547. 10,
  150548. 38,
  150549. 9,
  150550. 39,
  150551. 8,
  150552. 40,
  150553. 7,
  150554. 41,
  150555. 6,
  150556. 42,
  150557. 5,
  150558. 43,
  150559. 4,
  150560. 44,
  150561. 3,
  150562. 45,
  150563. 2,
  150564. 46,
  150565. 1,
  150566. 47,
  150567. 0,
  150568. 48,
  150569. };
  150570. static long _vq_lengthlist__44u7__p9_2[] = {
  150571. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150572. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150573. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150574. 8,
  150575. };
  150576. static float _vq_quantthresh__44u7__p9_2[] = {
  150577. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150578. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150579. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150580. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150581. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150582. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150583. };
  150584. static long _vq_quantmap__44u7__p9_2[] = {
  150585. 47, 45, 43, 41, 39, 37, 35, 33,
  150586. 31, 29, 27, 25, 23, 21, 19, 17,
  150587. 15, 13, 11, 9, 7, 5, 3, 1,
  150588. 0, 2, 4, 6, 8, 10, 12, 14,
  150589. 16, 18, 20, 22, 24, 26, 28, 30,
  150590. 32, 34, 36, 38, 40, 42, 44, 46,
  150591. 48,
  150592. };
  150593. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150594. _vq_quantthresh__44u7__p9_2,
  150595. _vq_quantmap__44u7__p9_2,
  150596. 49,
  150597. 49
  150598. };
  150599. static static_codebook _44u7__p9_2 = {
  150600. 1, 49,
  150601. _vq_lengthlist__44u7__p9_2,
  150602. 1, -526909440, 1611661312, 6, 0,
  150603. _vq_quantlist__44u7__p9_2,
  150604. NULL,
  150605. &_vq_auxt__44u7__p9_2,
  150606. NULL,
  150607. 0
  150608. };
  150609. static long _huff_lengthlist__44u7__short[] = {
  150610. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150611. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150612. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150613. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150614. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150615. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150616. 6, 8, 5, 9,
  150617. };
  150618. static static_codebook _huff_book__44u7__short = {
  150619. 2, 100,
  150620. _huff_lengthlist__44u7__short,
  150621. 0, 0, 0, 0, 0,
  150622. NULL,
  150623. NULL,
  150624. NULL,
  150625. NULL,
  150626. 0
  150627. };
  150628. static long _huff_lengthlist__44u8__long[] = {
  150629. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150630. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150631. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150632. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150633. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150634. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150635. 10, 8, 8, 9,
  150636. };
  150637. static static_codebook _huff_book__44u8__long = {
  150638. 2, 100,
  150639. _huff_lengthlist__44u8__long,
  150640. 0, 0, 0, 0, 0,
  150641. NULL,
  150642. NULL,
  150643. NULL,
  150644. NULL,
  150645. 0
  150646. };
  150647. static long _huff_lengthlist__44u8__short[] = {
  150648. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150649. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150650. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150651. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150652. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150653. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150654. 10,10,15,17,
  150655. };
  150656. static static_codebook _huff_book__44u8__short = {
  150657. 2, 100,
  150658. _huff_lengthlist__44u8__short,
  150659. 0, 0, 0, 0, 0,
  150660. NULL,
  150661. NULL,
  150662. NULL,
  150663. NULL,
  150664. 0
  150665. };
  150666. static long _vq_quantlist__44u8_p1_0[] = {
  150667. 1,
  150668. 0,
  150669. 2,
  150670. };
  150671. static long _vq_lengthlist__44u8_p1_0[] = {
  150672. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150673. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150674. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150675. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150676. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150677. 10,
  150678. };
  150679. static float _vq_quantthresh__44u8_p1_0[] = {
  150680. -0.5, 0.5,
  150681. };
  150682. static long _vq_quantmap__44u8_p1_0[] = {
  150683. 1, 0, 2,
  150684. };
  150685. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150686. _vq_quantthresh__44u8_p1_0,
  150687. _vq_quantmap__44u8_p1_0,
  150688. 3,
  150689. 3
  150690. };
  150691. static static_codebook _44u8_p1_0 = {
  150692. 4, 81,
  150693. _vq_lengthlist__44u8_p1_0,
  150694. 1, -535822336, 1611661312, 2, 0,
  150695. _vq_quantlist__44u8_p1_0,
  150696. NULL,
  150697. &_vq_auxt__44u8_p1_0,
  150698. NULL,
  150699. 0
  150700. };
  150701. static long _vq_quantlist__44u8_p2_0[] = {
  150702. 2,
  150703. 1,
  150704. 3,
  150705. 0,
  150706. 4,
  150707. };
  150708. static long _vq_lengthlist__44u8_p2_0[] = {
  150709. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150710. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150711. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150712. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150713. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150714. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150715. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150716. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150717. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150718. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150719. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150720. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150721. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150722. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150723. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150724. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150725. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150726. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150727. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150728. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150729. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150730. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150731. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150732. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150733. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150734. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150735. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150736. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150737. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150738. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150739. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150740. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150741. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150742. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150743. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150744. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150745. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150746. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150747. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150748. 14,
  150749. };
  150750. static float _vq_quantthresh__44u8_p2_0[] = {
  150751. -1.5, -0.5, 0.5, 1.5,
  150752. };
  150753. static long _vq_quantmap__44u8_p2_0[] = {
  150754. 3, 1, 0, 2, 4,
  150755. };
  150756. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150757. _vq_quantthresh__44u8_p2_0,
  150758. _vq_quantmap__44u8_p2_0,
  150759. 5,
  150760. 5
  150761. };
  150762. static static_codebook _44u8_p2_0 = {
  150763. 4, 625,
  150764. _vq_lengthlist__44u8_p2_0,
  150765. 1, -533725184, 1611661312, 3, 0,
  150766. _vq_quantlist__44u8_p2_0,
  150767. NULL,
  150768. &_vq_auxt__44u8_p2_0,
  150769. NULL,
  150770. 0
  150771. };
  150772. static long _vq_quantlist__44u8_p3_0[] = {
  150773. 4,
  150774. 3,
  150775. 5,
  150776. 2,
  150777. 6,
  150778. 1,
  150779. 7,
  150780. 0,
  150781. 8,
  150782. };
  150783. static long _vq_lengthlist__44u8_p3_0[] = {
  150784. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150785. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150786. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150787. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150788. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150789. 12,
  150790. };
  150791. static float _vq_quantthresh__44u8_p3_0[] = {
  150792. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150793. };
  150794. static long _vq_quantmap__44u8_p3_0[] = {
  150795. 7, 5, 3, 1, 0, 2, 4, 6,
  150796. 8,
  150797. };
  150798. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150799. _vq_quantthresh__44u8_p3_0,
  150800. _vq_quantmap__44u8_p3_0,
  150801. 9,
  150802. 9
  150803. };
  150804. static static_codebook _44u8_p3_0 = {
  150805. 2, 81,
  150806. _vq_lengthlist__44u8_p3_0,
  150807. 1, -531628032, 1611661312, 4, 0,
  150808. _vq_quantlist__44u8_p3_0,
  150809. NULL,
  150810. &_vq_auxt__44u8_p3_0,
  150811. NULL,
  150812. 0
  150813. };
  150814. static long _vq_quantlist__44u8_p4_0[] = {
  150815. 8,
  150816. 7,
  150817. 9,
  150818. 6,
  150819. 10,
  150820. 5,
  150821. 11,
  150822. 4,
  150823. 12,
  150824. 3,
  150825. 13,
  150826. 2,
  150827. 14,
  150828. 1,
  150829. 15,
  150830. 0,
  150831. 16,
  150832. };
  150833. static long _vq_lengthlist__44u8_p4_0[] = {
  150834. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150835. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150836. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150837. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150838. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150839. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150840. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150841. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150842. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150843. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150844. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150845. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150846. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150847. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150848. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150849. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150850. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150851. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150852. 14,
  150853. };
  150854. static float _vq_quantthresh__44u8_p4_0[] = {
  150855. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150856. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150857. };
  150858. static long _vq_quantmap__44u8_p4_0[] = {
  150859. 15, 13, 11, 9, 7, 5, 3, 1,
  150860. 0, 2, 4, 6, 8, 10, 12, 14,
  150861. 16,
  150862. };
  150863. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150864. _vq_quantthresh__44u8_p4_0,
  150865. _vq_quantmap__44u8_p4_0,
  150866. 17,
  150867. 17
  150868. };
  150869. static static_codebook _44u8_p4_0 = {
  150870. 2, 289,
  150871. _vq_lengthlist__44u8_p4_0,
  150872. 1, -529530880, 1611661312, 5, 0,
  150873. _vq_quantlist__44u8_p4_0,
  150874. NULL,
  150875. &_vq_auxt__44u8_p4_0,
  150876. NULL,
  150877. 0
  150878. };
  150879. static long _vq_quantlist__44u8_p5_0[] = {
  150880. 1,
  150881. 0,
  150882. 2,
  150883. };
  150884. static long _vq_lengthlist__44u8_p5_0[] = {
  150885. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150886. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150887. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150888. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150889. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150890. 10,
  150891. };
  150892. static float _vq_quantthresh__44u8_p5_0[] = {
  150893. -5.5, 5.5,
  150894. };
  150895. static long _vq_quantmap__44u8_p5_0[] = {
  150896. 1, 0, 2,
  150897. };
  150898. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150899. _vq_quantthresh__44u8_p5_0,
  150900. _vq_quantmap__44u8_p5_0,
  150901. 3,
  150902. 3
  150903. };
  150904. static static_codebook _44u8_p5_0 = {
  150905. 4, 81,
  150906. _vq_lengthlist__44u8_p5_0,
  150907. 1, -529137664, 1618345984, 2, 0,
  150908. _vq_quantlist__44u8_p5_0,
  150909. NULL,
  150910. &_vq_auxt__44u8_p5_0,
  150911. NULL,
  150912. 0
  150913. };
  150914. static long _vq_quantlist__44u8_p5_1[] = {
  150915. 5,
  150916. 4,
  150917. 6,
  150918. 3,
  150919. 7,
  150920. 2,
  150921. 8,
  150922. 1,
  150923. 9,
  150924. 0,
  150925. 10,
  150926. };
  150927. static long _vq_lengthlist__44u8_p5_1[] = {
  150928. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150929. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150930. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150931. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150932. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150933. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150934. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150935. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150936. };
  150937. static float _vq_quantthresh__44u8_p5_1[] = {
  150938. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150939. 3.5, 4.5,
  150940. };
  150941. static long _vq_quantmap__44u8_p5_1[] = {
  150942. 9, 7, 5, 3, 1, 0, 2, 4,
  150943. 6, 8, 10,
  150944. };
  150945. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150946. _vq_quantthresh__44u8_p5_1,
  150947. _vq_quantmap__44u8_p5_1,
  150948. 11,
  150949. 11
  150950. };
  150951. static static_codebook _44u8_p5_1 = {
  150952. 2, 121,
  150953. _vq_lengthlist__44u8_p5_1,
  150954. 1, -531365888, 1611661312, 4, 0,
  150955. _vq_quantlist__44u8_p5_1,
  150956. NULL,
  150957. &_vq_auxt__44u8_p5_1,
  150958. NULL,
  150959. 0
  150960. };
  150961. static long _vq_quantlist__44u8_p6_0[] = {
  150962. 6,
  150963. 5,
  150964. 7,
  150965. 4,
  150966. 8,
  150967. 3,
  150968. 9,
  150969. 2,
  150970. 10,
  150971. 1,
  150972. 11,
  150973. 0,
  150974. 12,
  150975. };
  150976. static long _vq_lengthlist__44u8_p6_0[] = {
  150977. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150978. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150979. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150980. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150981. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150982. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150983. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150984. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150985. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150986. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150987. 11,11,11,11,11,12,11,12,12,
  150988. };
  150989. static float _vq_quantthresh__44u8_p6_0[] = {
  150990. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150991. 12.5, 17.5, 22.5, 27.5,
  150992. };
  150993. static long _vq_quantmap__44u8_p6_0[] = {
  150994. 11, 9, 7, 5, 3, 1, 0, 2,
  150995. 4, 6, 8, 10, 12,
  150996. };
  150997. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150998. _vq_quantthresh__44u8_p6_0,
  150999. _vq_quantmap__44u8_p6_0,
  151000. 13,
  151001. 13
  151002. };
  151003. static static_codebook _44u8_p6_0 = {
  151004. 2, 169,
  151005. _vq_lengthlist__44u8_p6_0,
  151006. 1, -526516224, 1616117760, 4, 0,
  151007. _vq_quantlist__44u8_p6_0,
  151008. NULL,
  151009. &_vq_auxt__44u8_p6_0,
  151010. NULL,
  151011. 0
  151012. };
  151013. static long _vq_quantlist__44u8_p6_1[] = {
  151014. 2,
  151015. 1,
  151016. 3,
  151017. 0,
  151018. 4,
  151019. };
  151020. static long _vq_lengthlist__44u8_p6_1[] = {
  151021. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151022. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151023. };
  151024. static float _vq_quantthresh__44u8_p6_1[] = {
  151025. -1.5, -0.5, 0.5, 1.5,
  151026. };
  151027. static long _vq_quantmap__44u8_p6_1[] = {
  151028. 3, 1, 0, 2, 4,
  151029. };
  151030. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151031. _vq_quantthresh__44u8_p6_1,
  151032. _vq_quantmap__44u8_p6_1,
  151033. 5,
  151034. 5
  151035. };
  151036. static static_codebook _44u8_p6_1 = {
  151037. 2, 25,
  151038. _vq_lengthlist__44u8_p6_1,
  151039. 1, -533725184, 1611661312, 3, 0,
  151040. _vq_quantlist__44u8_p6_1,
  151041. NULL,
  151042. &_vq_auxt__44u8_p6_1,
  151043. NULL,
  151044. 0
  151045. };
  151046. static long _vq_quantlist__44u8_p7_0[] = {
  151047. 6,
  151048. 5,
  151049. 7,
  151050. 4,
  151051. 8,
  151052. 3,
  151053. 9,
  151054. 2,
  151055. 10,
  151056. 1,
  151057. 11,
  151058. 0,
  151059. 12,
  151060. };
  151061. static long _vq_lengthlist__44u8_p7_0[] = {
  151062. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151063. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151064. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151065. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151066. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151067. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151068. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151069. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151070. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151071. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151072. 13,13,14,14,14,15,15,15,16,
  151073. };
  151074. static float _vq_quantthresh__44u8_p7_0[] = {
  151075. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151076. 27.5, 38.5, 49.5, 60.5,
  151077. };
  151078. static long _vq_quantmap__44u8_p7_0[] = {
  151079. 11, 9, 7, 5, 3, 1, 0, 2,
  151080. 4, 6, 8, 10, 12,
  151081. };
  151082. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151083. _vq_quantthresh__44u8_p7_0,
  151084. _vq_quantmap__44u8_p7_0,
  151085. 13,
  151086. 13
  151087. };
  151088. static static_codebook _44u8_p7_0 = {
  151089. 2, 169,
  151090. _vq_lengthlist__44u8_p7_0,
  151091. 1, -523206656, 1618345984, 4, 0,
  151092. _vq_quantlist__44u8_p7_0,
  151093. NULL,
  151094. &_vq_auxt__44u8_p7_0,
  151095. NULL,
  151096. 0
  151097. };
  151098. static long _vq_quantlist__44u8_p7_1[] = {
  151099. 5,
  151100. 4,
  151101. 6,
  151102. 3,
  151103. 7,
  151104. 2,
  151105. 8,
  151106. 1,
  151107. 9,
  151108. 0,
  151109. 10,
  151110. };
  151111. static long _vq_lengthlist__44u8_p7_1[] = {
  151112. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151113. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151114. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151115. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151116. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151117. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151118. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151119. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151120. };
  151121. static float _vq_quantthresh__44u8_p7_1[] = {
  151122. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151123. 3.5, 4.5,
  151124. };
  151125. static long _vq_quantmap__44u8_p7_1[] = {
  151126. 9, 7, 5, 3, 1, 0, 2, 4,
  151127. 6, 8, 10,
  151128. };
  151129. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151130. _vq_quantthresh__44u8_p7_1,
  151131. _vq_quantmap__44u8_p7_1,
  151132. 11,
  151133. 11
  151134. };
  151135. static static_codebook _44u8_p7_1 = {
  151136. 2, 121,
  151137. _vq_lengthlist__44u8_p7_1,
  151138. 1, -531365888, 1611661312, 4, 0,
  151139. _vq_quantlist__44u8_p7_1,
  151140. NULL,
  151141. &_vq_auxt__44u8_p7_1,
  151142. NULL,
  151143. 0
  151144. };
  151145. static long _vq_quantlist__44u8_p8_0[] = {
  151146. 7,
  151147. 6,
  151148. 8,
  151149. 5,
  151150. 9,
  151151. 4,
  151152. 10,
  151153. 3,
  151154. 11,
  151155. 2,
  151156. 12,
  151157. 1,
  151158. 13,
  151159. 0,
  151160. 14,
  151161. };
  151162. static long _vq_lengthlist__44u8_p8_0[] = {
  151163. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151164. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151165. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151166. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151167. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151168. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151169. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151170. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151171. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151172. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151173. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151174. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151175. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151176. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151177. 17,
  151178. };
  151179. static float _vq_quantthresh__44u8_p8_0[] = {
  151180. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151181. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151182. };
  151183. static long _vq_quantmap__44u8_p8_0[] = {
  151184. 13, 11, 9, 7, 5, 3, 1, 0,
  151185. 2, 4, 6, 8, 10, 12, 14,
  151186. };
  151187. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151188. _vq_quantthresh__44u8_p8_0,
  151189. _vq_quantmap__44u8_p8_0,
  151190. 15,
  151191. 15
  151192. };
  151193. static static_codebook _44u8_p8_0 = {
  151194. 2, 225,
  151195. _vq_lengthlist__44u8_p8_0,
  151196. 1, -520986624, 1620377600, 4, 0,
  151197. _vq_quantlist__44u8_p8_0,
  151198. NULL,
  151199. &_vq_auxt__44u8_p8_0,
  151200. NULL,
  151201. 0
  151202. };
  151203. static long _vq_quantlist__44u8_p8_1[] = {
  151204. 10,
  151205. 9,
  151206. 11,
  151207. 8,
  151208. 12,
  151209. 7,
  151210. 13,
  151211. 6,
  151212. 14,
  151213. 5,
  151214. 15,
  151215. 4,
  151216. 16,
  151217. 3,
  151218. 17,
  151219. 2,
  151220. 18,
  151221. 1,
  151222. 19,
  151223. 0,
  151224. 20,
  151225. };
  151226. static long _vq_lengthlist__44u8_p8_1[] = {
  151227. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151228. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151229. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151230. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151231. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151232. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151233. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151234. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151235. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151236. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151237. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151238. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151239. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151240. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151241. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151242. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151243. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151244. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151245. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151246. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151247. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151248. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151249. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151250. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151251. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151252. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151253. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151254. 10,10,10,10,10,10,10,10,10,
  151255. };
  151256. static float _vq_quantthresh__44u8_p8_1[] = {
  151257. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151258. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151259. 6.5, 7.5, 8.5, 9.5,
  151260. };
  151261. static long _vq_quantmap__44u8_p8_1[] = {
  151262. 19, 17, 15, 13, 11, 9, 7, 5,
  151263. 3, 1, 0, 2, 4, 6, 8, 10,
  151264. 12, 14, 16, 18, 20,
  151265. };
  151266. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151267. _vq_quantthresh__44u8_p8_1,
  151268. _vq_quantmap__44u8_p8_1,
  151269. 21,
  151270. 21
  151271. };
  151272. static static_codebook _44u8_p8_1 = {
  151273. 2, 441,
  151274. _vq_lengthlist__44u8_p8_1,
  151275. 1, -529268736, 1611661312, 5, 0,
  151276. _vq_quantlist__44u8_p8_1,
  151277. NULL,
  151278. &_vq_auxt__44u8_p8_1,
  151279. NULL,
  151280. 0
  151281. };
  151282. static long _vq_quantlist__44u8_p9_0[] = {
  151283. 4,
  151284. 3,
  151285. 5,
  151286. 2,
  151287. 6,
  151288. 1,
  151289. 7,
  151290. 0,
  151291. 8,
  151292. };
  151293. static long _vq_lengthlist__44u8_p9_0[] = {
  151294. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151295. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151296. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151297. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151298. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151299. 8,
  151300. };
  151301. static float _vq_quantthresh__44u8_p9_0[] = {
  151302. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151303. };
  151304. static long _vq_quantmap__44u8_p9_0[] = {
  151305. 7, 5, 3, 1, 0, 2, 4, 6,
  151306. 8,
  151307. };
  151308. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151309. _vq_quantthresh__44u8_p9_0,
  151310. _vq_quantmap__44u8_p9_0,
  151311. 9,
  151312. 9
  151313. };
  151314. static static_codebook _44u8_p9_0 = {
  151315. 2, 81,
  151316. _vq_lengthlist__44u8_p9_0,
  151317. 1, -511895552, 1631393792, 4, 0,
  151318. _vq_quantlist__44u8_p9_0,
  151319. NULL,
  151320. &_vq_auxt__44u8_p9_0,
  151321. NULL,
  151322. 0
  151323. };
  151324. static long _vq_quantlist__44u8_p9_1[] = {
  151325. 9,
  151326. 8,
  151327. 10,
  151328. 7,
  151329. 11,
  151330. 6,
  151331. 12,
  151332. 5,
  151333. 13,
  151334. 4,
  151335. 14,
  151336. 3,
  151337. 15,
  151338. 2,
  151339. 16,
  151340. 1,
  151341. 17,
  151342. 0,
  151343. 18,
  151344. };
  151345. static long _vq_lengthlist__44u8_p9_1[] = {
  151346. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151347. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151348. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151349. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151350. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151351. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151352. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151353. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151354. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151355. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151356. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151357. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151358. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151359. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151360. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151361. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151362. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151363. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151364. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151365. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151366. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151367. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151368. 16,15,16,16,16,16,16,16,16,
  151369. };
  151370. static float _vq_quantthresh__44u8_p9_1[] = {
  151371. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151372. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151373. 367.5, 416.5,
  151374. };
  151375. static long _vq_quantmap__44u8_p9_1[] = {
  151376. 17, 15, 13, 11, 9, 7, 5, 3,
  151377. 1, 0, 2, 4, 6, 8, 10, 12,
  151378. 14, 16, 18,
  151379. };
  151380. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151381. _vq_quantthresh__44u8_p9_1,
  151382. _vq_quantmap__44u8_p9_1,
  151383. 19,
  151384. 19
  151385. };
  151386. static static_codebook _44u8_p9_1 = {
  151387. 2, 361,
  151388. _vq_lengthlist__44u8_p9_1,
  151389. 1, -518287360, 1622704128, 5, 0,
  151390. _vq_quantlist__44u8_p9_1,
  151391. NULL,
  151392. &_vq_auxt__44u8_p9_1,
  151393. NULL,
  151394. 0
  151395. };
  151396. static long _vq_quantlist__44u8_p9_2[] = {
  151397. 24,
  151398. 23,
  151399. 25,
  151400. 22,
  151401. 26,
  151402. 21,
  151403. 27,
  151404. 20,
  151405. 28,
  151406. 19,
  151407. 29,
  151408. 18,
  151409. 30,
  151410. 17,
  151411. 31,
  151412. 16,
  151413. 32,
  151414. 15,
  151415. 33,
  151416. 14,
  151417. 34,
  151418. 13,
  151419. 35,
  151420. 12,
  151421. 36,
  151422. 11,
  151423. 37,
  151424. 10,
  151425. 38,
  151426. 9,
  151427. 39,
  151428. 8,
  151429. 40,
  151430. 7,
  151431. 41,
  151432. 6,
  151433. 42,
  151434. 5,
  151435. 43,
  151436. 4,
  151437. 44,
  151438. 3,
  151439. 45,
  151440. 2,
  151441. 46,
  151442. 1,
  151443. 47,
  151444. 0,
  151445. 48,
  151446. };
  151447. static long _vq_lengthlist__44u8_p9_2[] = {
  151448. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151449. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151450. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151451. 7,
  151452. };
  151453. static float _vq_quantthresh__44u8_p9_2[] = {
  151454. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151455. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151456. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151457. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151458. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151459. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151460. };
  151461. static long _vq_quantmap__44u8_p9_2[] = {
  151462. 47, 45, 43, 41, 39, 37, 35, 33,
  151463. 31, 29, 27, 25, 23, 21, 19, 17,
  151464. 15, 13, 11, 9, 7, 5, 3, 1,
  151465. 0, 2, 4, 6, 8, 10, 12, 14,
  151466. 16, 18, 20, 22, 24, 26, 28, 30,
  151467. 32, 34, 36, 38, 40, 42, 44, 46,
  151468. 48,
  151469. };
  151470. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151471. _vq_quantthresh__44u8_p9_2,
  151472. _vq_quantmap__44u8_p9_2,
  151473. 49,
  151474. 49
  151475. };
  151476. static static_codebook _44u8_p9_2 = {
  151477. 1, 49,
  151478. _vq_lengthlist__44u8_p9_2,
  151479. 1, -526909440, 1611661312, 6, 0,
  151480. _vq_quantlist__44u8_p9_2,
  151481. NULL,
  151482. &_vq_auxt__44u8_p9_2,
  151483. NULL,
  151484. 0
  151485. };
  151486. static long _huff_lengthlist__44u9__long[] = {
  151487. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151488. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151489. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151490. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151491. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151492. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151493. 10, 8, 8, 9,
  151494. };
  151495. static static_codebook _huff_book__44u9__long = {
  151496. 2, 100,
  151497. _huff_lengthlist__44u9__long,
  151498. 0, 0, 0, 0, 0,
  151499. NULL,
  151500. NULL,
  151501. NULL,
  151502. NULL,
  151503. 0
  151504. };
  151505. static long _huff_lengthlist__44u9__short[] = {
  151506. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151507. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151508. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151509. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151510. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151511. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151512. 9, 9,12,15,
  151513. };
  151514. static static_codebook _huff_book__44u9__short = {
  151515. 2, 100,
  151516. _huff_lengthlist__44u9__short,
  151517. 0, 0, 0, 0, 0,
  151518. NULL,
  151519. NULL,
  151520. NULL,
  151521. NULL,
  151522. 0
  151523. };
  151524. static long _vq_quantlist__44u9_p1_0[] = {
  151525. 1,
  151526. 0,
  151527. 2,
  151528. };
  151529. static long _vq_lengthlist__44u9_p1_0[] = {
  151530. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151531. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151532. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151533. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151534. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151535. 10,
  151536. };
  151537. static float _vq_quantthresh__44u9_p1_0[] = {
  151538. -0.5, 0.5,
  151539. };
  151540. static long _vq_quantmap__44u9_p1_0[] = {
  151541. 1, 0, 2,
  151542. };
  151543. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151544. _vq_quantthresh__44u9_p1_0,
  151545. _vq_quantmap__44u9_p1_0,
  151546. 3,
  151547. 3
  151548. };
  151549. static static_codebook _44u9_p1_0 = {
  151550. 4, 81,
  151551. _vq_lengthlist__44u9_p1_0,
  151552. 1, -535822336, 1611661312, 2, 0,
  151553. _vq_quantlist__44u9_p1_0,
  151554. NULL,
  151555. &_vq_auxt__44u9_p1_0,
  151556. NULL,
  151557. 0
  151558. };
  151559. static long _vq_quantlist__44u9_p2_0[] = {
  151560. 2,
  151561. 1,
  151562. 3,
  151563. 0,
  151564. 4,
  151565. };
  151566. static long _vq_lengthlist__44u9_p2_0[] = {
  151567. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151568. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151569. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151570. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151571. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151572. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151573. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151574. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151575. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151576. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151577. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151578. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151579. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151580. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151581. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151582. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151583. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151584. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151585. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151586. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151587. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151588. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151589. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151590. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151591. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151592. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151593. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151594. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151595. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151596. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151597. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151598. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151599. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151600. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151601. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151602. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151603. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151604. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151605. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151606. 14,
  151607. };
  151608. static float _vq_quantthresh__44u9_p2_0[] = {
  151609. -1.5, -0.5, 0.5, 1.5,
  151610. };
  151611. static long _vq_quantmap__44u9_p2_0[] = {
  151612. 3, 1, 0, 2, 4,
  151613. };
  151614. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151615. _vq_quantthresh__44u9_p2_0,
  151616. _vq_quantmap__44u9_p2_0,
  151617. 5,
  151618. 5
  151619. };
  151620. static static_codebook _44u9_p2_0 = {
  151621. 4, 625,
  151622. _vq_lengthlist__44u9_p2_0,
  151623. 1, -533725184, 1611661312, 3, 0,
  151624. _vq_quantlist__44u9_p2_0,
  151625. NULL,
  151626. &_vq_auxt__44u9_p2_0,
  151627. NULL,
  151628. 0
  151629. };
  151630. static long _vq_quantlist__44u9_p3_0[] = {
  151631. 4,
  151632. 3,
  151633. 5,
  151634. 2,
  151635. 6,
  151636. 1,
  151637. 7,
  151638. 0,
  151639. 8,
  151640. };
  151641. static long _vq_lengthlist__44u9_p3_0[] = {
  151642. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151643. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151644. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151645. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151646. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151647. 11,
  151648. };
  151649. static float _vq_quantthresh__44u9_p3_0[] = {
  151650. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151651. };
  151652. static long _vq_quantmap__44u9_p3_0[] = {
  151653. 7, 5, 3, 1, 0, 2, 4, 6,
  151654. 8,
  151655. };
  151656. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151657. _vq_quantthresh__44u9_p3_0,
  151658. _vq_quantmap__44u9_p3_0,
  151659. 9,
  151660. 9
  151661. };
  151662. static static_codebook _44u9_p3_0 = {
  151663. 2, 81,
  151664. _vq_lengthlist__44u9_p3_0,
  151665. 1, -531628032, 1611661312, 4, 0,
  151666. _vq_quantlist__44u9_p3_0,
  151667. NULL,
  151668. &_vq_auxt__44u9_p3_0,
  151669. NULL,
  151670. 0
  151671. };
  151672. static long _vq_quantlist__44u9_p4_0[] = {
  151673. 8,
  151674. 7,
  151675. 9,
  151676. 6,
  151677. 10,
  151678. 5,
  151679. 11,
  151680. 4,
  151681. 12,
  151682. 3,
  151683. 13,
  151684. 2,
  151685. 14,
  151686. 1,
  151687. 15,
  151688. 0,
  151689. 16,
  151690. };
  151691. static long _vq_lengthlist__44u9_p4_0[] = {
  151692. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151693. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151694. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151695. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151696. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151697. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151698. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151699. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151700. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151701. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151702. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151703. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151704. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151705. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151706. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151707. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151708. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151709. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151710. 14,
  151711. };
  151712. static float _vq_quantthresh__44u9_p4_0[] = {
  151713. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151714. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151715. };
  151716. static long _vq_quantmap__44u9_p4_0[] = {
  151717. 15, 13, 11, 9, 7, 5, 3, 1,
  151718. 0, 2, 4, 6, 8, 10, 12, 14,
  151719. 16,
  151720. };
  151721. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151722. _vq_quantthresh__44u9_p4_0,
  151723. _vq_quantmap__44u9_p4_0,
  151724. 17,
  151725. 17
  151726. };
  151727. static static_codebook _44u9_p4_0 = {
  151728. 2, 289,
  151729. _vq_lengthlist__44u9_p4_0,
  151730. 1, -529530880, 1611661312, 5, 0,
  151731. _vq_quantlist__44u9_p4_0,
  151732. NULL,
  151733. &_vq_auxt__44u9_p4_0,
  151734. NULL,
  151735. 0
  151736. };
  151737. static long _vq_quantlist__44u9_p5_0[] = {
  151738. 1,
  151739. 0,
  151740. 2,
  151741. };
  151742. static long _vq_lengthlist__44u9_p5_0[] = {
  151743. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151744. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151745. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151746. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151747. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151748. 10,
  151749. };
  151750. static float _vq_quantthresh__44u9_p5_0[] = {
  151751. -5.5, 5.5,
  151752. };
  151753. static long _vq_quantmap__44u9_p5_0[] = {
  151754. 1, 0, 2,
  151755. };
  151756. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151757. _vq_quantthresh__44u9_p5_0,
  151758. _vq_quantmap__44u9_p5_0,
  151759. 3,
  151760. 3
  151761. };
  151762. static static_codebook _44u9_p5_0 = {
  151763. 4, 81,
  151764. _vq_lengthlist__44u9_p5_0,
  151765. 1, -529137664, 1618345984, 2, 0,
  151766. _vq_quantlist__44u9_p5_0,
  151767. NULL,
  151768. &_vq_auxt__44u9_p5_0,
  151769. NULL,
  151770. 0
  151771. };
  151772. static long _vq_quantlist__44u9_p5_1[] = {
  151773. 5,
  151774. 4,
  151775. 6,
  151776. 3,
  151777. 7,
  151778. 2,
  151779. 8,
  151780. 1,
  151781. 9,
  151782. 0,
  151783. 10,
  151784. };
  151785. static long _vq_lengthlist__44u9_p5_1[] = {
  151786. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151787. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151788. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151789. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151790. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151791. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151792. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151793. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151794. };
  151795. static float _vq_quantthresh__44u9_p5_1[] = {
  151796. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151797. 3.5, 4.5,
  151798. };
  151799. static long _vq_quantmap__44u9_p5_1[] = {
  151800. 9, 7, 5, 3, 1, 0, 2, 4,
  151801. 6, 8, 10,
  151802. };
  151803. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151804. _vq_quantthresh__44u9_p5_1,
  151805. _vq_quantmap__44u9_p5_1,
  151806. 11,
  151807. 11
  151808. };
  151809. static static_codebook _44u9_p5_1 = {
  151810. 2, 121,
  151811. _vq_lengthlist__44u9_p5_1,
  151812. 1, -531365888, 1611661312, 4, 0,
  151813. _vq_quantlist__44u9_p5_1,
  151814. NULL,
  151815. &_vq_auxt__44u9_p5_1,
  151816. NULL,
  151817. 0
  151818. };
  151819. static long _vq_quantlist__44u9_p6_0[] = {
  151820. 6,
  151821. 5,
  151822. 7,
  151823. 4,
  151824. 8,
  151825. 3,
  151826. 9,
  151827. 2,
  151828. 10,
  151829. 1,
  151830. 11,
  151831. 0,
  151832. 12,
  151833. };
  151834. static long _vq_lengthlist__44u9_p6_0[] = {
  151835. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151836. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151837. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151838. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151839. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151840. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151841. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151842. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151843. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151844. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151845. 10,11,11,11,11,12,11,12,12,
  151846. };
  151847. static float _vq_quantthresh__44u9_p6_0[] = {
  151848. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151849. 12.5, 17.5, 22.5, 27.5,
  151850. };
  151851. static long _vq_quantmap__44u9_p6_0[] = {
  151852. 11, 9, 7, 5, 3, 1, 0, 2,
  151853. 4, 6, 8, 10, 12,
  151854. };
  151855. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151856. _vq_quantthresh__44u9_p6_0,
  151857. _vq_quantmap__44u9_p6_0,
  151858. 13,
  151859. 13
  151860. };
  151861. static static_codebook _44u9_p6_0 = {
  151862. 2, 169,
  151863. _vq_lengthlist__44u9_p6_0,
  151864. 1, -526516224, 1616117760, 4, 0,
  151865. _vq_quantlist__44u9_p6_0,
  151866. NULL,
  151867. &_vq_auxt__44u9_p6_0,
  151868. NULL,
  151869. 0
  151870. };
  151871. static long _vq_quantlist__44u9_p6_1[] = {
  151872. 2,
  151873. 1,
  151874. 3,
  151875. 0,
  151876. 4,
  151877. };
  151878. static long _vq_lengthlist__44u9_p6_1[] = {
  151879. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151880. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151881. };
  151882. static float _vq_quantthresh__44u9_p6_1[] = {
  151883. -1.5, -0.5, 0.5, 1.5,
  151884. };
  151885. static long _vq_quantmap__44u9_p6_1[] = {
  151886. 3, 1, 0, 2, 4,
  151887. };
  151888. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151889. _vq_quantthresh__44u9_p6_1,
  151890. _vq_quantmap__44u9_p6_1,
  151891. 5,
  151892. 5
  151893. };
  151894. static static_codebook _44u9_p6_1 = {
  151895. 2, 25,
  151896. _vq_lengthlist__44u9_p6_1,
  151897. 1, -533725184, 1611661312, 3, 0,
  151898. _vq_quantlist__44u9_p6_1,
  151899. NULL,
  151900. &_vq_auxt__44u9_p6_1,
  151901. NULL,
  151902. 0
  151903. };
  151904. static long _vq_quantlist__44u9_p7_0[] = {
  151905. 6,
  151906. 5,
  151907. 7,
  151908. 4,
  151909. 8,
  151910. 3,
  151911. 9,
  151912. 2,
  151913. 10,
  151914. 1,
  151915. 11,
  151916. 0,
  151917. 12,
  151918. };
  151919. static long _vq_lengthlist__44u9_p7_0[] = {
  151920. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151921. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151922. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151923. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151924. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151925. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151926. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151927. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151928. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151929. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151930. 12,13,13,14,14,14,15,15,15,
  151931. };
  151932. static float _vq_quantthresh__44u9_p7_0[] = {
  151933. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151934. 27.5, 38.5, 49.5, 60.5,
  151935. };
  151936. static long _vq_quantmap__44u9_p7_0[] = {
  151937. 11, 9, 7, 5, 3, 1, 0, 2,
  151938. 4, 6, 8, 10, 12,
  151939. };
  151940. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151941. _vq_quantthresh__44u9_p7_0,
  151942. _vq_quantmap__44u9_p7_0,
  151943. 13,
  151944. 13
  151945. };
  151946. static static_codebook _44u9_p7_0 = {
  151947. 2, 169,
  151948. _vq_lengthlist__44u9_p7_0,
  151949. 1, -523206656, 1618345984, 4, 0,
  151950. _vq_quantlist__44u9_p7_0,
  151951. NULL,
  151952. &_vq_auxt__44u9_p7_0,
  151953. NULL,
  151954. 0
  151955. };
  151956. static long _vq_quantlist__44u9_p7_1[] = {
  151957. 5,
  151958. 4,
  151959. 6,
  151960. 3,
  151961. 7,
  151962. 2,
  151963. 8,
  151964. 1,
  151965. 9,
  151966. 0,
  151967. 10,
  151968. };
  151969. static long _vq_lengthlist__44u9_p7_1[] = {
  151970. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151971. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151972. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151973. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151974. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151975. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151976. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151977. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151978. };
  151979. static float _vq_quantthresh__44u9_p7_1[] = {
  151980. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151981. 3.5, 4.5,
  151982. };
  151983. static long _vq_quantmap__44u9_p7_1[] = {
  151984. 9, 7, 5, 3, 1, 0, 2, 4,
  151985. 6, 8, 10,
  151986. };
  151987. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151988. _vq_quantthresh__44u9_p7_1,
  151989. _vq_quantmap__44u9_p7_1,
  151990. 11,
  151991. 11
  151992. };
  151993. static static_codebook _44u9_p7_1 = {
  151994. 2, 121,
  151995. _vq_lengthlist__44u9_p7_1,
  151996. 1, -531365888, 1611661312, 4, 0,
  151997. _vq_quantlist__44u9_p7_1,
  151998. NULL,
  151999. &_vq_auxt__44u9_p7_1,
  152000. NULL,
  152001. 0
  152002. };
  152003. static long _vq_quantlist__44u9_p8_0[] = {
  152004. 7,
  152005. 6,
  152006. 8,
  152007. 5,
  152008. 9,
  152009. 4,
  152010. 10,
  152011. 3,
  152012. 11,
  152013. 2,
  152014. 12,
  152015. 1,
  152016. 13,
  152017. 0,
  152018. 14,
  152019. };
  152020. static long _vq_lengthlist__44u9_p8_0[] = {
  152021. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152022. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152023. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152024. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152025. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152026. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152027. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152028. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152029. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152030. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152031. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152032. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152033. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152034. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152035. 15,
  152036. };
  152037. static float _vq_quantthresh__44u9_p8_0[] = {
  152038. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152039. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152040. };
  152041. static long _vq_quantmap__44u9_p8_0[] = {
  152042. 13, 11, 9, 7, 5, 3, 1, 0,
  152043. 2, 4, 6, 8, 10, 12, 14,
  152044. };
  152045. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152046. _vq_quantthresh__44u9_p8_0,
  152047. _vq_quantmap__44u9_p8_0,
  152048. 15,
  152049. 15
  152050. };
  152051. static static_codebook _44u9_p8_0 = {
  152052. 2, 225,
  152053. _vq_lengthlist__44u9_p8_0,
  152054. 1, -520986624, 1620377600, 4, 0,
  152055. _vq_quantlist__44u9_p8_0,
  152056. NULL,
  152057. &_vq_auxt__44u9_p8_0,
  152058. NULL,
  152059. 0
  152060. };
  152061. static long _vq_quantlist__44u9_p8_1[] = {
  152062. 10,
  152063. 9,
  152064. 11,
  152065. 8,
  152066. 12,
  152067. 7,
  152068. 13,
  152069. 6,
  152070. 14,
  152071. 5,
  152072. 15,
  152073. 4,
  152074. 16,
  152075. 3,
  152076. 17,
  152077. 2,
  152078. 18,
  152079. 1,
  152080. 19,
  152081. 0,
  152082. 20,
  152083. };
  152084. static long _vq_lengthlist__44u9_p8_1[] = {
  152085. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152086. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152087. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152088. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152089. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152090. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152091. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152092. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152093. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152094. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152095. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152096. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152097. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152098. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152099. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152100. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152101. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152102. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152103. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152104. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152105. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152106. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152107. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152108. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152109. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152110. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152111. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152112. 10,10,10,10,10,10,10,10,10,
  152113. };
  152114. static float _vq_quantthresh__44u9_p8_1[] = {
  152115. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152116. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152117. 6.5, 7.5, 8.5, 9.5,
  152118. };
  152119. static long _vq_quantmap__44u9_p8_1[] = {
  152120. 19, 17, 15, 13, 11, 9, 7, 5,
  152121. 3, 1, 0, 2, 4, 6, 8, 10,
  152122. 12, 14, 16, 18, 20,
  152123. };
  152124. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152125. _vq_quantthresh__44u9_p8_1,
  152126. _vq_quantmap__44u9_p8_1,
  152127. 21,
  152128. 21
  152129. };
  152130. static static_codebook _44u9_p8_1 = {
  152131. 2, 441,
  152132. _vq_lengthlist__44u9_p8_1,
  152133. 1, -529268736, 1611661312, 5, 0,
  152134. _vq_quantlist__44u9_p8_1,
  152135. NULL,
  152136. &_vq_auxt__44u9_p8_1,
  152137. NULL,
  152138. 0
  152139. };
  152140. static long _vq_quantlist__44u9_p9_0[] = {
  152141. 7,
  152142. 6,
  152143. 8,
  152144. 5,
  152145. 9,
  152146. 4,
  152147. 10,
  152148. 3,
  152149. 11,
  152150. 2,
  152151. 12,
  152152. 1,
  152153. 13,
  152154. 0,
  152155. 14,
  152156. };
  152157. static long _vq_lengthlist__44u9_p9_0[] = {
  152158. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152159. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152160. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152163. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152164. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152170. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152171. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152172. 10,
  152173. };
  152174. static float _vq_quantthresh__44u9_p9_0[] = {
  152175. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152176. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152177. };
  152178. static long _vq_quantmap__44u9_p9_0[] = {
  152179. 13, 11, 9, 7, 5, 3, 1, 0,
  152180. 2, 4, 6, 8, 10, 12, 14,
  152181. };
  152182. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152183. _vq_quantthresh__44u9_p9_0,
  152184. _vq_quantmap__44u9_p9_0,
  152185. 15,
  152186. 15
  152187. };
  152188. static static_codebook _44u9_p9_0 = {
  152189. 2, 225,
  152190. _vq_lengthlist__44u9_p9_0,
  152191. 1, -510036736, 1631393792, 4, 0,
  152192. _vq_quantlist__44u9_p9_0,
  152193. NULL,
  152194. &_vq_auxt__44u9_p9_0,
  152195. NULL,
  152196. 0
  152197. };
  152198. static long _vq_quantlist__44u9_p9_1[] = {
  152199. 9,
  152200. 8,
  152201. 10,
  152202. 7,
  152203. 11,
  152204. 6,
  152205. 12,
  152206. 5,
  152207. 13,
  152208. 4,
  152209. 14,
  152210. 3,
  152211. 15,
  152212. 2,
  152213. 16,
  152214. 1,
  152215. 17,
  152216. 0,
  152217. 18,
  152218. };
  152219. static long _vq_lengthlist__44u9_p9_1[] = {
  152220. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152221. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152222. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152223. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152224. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152225. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152226. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152227. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152228. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152229. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152230. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152231. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152232. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152233. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152234. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152235. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152236. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152237. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152238. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152239. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152240. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152241. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152242. 17,17,15,17,15,17,16,16,17,
  152243. };
  152244. static float _vq_quantthresh__44u9_p9_1[] = {
  152245. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152246. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152247. 367.5, 416.5,
  152248. };
  152249. static long _vq_quantmap__44u9_p9_1[] = {
  152250. 17, 15, 13, 11, 9, 7, 5, 3,
  152251. 1, 0, 2, 4, 6, 8, 10, 12,
  152252. 14, 16, 18,
  152253. };
  152254. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152255. _vq_quantthresh__44u9_p9_1,
  152256. _vq_quantmap__44u9_p9_1,
  152257. 19,
  152258. 19
  152259. };
  152260. static static_codebook _44u9_p9_1 = {
  152261. 2, 361,
  152262. _vq_lengthlist__44u9_p9_1,
  152263. 1, -518287360, 1622704128, 5, 0,
  152264. _vq_quantlist__44u9_p9_1,
  152265. NULL,
  152266. &_vq_auxt__44u9_p9_1,
  152267. NULL,
  152268. 0
  152269. };
  152270. static long _vq_quantlist__44u9_p9_2[] = {
  152271. 24,
  152272. 23,
  152273. 25,
  152274. 22,
  152275. 26,
  152276. 21,
  152277. 27,
  152278. 20,
  152279. 28,
  152280. 19,
  152281. 29,
  152282. 18,
  152283. 30,
  152284. 17,
  152285. 31,
  152286. 16,
  152287. 32,
  152288. 15,
  152289. 33,
  152290. 14,
  152291. 34,
  152292. 13,
  152293. 35,
  152294. 12,
  152295. 36,
  152296. 11,
  152297. 37,
  152298. 10,
  152299. 38,
  152300. 9,
  152301. 39,
  152302. 8,
  152303. 40,
  152304. 7,
  152305. 41,
  152306. 6,
  152307. 42,
  152308. 5,
  152309. 43,
  152310. 4,
  152311. 44,
  152312. 3,
  152313. 45,
  152314. 2,
  152315. 46,
  152316. 1,
  152317. 47,
  152318. 0,
  152319. 48,
  152320. };
  152321. static long _vq_lengthlist__44u9_p9_2[] = {
  152322. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152323. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152324. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152325. 7,
  152326. };
  152327. static float _vq_quantthresh__44u9_p9_2[] = {
  152328. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152329. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152330. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152331. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152332. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152333. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152334. };
  152335. static long _vq_quantmap__44u9_p9_2[] = {
  152336. 47, 45, 43, 41, 39, 37, 35, 33,
  152337. 31, 29, 27, 25, 23, 21, 19, 17,
  152338. 15, 13, 11, 9, 7, 5, 3, 1,
  152339. 0, 2, 4, 6, 8, 10, 12, 14,
  152340. 16, 18, 20, 22, 24, 26, 28, 30,
  152341. 32, 34, 36, 38, 40, 42, 44, 46,
  152342. 48,
  152343. };
  152344. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152345. _vq_quantthresh__44u9_p9_2,
  152346. _vq_quantmap__44u9_p9_2,
  152347. 49,
  152348. 49
  152349. };
  152350. static static_codebook _44u9_p9_2 = {
  152351. 1, 49,
  152352. _vq_lengthlist__44u9_p9_2,
  152353. 1, -526909440, 1611661312, 6, 0,
  152354. _vq_quantlist__44u9_p9_2,
  152355. NULL,
  152356. &_vq_auxt__44u9_p9_2,
  152357. NULL,
  152358. 0
  152359. };
  152360. static long _huff_lengthlist__44un1__long[] = {
  152361. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152362. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152363. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152364. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152365. };
  152366. static static_codebook _huff_book__44un1__long = {
  152367. 2, 64,
  152368. _huff_lengthlist__44un1__long,
  152369. 0, 0, 0, 0, 0,
  152370. NULL,
  152371. NULL,
  152372. NULL,
  152373. NULL,
  152374. 0
  152375. };
  152376. static long _vq_quantlist__44un1__p1_0[] = {
  152377. 1,
  152378. 0,
  152379. 2,
  152380. };
  152381. static long _vq_lengthlist__44un1__p1_0[] = {
  152382. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152383. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152384. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152385. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152386. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152387. 12,
  152388. };
  152389. static float _vq_quantthresh__44un1__p1_0[] = {
  152390. -0.5, 0.5,
  152391. };
  152392. static long _vq_quantmap__44un1__p1_0[] = {
  152393. 1, 0, 2,
  152394. };
  152395. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152396. _vq_quantthresh__44un1__p1_0,
  152397. _vq_quantmap__44un1__p1_0,
  152398. 3,
  152399. 3
  152400. };
  152401. static static_codebook _44un1__p1_0 = {
  152402. 4, 81,
  152403. _vq_lengthlist__44un1__p1_0,
  152404. 1, -535822336, 1611661312, 2, 0,
  152405. _vq_quantlist__44un1__p1_0,
  152406. NULL,
  152407. &_vq_auxt__44un1__p1_0,
  152408. NULL,
  152409. 0
  152410. };
  152411. static long _vq_quantlist__44un1__p2_0[] = {
  152412. 1,
  152413. 0,
  152414. 2,
  152415. };
  152416. static long _vq_lengthlist__44un1__p2_0[] = {
  152417. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152418. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152419. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152420. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152421. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152422. 8,
  152423. };
  152424. static float _vq_quantthresh__44un1__p2_0[] = {
  152425. -0.5, 0.5,
  152426. };
  152427. static long _vq_quantmap__44un1__p2_0[] = {
  152428. 1, 0, 2,
  152429. };
  152430. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152431. _vq_quantthresh__44un1__p2_0,
  152432. _vq_quantmap__44un1__p2_0,
  152433. 3,
  152434. 3
  152435. };
  152436. static static_codebook _44un1__p2_0 = {
  152437. 4, 81,
  152438. _vq_lengthlist__44un1__p2_0,
  152439. 1, -535822336, 1611661312, 2, 0,
  152440. _vq_quantlist__44un1__p2_0,
  152441. NULL,
  152442. &_vq_auxt__44un1__p2_0,
  152443. NULL,
  152444. 0
  152445. };
  152446. static long _vq_quantlist__44un1__p3_0[] = {
  152447. 2,
  152448. 1,
  152449. 3,
  152450. 0,
  152451. 4,
  152452. };
  152453. static long _vq_lengthlist__44un1__p3_0[] = {
  152454. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152455. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152456. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152457. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152458. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152459. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152460. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152461. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152462. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152463. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152464. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152465. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152466. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152467. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152468. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152469. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152470. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152471. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152472. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152473. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152474. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152475. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152476. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152477. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152478. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152479. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152480. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152481. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152482. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152483. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152484. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152485. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152486. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152487. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152488. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152489. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152490. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152491. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152492. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152493. 17,
  152494. };
  152495. static float _vq_quantthresh__44un1__p3_0[] = {
  152496. -1.5, -0.5, 0.5, 1.5,
  152497. };
  152498. static long _vq_quantmap__44un1__p3_0[] = {
  152499. 3, 1, 0, 2, 4,
  152500. };
  152501. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152502. _vq_quantthresh__44un1__p3_0,
  152503. _vq_quantmap__44un1__p3_0,
  152504. 5,
  152505. 5
  152506. };
  152507. static static_codebook _44un1__p3_0 = {
  152508. 4, 625,
  152509. _vq_lengthlist__44un1__p3_0,
  152510. 1, -533725184, 1611661312, 3, 0,
  152511. _vq_quantlist__44un1__p3_0,
  152512. NULL,
  152513. &_vq_auxt__44un1__p3_0,
  152514. NULL,
  152515. 0
  152516. };
  152517. static long _vq_quantlist__44un1__p4_0[] = {
  152518. 2,
  152519. 1,
  152520. 3,
  152521. 0,
  152522. 4,
  152523. };
  152524. static long _vq_lengthlist__44un1__p4_0[] = {
  152525. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152526. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152527. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152528. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152529. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152530. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152531. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152532. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152533. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152534. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152535. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152536. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152537. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152538. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152539. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152540. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152541. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152542. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152543. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152544. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152545. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152546. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152547. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152548. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152549. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152550. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152551. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152552. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152553. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152554. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152555. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152556. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152557. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152558. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152559. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152560. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152561. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152562. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152563. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152564. 12,
  152565. };
  152566. static float _vq_quantthresh__44un1__p4_0[] = {
  152567. -1.5, -0.5, 0.5, 1.5,
  152568. };
  152569. static long _vq_quantmap__44un1__p4_0[] = {
  152570. 3, 1, 0, 2, 4,
  152571. };
  152572. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152573. _vq_quantthresh__44un1__p4_0,
  152574. _vq_quantmap__44un1__p4_0,
  152575. 5,
  152576. 5
  152577. };
  152578. static static_codebook _44un1__p4_0 = {
  152579. 4, 625,
  152580. _vq_lengthlist__44un1__p4_0,
  152581. 1, -533725184, 1611661312, 3, 0,
  152582. _vq_quantlist__44un1__p4_0,
  152583. NULL,
  152584. &_vq_auxt__44un1__p4_0,
  152585. NULL,
  152586. 0
  152587. };
  152588. static long _vq_quantlist__44un1__p5_0[] = {
  152589. 4,
  152590. 3,
  152591. 5,
  152592. 2,
  152593. 6,
  152594. 1,
  152595. 7,
  152596. 0,
  152597. 8,
  152598. };
  152599. static long _vq_lengthlist__44un1__p5_0[] = {
  152600. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152601. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152602. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152603. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152604. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152605. 12,
  152606. };
  152607. static float _vq_quantthresh__44un1__p5_0[] = {
  152608. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152609. };
  152610. static long _vq_quantmap__44un1__p5_0[] = {
  152611. 7, 5, 3, 1, 0, 2, 4, 6,
  152612. 8,
  152613. };
  152614. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152615. _vq_quantthresh__44un1__p5_0,
  152616. _vq_quantmap__44un1__p5_0,
  152617. 9,
  152618. 9
  152619. };
  152620. static static_codebook _44un1__p5_0 = {
  152621. 2, 81,
  152622. _vq_lengthlist__44un1__p5_0,
  152623. 1, -531628032, 1611661312, 4, 0,
  152624. _vq_quantlist__44un1__p5_0,
  152625. NULL,
  152626. &_vq_auxt__44un1__p5_0,
  152627. NULL,
  152628. 0
  152629. };
  152630. static long _vq_quantlist__44un1__p6_0[] = {
  152631. 6,
  152632. 5,
  152633. 7,
  152634. 4,
  152635. 8,
  152636. 3,
  152637. 9,
  152638. 2,
  152639. 10,
  152640. 1,
  152641. 11,
  152642. 0,
  152643. 12,
  152644. };
  152645. static long _vq_lengthlist__44un1__p6_0[] = {
  152646. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152647. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152648. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152649. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152650. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152651. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152652. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152653. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152654. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152655. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152656. 16, 0,15,18,18, 0,16, 0, 0,
  152657. };
  152658. static float _vq_quantthresh__44un1__p6_0[] = {
  152659. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152660. 12.5, 17.5, 22.5, 27.5,
  152661. };
  152662. static long _vq_quantmap__44un1__p6_0[] = {
  152663. 11, 9, 7, 5, 3, 1, 0, 2,
  152664. 4, 6, 8, 10, 12,
  152665. };
  152666. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152667. _vq_quantthresh__44un1__p6_0,
  152668. _vq_quantmap__44un1__p6_0,
  152669. 13,
  152670. 13
  152671. };
  152672. static static_codebook _44un1__p6_0 = {
  152673. 2, 169,
  152674. _vq_lengthlist__44un1__p6_0,
  152675. 1, -526516224, 1616117760, 4, 0,
  152676. _vq_quantlist__44un1__p6_0,
  152677. NULL,
  152678. &_vq_auxt__44un1__p6_0,
  152679. NULL,
  152680. 0
  152681. };
  152682. static long _vq_quantlist__44un1__p6_1[] = {
  152683. 2,
  152684. 1,
  152685. 3,
  152686. 0,
  152687. 4,
  152688. };
  152689. static long _vq_lengthlist__44un1__p6_1[] = {
  152690. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152691. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152692. };
  152693. static float _vq_quantthresh__44un1__p6_1[] = {
  152694. -1.5, -0.5, 0.5, 1.5,
  152695. };
  152696. static long _vq_quantmap__44un1__p6_1[] = {
  152697. 3, 1, 0, 2, 4,
  152698. };
  152699. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152700. _vq_quantthresh__44un1__p6_1,
  152701. _vq_quantmap__44un1__p6_1,
  152702. 5,
  152703. 5
  152704. };
  152705. static static_codebook _44un1__p6_1 = {
  152706. 2, 25,
  152707. _vq_lengthlist__44un1__p6_1,
  152708. 1, -533725184, 1611661312, 3, 0,
  152709. _vq_quantlist__44un1__p6_1,
  152710. NULL,
  152711. &_vq_auxt__44un1__p6_1,
  152712. NULL,
  152713. 0
  152714. };
  152715. static long _vq_quantlist__44un1__p7_0[] = {
  152716. 2,
  152717. 1,
  152718. 3,
  152719. 0,
  152720. 4,
  152721. };
  152722. static long _vq_lengthlist__44un1__p7_0[] = {
  152723. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152724. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152726. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152730. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152738. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152740. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152752. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152759. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152760. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152761. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152762. 10,
  152763. };
  152764. static float _vq_quantthresh__44un1__p7_0[] = {
  152765. -253.5, -84.5, 84.5, 253.5,
  152766. };
  152767. static long _vq_quantmap__44un1__p7_0[] = {
  152768. 3, 1, 0, 2, 4,
  152769. };
  152770. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152771. _vq_quantthresh__44un1__p7_0,
  152772. _vq_quantmap__44un1__p7_0,
  152773. 5,
  152774. 5
  152775. };
  152776. static static_codebook _44un1__p7_0 = {
  152777. 4, 625,
  152778. _vq_lengthlist__44un1__p7_0,
  152779. 1, -518709248, 1626677248, 3, 0,
  152780. _vq_quantlist__44un1__p7_0,
  152781. NULL,
  152782. &_vq_auxt__44un1__p7_0,
  152783. NULL,
  152784. 0
  152785. };
  152786. static long _vq_quantlist__44un1__p7_1[] = {
  152787. 6,
  152788. 5,
  152789. 7,
  152790. 4,
  152791. 8,
  152792. 3,
  152793. 9,
  152794. 2,
  152795. 10,
  152796. 1,
  152797. 11,
  152798. 0,
  152799. 12,
  152800. };
  152801. static long _vq_lengthlist__44un1__p7_1[] = {
  152802. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152803. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152804. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152805. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152806. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152807. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152808. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152809. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152810. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152811. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152812. 12,13,13,12,13,13,14,14,14,
  152813. };
  152814. static float _vq_quantthresh__44un1__p7_1[] = {
  152815. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152816. 32.5, 45.5, 58.5, 71.5,
  152817. };
  152818. static long _vq_quantmap__44un1__p7_1[] = {
  152819. 11, 9, 7, 5, 3, 1, 0, 2,
  152820. 4, 6, 8, 10, 12,
  152821. };
  152822. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152823. _vq_quantthresh__44un1__p7_1,
  152824. _vq_quantmap__44un1__p7_1,
  152825. 13,
  152826. 13
  152827. };
  152828. static static_codebook _44un1__p7_1 = {
  152829. 2, 169,
  152830. _vq_lengthlist__44un1__p7_1,
  152831. 1, -523010048, 1618608128, 4, 0,
  152832. _vq_quantlist__44un1__p7_1,
  152833. NULL,
  152834. &_vq_auxt__44un1__p7_1,
  152835. NULL,
  152836. 0
  152837. };
  152838. static long _vq_quantlist__44un1__p7_2[] = {
  152839. 6,
  152840. 5,
  152841. 7,
  152842. 4,
  152843. 8,
  152844. 3,
  152845. 9,
  152846. 2,
  152847. 10,
  152848. 1,
  152849. 11,
  152850. 0,
  152851. 12,
  152852. };
  152853. static long _vq_lengthlist__44un1__p7_2[] = {
  152854. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152855. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152856. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152857. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152858. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152859. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152860. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152861. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152862. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152863. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152864. 9, 9, 9,10,10,10,10,10,10,
  152865. };
  152866. static float _vq_quantthresh__44un1__p7_2[] = {
  152867. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152868. 2.5, 3.5, 4.5, 5.5,
  152869. };
  152870. static long _vq_quantmap__44un1__p7_2[] = {
  152871. 11, 9, 7, 5, 3, 1, 0, 2,
  152872. 4, 6, 8, 10, 12,
  152873. };
  152874. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152875. _vq_quantthresh__44un1__p7_2,
  152876. _vq_quantmap__44un1__p7_2,
  152877. 13,
  152878. 13
  152879. };
  152880. static static_codebook _44un1__p7_2 = {
  152881. 2, 169,
  152882. _vq_lengthlist__44un1__p7_2,
  152883. 1, -531103744, 1611661312, 4, 0,
  152884. _vq_quantlist__44un1__p7_2,
  152885. NULL,
  152886. &_vq_auxt__44un1__p7_2,
  152887. NULL,
  152888. 0
  152889. };
  152890. static long _huff_lengthlist__44un1__short[] = {
  152891. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152892. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152893. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152894. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152895. };
  152896. static static_codebook _huff_book__44un1__short = {
  152897. 2, 64,
  152898. _huff_lengthlist__44un1__short,
  152899. 0, 0, 0, 0, 0,
  152900. NULL,
  152901. NULL,
  152902. NULL,
  152903. NULL,
  152904. 0
  152905. };
  152906. /*** End of inlined file: res_books_uncoupled.h ***/
  152907. /***** residue backends *********************************************/
  152908. static vorbis_info_residue0 _residue_44_low_un={
  152909. 0,-1, -1, 8,-1,
  152910. {0},
  152911. {-1},
  152912. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152913. { -1, 25, -1, 45, -1, -1, -1}
  152914. };
  152915. static vorbis_info_residue0 _residue_44_mid_un={
  152916. 0,-1, -1, 10,-1,
  152917. /* 0 1 2 3 4 5 6 7 8 9 */
  152918. {0},
  152919. {-1},
  152920. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152921. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152922. };
  152923. static vorbis_info_residue0 _residue_44_hi_un={
  152924. 0,-1, -1, 10,-1,
  152925. /* 0 1 2 3 4 5 6 7 8 9 */
  152926. {0},
  152927. {-1},
  152928. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152929. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152930. };
  152931. /* mapping conventions:
  152932. only one submap (this would change for efficient 5.1 support for example)*/
  152933. /* Four psychoacoustic profiles are used, one for each blocktype */
  152934. static vorbis_info_mapping0 _map_nominal_u[2]={
  152935. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152936. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152937. };
  152938. static static_bookblock _resbook_44u_n1={
  152939. {
  152940. {0},
  152941. {0,0,&_44un1__p1_0},
  152942. {0,0,&_44un1__p2_0},
  152943. {0,0,&_44un1__p3_0},
  152944. {0,0,&_44un1__p4_0},
  152945. {0,0,&_44un1__p5_0},
  152946. {&_44un1__p6_0,&_44un1__p6_1},
  152947. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152948. }
  152949. };
  152950. static static_bookblock _resbook_44u_0={
  152951. {
  152952. {0},
  152953. {0,0,&_44u0__p1_0},
  152954. {0,0,&_44u0__p2_0},
  152955. {0,0,&_44u0__p3_0},
  152956. {0,0,&_44u0__p4_0},
  152957. {0,0,&_44u0__p5_0},
  152958. {&_44u0__p6_0,&_44u0__p6_1},
  152959. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152960. }
  152961. };
  152962. static static_bookblock _resbook_44u_1={
  152963. {
  152964. {0},
  152965. {0,0,&_44u1__p1_0},
  152966. {0,0,&_44u1__p2_0},
  152967. {0,0,&_44u1__p3_0},
  152968. {0,0,&_44u1__p4_0},
  152969. {0,0,&_44u1__p5_0},
  152970. {&_44u1__p6_0,&_44u1__p6_1},
  152971. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152972. }
  152973. };
  152974. static static_bookblock _resbook_44u_2={
  152975. {
  152976. {0},
  152977. {0,0,&_44u2__p1_0},
  152978. {0,0,&_44u2__p2_0},
  152979. {0,0,&_44u2__p3_0},
  152980. {0,0,&_44u2__p4_0},
  152981. {0,0,&_44u2__p5_0},
  152982. {&_44u2__p6_0,&_44u2__p6_1},
  152983. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152984. }
  152985. };
  152986. static static_bookblock _resbook_44u_3={
  152987. {
  152988. {0},
  152989. {0,0,&_44u3__p1_0},
  152990. {0,0,&_44u3__p2_0},
  152991. {0,0,&_44u3__p3_0},
  152992. {0,0,&_44u3__p4_0},
  152993. {0,0,&_44u3__p5_0},
  152994. {&_44u3__p6_0,&_44u3__p6_1},
  152995. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152996. }
  152997. };
  152998. static static_bookblock _resbook_44u_4={
  152999. {
  153000. {0},
  153001. {0,0,&_44u4__p1_0},
  153002. {0,0,&_44u4__p2_0},
  153003. {0,0,&_44u4__p3_0},
  153004. {0,0,&_44u4__p4_0},
  153005. {0,0,&_44u4__p5_0},
  153006. {&_44u4__p6_0,&_44u4__p6_1},
  153007. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153008. }
  153009. };
  153010. static static_bookblock _resbook_44u_5={
  153011. {
  153012. {0},
  153013. {0,0,&_44u5__p1_0},
  153014. {0,0,&_44u5__p2_0},
  153015. {0,0,&_44u5__p3_0},
  153016. {0,0,&_44u5__p4_0},
  153017. {0,0,&_44u5__p5_0},
  153018. {0,0,&_44u5__p6_0},
  153019. {&_44u5__p7_0,&_44u5__p7_1},
  153020. {&_44u5__p8_0,&_44u5__p8_1},
  153021. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153022. }
  153023. };
  153024. static static_bookblock _resbook_44u_6={
  153025. {
  153026. {0},
  153027. {0,0,&_44u6__p1_0},
  153028. {0,0,&_44u6__p2_0},
  153029. {0,0,&_44u6__p3_0},
  153030. {0,0,&_44u6__p4_0},
  153031. {0,0,&_44u6__p5_0},
  153032. {0,0,&_44u6__p6_0},
  153033. {&_44u6__p7_0,&_44u6__p7_1},
  153034. {&_44u6__p8_0,&_44u6__p8_1},
  153035. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153036. }
  153037. };
  153038. static static_bookblock _resbook_44u_7={
  153039. {
  153040. {0},
  153041. {0,0,&_44u7__p1_0},
  153042. {0,0,&_44u7__p2_0},
  153043. {0,0,&_44u7__p3_0},
  153044. {0,0,&_44u7__p4_0},
  153045. {0,0,&_44u7__p5_0},
  153046. {0,0,&_44u7__p6_0},
  153047. {&_44u7__p7_0,&_44u7__p7_1},
  153048. {&_44u7__p8_0,&_44u7__p8_1},
  153049. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153050. }
  153051. };
  153052. static static_bookblock _resbook_44u_8={
  153053. {
  153054. {0},
  153055. {0,0,&_44u8_p1_0},
  153056. {0,0,&_44u8_p2_0},
  153057. {0,0,&_44u8_p3_0},
  153058. {0,0,&_44u8_p4_0},
  153059. {&_44u8_p5_0,&_44u8_p5_1},
  153060. {&_44u8_p6_0,&_44u8_p6_1},
  153061. {&_44u8_p7_0,&_44u8_p7_1},
  153062. {&_44u8_p8_0,&_44u8_p8_1},
  153063. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153064. }
  153065. };
  153066. static static_bookblock _resbook_44u_9={
  153067. {
  153068. {0},
  153069. {0,0,&_44u9_p1_0},
  153070. {0,0,&_44u9_p2_0},
  153071. {0,0,&_44u9_p3_0},
  153072. {0,0,&_44u9_p4_0},
  153073. {&_44u9_p5_0,&_44u9_p5_1},
  153074. {&_44u9_p6_0,&_44u9_p6_1},
  153075. {&_44u9_p7_0,&_44u9_p7_1},
  153076. {&_44u9_p8_0,&_44u9_p8_1},
  153077. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153078. }
  153079. };
  153080. static vorbis_residue_template _res_44u_n1[]={
  153081. {1,0, &_residue_44_low_un,
  153082. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153083. &_resbook_44u_n1,&_resbook_44u_n1},
  153084. {1,0, &_residue_44_low_un,
  153085. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153086. &_resbook_44u_n1,&_resbook_44u_n1}
  153087. };
  153088. static vorbis_residue_template _res_44u_0[]={
  153089. {1,0, &_residue_44_low_un,
  153090. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153091. &_resbook_44u_0,&_resbook_44u_0},
  153092. {1,0, &_residue_44_low_un,
  153093. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153094. &_resbook_44u_0,&_resbook_44u_0}
  153095. };
  153096. static vorbis_residue_template _res_44u_1[]={
  153097. {1,0, &_residue_44_low_un,
  153098. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153099. &_resbook_44u_1,&_resbook_44u_1},
  153100. {1,0, &_residue_44_low_un,
  153101. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153102. &_resbook_44u_1,&_resbook_44u_1}
  153103. };
  153104. static vorbis_residue_template _res_44u_2[]={
  153105. {1,0, &_residue_44_low_un,
  153106. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153107. &_resbook_44u_2,&_resbook_44u_2},
  153108. {1,0, &_residue_44_low_un,
  153109. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153110. &_resbook_44u_2,&_resbook_44u_2}
  153111. };
  153112. static vorbis_residue_template _res_44u_3[]={
  153113. {1,0, &_residue_44_low_un,
  153114. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153115. &_resbook_44u_3,&_resbook_44u_3},
  153116. {1,0, &_residue_44_low_un,
  153117. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153118. &_resbook_44u_3,&_resbook_44u_3}
  153119. };
  153120. static vorbis_residue_template _res_44u_4[]={
  153121. {1,0, &_residue_44_low_un,
  153122. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153123. &_resbook_44u_4,&_resbook_44u_4},
  153124. {1,0, &_residue_44_low_un,
  153125. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153126. &_resbook_44u_4,&_resbook_44u_4}
  153127. };
  153128. static vorbis_residue_template _res_44u_5[]={
  153129. {1,0, &_residue_44_mid_un,
  153130. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153131. &_resbook_44u_5,&_resbook_44u_5},
  153132. {1,0, &_residue_44_mid_un,
  153133. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153134. &_resbook_44u_5,&_resbook_44u_5}
  153135. };
  153136. static vorbis_residue_template _res_44u_6[]={
  153137. {1,0, &_residue_44_mid_un,
  153138. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153139. &_resbook_44u_6,&_resbook_44u_6},
  153140. {1,0, &_residue_44_mid_un,
  153141. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153142. &_resbook_44u_6,&_resbook_44u_6}
  153143. };
  153144. static vorbis_residue_template _res_44u_7[]={
  153145. {1,0, &_residue_44_mid_un,
  153146. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153147. &_resbook_44u_7,&_resbook_44u_7},
  153148. {1,0, &_residue_44_mid_un,
  153149. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153150. &_resbook_44u_7,&_resbook_44u_7}
  153151. };
  153152. static vorbis_residue_template _res_44u_8[]={
  153153. {1,0, &_residue_44_hi_un,
  153154. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153155. &_resbook_44u_8,&_resbook_44u_8},
  153156. {1,0, &_residue_44_hi_un,
  153157. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153158. &_resbook_44u_8,&_resbook_44u_8}
  153159. };
  153160. static vorbis_residue_template _res_44u_9[]={
  153161. {1,0, &_residue_44_hi_un,
  153162. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153163. &_resbook_44u_9,&_resbook_44u_9},
  153164. {1,0, &_residue_44_hi_un,
  153165. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153166. &_resbook_44u_9,&_resbook_44u_9}
  153167. };
  153168. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153169. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153170. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153171. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153172. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153173. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153174. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153175. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153176. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153177. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153178. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153179. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153180. };
  153181. /*** End of inlined file: residue_44u.h ***/
  153182. static double rate_mapping_44_un[12]={
  153183. 32000.,48000.,60000.,70000.,80000.,86000.,
  153184. 96000.,110000.,120000.,140000.,160000.,240001.
  153185. };
  153186. ve_setup_data_template ve_setup_44_uncoupled={
  153187. 11,
  153188. rate_mapping_44_un,
  153189. quality_mapping_44,
  153190. -1,
  153191. 40000,
  153192. 50000,
  153193. blocksize_short_44,
  153194. blocksize_long_44,
  153195. _psy_tone_masteratt_44,
  153196. _psy_tone_0dB,
  153197. _psy_tone_suppress,
  153198. _vp_tonemask_adj_otherblock,
  153199. _vp_tonemask_adj_longblock,
  153200. _vp_tonemask_adj_otherblock,
  153201. _psy_noiseguards_44,
  153202. _psy_noisebias_impulse,
  153203. _psy_noisebias_padding,
  153204. _psy_noisebias_trans,
  153205. _psy_noisebias_long,
  153206. _psy_noise_suppress,
  153207. _psy_compand_44,
  153208. _psy_compand_short_mapping,
  153209. _psy_compand_long_mapping,
  153210. {_noise_start_short_44,_noise_start_long_44},
  153211. {_noise_part_short_44,_noise_part_long_44},
  153212. _noise_thresh_44,
  153213. _psy_ath_floater,
  153214. _psy_ath_abs,
  153215. _psy_lowpass_44,
  153216. _psy_global_44,
  153217. _global_mapping_44,
  153218. NULL,
  153219. _floor_books,
  153220. _floor,
  153221. _floor_short_mapping_44,
  153222. _floor_long_mapping_44,
  153223. _mapres_template_44_uncoupled
  153224. };
  153225. /*** End of inlined file: setup_44u.h ***/
  153226. /*** Start of inlined file: setup_32.h ***/
  153227. static double rate_mapping_32[12]={
  153228. 18000.,28000.,35000.,45000.,56000.,60000.,
  153229. 75000.,90000.,100000.,115000.,150000.,190000.,
  153230. };
  153231. static double rate_mapping_32_un[12]={
  153232. 30000.,42000.,52000.,64000.,72000.,78000.,
  153233. 86000.,92000.,110000.,120000.,140000.,190000.,
  153234. };
  153235. static double _psy_lowpass_32[12]={
  153236. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153237. };
  153238. ve_setup_data_template ve_setup_32_stereo={
  153239. 11,
  153240. rate_mapping_32,
  153241. quality_mapping_44,
  153242. 2,
  153243. 26000,
  153244. 40000,
  153245. blocksize_short_44,
  153246. blocksize_long_44,
  153247. _psy_tone_masteratt_44,
  153248. _psy_tone_0dB,
  153249. _psy_tone_suppress,
  153250. _vp_tonemask_adj_otherblock,
  153251. _vp_tonemask_adj_longblock,
  153252. _vp_tonemask_adj_otherblock,
  153253. _psy_noiseguards_44,
  153254. _psy_noisebias_impulse,
  153255. _psy_noisebias_padding,
  153256. _psy_noisebias_trans,
  153257. _psy_noisebias_long,
  153258. _psy_noise_suppress,
  153259. _psy_compand_44,
  153260. _psy_compand_short_mapping,
  153261. _psy_compand_long_mapping,
  153262. {_noise_start_short_44,_noise_start_long_44},
  153263. {_noise_part_short_44,_noise_part_long_44},
  153264. _noise_thresh_44,
  153265. _psy_ath_floater,
  153266. _psy_ath_abs,
  153267. _psy_lowpass_32,
  153268. _psy_global_44,
  153269. _global_mapping_44,
  153270. _psy_stereo_modes_44,
  153271. _floor_books,
  153272. _floor,
  153273. _floor_short_mapping_44,
  153274. _floor_long_mapping_44,
  153275. _mapres_template_44_stereo
  153276. };
  153277. ve_setup_data_template ve_setup_32_uncoupled={
  153278. 11,
  153279. rate_mapping_32_un,
  153280. quality_mapping_44,
  153281. -1,
  153282. 26000,
  153283. 40000,
  153284. blocksize_short_44,
  153285. blocksize_long_44,
  153286. _psy_tone_masteratt_44,
  153287. _psy_tone_0dB,
  153288. _psy_tone_suppress,
  153289. _vp_tonemask_adj_otherblock,
  153290. _vp_tonemask_adj_longblock,
  153291. _vp_tonemask_adj_otherblock,
  153292. _psy_noiseguards_44,
  153293. _psy_noisebias_impulse,
  153294. _psy_noisebias_padding,
  153295. _psy_noisebias_trans,
  153296. _psy_noisebias_long,
  153297. _psy_noise_suppress,
  153298. _psy_compand_44,
  153299. _psy_compand_short_mapping,
  153300. _psy_compand_long_mapping,
  153301. {_noise_start_short_44,_noise_start_long_44},
  153302. {_noise_part_short_44,_noise_part_long_44},
  153303. _noise_thresh_44,
  153304. _psy_ath_floater,
  153305. _psy_ath_abs,
  153306. _psy_lowpass_32,
  153307. _psy_global_44,
  153308. _global_mapping_44,
  153309. NULL,
  153310. _floor_books,
  153311. _floor,
  153312. _floor_short_mapping_44,
  153313. _floor_long_mapping_44,
  153314. _mapres_template_44_uncoupled
  153315. };
  153316. /*** End of inlined file: setup_32.h ***/
  153317. /*** Start of inlined file: setup_8.h ***/
  153318. /*** Start of inlined file: psych_8.h ***/
  153319. static att3 _psy_tone_masteratt_8[3]={
  153320. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153321. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153322. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153323. };
  153324. static vp_adjblock _vp_tonemask_adj_8[3]={
  153325. /* adjust for mode zero */
  153326. /* 63 125 250 500 1 2 4 8 16 */
  153327. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153328. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153329. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153330. };
  153331. static noise3 _psy_noisebias_8[3]={
  153332. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153333. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153334. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153335. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153336. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153337. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153338. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153339. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153340. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153341. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153342. };
  153343. /* stereo mode by base quality level */
  153344. static adj_stereo _psy_stereo_modes_8[3]={
  153345. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153346. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153347. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153348. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153349. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153350. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153351. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153352. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153353. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153354. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153355. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153356. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153357. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153358. };
  153359. static noiseguard _psy_noiseguards_8[2]={
  153360. {10,10,-1},
  153361. {10,10,-1},
  153362. };
  153363. static compandblock _psy_compand_8[2]={
  153364. {{
  153365. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153366. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153367. 12,12,13,13,14,14,15, 15, /* 23dB */
  153368. 16,16,17,17,17,18,18, 19, /* 31dB */
  153369. 19,19,20,21,22,23,24, 25, /* 39dB */
  153370. }},
  153371. {{
  153372. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153373. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153374. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153375. 9,10,11,12,13,14,15, 16, /* 31dB */
  153376. 17,18,19,20,21,22,23, 24, /* 39dB */
  153377. }},
  153378. };
  153379. static double _psy_lowpass_8[3]={3.,4.,4.};
  153380. static int _noise_start_8[2]={
  153381. 64,64,
  153382. };
  153383. static int _noise_part_8[2]={
  153384. 8,8,
  153385. };
  153386. static int _psy_ath_floater_8[3]={
  153387. -100,-100,-105,
  153388. };
  153389. static int _psy_ath_abs_8[3]={
  153390. -130,-130,-140,
  153391. };
  153392. /*** End of inlined file: psych_8.h ***/
  153393. /*** Start of inlined file: residue_8.h ***/
  153394. /***** residue backends *********************************************/
  153395. static static_bookblock _resbook_8s_0={
  153396. {
  153397. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153398. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153399. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153400. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153401. }
  153402. };
  153403. static static_bookblock _resbook_8s_1={
  153404. {
  153405. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153406. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153407. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153408. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153409. }
  153410. };
  153411. static vorbis_residue_template _res_8s_0[]={
  153412. {2,0, &_residue_44_mid,
  153413. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153414. &_resbook_8s_0,&_resbook_8s_0},
  153415. };
  153416. static vorbis_residue_template _res_8s_1[]={
  153417. {2,0, &_residue_44_mid,
  153418. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153419. &_resbook_8s_1,&_resbook_8s_1},
  153420. };
  153421. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153422. { _map_nominal, _res_8s_0 }, /* 0 */
  153423. { _map_nominal, _res_8s_1 }, /* 1 */
  153424. };
  153425. static static_bookblock _resbook_8u_0={
  153426. {
  153427. {0},
  153428. {0,0,&_8u0__p1_0},
  153429. {0,0,&_8u0__p2_0},
  153430. {0,0,&_8u0__p3_0},
  153431. {0,0,&_8u0__p4_0},
  153432. {0,0,&_8u0__p5_0},
  153433. {&_8u0__p6_0,&_8u0__p6_1},
  153434. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153435. }
  153436. };
  153437. static static_bookblock _resbook_8u_1={
  153438. {
  153439. {0},
  153440. {0,0,&_8u1__p1_0},
  153441. {0,0,&_8u1__p2_0},
  153442. {0,0,&_8u1__p3_0},
  153443. {0,0,&_8u1__p4_0},
  153444. {0,0,&_8u1__p5_0},
  153445. {0,0,&_8u1__p6_0},
  153446. {&_8u1__p7_0,&_8u1__p7_1},
  153447. {&_8u1__p8_0,&_8u1__p8_1},
  153448. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153449. }
  153450. };
  153451. static vorbis_residue_template _res_8u_0[]={
  153452. {1,0, &_residue_44_low_un,
  153453. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153454. &_resbook_8u_0,&_resbook_8u_0},
  153455. };
  153456. static vorbis_residue_template _res_8u_1[]={
  153457. {1,0, &_residue_44_mid_un,
  153458. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153459. &_resbook_8u_1,&_resbook_8u_1},
  153460. };
  153461. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153462. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153463. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153464. };
  153465. /*** End of inlined file: residue_8.h ***/
  153466. static int blocksize_8[2]={
  153467. 512,512
  153468. };
  153469. static int _floor_mapping_8[2]={
  153470. 6,6,
  153471. };
  153472. static double rate_mapping_8[3]={
  153473. 6000.,9000.,32000.,
  153474. };
  153475. static double rate_mapping_8_uncoupled[3]={
  153476. 8000.,14000.,42000.,
  153477. };
  153478. static double quality_mapping_8[3]={
  153479. -.1,.0,1.
  153480. };
  153481. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153482. static double _global_mapping_8[3]={ 1., 2., 3. };
  153483. ve_setup_data_template ve_setup_8_stereo={
  153484. 2,
  153485. rate_mapping_8,
  153486. quality_mapping_8,
  153487. 2,
  153488. 8000,
  153489. 9000,
  153490. blocksize_8,
  153491. blocksize_8,
  153492. _psy_tone_masteratt_8,
  153493. _psy_tone_0dB,
  153494. _psy_tone_suppress,
  153495. _vp_tonemask_adj_8,
  153496. NULL,
  153497. _vp_tonemask_adj_8,
  153498. _psy_noiseguards_8,
  153499. _psy_noisebias_8,
  153500. _psy_noisebias_8,
  153501. NULL,
  153502. NULL,
  153503. _psy_noise_suppress,
  153504. _psy_compand_8,
  153505. _psy_compand_8_mapping,
  153506. NULL,
  153507. {_noise_start_8,_noise_start_8},
  153508. {_noise_part_8,_noise_part_8},
  153509. _noise_thresh_5only,
  153510. _psy_ath_floater_8,
  153511. _psy_ath_abs_8,
  153512. _psy_lowpass_8,
  153513. _psy_global_44,
  153514. _global_mapping_8,
  153515. _psy_stereo_modes_8,
  153516. _floor_books,
  153517. _floor,
  153518. _floor_mapping_8,
  153519. NULL,
  153520. _mapres_template_8_stereo
  153521. };
  153522. ve_setup_data_template ve_setup_8_uncoupled={
  153523. 2,
  153524. rate_mapping_8_uncoupled,
  153525. quality_mapping_8,
  153526. -1,
  153527. 8000,
  153528. 9000,
  153529. blocksize_8,
  153530. blocksize_8,
  153531. _psy_tone_masteratt_8,
  153532. _psy_tone_0dB,
  153533. _psy_tone_suppress,
  153534. _vp_tonemask_adj_8,
  153535. NULL,
  153536. _vp_tonemask_adj_8,
  153537. _psy_noiseguards_8,
  153538. _psy_noisebias_8,
  153539. _psy_noisebias_8,
  153540. NULL,
  153541. NULL,
  153542. _psy_noise_suppress,
  153543. _psy_compand_8,
  153544. _psy_compand_8_mapping,
  153545. NULL,
  153546. {_noise_start_8,_noise_start_8},
  153547. {_noise_part_8,_noise_part_8},
  153548. _noise_thresh_5only,
  153549. _psy_ath_floater_8,
  153550. _psy_ath_abs_8,
  153551. _psy_lowpass_8,
  153552. _psy_global_44,
  153553. _global_mapping_8,
  153554. _psy_stereo_modes_8,
  153555. _floor_books,
  153556. _floor,
  153557. _floor_mapping_8,
  153558. NULL,
  153559. _mapres_template_8_uncoupled
  153560. };
  153561. /*** End of inlined file: setup_8.h ***/
  153562. /*** Start of inlined file: setup_11.h ***/
  153563. /*** Start of inlined file: psych_11.h ***/
  153564. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153565. static att3 _psy_tone_masteratt_11[3]={
  153566. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153567. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153568. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153569. };
  153570. static vp_adjblock _vp_tonemask_adj_11[3]={
  153571. /* adjust for mode zero */
  153572. /* 63 125 250 500 1 2 4 8 16 */
  153573. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153574. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153575. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153576. };
  153577. static noise3 _psy_noisebias_11[3]={
  153578. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153579. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153580. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153581. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153582. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153583. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153584. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153585. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153586. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153587. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153588. };
  153589. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153590. /*** End of inlined file: psych_11.h ***/
  153591. static int blocksize_11[2]={
  153592. 512,512
  153593. };
  153594. static int _floor_mapping_11[2]={
  153595. 6,6,
  153596. };
  153597. static double rate_mapping_11[3]={
  153598. 8000.,13000.,44000.,
  153599. };
  153600. static double rate_mapping_11_uncoupled[3]={
  153601. 12000.,20000.,50000.,
  153602. };
  153603. static double quality_mapping_11[3]={
  153604. -.1,.0,1.
  153605. };
  153606. ve_setup_data_template ve_setup_11_stereo={
  153607. 2,
  153608. rate_mapping_11,
  153609. quality_mapping_11,
  153610. 2,
  153611. 9000,
  153612. 15000,
  153613. blocksize_11,
  153614. blocksize_11,
  153615. _psy_tone_masteratt_11,
  153616. _psy_tone_0dB,
  153617. _psy_tone_suppress,
  153618. _vp_tonemask_adj_11,
  153619. NULL,
  153620. _vp_tonemask_adj_11,
  153621. _psy_noiseguards_8,
  153622. _psy_noisebias_11,
  153623. _psy_noisebias_11,
  153624. NULL,
  153625. NULL,
  153626. _psy_noise_suppress,
  153627. _psy_compand_8,
  153628. _psy_compand_8_mapping,
  153629. NULL,
  153630. {_noise_start_8,_noise_start_8},
  153631. {_noise_part_8,_noise_part_8},
  153632. _noise_thresh_11,
  153633. _psy_ath_floater_8,
  153634. _psy_ath_abs_8,
  153635. _psy_lowpass_11,
  153636. _psy_global_44,
  153637. _global_mapping_8,
  153638. _psy_stereo_modes_8,
  153639. _floor_books,
  153640. _floor,
  153641. _floor_mapping_11,
  153642. NULL,
  153643. _mapres_template_8_stereo
  153644. };
  153645. ve_setup_data_template ve_setup_11_uncoupled={
  153646. 2,
  153647. rate_mapping_11_uncoupled,
  153648. quality_mapping_11,
  153649. -1,
  153650. 9000,
  153651. 15000,
  153652. blocksize_11,
  153653. blocksize_11,
  153654. _psy_tone_masteratt_11,
  153655. _psy_tone_0dB,
  153656. _psy_tone_suppress,
  153657. _vp_tonemask_adj_11,
  153658. NULL,
  153659. _vp_tonemask_adj_11,
  153660. _psy_noiseguards_8,
  153661. _psy_noisebias_11,
  153662. _psy_noisebias_11,
  153663. NULL,
  153664. NULL,
  153665. _psy_noise_suppress,
  153666. _psy_compand_8,
  153667. _psy_compand_8_mapping,
  153668. NULL,
  153669. {_noise_start_8,_noise_start_8},
  153670. {_noise_part_8,_noise_part_8},
  153671. _noise_thresh_11,
  153672. _psy_ath_floater_8,
  153673. _psy_ath_abs_8,
  153674. _psy_lowpass_11,
  153675. _psy_global_44,
  153676. _global_mapping_8,
  153677. _psy_stereo_modes_8,
  153678. _floor_books,
  153679. _floor,
  153680. _floor_mapping_11,
  153681. NULL,
  153682. _mapres_template_8_uncoupled
  153683. };
  153684. /*** End of inlined file: setup_11.h ***/
  153685. /*** Start of inlined file: setup_16.h ***/
  153686. /*** Start of inlined file: psych_16.h ***/
  153687. /* stereo mode by base quality level */
  153688. static adj_stereo _psy_stereo_modes_16[4]={
  153689. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153690. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153691. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153692. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153693. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153694. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153695. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153696. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153697. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153698. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153699. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153700. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153701. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153702. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153703. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153704. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153705. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153706. };
  153707. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153708. static att3 _psy_tone_masteratt_16[4]={
  153709. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153710. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153711. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153712. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153713. };
  153714. static vp_adjblock _vp_tonemask_adj_16[4]={
  153715. /* adjust for mode zero */
  153716. /* 63 125 250 500 1 2 4 8 16 */
  153717. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153718. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153719. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153720. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153721. };
  153722. static noise3 _psy_noisebias_16_short[4]={
  153723. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153724. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153725. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153726. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153727. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153728. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153729. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153730. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153731. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153732. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153733. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153734. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153735. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153736. };
  153737. static noise3 _psy_noisebias_16_impulse[4]={
  153738. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153739. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153740. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153741. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153742. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153743. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153744. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153745. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153746. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153747. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153748. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153749. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153750. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153751. };
  153752. static noise3 _psy_noisebias_16[4]={
  153753. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153754. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153755. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153756. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153757. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153758. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153759. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153760. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153761. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153762. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153763. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153764. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153765. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153766. };
  153767. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153768. static int _noise_start_16[3]={ 256,256,9999 };
  153769. static int _noise_part_16[4]={ 8,8,8,8 };
  153770. static int _psy_ath_floater_16[4]={
  153771. -100,-100,-100,-105,
  153772. };
  153773. static int _psy_ath_abs_16[4]={
  153774. -130,-130,-130,-140,
  153775. };
  153776. /*** End of inlined file: psych_16.h ***/
  153777. /*** Start of inlined file: residue_16.h ***/
  153778. /***** residue backends *********************************************/
  153779. static static_bookblock _resbook_16s_0={
  153780. {
  153781. {0},
  153782. {0,0,&_16c0_s_p1_0},
  153783. {0,0,&_16c0_s_p2_0},
  153784. {0,0,&_16c0_s_p3_0},
  153785. {0,0,&_16c0_s_p4_0},
  153786. {0,0,&_16c0_s_p5_0},
  153787. {0,0,&_16c0_s_p6_0},
  153788. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153789. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153790. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153791. }
  153792. };
  153793. static static_bookblock _resbook_16s_1={
  153794. {
  153795. {0},
  153796. {0,0,&_16c1_s_p1_0},
  153797. {0,0,&_16c1_s_p2_0},
  153798. {0,0,&_16c1_s_p3_0},
  153799. {0,0,&_16c1_s_p4_0},
  153800. {0,0,&_16c1_s_p5_0},
  153801. {0,0,&_16c1_s_p6_0},
  153802. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153803. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153804. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153805. }
  153806. };
  153807. static static_bookblock _resbook_16s_2={
  153808. {
  153809. {0},
  153810. {0,0,&_16c2_s_p1_0},
  153811. {0,0,&_16c2_s_p2_0},
  153812. {0,0,&_16c2_s_p3_0},
  153813. {0,0,&_16c2_s_p4_0},
  153814. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153815. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153816. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153817. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153818. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153819. }
  153820. };
  153821. static vorbis_residue_template _res_16s_0[]={
  153822. {2,0, &_residue_44_mid,
  153823. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153824. &_resbook_16s_0,&_resbook_16s_0},
  153825. };
  153826. static vorbis_residue_template _res_16s_1[]={
  153827. {2,0, &_residue_44_mid,
  153828. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153829. &_resbook_16s_1,&_resbook_16s_1},
  153830. {2,0, &_residue_44_mid,
  153831. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153832. &_resbook_16s_1,&_resbook_16s_1}
  153833. };
  153834. static vorbis_residue_template _res_16s_2[]={
  153835. {2,0, &_residue_44_high,
  153836. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153837. &_resbook_16s_2,&_resbook_16s_2},
  153838. {2,0, &_residue_44_high,
  153839. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153840. &_resbook_16s_2,&_resbook_16s_2}
  153841. };
  153842. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153843. { _map_nominal, _res_16s_0 }, /* 0 */
  153844. { _map_nominal, _res_16s_1 }, /* 1 */
  153845. { _map_nominal, _res_16s_2 }, /* 2 */
  153846. };
  153847. static static_bookblock _resbook_16u_0={
  153848. {
  153849. {0},
  153850. {0,0,&_16u0__p1_0},
  153851. {0,0,&_16u0__p2_0},
  153852. {0,0,&_16u0__p3_0},
  153853. {0,0,&_16u0__p4_0},
  153854. {0,0,&_16u0__p5_0},
  153855. {&_16u0__p6_0,&_16u0__p6_1},
  153856. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153857. }
  153858. };
  153859. static static_bookblock _resbook_16u_1={
  153860. {
  153861. {0},
  153862. {0,0,&_16u1__p1_0},
  153863. {0,0,&_16u1__p2_0},
  153864. {0,0,&_16u1__p3_0},
  153865. {0,0,&_16u1__p4_0},
  153866. {0,0,&_16u1__p5_0},
  153867. {0,0,&_16u1__p6_0},
  153868. {&_16u1__p7_0,&_16u1__p7_1},
  153869. {&_16u1__p8_0,&_16u1__p8_1},
  153870. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153871. }
  153872. };
  153873. static static_bookblock _resbook_16u_2={
  153874. {
  153875. {0},
  153876. {0,0,&_16u2_p1_0},
  153877. {0,0,&_16u2_p2_0},
  153878. {0,0,&_16u2_p3_0},
  153879. {0,0,&_16u2_p4_0},
  153880. {&_16u2_p5_0,&_16u2_p5_1},
  153881. {&_16u2_p6_0,&_16u2_p6_1},
  153882. {&_16u2_p7_0,&_16u2_p7_1},
  153883. {&_16u2_p8_0,&_16u2_p8_1},
  153884. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153885. }
  153886. };
  153887. static vorbis_residue_template _res_16u_0[]={
  153888. {1,0, &_residue_44_low_un,
  153889. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153890. &_resbook_16u_0,&_resbook_16u_0},
  153891. };
  153892. static vorbis_residue_template _res_16u_1[]={
  153893. {1,0, &_residue_44_mid_un,
  153894. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153895. &_resbook_16u_1,&_resbook_16u_1},
  153896. {1,0, &_residue_44_mid_un,
  153897. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153898. &_resbook_16u_1,&_resbook_16u_1}
  153899. };
  153900. static vorbis_residue_template _res_16u_2[]={
  153901. {1,0, &_residue_44_hi_un,
  153902. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153903. &_resbook_16u_2,&_resbook_16u_2},
  153904. {1,0, &_residue_44_hi_un,
  153905. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153906. &_resbook_16u_2,&_resbook_16u_2}
  153907. };
  153908. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153909. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153910. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153911. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153912. };
  153913. /*** End of inlined file: residue_16.h ***/
  153914. static int blocksize_16_short[3]={
  153915. 1024,512,512
  153916. };
  153917. static int blocksize_16_long[3]={
  153918. 1024,1024,1024
  153919. };
  153920. static int _floor_mapping_16_short[3]={
  153921. 9,3,3
  153922. };
  153923. static int _floor_mapping_16[3]={
  153924. 9,9,9
  153925. };
  153926. static double rate_mapping_16[4]={
  153927. 12000.,20000.,44000.,86000.
  153928. };
  153929. static double rate_mapping_16_uncoupled[4]={
  153930. 16000.,28000.,64000.,100000.
  153931. };
  153932. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153933. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153934. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153935. ve_setup_data_template ve_setup_16_stereo={
  153936. 3,
  153937. rate_mapping_16,
  153938. quality_mapping_16,
  153939. 2,
  153940. 15000,
  153941. 19000,
  153942. blocksize_16_short,
  153943. blocksize_16_long,
  153944. _psy_tone_masteratt_16,
  153945. _psy_tone_0dB,
  153946. _psy_tone_suppress,
  153947. _vp_tonemask_adj_16,
  153948. _vp_tonemask_adj_16,
  153949. _vp_tonemask_adj_16,
  153950. _psy_noiseguards_8,
  153951. _psy_noisebias_16_impulse,
  153952. _psy_noisebias_16_short,
  153953. _psy_noisebias_16_short,
  153954. _psy_noisebias_16,
  153955. _psy_noise_suppress,
  153956. _psy_compand_8,
  153957. _psy_compand_16_mapping,
  153958. _psy_compand_16_mapping,
  153959. {_noise_start_16,_noise_start_16},
  153960. { _noise_part_16, _noise_part_16},
  153961. _noise_thresh_16,
  153962. _psy_ath_floater_16,
  153963. _psy_ath_abs_16,
  153964. _psy_lowpass_16,
  153965. _psy_global_44,
  153966. _global_mapping_16,
  153967. _psy_stereo_modes_16,
  153968. _floor_books,
  153969. _floor,
  153970. _floor_mapping_16_short,
  153971. _floor_mapping_16,
  153972. _mapres_template_16_stereo
  153973. };
  153974. ve_setup_data_template ve_setup_16_uncoupled={
  153975. 3,
  153976. rate_mapping_16_uncoupled,
  153977. quality_mapping_16,
  153978. -1,
  153979. 15000,
  153980. 19000,
  153981. blocksize_16_short,
  153982. blocksize_16_long,
  153983. _psy_tone_masteratt_16,
  153984. _psy_tone_0dB,
  153985. _psy_tone_suppress,
  153986. _vp_tonemask_adj_16,
  153987. _vp_tonemask_adj_16,
  153988. _vp_tonemask_adj_16,
  153989. _psy_noiseguards_8,
  153990. _psy_noisebias_16_impulse,
  153991. _psy_noisebias_16_short,
  153992. _psy_noisebias_16_short,
  153993. _psy_noisebias_16,
  153994. _psy_noise_suppress,
  153995. _psy_compand_8,
  153996. _psy_compand_16_mapping,
  153997. _psy_compand_16_mapping,
  153998. {_noise_start_16,_noise_start_16},
  153999. { _noise_part_16, _noise_part_16},
  154000. _noise_thresh_16,
  154001. _psy_ath_floater_16,
  154002. _psy_ath_abs_16,
  154003. _psy_lowpass_16,
  154004. _psy_global_44,
  154005. _global_mapping_16,
  154006. _psy_stereo_modes_16,
  154007. _floor_books,
  154008. _floor,
  154009. _floor_mapping_16_short,
  154010. _floor_mapping_16,
  154011. _mapres_template_16_uncoupled
  154012. };
  154013. /*** End of inlined file: setup_16.h ***/
  154014. /*** Start of inlined file: setup_22.h ***/
  154015. static double rate_mapping_22[4]={
  154016. 15000.,20000.,44000.,86000.
  154017. };
  154018. static double rate_mapping_22_uncoupled[4]={
  154019. 16000.,28000.,50000.,90000.
  154020. };
  154021. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154022. ve_setup_data_template ve_setup_22_stereo={
  154023. 3,
  154024. rate_mapping_22,
  154025. quality_mapping_16,
  154026. 2,
  154027. 19000,
  154028. 26000,
  154029. blocksize_16_short,
  154030. blocksize_16_long,
  154031. _psy_tone_masteratt_16,
  154032. _psy_tone_0dB,
  154033. _psy_tone_suppress,
  154034. _vp_tonemask_adj_16,
  154035. _vp_tonemask_adj_16,
  154036. _vp_tonemask_adj_16,
  154037. _psy_noiseguards_8,
  154038. _psy_noisebias_16_impulse,
  154039. _psy_noisebias_16_short,
  154040. _psy_noisebias_16_short,
  154041. _psy_noisebias_16,
  154042. _psy_noise_suppress,
  154043. _psy_compand_8,
  154044. _psy_compand_8_mapping,
  154045. _psy_compand_8_mapping,
  154046. {_noise_start_16,_noise_start_16},
  154047. { _noise_part_16, _noise_part_16},
  154048. _noise_thresh_16,
  154049. _psy_ath_floater_16,
  154050. _psy_ath_abs_16,
  154051. _psy_lowpass_22,
  154052. _psy_global_44,
  154053. _global_mapping_16,
  154054. _psy_stereo_modes_16,
  154055. _floor_books,
  154056. _floor,
  154057. _floor_mapping_16_short,
  154058. _floor_mapping_16,
  154059. _mapres_template_16_stereo
  154060. };
  154061. ve_setup_data_template ve_setup_22_uncoupled={
  154062. 3,
  154063. rate_mapping_22_uncoupled,
  154064. quality_mapping_16,
  154065. -1,
  154066. 19000,
  154067. 26000,
  154068. blocksize_16_short,
  154069. blocksize_16_long,
  154070. _psy_tone_masteratt_16,
  154071. _psy_tone_0dB,
  154072. _psy_tone_suppress,
  154073. _vp_tonemask_adj_16,
  154074. _vp_tonemask_adj_16,
  154075. _vp_tonemask_adj_16,
  154076. _psy_noiseguards_8,
  154077. _psy_noisebias_16_impulse,
  154078. _psy_noisebias_16_short,
  154079. _psy_noisebias_16_short,
  154080. _psy_noisebias_16,
  154081. _psy_noise_suppress,
  154082. _psy_compand_8,
  154083. _psy_compand_8_mapping,
  154084. _psy_compand_8_mapping,
  154085. {_noise_start_16,_noise_start_16},
  154086. { _noise_part_16, _noise_part_16},
  154087. _noise_thresh_16,
  154088. _psy_ath_floater_16,
  154089. _psy_ath_abs_16,
  154090. _psy_lowpass_22,
  154091. _psy_global_44,
  154092. _global_mapping_16,
  154093. _psy_stereo_modes_16,
  154094. _floor_books,
  154095. _floor,
  154096. _floor_mapping_16_short,
  154097. _floor_mapping_16,
  154098. _mapres_template_16_uncoupled
  154099. };
  154100. /*** End of inlined file: setup_22.h ***/
  154101. /*** Start of inlined file: setup_X.h ***/
  154102. static double rate_mapping_X[12]={
  154103. -1.,-1.,-1.,-1.,-1.,-1.,
  154104. -1.,-1.,-1.,-1.,-1.,-1.
  154105. };
  154106. ve_setup_data_template ve_setup_X_stereo={
  154107. 11,
  154108. rate_mapping_X,
  154109. quality_mapping_44,
  154110. 2,
  154111. 50000,
  154112. 200000,
  154113. blocksize_short_44,
  154114. blocksize_long_44,
  154115. _psy_tone_masteratt_44,
  154116. _psy_tone_0dB,
  154117. _psy_tone_suppress,
  154118. _vp_tonemask_adj_otherblock,
  154119. _vp_tonemask_adj_longblock,
  154120. _vp_tonemask_adj_otherblock,
  154121. _psy_noiseguards_44,
  154122. _psy_noisebias_impulse,
  154123. _psy_noisebias_padding,
  154124. _psy_noisebias_trans,
  154125. _psy_noisebias_long,
  154126. _psy_noise_suppress,
  154127. _psy_compand_44,
  154128. _psy_compand_short_mapping,
  154129. _psy_compand_long_mapping,
  154130. {_noise_start_short_44,_noise_start_long_44},
  154131. {_noise_part_short_44,_noise_part_long_44},
  154132. _noise_thresh_44,
  154133. _psy_ath_floater,
  154134. _psy_ath_abs,
  154135. _psy_lowpass_44,
  154136. _psy_global_44,
  154137. _global_mapping_44,
  154138. _psy_stereo_modes_44,
  154139. _floor_books,
  154140. _floor,
  154141. _floor_short_mapping_44,
  154142. _floor_long_mapping_44,
  154143. _mapres_template_44_stereo
  154144. };
  154145. ve_setup_data_template ve_setup_X_uncoupled={
  154146. 11,
  154147. rate_mapping_X,
  154148. quality_mapping_44,
  154149. -1,
  154150. 50000,
  154151. 200000,
  154152. blocksize_short_44,
  154153. blocksize_long_44,
  154154. _psy_tone_masteratt_44,
  154155. _psy_tone_0dB,
  154156. _psy_tone_suppress,
  154157. _vp_tonemask_adj_otherblock,
  154158. _vp_tonemask_adj_longblock,
  154159. _vp_tonemask_adj_otherblock,
  154160. _psy_noiseguards_44,
  154161. _psy_noisebias_impulse,
  154162. _psy_noisebias_padding,
  154163. _psy_noisebias_trans,
  154164. _psy_noisebias_long,
  154165. _psy_noise_suppress,
  154166. _psy_compand_44,
  154167. _psy_compand_short_mapping,
  154168. _psy_compand_long_mapping,
  154169. {_noise_start_short_44,_noise_start_long_44},
  154170. {_noise_part_short_44,_noise_part_long_44},
  154171. _noise_thresh_44,
  154172. _psy_ath_floater,
  154173. _psy_ath_abs,
  154174. _psy_lowpass_44,
  154175. _psy_global_44,
  154176. _global_mapping_44,
  154177. NULL,
  154178. _floor_books,
  154179. _floor,
  154180. _floor_short_mapping_44,
  154181. _floor_long_mapping_44,
  154182. _mapres_template_44_uncoupled
  154183. };
  154184. ve_setup_data_template ve_setup_XX_stereo={
  154185. 2,
  154186. rate_mapping_X,
  154187. quality_mapping_8,
  154188. 2,
  154189. 0,
  154190. 8000,
  154191. blocksize_8,
  154192. blocksize_8,
  154193. _psy_tone_masteratt_8,
  154194. _psy_tone_0dB,
  154195. _psy_tone_suppress,
  154196. _vp_tonemask_adj_8,
  154197. NULL,
  154198. _vp_tonemask_adj_8,
  154199. _psy_noiseguards_8,
  154200. _psy_noisebias_8,
  154201. _psy_noisebias_8,
  154202. NULL,
  154203. NULL,
  154204. _psy_noise_suppress,
  154205. _psy_compand_8,
  154206. _psy_compand_8_mapping,
  154207. NULL,
  154208. {_noise_start_8,_noise_start_8},
  154209. {_noise_part_8,_noise_part_8},
  154210. _noise_thresh_5only,
  154211. _psy_ath_floater_8,
  154212. _psy_ath_abs_8,
  154213. _psy_lowpass_8,
  154214. _psy_global_44,
  154215. _global_mapping_8,
  154216. _psy_stereo_modes_8,
  154217. _floor_books,
  154218. _floor,
  154219. _floor_mapping_8,
  154220. NULL,
  154221. _mapres_template_8_stereo
  154222. };
  154223. ve_setup_data_template ve_setup_XX_uncoupled={
  154224. 2,
  154225. rate_mapping_X,
  154226. quality_mapping_8,
  154227. -1,
  154228. 0,
  154229. 8000,
  154230. blocksize_8,
  154231. blocksize_8,
  154232. _psy_tone_masteratt_8,
  154233. _psy_tone_0dB,
  154234. _psy_tone_suppress,
  154235. _vp_tonemask_adj_8,
  154236. NULL,
  154237. _vp_tonemask_adj_8,
  154238. _psy_noiseguards_8,
  154239. _psy_noisebias_8,
  154240. _psy_noisebias_8,
  154241. NULL,
  154242. NULL,
  154243. _psy_noise_suppress,
  154244. _psy_compand_8,
  154245. _psy_compand_8_mapping,
  154246. NULL,
  154247. {_noise_start_8,_noise_start_8},
  154248. {_noise_part_8,_noise_part_8},
  154249. _noise_thresh_5only,
  154250. _psy_ath_floater_8,
  154251. _psy_ath_abs_8,
  154252. _psy_lowpass_8,
  154253. _psy_global_44,
  154254. _global_mapping_8,
  154255. _psy_stereo_modes_8,
  154256. _floor_books,
  154257. _floor,
  154258. _floor_mapping_8,
  154259. NULL,
  154260. _mapres_template_8_uncoupled
  154261. };
  154262. /*** End of inlined file: setup_X.h ***/
  154263. static ve_setup_data_template *setup_list[]={
  154264. &ve_setup_44_stereo,
  154265. &ve_setup_44_uncoupled,
  154266. &ve_setup_32_stereo,
  154267. &ve_setup_32_uncoupled,
  154268. &ve_setup_22_stereo,
  154269. &ve_setup_22_uncoupled,
  154270. &ve_setup_16_stereo,
  154271. &ve_setup_16_uncoupled,
  154272. &ve_setup_11_stereo,
  154273. &ve_setup_11_uncoupled,
  154274. &ve_setup_8_stereo,
  154275. &ve_setup_8_uncoupled,
  154276. &ve_setup_X_stereo,
  154277. &ve_setup_X_uncoupled,
  154278. &ve_setup_XX_stereo,
  154279. &ve_setup_XX_uncoupled,
  154280. 0
  154281. };
  154282. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154283. if(vi && vi->codec_setup){
  154284. vi->version=0;
  154285. vi->channels=ch;
  154286. vi->rate=rate;
  154287. return(0);
  154288. }
  154289. return(OV_EINVAL);
  154290. }
  154291. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154292. static_codebook ***books,
  154293. vorbis_info_floor1 *in,
  154294. int *x){
  154295. int i,k,is=s;
  154296. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154297. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154298. memcpy(f,in+x[is],sizeof(*f));
  154299. /* fill in the lowpass field, even if it's temporary */
  154300. f->n=ci->blocksizes[block]>>1;
  154301. /* books */
  154302. {
  154303. int partitions=f->partitions;
  154304. int maxclass=-1;
  154305. int maxbook=-1;
  154306. for(i=0;i<partitions;i++)
  154307. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154308. for(i=0;i<=maxclass;i++){
  154309. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154310. f->class_book[i]+=ci->books;
  154311. for(k=0;k<(1<<f->class_subs[i]);k++){
  154312. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154313. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154314. }
  154315. }
  154316. for(i=0;i<=maxbook;i++)
  154317. ci->book_param[ci->books++]=books[x[is]][i];
  154318. }
  154319. /* for now, we're only using floor 1 */
  154320. ci->floor_type[ci->floors]=1;
  154321. ci->floor_param[ci->floors]=f;
  154322. ci->floors++;
  154323. return;
  154324. }
  154325. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154326. vorbis_info_psy_global *in,
  154327. double *x){
  154328. int i,is=s;
  154329. double ds=s-is;
  154330. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154331. vorbis_info_psy_global *g=&ci->psy_g_param;
  154332. memcpy(g,in+(int)x[is],sizeof(*g));
  154333. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154334. is=(int)ds;
  154335. ds-=is;
  154336. if(ds==0 && is>0){
  154337. is--;
  154338. ds=1.;
  154339. }
  154340. /* interpolate the trigger threshholds */
  154341. for(i=0;i<4;i++){
  154342. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154343. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154344. }
  154345. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154346. return;
  154347. }
  154348. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154349. highlevel_encode_setup *hi,
  154350. adj_stereo *p){
  154351. float s=hi->stereo_point_setting;
  154352. int i,is=s;
  154353. double ds=s-is;
  154354. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154355. vorbis_info_psy_global *g=&ci->psy_g_param;
  154356. if(p){
  154357. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154358. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154359. if(hi->managed){
  154360. /* interpolate the kHz threshholds */
  154361. for(i=0;i<PACKETBLOBS;i++){
  154362. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154363. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154364. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154365. g->coupling_pkHz[i]=kHz;
  154366. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154367. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154368. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154369. }
  154370. }else{
  154371. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154372. for(i=0;i<PACKETBLOBS;i++){
  154373. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154374. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154375. g->coupling_pkHz[i]=kHz;
  154376. }
  154377. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154378. for(i=0;i<PACKETBLOBS;i++){
  154379. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154380. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154381. }
  154382. }
  154383. }else{
  154384. for(i=0;i<PACKETBLOBS;i++){
  154385. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154386. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154387. }
  154388. }
  154389. return;
  154390. }
  154391. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154392. int *nn_start,
  154393. int *nn_partition,
  154394. double *nn_thresh,
  154395. int block){
  154396. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154397. vorbis_info_psy *p=ci->psy_param[block];
  154398. highlevel_encode_setup *hi=&ci->hi;
  154399. int is=s;
  154400. if(block>=ci->psys)
  154401. ci->psys=block+1;
  154402. if(!p){
  154403. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154404. ci->psy_param[block]=p;
  154405. }
  154406. memcpy(p,&_psy_info_template,sizeof(*p));
  154407. p->blockflag=block>>1;
  154408. if(hi->noise_normalize_p){
  154409. p->normal_channel_p=1;
  154410. p->normal_point_p=1;
  154411. p->normal_start=nn_start[is];
  154412. p->normal_partition=nn_partition[is];
  154413. p->normal_thresh=nn_thresh[is];
  154414. }
  154415. return;
  154416. }
  154417. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154418. att3 *att,
  154419. int *max,
  154420. vp_adjblock *in){
  154421. int i,is=s;
  154422. double ds=s-is;
  154423. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154424. vorbis_info_psy *p=ci->psy_param[block];
  154425. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154426. filling the values in here */
  154427. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154428. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154429. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154430. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154431. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154432. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154433. for(i=0;i<P_BANDS;i++)
  154434. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154435. return;
  154436. }
  154437. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154438. compandblock *in, double *x){
  154439. int i,is=s;
  154440. double ds=s-is;
  154441. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154442. vorbis_info_psy *p=ci->psy_param[block];
  154443. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154444. is=(int)ds;
  154445. ds-=is;
  154446. if(ds==0 && is>0){
  154447. is--;
  154448. ds=1.;
  154449. }
  154450. /* interpolate the compander settings */
  154451. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154452. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154453. return;
  154454. }
  154455. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154456. int *suppress){
  154457. int is=s;
  154458. double ds=s-is;
  154459. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154460. vorbis_info_psy *p=ci->psy_param[block];
  154461. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154462. return;
  154463. }
  154464. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154465. int *suppress,
  154466. noise3 *in,
  154467. noiseguard *guard,
  154468. double userbias){
  154469. int i,is=s,j;
  154470. double ds=s-is;
  154471. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154472. vorbis_info_psy *p=ci->psy_param[block];
  154473. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154474. p->noisewindowlomin=guard[block].lo;
  154475. p->noisewindowhimin=guard[block].hi;
  154476. p->noisewindowfixed=guard[block].fixed;
  154477. for(j=0;j<P_NOISECURVES;j++)
  154478. for(i=0;i<P_BANDS;i++)
  154479. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154480. /* impulse blocks may take a user specified bias to boost the
  154481. nominal/high noise encoding depth */
  154482. for(j=0;j<P_NOISECURVES;j++){
  154483. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154484. for(i=0;i<P_BANDS;i++){
  154485. p->noiseoff[j][i]+=userbias;
  154486. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154487. }
  154488. }
  154489. return;
  154490. }
  154491. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154492. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154493. vorbis_info_psy *p=ci->psy_param[block];
  154494. p->ath_adjatt=ci->hi.ath_floating_dB;
  154495. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154496. return;
  154497. }
  154498. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154499. int i;
  154500. for(i=0;i<ci->books;i++)
  154501. if(ci->book_param[i]==book)return(i);
  154502. return(ci->books++);
  154503. }
  154504. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154505. int *shortb,int *longb){
  154506. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154507. int is=s;
  154508. int blockshort=shortb[is];
  154509. int blocklong=longb[is];
  154510. ci->blocksizes[0]=blockshort;
  154511. ci->blocksizes[1]=blocklong;
  154512. }
  154513. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154514. int number, int block,
  154515. vorbis_residue_template *res){
  154516. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154517. int i,n;
  154518. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154519. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154520. memcpy(r,res->res,sizeof(*r));
  154521. if(ci->residues<=number)ci->residues=number+1;
  154522. switch(ci->blocksizes[block]){
  154523. case 64:case 128:case 256:
  154524. r->grouping=16;
  154525. break;
  154526. default:
  154527. r->grouping=32;
  154528. break;
  154529. }
  154530. ci->residue_type[number]=res->res_type;
  154531. /* to be adjusted by lowpass/pointlimit later */
  154532. n=r->end=ci->blocksizes[block]>>1;
  154533. if(res->res_type==2)
  154534. n=r->end*=vi->channels;
  154535. /* fill in all the books */
  154536. {
  154537. int booklist=0,k;
  154538. if(ci->hi.managed){
  154539. for(i=0;i<r->partitions;i++)
  154540. for(k=0;k<3;k++)
  154541. if(res->books_base_managed->books[i][k])
  154542. r->secondstages[i]|=(1<<k);
  154543. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154544. ci->book_param[r->groupbook]=res->book_aux_managed;
  154545. for(i=0;i<r->partitions;i++){
  154546. for(k=0;k<3;k++){
  154547. if(res->books_base_managed->books[i][k]){
  154548. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154549. r->booklist[booklist++]=bookid;
  154550. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154551. }
  154552. }
  154553. }
  154554. }else{
  154555. for(i=0;i<r->partitions;i++)
  154556. for(k=0;k<3;k++)
  154557. if(res->books_base->books[i][k])
  154558. r->secondstages[i]|=(1<<k);
  154559. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154560. ci->book_param[r->groupbook]=res->book_aux;
  154561. for(i=0;i<r->partitions;i++){
  154562. for(k=0;k<3;k++){
  154563. if(res->books_base->books[i][k]){
  154564. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154565. r->booklist[booklist++]=bookid;
  154566. ci->book_param[bookid]=res->books_base->books[i][k];
  154567. }
  154568. }
  154569. }
  154570. }
  154571. }
  154572. /* lowpass setup/pointlimit */
  154573. {
  154574. double freq=ci->hi.lowpass_kHz*1000.;
  154575. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154576. double nyq=vi->rate/2.;
  154577. long blocksize=ci->blocksizes[block]>>1;
  154578. /* lowpass needs to be set in the floor and the residue. */
  154579. if(freq>nyq)freq=nyq;
  154580. /* in the floor, the granularity can be very fine; it doesn't alter
  154581. the encoding structure, only the samples used to fit the floor
  154582. approximation */
  154583. f->n=freq/nyq*blocksize;
  154584. /* this res may by limited by the maximum pointlimit of the mode,
  154585. not the lowpass. the floor is always lowpass limited. */
  154586. if(res->limit_type){
  154587. if(ci->hi.managed)
  154588. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154589. else
  154590. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154591. if(freq>nyq)freq=nyq;
  154592. }
  154593. /* in the residue, we're constrained, physically, by partition
  154594. boundaries. We still lowpass 'wherever', but we have to round up
  154595. here to next boundary, or the vorbis spec will round it *down* to
  154596. previous boundary in encode/decode */
  154597. if(ci->residue_type[block]==2)
  154598. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154599. r->grouping;
  154600. else
  154601. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154602. r->grouping;
  154603. }
  154604. }
  154605. /* we assume two maps in this encoder */
  154606. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154607. vorbis_mapping_template *maps){
  154608. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154609. int i,j,is=s,modes=2;
  154610. vorbis_info_mapping0 *map=maps[is].map;
  154611. vorbis_info_mode *mode=_mode_template;
  154612. vorbis_residue_template *res=maps[is].res;
  154613. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154614. for(i=0;i<modes;i++){
  154615. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154616. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154617. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154618. if(i>=ci->modes)ci->modes=i+1;
  154619. ci->map_type[i]=0;
  154620. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154621. if(i>=ci->maps)ci->maps=i+1;
  154622. for(j=0;j<map[i].submaps;j++)
  154623. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154624. ,res+map[i].residuesubmap[j]);
  154625. }
  154626. }
  154627. static double setting_to_approx_bitrate(vorbis_info *vi){
  154628. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154629. highlevel_encode_setup *hi=&ci->hi;
  154630. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154631. int is=hi->base_setting;
  154632. double ds=hi->base_setting-is;
  154633. int ch=vi->channels;
  154634. double *r=setup->rate_mapping;
  154635. if(r==NULL)
  154636. return(-1);
  154637. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154638. }
  154639. static void get_setup_template(vorbis_info *vi,
  154640. long ch,long srate,
  154641. double req,int q_or_bitrate){
  154642. int i=0,j;
  154643. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154644. highlevel_encode_setup *hi=&ci->hi;
  154645. if(q_or_bitrate)req/=ch;
  154646. while(setup_list[i]){
  154647. if(setup_list[i]->coupling_restriction==-1 ||
  154648. setup_list[i]->coupling_restriction==ch){
  154649. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154650. srate<=setup_list[i]->samplerate_max_restriction){
  154651. int mappings=setup_list[i]->mappings;
  154652. double *map=(q_or_bitrate?
  154653. setup_list[i]->rate_mapping:
  154654. setup_list[i]->quality_mapping);
  154655. /* the template matches. Does the requested quality mode
  154656. fall within this template's modes? */
  154657. if(req<map[0]){++i;continue;}
  154658. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154659. for(j=0;j<mappings;j++)
  154660. if(req>=map[j] && req<map[j+1])break;
  154661. /* an all-points match */
  154662. hi->setup=setup_list[i];
  154663. if(j==mappings)
  154664. hi->base_setting=j-.001;
  154665. else{
  154666. float low=map[j];
  154667. float high=map[j+1];
  154668. float del=(req-low)/(high-low);
  154669. hi->base_setting=j+del;
  154670. }
  154671. return;
  154672. }
  154673. }
  154674. i++;
  154675. }
  154676. hi->setup=NULL;
  154677. }
  154678. /* encoders will need to use vorbis_info_init beforehand and call
  154679. vorbis_info clear when all done */
  154680. /* two interfaces; this, more detailed one, and later a convenience
  154681. layer on top */
  154682. /* the final setup call */
  154683. int vorbis_encode_setup_init(vorbis_info *vi){
  154684. int i0=0,singleblock=0;
  154685. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154686. ve_setup_data_template *setup=NULL;
  154687. highlevel_encode_setup *hi=&ci->hi;
  154688. if(ci==NULL)return(OV_EINVAL);
  154689. if(!hi->impulse_block_p)i0=1;
  154690. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154691. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154692. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154693. /* again, bound this to avoid the app shooting itself int he foot
  154694. too badly */
  154695. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154696. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154697. /* get the appropriate setup template; matches the fetch in previous
  154698. stages */
  154699. setup=(ve_setup_data_template *)hi->setup;
  154700. if(setup==NULL)return(OV_EINVAL);
  154701. hi->set_in_stone=1;
  154702. /* choose block sizes from configured sizes as well as paying
  154703. attention to long_block_p and short_block_p. If the configured
  154704. short and long blocks are the same length, we set long_block_p
  154705. and unset short_block_p */
  154706. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154707. setup->blocksize_short,
  154708. setup->blocksize_long);
  154709. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154710. /* floor setup; choose proper floor params. Allocated on the floor
  154711. stack in order; if we alloc only long floor, it's 0 */
  154712. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154713. setup->floor_books,
  154714. setup->floor_params,
  154715. setup->floor_short_mapping);
  154716. if(!singleblock)
  154717. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154718. setup->floor_books,
  154719. setup->floor_params,
  154720. setup->floor_long_mapping);
  154721. /* setup of [mostly] short block detection and stereo*/
  154722. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154723. setup->global_params,
  154724. setup->global_mapping);
  154725. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154726. /* basic psych setup and noise normalization */
  154727. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154728. setup->psy_noise_normal_start[0],
  154729. setup->psy_noise_normal_partition[0],
  154730. setup->psy_noise_normal_thresh,
  154731. 0);
  154732. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154733. setup->psy_noise_normal_start[0],
  154734. setup->psy_noise_normal_partition[0],
  154735. setup->psy_noise_normal_thresh,
  154736. 1);
  154737. if(!singleblock){
  154738. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154739. setup->psy_noise_normal_start[1],
  154740. setup->psy_noise_normal_partition[1],
  154741. setup->psy_noise_normal_thresh,
  154742. 2);
  154743. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154744. setup->psy_noise_normal_start[1],
  154745. setup->psy_noise_normal_partition[1],
  154746. setup->psy_noise_normal_thresh,
  154747. 3);
  154748. }
  154749. /* tone masking setup */
  154750. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154751. setup->psy_tone_masteratt,
  154752. setup->psy_tone_0dB,
  154753. setup->psy_tone_adj_impulse);
  154754. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154755. setup->psy_tone_masteratt,
  154756. setup->psy_tone_0dB,
  154757. setup->psy_tone_adj_other);
  154758. if(!singleblock){
  154759. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154760. setup->psy_tone_masteratt,
  154761. setup->psy_tone_0dB,
  154762. setup->psy_tone_adj_other);
  154763. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154764. setup->psy_tone_masteratt,
  154765. setup->psy_tone_0dB,
  154766. setup->psy_tone_adj_long);
  154767. }
  154768. /* noise companding setup */
  154769. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154770. setup->psy_noise_compand,
  154771. setup->psy_noise_compand_short_mapping);
  154772. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154773. setup->psy_noise_compand,
  154774. setup->psy_noise_compand_short_mapping);
  154775. if(!singleblock){
  154776. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154777. setup->psy_noise_compand,
  154778. setup->psy_noise_compand_long_mapping);
  154779. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154780. setup->psy_noise_compand,
  154781. setup->psy_noise_compand_long_mapping);
  154782. }
  154783. /* peak guarding setup */
  154784. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154785. setup->psy_tone_dBsuppress);
  154786. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154787. setup->psy_tone_dBsuppress);
  154788. if(!singleblock){
  154789. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154790. setup->psy_tone_dBsuppress);
  154791. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154792. setup->psy_tone_dBsuppress);
  154793. }
  154794. /* noise bias setup */
  154795. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154796. setup->psy_noise_dBsuppress,
  154797. setup->psy_noise_bias_impulse,
  154798. setup->psy_noiseguards,
  154799. (i0==0?hi->impulse_noisetune:0.));
  154800. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154801. setup->psy_noise_dBsuppress,
  154802. setup->psy_noise_bias_padding,
  154803. setup->psy_noiseguards,0.);
  154804. if(!singleblock){
  154805. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154806. setup->psy_noise_dBsuppress,
  154807. setup->psy_noise_bias_trans,
  154808. setup->psy_noiseguards,0.);
  154809. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154810. setup->psy_noise_dBsuppress,
  154811. setup->psy_noise_bias_long,
  154812. setup->psy_noiseguards,0.);
  154813. }
  154814. vorbis_encode_ath_setup(vi,0);
  154815. vorbis_encode_ath_setup(vi,1);
  154816. if(!singleblock){
  154817. vorbis_encode_ath_setup(vi,2);
  154818. vorbis_encode_ath_setup(vi,3);
  154819. }
  154820. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154821. /* set bitrate readonlies and management */
  154822. if(hi->bitrate_av>0)
  154823. vi->bitrate_nominal=hi->bitrate_av;
  154824. else{
  154825. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154826. }
  154827. vi->bitrate_lower=hi->bitrate_min;
  154828. vi->bitrate_upper=hi->bitrate_max;
  154829. if(hi->bitrate_av)
  154830. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154831. else
  154832. vi->bitrate_window=0.;
  154833. if(hi->managed){
  154834. ci->bi.avg_rate=hi->bitrate_av;
  154835. ci->bi.min_rate=hi->bitrate_min;
  154836. ci->bi.max_rate=hi->bitrate_max;
  154837. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154838. ci->bi.reservoir_bias=
  154839. hi->bitrate_reservoir_bias;
  154840. ci->bi.slew_damp=hi->bitrate_av_damp;
  154841. }
  154842. return(0);
  154843. }
  154844. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154845. long channels,
  154846. long rate){
  154847. int ret=0,i,is;
  154848. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154849. highlevel_encode_setup *hi=&ci->hi;
  154850. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154851. double ds;
  154852. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154853. if(ret)return(ret);
  154854. is=hi->base_setting;
  154855. ds=hi->base_setting-is;
  154856. hi->short_setting=hi->base_setting;
  154857. hi->long_setting=hi->base_setting;
  154858. hi->managed=0;
  154859. hi->impulse_block_p=1;
  154860. hi->noise_normalize_p=1;
  154861. hi->stereo_point_setting=hi->base_setting;
  154862. hi->lowpass_kHz=
  154863. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154864. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154865. setup->psy_ath_float[is+1]*ds;
  154866. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154867. setup->psy_ath_abs[is+1]*ds;
  154868. hi->amplitude_track_dBpersec=-6.;
  154869. hi->trigger_setting=hi->base_setting;
  154870. for(i=0;i<4;i++){
  154871. hi->block[i].tone_mask_setting=hi->base_setting;
  154872. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154873. hi->block[i].noise_bias_setting=hi->base_setting;
  154874. hi->block[i].noise_compand_setting=hi->base_setting;
  154875. }
  154876. return(ret);
  154877. }
  154878. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154879. long channels,
  154880. long rate,
  154881. float quality){
  154882. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154883. highlevel_encode_setup *hi=&ci->hi;
  154884. quality+=.0000001;
  154885. if(quality>=1.)quality=.9999;
  154886. get_setup_template(vi,channels,rate,quality,0);
  154887. if(!hi->setup)return OV_EIMPL;
  154888. return vorbis_encode_setup_setting(vi,channels,rate);
  154889. }
  154890. int vorbis_encode_init_vbr(vorbis_info *vi,
  154891. long channels,
  154892. long rate,
  154893. float base_quality /* 0. to 1. */
  154894. ){
  154895. int ret=0;
  154896. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154897. if(ret){
  154898. vorbis_info_clear(vi);
  154899. return ret;
  154900. }
  154901. ret=vorbis_encode_setup_init(vi);
  154902. if(ret)
  154903. vorbis_info_clear(vi);
  154904. return(ret);
  154905. }
  154906. int vorbis_encode_setup_managed(vorbis_info *vi,
  154907. long channels,
  154908. long rate,
  154909. long max_bitrate,
  154910. long nominal_bitrate,
  154911. long min_bitrate){
  154912. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154913. highlevel_encode_setup *hi=&ci->hi;
  154914. double tnominal=nominal_bitrate;
  154915. int ret=0;
  154916. if(nominal_bitrate<=0.){
  154917. if(max_bitrate>0.){
  154918. if(min_bitrate>0.)
  154919. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154920. else
  154921. nominal_bitrate=max_bitrate*.875;
  154922. }else{
  154923. if(min_bitrate>0.){
  154924. nominal_bitrate=min_bitrate;
  154925. }else{
  154926. return(OV_EINVAL);
  154927. }
  154928. }
  154929. }
  154930. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154931. if(!hi->setup)return OV_EIMPL;
  154932. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154933. if(ret){
  154934. vorbis_info_clear(vi);
  154935. return ret;
  154936. }
  154937. /* initialize management with sane defaults */
  154938. hi->managed=1;
  154939. hi->bitrate_min=min_bitrate;
  154940. hi->bitrate_max=max_bitrate;
  154941. hi->bitrate_av=tnominal;
  154942. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154943. hi->bitrate_reservoir=nominal_bitrate*2;
  154944. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154945. return(ret);
  154946. }
  154947. int vorbis_encode_init(vorbis_info *vi,
  154948. long channels,
  154949. long rate,
  154950. long max_bitrate,
  154951. long nominal_bitrate,
  154952. long min_bitrate){
  154953. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154954. max_bitrate,
  154955. nominal_bitrate,
  154956. min_bitrate);
  154957. if(ret){
  154958. vorbis_info_clear(vi);
  154959. return(ret);
  154960. }
  154961. ret=vorbis_encode_setup_init(vi);
  154962. if(ret)
  154963. vorbis_info_clear(vi);
  154964. return(ret);
  154965. }
  154966. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154967. if(vi){
  154968. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154969. highlevel_encode_setup *hi=&ci->hi;
  154970. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154971. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154972. switch(number){
  154973. /* now deprecated *****************/
  154974. case OV_ECTL_RATEMANAGE_GET:
  154975. {
  154976. struct ovectl_ratemanage_arg *ai=
  154977. (struct ovectl_ratemanage_arg *)arg;
  154978. ai->management_active=hi->managed;
  154979. ai->bitrate_hard_window=ai->bitrate_av_window=
  154980. (double)hi->bitrate_reservoir/vi->rate;
  154981. ai->bitrate_av_window_center=1.;
  154982. ai->bitrate_hard_min=hi->bitrate_min;
  154983. ai->bitrate_hard_max=hi->bitrate_max;
  154984. ai->bitrate_av_lo=hi->bitrate_av;
  154985. ai->bitrate_av_hi=hi->bitrate_av;
  154986. }
  154987. return(0);
  154988. /* now deprecated *****************/
  154989. case OV_ECTL_RATEMANAGE_SET:
  154990. {
  154991. struct ovectl_ratemanage_arg *ai=
  154992. (struct ovectl_ratemanage_arg *)arg;
  154993. if(ai==NULL){
  154994. hi->managed=0;
  154995. }else{
  154996. hi->managed=ai->management_active;
  154997. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154998. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154999. }
  155000. }
  155001. return 0;
  155002. /* now deprecated *****************/
  155003. case OV_ECTL_RATEMANAGE_AVG:
  155004. {
  155005. struct ovectl_ratemanage_arg *ai=
  155006. (struct ovectl_ratemanage_arg *)arg;
  155007. if(ai==NULL){
  155008. hi->bitrate_av=0;
  155009. }else{
  155010. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155011. }
  155012. }
  155013. return(0);
  155014. /* now deprecated *****************/
  155015. case OV_ECTL_RATEMANAGE_HARD:
  155016. {
  155017. struct ovectl_ratemanage_arg *ai=
  155018. (struct ovectl_ratemanage_arg *)arg;
  155019. if(ai==NULL){
  155020. hi->bitrate_min=0;
  155021. hi->bitrate_max=0;
  155022. }else{
  155023. hi->bitrate_min=ai->bitrate_hard_min;
  155024. hi->bitrate_max=ai->bitrate_hard_max;
  155025. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155026. (hi->bitrate_max+hi->bitrate_min)*.5;
  155027. }
  155028. if(hi->bitrate_reservoir<128.)
  155029. hi->bitrate_reservoir=128.;
  155030. }
  155031. return(0);
  155032. /* replacement ratemanage interface */
  155033. case OV_ECTL_RATEMANAGE2_GET:
  155034. {
  155035. struct ovectl_ratemanage2_arg *ai=
  155036. (struct ovectl_ratemanage2_arg *)arg;
  155037. if(ai==NULL)return OV_EINVAL;
  155038. ai->management_active=hi->managed;
  155039. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155040. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155041. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155042. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155043. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155044. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155045. }
  155046. return (0);
  155047. case OV_ECTL_RATEMANAGE2_SET:
  155048. {
  155049. struct ovectl_ratemanage2_arg *ai=
  155050. (struct ovectl_ratemanage2_arg *)arg;
  155051. if(ai==NULL){
  155052. hi->managed=0;
  155053. }else{
  155054. /* sanity check; only catch invariant violations */
  155055. if(ai->bitrate_limit_min_kbps>0 &&
  155056. ai->bitrate_average_kbps>0 &&
  155057. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155058. return OV_EINVAL;
  155059. if(ai->bitrate_limit_max_kbps>0 &&
  155060. ai->bitrate_average_kbps>0 &&
  155061. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155062. return OV_EINVAL;
  155063. if(ai->bitrate_limit_min_kbps>0 &&
  155064. ai->bitrate_limit_max_kbps>0 &&
  155065. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155066. return OV_EINVAL;
  155067. if(ai->bitrate_average_damping <= 0.)
  155068. return OV_EINVAL;
  155069. if(ai->bitrate_limit_reservoir_bits < 0)
  155070. return OV_EINVAL;
  155071. if(ai->bitrate_limit_reservoir_bias < 0.)
  155072. return OV_EINVAL;
  155073. if(ai->bitrate_limit_reservoir_bias > 1.)
  155074. return OV_EINVAL;
  155075. hi->managed=ai->management_active;
  155076. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155077. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155078. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155079. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155080. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155081. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155082. }
  155083. }
  155084. return 0;
  155085. case OV_ECTL_LOWPASS_GET:
  155086. {
  155087. double *farg=(double *)arg;
  155088. *farg=hi->lowpass_kHz;
  155089. }
  155090. return(0);
  155091. case OV_ECTL_LOWPASS_SET:
  155092. {
  155093. double *farg=(double *)arg;
  155094. hi->lowpass_kHz=*farg;
  155095. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155096. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155097. }
  155098. return(0);
  155099. case OV_ECTL_IBLOCK_GET:
  155100. {
  155101. double *farg=(double *)arg;
  155102. *farg=hi->impulse_noisetune;
  155103. }
  155104. return(0);
  155105. case OV_ECTL_IBLOCK_SET:
  155106. {
  155107. double *farg=(double *)arg;
  155108. hi->impulse_noisetune=*farg;
  155109. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155110. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155111. }
  155112. return(0);
  155113. }
  155114. return(OV_EIMPL);
  155115. }
  155116. return(OV_EINVAL);
  155117. }
  155118. #endif
  155119. /*** End of inlined file: vorbisenc.c ***/
  155120. /*** Start of inlined file: vorbisfile.c ***/
  155121. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155122. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155123. // tasks..
  155124. #if JUCE_MSVC
  155125. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155126. #endif
  155127. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155128. #if JUCE_USE_OGGVORBIS
  155129. #include <stdlib.h>
  155130. #include <stdio.h>
  155131. #include <errno.h>
  155132. #include <string.h>
  155133. #include <math.h>
  155134. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155135. one logical bitstream arranged end to end (the only form of Ogg
  155136. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155137. multiplexing] is not allowed in Vorbis) */
  155138. /* A Vorbis file can be played beginning to end (streamed) without
  155139. worrying ahead of time about chaining (see decoder_example.c). If
  155140. we have the whole file, however, and want random access
  155141. (seeking/scrubbing) or desire to know the total length/time of a
  155142. file, we need to account for the possibility of chaining. */
  155143. /* We can handle things a number of ways; we can determine the entire
  155144. bitstream structure right off the bat, or find pieces on demand.
  155145. This example determines and caches structure for the entire
  155146. bitstream, but builds a virtual decoder on the fly when moving
  155147. between links in the chain. */
  155148. /* There are also different ways to implement seeking. Enough
  155149. information exists in an Ogg bitstream to seek to
  155150. sample-granularity positions in the output. Or, one can seek by
  155151. picking some portion of the stream roughly in the desired area if
  155152. we only want coarse navigation through the stream. */
  155153. /*************************************************************************
  155154. * Many, many internal helpers. The intention is not to be confusing;
  155155. * rampant duplication and monolithic function implementation would be
  155156. * harder to understand anyway. The high level functions are last. Begin
  155157. * grokking near the end of the file */
  155158. /* read a little more data from the file/pipe into the ogg_sync framer
  155159. */
  155160. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155161. over 8k gets what they deserve */
  155162. static long _get_data(OggVorbis_File *vf){
  155163. errno=0;
  155164. if(vf->datasource){
  155165. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155166. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155167. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155168. if(bytes==0 && errno)return(-1);
  155169. return(bytes);
  155170. }else
  155171. return(0);
  155172. }
  155173. /* save a tiny smidge of verbosity to make the code more readable */
  155174. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155175. if(vf->datasource){
  155176. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155177. vf->offset=offset;
  155178. ogg_sync_reset(&vf->oy);
  155179. }else{
  155180. /* shouldn't happen unless someone writes a broken callback */
  155181. return;
  155182. }
  155183. }
  155184. /* The read/seek functions track absolute position within the stream */
  155185. /* from the head of the stream, get the next page. boundary specifies
  155186. if the function is allowed to fetch more data from the stream (and
  155187. how much) or only use internally buffered data.
  155188. boundary: -1) unbounded search
  155189. 0) read no additional data; use cached only
  155190. n) search for a new page beginning for n bytes
  155191. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155192. n) found a page at absolute offset n */
  155193. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155194. ogg_int64_t boundary){
  155195. if(boundary>0)boundary+=vf->offset;
  155196. while(1){
  155197. long more;
  155198. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155199. more=ogg_sync_pageseek(&vf->oy,og);
  155200. if(more<0){
  155201. /* skipped n bytes */
  155202. vf->offset-=more;
  155203. }else{
  155204. if(more==0){
  155205. /* send more paramedics */
  155206. if(!boundary)return(OV_FALSE);
  155207. {
  155208. long ret=_get_data(vf);
  155209. if(ret==0)return(OV_EOF);
  155210. if(ret<0)return(OV_EREAD);
  155211. }
  155212. }else{
  155213. /* got a page. Return the offset at the page beginning,
  155214. advance the internal offset past the page end */
  155215. ogg_int64_t ret=vf->offset;
  155216. vf->offset+=more;
  155217. return(ret);
  155218. }
  155219. }
  155220. }
  155221. }
  155222. /* find the latest page beginning before the current stream cursor
  155223. position. Much dirtier than the above as Ogg doesn't have any
  155224. backward search linkage. no 'readp' as it will certainly have to
  155225. read. */
  155226. /* returns offset or OV_EREAD, OV_FAULT */
  155227. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155228. ogg_int64_t begin=vf->offset;
  155229. ogg_int64_t end=begin;
  155230. ogg_int64_t ret;
  155231. ogg_int64_t offset=-1;
  155232. while(offset==-1){
  155233. begin-=CHUNKSIZE;
  155234. if(begin<0)
  155235. begin=0;
  155236. _seek_helper(vf,begin);
  155237. while(vf->offset<end){
  155238. ret=_get_next_page(vf,og,end-vf->offset);
  155239. if(ret==OV_EREAD)return(OV_EREAD);
  155240. if(ret<0){
  155241. break;
  155242. }else{
  155243. offset=ret;
  155244. }
  155245. }
  155246. }
  155247. /* we have the offset. Actually snork and hold the page now */
  155248. _seek_helper(vf,offset);
  155249. ret=_get_next_page(vf,og,CHUNKSIZE);
  155250. if(ret<0)
  155251. /* this shouldn't be possible */
  155252. return(OV_EFAULT);
  155253. return(offset);
  155254. }
  155255. /* finds each bitstream link one at a time using a bisection search
  155256. (has to begin by knowing the offset of the lb's initial page).
  155257. Recurses for each link so it can alloc the link storage after
  155258. finding them all, then unroll and fill the cache at the same time */
  155259. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155260. ogg_int64_t begin,
  155261. ogg_int64_t searched,
  155262. ogg_int64_t end,
  155263. long currentno,
  155264. long m){
  155265. ogg_int64_t endsearched=end;
  155266. ogg_int64_t next=end;
  155267. ogg_page og;
  155268. ogg_int64_t ret;
  155269. /* the below guards against garbage seperating the last and
  155270. first pages of two links. */
  155271. while(searched<endsearched){
  155272. ogg_int64_t bisect;
  155273. if(endsearched-searched<CHUNKSIZE){
  155274. bisect=searched;
  155275. }else{
  155276. bisect=(searched+endsearched)/2;
  155277. }
  155278. _seek_helper(vf,bisect);
  155279. ret=_get_next_page(vf,&og,-1);
  155280. if(ret==OV_EREAD)return(OV_EREAD);
  155281. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155282. endsearched=bisect;
  155283. if(ret>=0)next=ret;
  155284. }else{
  155285. searched=ret+og.header_len+og.body_len;
  155286. }
  155287. }
  155288. _seek_helper(vf,next);
  155289. ret=_get_next_page(vf,&og,-1);
  155290. if(ret==OV_EREAD)return(OV_EREAD);
  155291. if(searched>=end || ret<0){
  155292. vf->links=m+1;
  155293. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155294. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155295. vf->offsets[m+1]=searched;
  155296. }else{
  155297. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155298. end,ogg_page_serialno(&og),m+1);
  155299. if(ret==OV_EREAD)return(OV_EREAD);
  155300. }
  155301. vf->offsets[m]=begin;
  155302. vf->serialnos[m]=currentno;
  155303. return(0);
  155304. }
  155305. /* uses the local ogg_stream storage in vf; this is important for
  155306. non-streaming input sources */
  155307. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155308. long *serialno,ogg_page *og_ptr){
  155309. ogg_page og;
  155310. ogg_packet op;
  155311. int i,ret;
  155312. if(!og_ptr){
  155313. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155314. if(llret==OV_EREAD)return(OV_EREAD);
  155315. if(llret<0)return OV_ENOTVORBIS;
  155316. og_ptr=&og;
  155317. }
  155318. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155319. if(serialno)*serialno=vf->os.serialno;
  155320. vf->ready_state=STREAMSET;
  155321. /* extract the initial header from the first page and verify that the
  155322. Ogg bitstream is in fact Vorbis data */
  155323. vorbis_info_init(vi);
  155324. vorbis_comment_init(vc);
  155325. i=0;
  155326. while(i<3){
  155327. ogg_stream_pagein(&vf->os,og_ptr);
  155328. while(i<3){
  155329. int result=ogg_stream_packetout(&vf->os,&op);
  155330. if(result==0)break;
  155331. if(result==-1){
  155332. ret=OV_EBADHEADER;
  155333. goto bail_header;
  155334. }
  155335. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155336. goto bail_header;
  155337. }
  155338. i++;
  155339. }
  155340. if(i<3)
  155341. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155342. ret=OV_EBADHEADER;
  155343. goto bail_header;
  155344. }
  155345. }
  155346. return 0;
  155347. bail_header:
  155348. vorbis_info_clear(vi);
  155349. vorbis_comment_clear(vc);
  155350. vf->ready_state=OPENED;
  155351. return ret;
  155352. }
  155353. /* last step of the OggVorbis_File initialization; get all the
  155354. vorbis_info structs and PCM positions. Only called by the seekable
  155355. initialization (local stream storage is hacked slightly; pay
  155356. attention to how that's done) */
  155357. /* this is void and does not propogate errors up because we want to be
  155358. able to open and use damaged bitstreams as well as we can. Just
  155359. watch out for missing information for links in the OggVorbis_File
  155360. struct */
  155361. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155362. ogg_page og;
  155363. int i;
  155364. ogg_int64_t ret;
  155365. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155366. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155367. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155368. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155369. for(i=0;i<vf->links;i++){
  155370. if(i==0){
  155371. /* we already grabbed the initial header earlier. Just set the offset */
  155372. vf->dataoffsets[i]=dataoffset;
  155373. _seek_helper(vf,dataoffset);
  155374. }else{
  155375. /* seek to the location of the initial header */
  155376. _seek_helper(vf,vf->offsets[i]);
  155377. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155378. vf->dataoffsets[i]=-1;
  155379. }else{
  155380. vf->dataoffsets[i]=vf->offset;
  155381. }
  155382. }
  155383. /* fetch beginning PCM offset */
  155384. if(vf->dataoffsets[i]!=-1){
  155385. ogg_int64_t accumulated=0;
  155386. long lastblock=-1;
  155387. int result;
  155388. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155389. while(1){
  155390. ogg_packet op;
  155391. ret=_get_next_page(vf,&og,-1);
  155392. if(ret<0)
  155393. /* this should not be possible unless the file is
  155394. truncated/mangled */
  155395. break;
  155396. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155397. break;
  155398. /* count blocksizes of all frames in the page */
  155399. ogg_stream_pagein(&vf->os,&og);
  155400. while((result=ogg_stream_packetout(&vf->os,&op))){
  155401. if(result>0){ /* ignore holes */
  155402. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155403. if(lastblock!=-1)
  155404. accumulated+=(lastblock+thisblock)>>2;
  155405. lastblock=thisblock;
  155406. }
  155407. }
  155408. if(ogg_page_granulepos(&og)!=-1){
  155409. /* pcm offset of last packet on the first audio page */
  155410. accumulated= ogg_page_granulepos(&og)-accumulated;
  155411. break;
  155412. }
  155413. }
  155414. /* less than zero? This is a stream with samples trimmed off
  155415. the beginning, a normal occurrence; set the offset to zero */
  155416. if(accumulated<0)accumulated=0;
  155417. vf->pcmlengths[i*2]=accumulated;
  155418. }
  155419. /* get the PCM length of this link. To do this,
  155420. get the last page of the stream */
  155421. {
  155422. ogg_int64_t end=vf->offsets[i+1];
  155423. _seek_helper(vf,end);
  155424. while(1){
  155425. ret=_get_prev_page(vf,&og);
  155426. if(ret<0){
  155427. /* this should not be possible */
  155428. vorbis_info_clear(vf->vi+i);
  155429. vorbis_comment_clear(vf->vc+i);
  155430. break;
  155431. }
  155432. if(ogg_page_granulepos(&og)!=-1){
  155433. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155434. break;
  155435. }
  155436. vf->offset=ret;
  155437. }
  155438. }
  155439. }
  155440. }
  155441. static int _make_decode_ready(OggVorbis_File *vf){
  155442. if(vf->ready_state>STREAMSET)return 0;
  155443. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155444. if(vf->seekable){
  155445. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155446. return OV_EBADLINK;
  155447. }else{
  155448. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155449. return OV_EBADLINK;
  155450. }
  155451. vorbis_block_init(&vf->vd,&vf->vb);
  155452. vf->ready_state=INITSET;
  155453. vf->bittrack=0.f;
  155454. vf->samptrack=0.f;
  155455. return 0;
  155456. }
  155457. static int _open_seekable2(OggVorbis_File *vf){
  155458. long serialno=vf->current_serialno;
  155459. ogg_int64_t dataoffset=vf->offset, end;
  155460. ogg_page og;
  155461. /* we're partially open and have a first link header state in
  155462. storage in vf */
  155463. /* we can seek, so set out learning all about this file */
  155464. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155465. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155466. /* We get the offset for the last page of the physical bitstream.
  155467. Most OggVorbis files will contain a single logical bitstream */
  155468. end=_get_prev_page(vf,&og);
  155469. if(end<0)return(end);
  155470. /* more than one logical bitstream? */
  155471. if(ogg_page_serialno(&og)!=serialno){
  155472. /* Chained bitstream. Bisect-search each logical bitstream
  155473. section. Do so based on serial number only */
  155474. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155475. }else{
  155476. /* Only one logical bitstream */
  155477. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155478. }
  155479. /* the initial header memory is referenced by vf after; don't free it */
  155480. _prefetch_all_headers(vf,dataoffset);
  155481. return(ov_raw_seek(vf,0));
  155482. }
  155483. /* clear out the current logical bitstream decoder */
  155484. static void _decode_clear(OggVorbis_File *vf){
  155485. vorbis_dsp_clear(&vf->vd);
  155486. vorbis_block_clear(&vf->vb);
  155487. vf->ready_state=OPENED;
  155488. }
  155489. /* fetch and process a packet. Handles the case where we're at a
  155490. bitstream boundary and dumps the decoding machine. If the decoding
  155491. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155492. date (seek and read both use this. seek uses a special hack with
  155493. readp).
  155494. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155495. 0) need more data (only if readp==0)
  155496. 1) got a packet
  155497. */
  155498. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155499. ogg_packet *op_in,
  155500. int readp,
  155501. int spanp){
  155502. ogg_page og;
  155503. /* handle one packet. Try to fetch it from current stream state */
  155504. /* extract packets from page */
  155505. while(1){
  155506. /* process a packet if we can. If the machine isn't loaded,
  155507. neither is a page */
  155508. if(vf->ready_state==INITSET){
  155509. while(1) {
  155510. ogg_packet op;
  155511. ogg_packet *op_ptr=(op_in?op_in:&op);
  155512. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155513. ogg_int64_t granulepos;
  155514. op_in=NULL;
  155515. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155516. if(result>0){
  155517. /* got a packet. process it */
  155518. granulepos=op_ptr->granulepos;
  155519. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155520. header handling. The
  155521. header packets aren't
  155522. audio, so if/when we
  155523. submit them,
  155524. vorbis_synthesis will
  155525. reject them */
  155526. /* suck in the synthesis data and track bitrate */
  155527. {
  155528. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155529. /* for proper use of libvorbis within libvorbisfile,
  155530. oldsamples will always be zero. */
  155531. if(oldsamples)return(OV_EFAULT);
  155532. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155533. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155534. vf->bittrack+=op_ptr->bytes*8;
  155535. }
  155536. /* update the pcm offset. */
  155537. if(granulepos!=-1 && !op_ptr->e_o_s){
  155538. int link=(vf->seekable?vf->current_link:0);
  155539. int i,samples;
  155540. /* this packet has a pcm_offset on it (the last packet
  155541. completed on a page carries the offset) After processing
  155542. (above), we know the pcm position of the *last* sample
  155543. ready to be returned. Find the offset of the *first*
  155544. As an aside, this trick is inaccurate if we begin
  155545. reading anew right at the last page; the end-of-stream
  155546. granulepos declares the last frame in the stream, and the
  155547. last packet of the last page may be a partial frame.
  155548. So, we need a previous granulepos from an in-sequence page
  155549. to have a reference point. Thus the !op_ptr->e_o_s clause
  155550. above */
  155551. if(vf->seekable && link>0)
  155552. granulepos-=vf->pcmlengths[link*2];
  155553. if(granulepos<0)granulepos=0; /* actually, this
  155554. shouldn't be possible
  155555. here unless the stream
  155556. is very broken */
  155557. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155558. granulepos-=samples;
  155559. for(i=0;i<link;i++)
  155560. granulepos+=vf->pcmlengths[i*2+1];
  155561. vf->pcm_offset=granulepos;
  155562. }
  155563. return(1);
  155564. }
  155565. }
  155566. else
  155567. break;
  155568. }
  155569. }
  155570. if(vf->ready_state>=OPENED){
  155571. ogg_int64_t ret;
  155572. if(!readp)return(0);
  155573. if((ret=_get_next_page(vf,&og,-1))<0){
  155574. return(OV_EOF); /* eof.
  155575. leave unitialized */
  155576. }
  155577. /* bitrate tracking; add the header's bytes here, the body bytes
  155578. are done by packet above */
  155579. vf->bittrack+=og.header_len*8;
  155580. /* has our decoding just traversed a bitstream boundary? */
  155581. if(vf->ready_state==INITSET){
  155582. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155583. if(!spanp)
  155584. return(OV_EOF);
  155585. _decode_clear(vf);
  155586. if(!vf->seekable){
  155587. vorbis_info_clear(vf->vi);
  155588. vorbis_comment_clear(vf->vc);
  155589. }
  155590. }
  155591. }
  155592. }
  155593. /* Do we need to load a new machine before submitting the page? */
  155594. /* This is different in the seekable and non-seekable cases.
  155595. In the seekable case, we already have all the header
  155596. information loaded and cached; we just initialize the machine
  155597. with it and continue on our merry way.
  155598. In the non-seekable (streaming) case, we'll only be at a
  155599. boundary if we just left the previous logical bitstream and
  155600. we're now nominally at the header of the next bitstream
  155601. */
  155602. if(vf->ready_state!=INITSET){
  155603. int link;
  155604. if(vf->ready_state<STREAMSET){
  155605. if(vf->seekable){
  155606. vf->current_serialno=ogg_page_serialno(&og);
  155607. /* match the serialno to bitstream section. We use this rather than
  155608. offset positions to avoid problems near logical bitstream
  155609. boundaries */
  155610. for(link=0;link<vf->links;link++)
  155611. if(vf->serialnos[link]==vf->current_serialno)break;
  155612. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155613. stream. error out,
  155614. leave machine
  155615. uninitialized */
  155616. vf->current_link=link;
  155617. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155618. vf->ready_state=STREAMSET;
  155619. }else{
  155620. /* we're streaming */
  155621. /* fetch the three header packets, build the info struct */
  155622. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155623. if(ret)return(ret);
  155624. vf->current_link++;
  155625. link=0;
  155626. }
  155627. }
  155628. {
  155629. int ret=_make_decode_ready(vf);
  155630. if(ret<0)return ret;
  155631. }
  155632. }
  155633. ogg_stream_pagein(&vf->os,&og);
  155634. }
  155635. }
  155636. /* if, eg, 64 bit stdio is configured by default, this will build with
  155637. fseek64 */
  155638. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155639. if(f==NULL)return(-1);
  155640. return fseek(f,off,whence);
  155641. }
  155642. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155643. long ibytes, ov_callbacks callbacks){
  155644. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155645. int ret;
  155646. memset(vf,0,sizeof(*vf));
  155647. vf->datasource=f;
  155648. vf->callbacks = callbacks;
  155649. /* init the framing state */
  155650. ogg_sync_init(&vf->oy);
  155651. /* perhaps some data was previously read into a buffer for testing
  155652. against other stream types. Allow initialization from this
  155653. previously read data (as we may be reading from a non-seekable
  155654. stream) */
  155655. if(initial){
  155656. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155657. memcpy(buffer,initial,ibytes);
  155658. ogg_sync_wrote(&vf->oy,ibytes);
  155659. }
  155660. /* can we seek? Stevens suggests the seek test was portable */
  155661. if(offsettest!=-1)vf->seekable=1;
  155662. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155663. entry for partial open */
  155664. vf->links=1;
  155665. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155666. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155667. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155668. /* Try to fetch the headers, maintaining all the storage */
  155669. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155670. vf->datasource=NULL;
  155671. ov_clear(vf);
  155672. }else
  155673. vf->ready_state=PARTOPEN;
  155674. return(ret);
  155675. }
  155676. static int _ov_open2(OggVorbis_File *vf){
  155677. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155678. vf->ready_state=OPENED;
  155679. if(vf->seekable){
  155680. int ret=_open_seekable2(vf);
  155681. if(ret){
  155682. vf->datasource=NULL;
  155683. ov_clear(vf);
  155684. }
  155685. return(ret);
  155686. }else
  155687. vf->ready_state=STREAMSET;
  155688. return 0;
  155689. }
  155690. /* clear out the OggVorbis_File struct */
  155691. int ov_clear(OggVorbis_File *vf){
  155692. if(vf){
  155693. vorbis_block_clear(&vf->vb);
  155694. vorbis_dsp_clear(&vf->vd);
  155695. ogg_stream_clear(&vf->os);
  155696. if(vf->vi && vf->links){
  155697. int i;
  155698. for(i=0;i<vf->links;i++){
  155699. vorbis_info_clear(vf->vi+i);
  155700. vorbis_comment_clear(vf->vc+i);
  155701. }
  155702. _ogg_free(vf->vi);
  155703. _ogg_free(vf->vc);
  155704. }
  155705. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155706. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155707. if(vf->serialnos)_ogg_free(vf->serialnos);
  155708. if(vf->offsets)_ogg_free(vf->offsets);
  155709. ogg_sync_clear(&vf->oy);
  155710. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155711. memset(vf,0,sizeof(*vf));
  155712. }
  155713. #ifdef DEBUG_LEAKS
  155714. _VDBG_dump();
  155715. #endif
  155716. return(0);
  155717. }
  155718. /* inspects the OggVorbis file and finds/documents all the logical
  155719. bitstreams contained in it. Tries to be tolerant of logical
  155720. bitstream sections that are truncated/woogie.
  155721. return: -1) error
  155722. 0) OK
  155723. */
  155724. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155725. ov_callbacks callbacks){
  155726. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155727. if(ret)return ret;
  155728. return _ov_open2(vf);
  155729. }
  155730. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155731. ov_callbacks callbacks = {
  155732. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155733. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155734. (int (*)(void *)) fclose,
  155735. (long (*)(void *)) ftell
  155736. };
  155737. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155738. }
  155739. /* cheap hack for game usage where downsampling is desirable; there's
  155740. no need for SRC as we can just do it cheaply in libvorbis. */
  155741. int ov_halfrate(OggVorbis_File *vf,int flag){
  155742. int i;
  155743. if(vf->vi==NULL)return OV_EINVAL;
  155744. if(!vf->seekable)return OV_EINVAL;
  155745. if(vf->ready_state>=STREAMSET)
  155746. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155747. will be able to swap this on the fly, but
  155748. for now dumping the decode machine is needed
  155749. to reinit the MDCT lookups. 1.1 libvorbis
  155750. is planned to be able to switch on the fly */
  155751. for(i=0;i<vf->links;i++){
  155752. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155753. ov_halfrate(vf,0);
  155754. return OV_EINVAL;
  155755. }
  155756. }
  155757. return 0;
  155758. }
  155759. int ov_halfrate_p(OggVorbis_File *vf){
  155760. if(vf->vi==NULL)return OV_EINVAL;
  155761. return vorbis_synthesis_halfrate_p(vf->vi);
  155762. }
  155763. /* Only partially open the vorbis file; test for Vorbisness, and load
  155764. the headers for the first chain. Do not seek (although test for
  155765. seekability). Use ov_test_open to finish opening the file, else
  155766. ov_clear to close/free it. Same return codes as open. */
  155767. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155768. ov_callbacks callbacks)
  155769. {
  155770. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155771. }
  155772. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155773. ov_callbacks callbacks = {
  155774. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155775. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155776. (int (*)(void *)) fclose,
  155777. (long (*)(void *)) ftell
  155778. };
  155779. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155780. }
  155781. int ov_test_open(OggVorbis_File *vf){
  155782. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155783. return _ov_open2(vf);
  155784. }
  155785. /* How many logical bitstreams in this physical bitstream? */
  155786. long ov_streams(OggVorbis_File *vf){
  155787. return vf->links;
  155788. }
  155789. /* Is the FILE * associated with vf seekable? */
  155790. long ov_seekable(OggVorbis_File *vf){
  155791. return vf->seekable;
  155792. }
  155793. /* returns the bitrate for a given logical bitstream or the entire
  155794. physical bitstream. If the file is open for random access, it will
  155795. find the *actual* average bitrate. If the file is streaming, it
  155796. returns the nominal bitrate (if set) else the average of the
  155797. upper/lower bounds (if set) else -1 (unset).
  155798. If you want the actual bitrate field settings, get them from the
  155799. vorbis_info structs */
  155800. long ov_bitrate(OggVorbis_File *vf,int i){
  155801. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155802. if(i>=vf->links)return(OV_EINVAL);
  155803. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155804. if(i<0){
  155805. ogg_int64_t bits=0;
  155806. int i;
  155807. float br;
  155808. for(i=0;i<vf->links;i++)
  155809. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155810. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155811. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155812. * so this is slightly transformed to make it work.
  155813. */
  155814. br = bits/ov_time_total(vf,-1);
  155815. return(rint(br));
  155816. }else{
  155817. if(vf->seekable){
  155818. /* return the actual bitrate */
  155819. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155820. }else{
  155821. /* return nominal if set */
  155822. if(vf->vi[i].bitrate_nominal>0){
  155823. return vf->vi[i].bitrate_nominal;
  155824. }else{
  155825. if(vf->vi[i].bitrate_upper>0){
  155826. if(vf->vi[i].bitrate_lower>0){
  155827. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155828. }else{
  155829. return vf->vi[i].bitrate_upper;
  155830. }
  155831. }
  155832. return(OV_FALSE);
  155833. }
  155834. }
  155835. }
  155836. }
  155837. /* returns the actual bitrate since last call. returns -1 if no
  155838. additional data to offer since last call (or at beginning of stream),
  155839. EINVAL if stream is only partially open
  155840. */
  155841. long ov_bitrate_instant(OggVorbis_File *vf){
  155842. int link=(vf->seekable?vf->current_link:0);
  155843. long ret;
  155844. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155845. if(vf->samptrack==0)return(OV_FALSE);
  155846. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155847. vf->bittrack=0.f;
  155848. vf->samptrack=0.f;
  155849. return(ret);
  155850. }
  155851. /* Guess */
  155852. long ov_serialnumber(OggVorbis_File *vf,int i){
  155853. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155854. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155855. if(i<0){
  155856. return(vf->current_serialno);
  155857. }else{
  155858. return(vf->serialnos[i]);
  155859. }
  155860. }
  155861. /* returns: total raw (compressed) length of content if i==-1
  155862. raw (compressed) length of that logical bitstream for i==0 to n
  155863. OV_EINVAL if the stream is not seekable (we can't know the length)
  155864. or if stream is only partially open
  155865. */
  155866. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155867. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155868. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155869. if(i<0){
  155870. ogg_int64_t acc=0;
  155871. int i;
  155872. for(i=0;i<vf->links;i++)
  155873. acc+=ov_raw_total(vf,i);
  155874. return(acc);
  155875. }else{
  155876. return(vf->offsets[i+1]-vf->offsets[i]);
  155877. }
  155878. }
  155879. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155880. (samples) of that logical bitstream for i==0 to n
  155881. OV_EINVAL if the stream is not seekable (we can't know the
  155882. length) or only partially open
  155883. */
  155884. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155885. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155886. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155887. if(i<0){
  155888. ogg_int64_t acc=0;
  155889. int i;
  155890. for(i=0;i<vf->links;i++)
  155891. acc+=ov_pcm_total(vf,i);
  155892. return(acc);
  155893. }else{
  155894. return(vf->pcmlengths[i*2+1]);
  155895. }
  155896. }
  155897. /* returns: total seconds of content if i==-1
  155898. seconds in that logical bitstream for i==0 to n
  155899. OV_EINVAL if the stream is not seekable (we can't know the
  155900. length) or only partially open
  155901. */
  155902. double ov_time_total(OggVorbis_File *vf,int i){
  155903. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155904. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155905. if(i<0){
  155906. double acc=0;
  155907. int i;
  155908. for(i=0;i<vf->links;i++)
  155909. acc+=ov_time_total(vf,i);
  155910. return(acc);
  155911. }else{
  155912. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155913. }
  155914. }
  155915. /* seek to an offset relative to the *compressed* data. This also
  155916. scans packets to update the PCM cursor. It will cross a logical
  155917. bitstream boundary, but only if it can't get any packets out of the
  155918. tail of the bitstream we seek to (so no surprises).
  155919. returns zero on success, nonzero on failure */
  155920. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155921. ogg_stream_state work_os;
  155922. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155923. if(!vf->seekable)
  155924. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155925. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155926. /* don't yet clear out decoding machine (if it's initialized), in
  155927. the case we're in the same link. Restart the decode lapping, and
  155928. let _fetch_and_process_packet deal with a potential bitstream
  155929. boundary */
  155930. vf->pcm_offset=-1;
  155931. ogg_stream_reset_serialno(&vf->os,
  155932. vf->current_serialno); /* must set serialno */
  155933. vorbis_synthesis_restart(&vf->vd);
  155934. _seek_helper(vf,pos);
  155935. /* we need to make sure the pcm_offset is set, but we don't want to
  155936. advance the raw cursor past good packets just to get to the first
  155937. with a granulepos. That's not equivalent behavior to beginning
  155938. decoding as immediately after the seek position as possible.
  155939. So, a hack. We use two stream states; a local scratch state and
  155940. the shared vf->os stream state. We use the local state to
  155941. scan, and the shared state as a buffer for later decode.
  155942. Unfortuantely, on the last page we still advance to last packet
  155943. because the granulepos on the last page is not necessarily on a
  155944. packet boundary, and we need to make sure the granpos is
  155945. correct.
  155946. */
  155947. {
  155948. ogg_page og;
  155949. ogg_packet op;
  155950. int lastblock=0;
  155951. int accblock=0;
  155952. int thisblock;
  155953. int eosflag;
  155954. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155955. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155956. return from not necessarily
  155957. starting from the beginning */
  155958. while(1){
  155959. if(vf->ready_state>=STREAMSET){
  155960. /* snarf/scan a packet if we can */
  155961. int result=ogg_stream_packetout(&work_os,&op);
  155962. if(result>0){
  155963. if(vf->vi[vf->current_link].codec_setup){
  155964. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155965. if(thisblock<0){
  155966. ogg_stream_packetout(&vf->os,NULL);
  155967. thisblock=0;
  155968. }else{
  155969. if(eosflag)
  155970. ogg_stream_packetout(&vf->os,NULL);
  155971. else
  155972. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155973. }
  155974. if(op.granulepos!=-1){
  155975. int i,link=vf->current_link;
  155976. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155977. if(granulepos<0)granulepos=0;
  155978. for(i=0;i<link;i++)
  155979. granulepos+=vf->pcmlengths[i*2+1];
  155980. vf->pcm_offset=granulepos-accblock;
  155981. break;
  155982. }
  155983. lastblock=thisblock;
  155984. continue;
  155985. }else
  155986. ogg_stream_packetout(&vf->os,NULL);
  155987. }
  155988. }
  155989. if(!lastblock){
  155990. if(_get_next_page(vf,&og,-1)<0){
  155991. vf->pcm_offset=ov_pcm_total(vf,-1);
  155992. break;
  155993. }
  155994. }else{
  155995. /* huh? Bogus stream with packets but no granulepos */
  155996. vf->pcm_offset=-1;
  155997. break;
  155998. }
  155999. /* has our decoding just traversed a bitstream boundary? */
  156000. if(vf->ready_state>=STREAMSET)
  156001. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156002. _decode_clear(vf); /* clear out stream state */
  156003. ogg_stream_clear(&work_os);
  156004. }
  156005. if(vf->ready_state<STREAMSET){
  156006. int link;
  156007. vf->current_serialno=ogg_page_serialno(&og);
  156008. for(link=0;link<vf->links;link++)
  156009. if(vf->serialnos[link]==vf->current_serialno)break;
  156010. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156011. error out, leave
  156012. machine uninitialized */
  156013. vf->current_link=link;
  156014. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156015. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156016. vf->ready_state=STREAMSET;
  156017. }
  156018. ogg_stream_pagein(&vf->os,&og);
  156019. ogg_stream_pagein(&work_os,&og);
  156020. eosflag=ogg_page_eos(&og);
  156021. }
  156022. }
  156023. ogg_stream_clear(&work_os);
  156024. vf->bittrack=0.f;
  156025. vf->samptrack=0.f;
  156026. return(0);
  156027. seek_error:
  156028. /* dump the machine so we're in a known state */
  156029. vf->pcm_offset=-1;
  156030. ogg_stream_clear(&work_os);
  156031. _decode_clear(vf);
  156032. return OV_EBADLINK;
  156033. }
  156034. /* Page granularity seek (faster than sample granularity because we
  156035. don't do the last bit of decode to find a specific sample).
  156036. Seek to the last [granule marked] page preceeding the specified pos
  156037. location, such that decoding past the returned point will quickly
  156038. arrive at the requested position. */
  156039. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156040. int link=-1;
  156041. ogg_int64_t result=0;
  156042. ogg_int64_t total=ov_pcm_total(vf,-1);
  156043. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156044. if(!vf->seekable)return(OV_ENOSEEK);
  156045. if(pos<0 || pos>total)return(OV_EINVAL);
  156046. /* which bitstream section does this pcm offset occur in? */
  156047. for(link=vf->links-1;link>=0;link--){
  156048. total-=vf->pcmlengths[link*2+1];
  156049. if(pos>=total)break;
  156050. }
  156051. /* search within the logical bitstream for the page with the highest
  156052. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156053. missing pages or incorrect frame number information in the
  156054. bitstream could make our task impossible. Account for that (it
  156055. would be an error condition) */
  156056. /* new search algorithm by HB (Nicholas Vinen) */
  156057. {
  156058. ogg_int64_t end=vf->offsets[link+1];
  156059. ogg_int64_t begin=vf->offsets[link];
  156060. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156061. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156062. ogg_int64_t target=pos-total+begintime;
  156063. ogg_int64_t best=begin;
  156064. ogg_page og;
  156065. while(begin<end){
  156066. ogg_int64_t bisect;
  156067. if(end-begin<CHUNKSIZE){
  156068. bisect=begin;
  156069. }else{
  156070. /* take a (pretty decent) guess. */
  156071. bisect=begin +
  156072. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156073. if(bisect<=begin)
  156074. bisect=begin+1;
  156075. }
  156076. _seek_helper(vf,bisect);
  156077. while(begin<end){
  156078. result=_get_next_page(vf,&og,end-vf->offset);
  156079. if(result==OV_EREAD) goto seek_error;
  156080. if(result<0){
  156081. if(bisect<=begin+1)
  156082. end=begin; /* found it */
  156083. else{
  156084. if(bisect==0) goto seek_error;
  156085. bisect-=CHUNKSIZE;
  156086. if(bisect<=begin)bisect=begin+1;
  156087. _seek_helper(vf,bisect);
  156088. }
  156089. }else{
  156090. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156091. if(granulepos==-1)continue;
  156092. if(granulepos<target){
  156093. best=result; /* raw offset of packet with granulepos */
  156094. begin=vf->offset; /* raw offset of next page */
  156095. begintime=granulepos;
  156096. if(target-begintime>44100)break;
  156097. bisect=begin; /* *not* begin + 1 */
  156098. }else{
  156099. if(bisect<=begin+1)
  156100. end=begin; /* found it */
  156101. else{
  156102. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156103. end=result;
  156104. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156105. if(bisect<=begin)bisect=begin+1;
  156106. _seek_helper(vf,bisect);
  156107. }else{
  156108. end=result;
  156109. endtime=granulepos;
  156110. break;
  156111. }
  156112. }
  156113. }
  156114. }
  156115. }
  156116. }
  156117. /* found our page. seek to it, update pcm offset. Easier case than
  156118. raw_seek, don't keep packets preceeding granulepos. */
  156119. {
  156120. ogg_page og;
  156121. ogg_packet op;
  156122. /* seek */
  156123. _seek_helper(vf,best);
  156124. vf->pcm_offset=-1;
  156125. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156126. if(link!=vf->current_link){
  156127. /* Different link; dump entire decode machine */
  156128. _decode_clear(vf);
  156129. vf->current_link=link;
  156130. vf->current_serialno=ogg_page_serialno(&og);
  156131. vf->ready_state=STREAMSET;
  156132. }else{
  156133. vorbis_synthesis_restart(&vf->vd);
  156134. }
  156135. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156136. ogg_stream_pagein(&vf->os,&og);
  156137. /* pull out all but last packet; the one with granulepos */
  156138. while(1){
  156139. result=ogg_stream_packetpeek(&vf->os,&op);
  156140. if(result==0){
  156141. /* !!! the packet finishing this page originated on a
  156142. preceeding page. Keep fetching previous pages until we
  156143. get one with a granulepos or without the 'continued' flag
  156144. set. Then just use raw_seek for simplicity. */
  156145. _seek_helper(vf,best);
  156146. while(1){
  156147. result=_get_prev_page(vf,&og);
  156148. if(result<0) goto seek_error;
  156149. if(ogg_page_granulepos(&og)>-1 ||
  156150. !ogg_page_continued(&og)){
  156151. return ov_raw_seek(vf,result);
  156152. }
  156153. vf->offset=result;
  156154. }
  156155. }
  156156. if(result<0){
  156157. result = OV_EBADPACKET;
  156158. goto seek_error;
  156159. }
  156160. if(op.granulepos!=-1){
  156161. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156162. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156163. vf->pcm_offset+=total;
  156164. break;
  156165. }else
  156166. result=ogg_stream_packetout(&vf->os,NULL);
  156167. }
  156168. }
  156169. }
  156170. /* verify result */
  156171. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156172. result=OV_EFAULT;
  156173. goto seek_error;
  156174. }
  156175. vf->bittrack=0.f;
  156176. vf->samptrack=0.f;
  156177. return(0);
  156178. seek_error:
  156179. /* dump machine so we're in a known state */
  156180. vf->pcm_offset=-1;
  156181. _decode_clear(vf);
  156182. return (int)result;
  156183. }
  156184. /* seek to a sample offset relative to the decompressed pcm stream
  156185. returns zero on success, nonzero on failure */
  156186. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156187. int thisblock,lastblock=0;
  156188. int ret=ov_pcm_seek_page(vf,pos);
  156189. if(ret<0)return(ret);
  156190. if((ret=_make_decode_ready(vf)))return ret;
  156191. /* discard leading packets we don't need for the lapping of the
  156192. position we want; don't decode them */
  156193. while(1){
  156194. ogg_packet op;
  156195. ogg_page og;
  156196. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156197. if(ret>0){
  156198. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156199. if(thisblock<0){
  156200. ogg_stream_packetout(&vf->os,NULL);
  156201. continue; /* non audio packet */
  156202. }
  156203. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156204. if(vf->pcm_offset+((thisblock+
  156205. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156206. /* remove the packet from packet queue and track its granulepos */
  156207. ogg_stream_packetout(&vf->os,NULL);
  156208. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156209. only tracking, no
  156210. pcm_decode */
  156211. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156212. /* end of logical stream case is hard, especially with exact
  156213. length positioning. */
  156214. if(op.granulepos>-1){
  156215. int i;
  156216. /* always believe the stream markers */
  156217. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156218. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156219. for(i=0;i<vf->current_link;i++)
  156220. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156221. }
  156222. lastblock=thisblock;
  156223. }else{
  156224. if(ret<0 && ret!=OV_HOLE)break;
  156225. /* suck in a new page */
  156226. if(_get_next_page(vf,&og,-1)<0)break;
  156227. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156228. if(vf->ready_state<STREAMSET){
  156229. int link;
  156230. vf->current_serialno=ogg_page_serialno(&og);
  156231. for(link=0;link<vf->links;link++)
  156232. if(vf->serialnos[link]==vf->current_serialno)break;
  156233. if(link==vf->links)return(OV_EBADLINK);
  156234. vf->current_link=link;
  156235. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156236. vf->ready_state=STREAMSET;
  156237. ret=_make_decode_ready(vf);
  156238. if(ret)return ret;
  156239. lastblock=0;
  156240. }
  156241. ogg_stream_pagein(&vf->os,&og);
  156242. }
  156243. }
  156244. vf->bittrack=0.f;
  156245. vf->samptrack=0.f;
  156246. /* discard samples until we reach the desired position. Crossing a
  156247. logical bitstream boundary with abandon is OK. */
  156248. while(vf->pcm_offset<pos){
  156249. ogg_int64_t target=pos-vf->pcm_offset;
  156250. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156251. if(samples>target)samples=target;
  156252. vorbis_synthesis_read(&vf->vd,samples);
  156253. vf->pcm_offset+=samples;
  156254. if(samples<target)
  156255. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156256. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156257. }
  156258. return 0;
  156259. }
  156260. /* seek to a playback time relative to the decompressed pcm stream
  156261. returns zero on success, nonzero on failure */
  156262. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156263. /* translate time to PCM position and call ov_pcm_seek */
  156264. int link=-1;
  156265. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156266. double time_total=ov_time_total(vf,-1);
  156267. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156268. if(!vf->seekable)return(OV_ENOSEEK);
  156269. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156270. /* which bitstream section does this time offset occur in? */
  156271. for(link=vf->links-1;link>=0;link--){
  156272. pcm_total-=vf->pcmlengths[link*2+1];
  156273. time_total-=ov_time_total(vf,link);
  156274. if(seconds>=time_total)break;
  156275. }
  156276. /* enough information to convert time offset to pcm offset */
  156277. {
  156278. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156279. return(ov_pcm_seek(vf,target));
  156280. }
  156281. }
  156282. /* page-granularity version of ov_time_seek
  156283. returns zero on success, nonzero on failure */
  156284. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156285. /* translate time to PCM position and call ov_pcm_seek */
  156286. int link=-1;
  156287. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156288. double time_total=ov_time_total(vf,-1);
  156289. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156290. if(!vf->seekable)return(OV_ENOSEEK);
  156291. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156292. /* which bitstream section does this time offset occur in? */
  156293. for(link=vf->links-1;link>=0;link--){
  156294. pcm_total-=vf->pcmlengths[link*2+1];
  156295. time_total-=ov_time_total(vf,link);
  156296. if(seconds>=time_total)break;
  156297. }
  156298. /* enough information to convert time offset to pcm offset */
  156299. {
  156300. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156301. return(ov_pcm_seek_page(vf,target));
  156302. }
  156303. }
  156304. /* tell the current stream offset cursor. Note that seek followed by
  156305. tell will likely not give the set offset due to caching */
  156306. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156307. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156308. return(vf->offset);
  156309. }
  156310. /* return PCM offset (sample) of next PCM sample to be read */
  156311. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156312. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156313. return(vf->pcm_offset);
  156314. }
  156315. /* return time offset (seconds) of next PCM sample to be read */
  156316. double ov_time_tell(OggVorbis_File *vf){
  156317. int link=0;
  156318. ogg_int64_t pcm_total=0;
  156319. double time_total=0.f;
  156320. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156321. if(vf->seekable){
  156322. pcm_total=ov_pcm_total(vf,-1);
  156323. time_total=ov_time_total(vf,-1);
  156324. /* which bitstream section does this time offset occur in? */
  156325. for(link=vf->links-1;link>=0;link--){
  156326. pcm_total-=vf->pcmlengths[link*2+1];
  156327. time_total-=ov_time_total(vf,link);
  156328. if(vf->pcm_offset>=pcm_total)break;
  156329. }
  156330. }
  156331. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156332. }
  156333. /* link: -1) return the vorbis_info struct for the bitstream section
  156334. currently being decoded
  156335. 0-n) to request information for a specific bitstream section
  156336. In the case of a non-seekable bitstream, any call returns the
  156337. current bitstream. NULL in the case that the machine is not
  156338. initialized */
  156339. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156340. if(vf->seekable){
  156341. if(link<0)
  156342. if(vf->ready_state>=STREAMSET)
  156343. return vf->vi+vf->current_link;
  156344. else
  156345. return vf->vi;
  156346. else
  156347. if(link>=vf->links)
  156348. return NULL;
  156349. else
  156350. return vf->vi+link;
  156351. }else{
  156352. return vf->vi;
  156353. }
  156354. }
  156355. /* grr, strong typing, grr, no templates/inheritence, grr */
  156356. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156357. if(vf->seekable){
  156358. if(link<0)
  156359. if(vf->ready_state>=STREAMSET)
  156360. return vf->vc+vf->current_link;
  156361. else
  156362. return vf->vc;
  156363. else
  156364. if(link>=vf->links)
  156365. return NULL;
  156366. else
  156367. return vf->vc+link;
  156368. }else{
  156369. return vf->vc;
  156370. }
  156371. }
  156372. static int host_is_big_endian() {
  156373. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156374. unsigned char *bytewise = (unsigned char *)&pattern;
  156375. if (bytewise[0] == 0xfe) return 1;
  156376. return 0;
  156377. }
  156378. /* up to this point, everything could more or less hide the multiple
  156379. logical bitstream nature of chaining from the toplevel application
  156380. if the toplevel application didn't particularly care. However, at
  156381. the point that we actually read audio back, the multiple-section
  156382. nature must surface: Multiple bitstream sections do not necessarily
  156383. have to have the same number of channels or sampling rate.
  156384. ov_read returns the sequential logical bitstream number currently
  156385. being decoded along with the PCM data in order that the toplevel
  156386. application can take action on channel/sample rate changes. This
  156387. number will be incremented even for streamed (non-seekable) streams
  156388. (for seekable streams, it represents the actual logical bitstream
  156389. index within the physical bitstream. Note that the accessor
  156390. functions above are aware of this dichotomy).
  156391. input values: buffer) a buffer to hold packed PCM data for return
  156392. length) the byte length requested to be placed into buffer
  156393. bigendianp) should the data be packed LSB first (0) or
  156394. MSB first (1)
  156395. word) word size for output. currently 1 (byte) or
  156396. 2 (16 bit short)
  156397. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156398. 0) EOF
  156399. n) number of bytes of PCM actually returned. The
  156400. below works on a packet-by-packet basis, so the
  156401. return length is not related to the 'length' passed
  156402. in, just guaranteed to fit.
  156403. *section) set to the logical bitstream number */
  156404. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156405. int bigendianp,int word,int sgned,int *bitstream){
  156406. int i,j;
  156407. int host_endian = host_is_big_endian();
  156408. float **pcm;
  156409. long samples;
  156410. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156411. while(1){
  156412. if(vf->ready_state==INITSET){
  156413. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156414. if(samples)break;
  156415. }
  156416. /* suck in another packet */
  156417. {
  156418. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156419. if(ret==OV_EOF)
  156420. return(0);
  156421. if(ret<=0)
  156422. return(ret);
  156423. }
  156424. }
  156425. if(samples>0){
  156426. /* yay! proceed to pack data into the byte buffer */
  156427. long channels=ov_info(vf,-1)->channels;
  156428. long bytespersample=word * channels;
  156429. vorbis_fpu_control fpu;
  156430. (void) fpu; // (to avoid a warning about it being unused)
  156431. if(samples>length/bytespersample)samples=length/bytespersample;
  156432. if(samples <= 0)
  156433. return OV_EINVAL;
  156434. /* a tight loop to pack each size */
  156435. {
  156436. int val;
  156437. if(word==1){
  156438. int off=(sgned?0:128);
  156439. vorbis_fpu_setround(&fpu);
  156440. for(j=0;j<samples;j++)
  156441. for(i=0;i<channels;i++){
  156442. val=vorbis_ftoi(pcm[i][j]*128.f);
  156443. if(val>127)val=127;
  156444. else if(val<-128)val=-128;
  156445. *buffer++=val+off;
  156446. }
  156447. vorbis_fpu_restore(fpu);
  156448. }else{
  156449. int off=(sgned?0:32768);
  156450. if(host_endian==bigendianp){
  156451. if(sgned){
  156452. vorbis_fpu_setround(&fpu);
  156453. for(i=0;i<channels;i++) { /* It's faster in this order */
  156454. float *src=pcm[i];
  156455. short *dest=((short *)buffer)+i;
  156456. for(j=0;j<samples;j++) {
  156457. val=vorbis_ftoi(src[j]*32768.f);
  156458. if(val>32767)val=32767;
  156459. else if(val<-32768)val=-32768;
  156460. *dest=val;
  156461. dest+=channels;
  156462. }
  156463. }
  156464. vorbis_fpu_restore(fpu);
  156465. }else{
  156466. vorbis_fpu_setround(&fpu);
  156467. for(i=0;i<channels;i++) {
  156468. float *src=pcm[i];
  156469. short *dest=((short *)buffer)+i;
  156470. for(j=0;j<samples;j++) {
  156471. val=vorbis_ftoi(src[j]*32768.f);
  156472. if(val>32767)val=32767;
  156473. else if(val<-32768)val=-32768;
  156474. *dest=val+off;
  156475. dest+=channels;
  156476. }
  156477. }
  156478. vorbis_fpu_restore(fpu);
  156479. }
  156480. }else if(bigendianp){
  156481. vorbis_fpu_setround(&fpu);
  156482. for(j=0;j<samples;j++)
  156483. for(i=0;i<channels;i++){
  156484. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156485. if(val>32767)val=32767;
  156486. else if(val<-32768)val=-32768;
  156487. val+=off;
  156488. *buffer++=(val>>8);
  156489. *buffer++=(val&0xff);
  156490. }
  156491. vorbis_fpu_restore(fpu);
  156492. }else{
  156493. int val;
  156494. vorbis_fpu_setround(&fpu);
  156495. for(j=0;j<samples;j++)
  156496. for(i=0;i<channels;i++){
  156497. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156498. if(val>32767)val=32767;
  156499. else if(val<-32768)val=-32768;
  156500. val+=off;
  156501. *buffer++=(val&0xff);
  156502. *buffer++=(val>>8);
  156503. }
  156504. vorbis_fpu_restore(fpu);
  156505. }
  156506. }
  156507. }
  156508. vorbis_synthesis_read(&vf->vd,samples);
  156509. vf->pcm_offset+=samples;
  156510. if(bitstream)*bitstream=vf->current_link;
  156511. return(samples*bytespersample);
  156512. }else{
  156513. return(samples);
  156514. }
  156515. }
  156516. /* input values: pcm_channels) a float vector per channel of output
  156517. length) the sample length being read by the app
  156518. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156519. 0) EOF
  156520. n) number of samples of PCM actually returned. The
  156521. below works on a packet-by-packet basis, so the
  156522. return length is not related to the 'length' passed
  156523. in, just guaranteed to fit.
  156524. *section) set to the logical bitstream number */
  156525. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156526. int *bitstream){
  156527. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156528. while(1){
  156529. if(vf->ready_state==INITSET){
  156530. float **pcm;
  156531. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156532. if(samples){
  156533. if(pcm_channels)*pcm_channels=pcm;
  156534. if(samples>length)samples=length;
  156535. vorbis_synthesis_read(&vf->vd,samples);
  156536. vf->pcm_offset+=samples;
  156537. if(bitstream)*bitstream=vf->current_link;
  156538. return samples;
  156539. }
  156540. }
  156541. /* suck in another packet */
  156542. {
  156543. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156544. if(ret==OV_EOF)return(0);
  156545. if(ret<=0)return(ret);
  156546. }
  156547. }
  156548. }
  156549. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156550. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156551. ogg_int64_t off);
  156552. static void _ov_splice(float **pcm,float **lappcm,
  156553. int n1, int n2,
  156554. int ch1, int ch2,
  156555. float *w1, float *w2){
  156556. int i,j;
  156557. float *w=w1;
  156558. int n=n1;
  156559. if(n1>n2){
  156560. n=n2;
  156561. w=w2;
  156562. }
  156563. /* splice */
  156564. for(j=0;j<ch1 && j<ch2;j++){
  156565. float *s=lappcm[j];
  156566. float *d=pcm[j];
  156567. for(i=0;i<n;i++){
  156568. float wd=w[i]*w[i];
  156569. float ws=1.-wd;
  156570. d[i]=d[i]*wd + s[i]*ws;
  156571. }
  156572. }
  156573. /* window from zero */
  156574. for(;j<ch2;j++){
  156575. float *d=pcm[j];
  156576. for(i=0;i<n;i++){
  156577. float wd=w[i]*w[i];
  156578. d[i]=d[i]*wd;
  156579. }
  156580. }
  156581. }
  156582. /* make sure vf is INITSET */
  156583. static int _ov_initset(OggVorbis_File *vf){
  156584. while(1){
  156585. if(vf->ready_state==INITSET)break;
  156586. /* suck in another packet */
  156587. {
  156588. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156589. if(ret<0 && ret!=OV_HOLE)return(ret);
  156590. }
  156591. }
  156592. return 0;
  156593. }
  156594. /* make sure vf is INITSET and that we have a primed buffer; if
  156595. we're crosslapping at a stream section boundary, this also makes
  156596. sure we're sanity checking against the right stream information */
  156597. static int _ov_initprime(OggVorbis_File *vf){
  156598. vorbis_dsp_state *vd=&vf->vd;
  156599. while(1){
  156600. if(vf->ready_state==INITSET)
  156601. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156602. /* suck in another packet */
  156603. {
  156604. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156605. if(ret<0 && ret!=OV_HOLE)return(ret);
  156606. }
  156607. }
  156608. return 0;
  156609. }
  156610. /* grab enough data for lapping from vf; this may be in the form of
  156611. unreturned, already-decoded pcm, remaining PCM we will need to
  156612. decode, or synthetic postextrapolation from last packets. */
  156613. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156614. float **lappcm,int lapsize){
  156615. int lapcount=0,i;
  156616. float **pcm;
  156617. /* try first to decode the lapping data */
  156618. while(lapcount<lapsize){
  156619. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156620. if(samples){
  156621. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156622. for(i=0;i<vi->channels;i++)
  156623. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156624. lapcount+=samples;
  156625. vorbis_synthesis_read(vd,samples);
  156626. }else{
  156627. /* suck in another packet */
  156628. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156629. if(ret==OV_EOF)break;
  156630. }
  156631. }
  156632. if(lapcount<lapsize){
  156633. /* failed to get lapping data from normal decode; pry it from the
  156634. postextrapolation buffering, or the second half of the MDCT
  156635. from the last packet */
  156636. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156637. if(samples==0){
  156638. for(i=0;i<vi->channels;i++)
  156639. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156640. lapcount=lapsize;
  156641. }else{
  156642. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156643. for(i=0;i<vi->channels;i++)
  156644. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156645. lapcount+=samples;
  156646. }
  156647. }
  156648. }
  156649. /* this sets up crosslapping of a sample by using trailing data from
  156650. sample 1 and lapping it into the windowing buffer of sample 2 */
  156651. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156652. vorbis_info *vi1,*vi2;
  156653. float **lappcm;
  156654. float **pcm;
  156655. float *w1,*w2;
  156656. int n1,n2,i,ret,hs1,hs2;
  156657. if(vf1==vf2)return(0); /* degenerate case */
  156658. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156659. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156660. /* the relevant overlap buffers must be pre-checked and pre-primed
  156661. before looking at settings in the event that priming would cross
  156662. a bitstream boundary. So, do it now */
  156663. ret=_ov_initset(vf1);
  156664. if(ret)return(ret);
  156665. ret=_ov_initprime(vf2);
  156666. if(ret)return(ret);
  156667. vi1=ov_info(vf1,-1);
  156668. vi2=ov_info(vf2,-1);
  156669. hs1=ov_halfrate_p(vf1);
  156670. hs2=ov_halfrate_p(vf2);
  156671. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156672. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156673. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156674. w1=vorbis_window(&vf1->vd,0);
  156675. w2=vorbis_window(&vf2->vd,0);
  156676. for(i=0;i<vi1->channels;i++)
  156677. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156678. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156679. /* have a lapping buffer from vf1; now to splice it into the lapping
  156680. buffer of vf2 */
  156681. /* consolidate and expose the buffer. */
  156682. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156683. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156684. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156685. /* splice */
  156686. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156687. /* done */
  156688. return(0);
  156689. }
  156690. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156691. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156692. vorbis_info *vi;
  156693. float **lappcm;
  156694. float **pcm;
  156695. float *w1,*w2;
  156696. int n1,n2,ch1,ch2,hs;
  156697. int i,ret;
  156698. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156699. ret=_ov_initset(vf);
  156700. if(ret)return(ret);
  156701. vi=ov_info(vf,-1);
  156702. hs=ov_halfrate_p(vf);
  156703. ch1=vi->channels;
  156704. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156705. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156706. persistent; even if the decode state
  156707. from this link gets dumped, this
  156708. window array continues to exist */
  156709. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156710. for(i=0;i<ch1;i++)
  156711. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156712. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156713. /* have lapping data; seek and prime the buffer */
  156714. ret=localseek(vf,pos);
  156715. if(ret)return ret;
  156716. ret=_ov_initprime(vf);
  156717. if(ret)return(ret);
  156718. /* Guard against cross-link changes; they're perfectly legal */
  156719. vi=ov_info(vf,-1);
  156720. ch2=vi->channels;
  156721. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156722. w2=vorbis_window(&vf->vd,0);
  156723. /* consolidate and expose the buffer. */
  156724. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156725. /* splice */
  156726. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156727. /* done */
  156728. return(0);
  156729. }
  156730. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156731. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156732. }
  156733. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156734. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156735. }
  156736. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156737. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156738. }
  156739. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156740. int (*localseek)(OggVorbis_File *,double)){
  156741. vorbis_info *vi;
  156742. float **lappcm;
  156743. float **pcm;
  156744. float *w1,*w2;
  156745. int n1,n2,ch1,ch2,hs;
  156746. int i,ret;
  156747. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156748. ret=_ov_initset(vf);
  156749. if(ret)return(ret);
  156750. vi=ov_info(vf,-1);
  156751. hs=ov_halfrate_p(vf);
  156752. ch1=vi->channels;
  156753. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156754. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156755. persistent; even if the decode state
  156756. from this link gets dumped, this
  156757. window array continues to exist */
  156758. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156759. for(i=0;i<ch1;i++)
  156760. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156761. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156762. /* have lapping data; seek and prime the buffer */
  156763. ret=localseek(vf,pos);
  156764. if(ret)return ret;
  156765. ret=_ov_initprime(vf);
  156766. if(ret)return(ret);
  156767. /* Guard against cross-link changes; they're perfectly legal */
  156768. vi=ov_info(vf,-1);
  156769. ch2=vi->channels;
  156770. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156771. w2=vorbis_window(&vf->vd,0);
  156772. /* consolidate and expose the buffer. */
  156773. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156774. /* splice */
  156775. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156776. /* done */
  156777. return(0);
  156778. }
  156779. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156780. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156781. }
  156782. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156783. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156784. }
  156785. #endif
  156786. /*** End of inlined file: vorbisfile.c ***/
  156787. /*** Start of inlined file: window.c ***/
  156788. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156789. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156790. // tasks..
  156791. #if JUCE_MSVC
  156792. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156793. #endif
  156794. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156795. #if JUCE_USE_OGGVORBIS
  156796. #include <stdlib.h>
  156797. #include <math.h>
  156798. static float vwin64[32] = {
  156799. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156800. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156801. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156802. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156803. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156804. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156805. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156806. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156807. };
  156808. static float vwin128[64] = {
  156809. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156810. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156811. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156812. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156813. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156814. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156815. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156816. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156817. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156818. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156819. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156820. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156821. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156822. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156823. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156824. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156825. };
  156826. static float vwin256[128] = {
  156827. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156828. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156829. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156830. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156831. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156832. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156833. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156834. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156835. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156836. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156837. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156838. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156839. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156840. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156841. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156842. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156843. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156844. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156845. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156846. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156847. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156848. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156849. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156850. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156851. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156852. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156853. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156854. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156855. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156856. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156857. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156858. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156859. };
  156860. static float vwin512[256] = {
  156861. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156862. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156863. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156864. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156865. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156866. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156867. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156868. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156869. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156870. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156871. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156872. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156873. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156874. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156875. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156876. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156877. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156878. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156879. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156880. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156881. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156882. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156883. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156884. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156885. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156886. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156887. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156888. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156889. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156890. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156891. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156892. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156893. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156894. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156895. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156896. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156897. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156898. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156899. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156900. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156901. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156902. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156903. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156904. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156905. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156906. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156907. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156908. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156909. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156910. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156911. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156912. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156913. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156914. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156915. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156916. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156917. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156918. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156919. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156920. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156921. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156922. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156923. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156924. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156925. };
  156926. static float vwin1024[512] = {
  156927. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156928. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156929. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156930. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156931. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156932. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156933. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156934. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156935. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156936. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156937. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156938. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156939. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156940. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156941. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156942. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156943. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156944. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156945. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156946. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156947. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156948. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156949. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156950. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156951. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156952. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156953. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156954. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156955. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156956. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156957. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156958. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156959. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156960. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156961. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156962. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156963. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156964. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156965. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156966. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156967. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156968. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156969. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156970. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156971. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156972. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156973. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156974. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156975. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156976. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156977. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156978. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156979. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156980. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156981. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156982. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156983. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156984. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156985. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156986. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156987. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156988. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156989. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156990. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156991. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156992. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156993. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156994. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156995. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156996. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156997. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156998. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156999. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157000. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157001. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157002. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157003. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157004. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157005. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157006. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157007. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157008. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157009. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157010. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157011. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157012. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157013. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157014. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157015. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157016. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157017. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157018. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157019. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157020. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157021. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157022. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157023. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157024. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157025. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157026. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157027. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157028. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157029. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157030. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157031. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157032. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157033. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157034. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157035. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157036. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157037. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157038. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157039. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157040. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157041. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157042. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157043. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157044. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157045. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157046. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157047. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157048. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157049. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157050. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157051. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157052. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157053. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157054. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157055. };
  157056. static float vwin2048[1024] = {
  157057. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157058. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157059. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157060. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157061. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157062. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157063. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157064. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157065. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157066. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157067. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157068. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157069. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157070. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157071. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157072. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157073. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157074. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157075. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157076. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157077. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157078. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157079. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157080. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157081. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157082. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157083. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157084. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157085. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157086. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157087. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157088. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157089. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157090. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157091. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157092. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157093. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157094. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157095. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157096. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157097. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157098. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157099. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157100. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157101. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157102. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157103. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157104. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157105. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157106. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157107. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157108. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157109. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157110. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157111. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157112. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157113. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157114. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157115. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157116. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157117. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157118. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157119. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157120. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157121. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157122. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157123. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157124. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157125. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157126. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157127. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157128. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157129. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157130. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157131. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157132. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157133. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157134. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157135. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157136. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157137. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157138. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157139. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157140. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157141. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157142. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157143. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157144. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157145. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157146. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157147. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157148. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157149. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157150. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157151. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157152. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157153. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157154. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157155. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157156. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157157. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157158. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157159. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157160. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157161. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157162. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157163. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157164. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157165. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157166. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157167. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157168. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157169. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157170. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157171. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157172. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157173. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157174. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157175. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157176. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157177. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157178. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157179. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157180. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157181. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157182. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157183. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157184. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157185. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157186. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157187. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157188. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157189. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157190. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157191. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157192. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157193. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157194. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157195. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157196. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157197. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157198. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157199. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157200. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157201. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157202. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157203. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157204. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157205. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157206. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157207. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157208. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157209. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157210. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157211. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157212. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157213. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157214. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157215. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157216. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157217. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157218. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157219. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157220. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157221. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157222. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157223. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157224. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157225. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157226. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157227. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157228. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157229. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157230. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157231. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157232. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157233. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157234. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157235. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157236. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157237. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157238. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157239. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157240. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157241. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157242. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157243. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157244. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157245. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157246. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157247. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157248. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157249. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157250. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157251. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157252. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157253. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157254. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157255. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157256. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157257. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157258. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157259. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157260. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157261. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157262. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157263. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157264. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157265. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157266. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157267. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157268. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157269. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157270. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157271. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157272. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157273. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157274. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157275. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157276. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157277. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157278. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157279. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157280. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157281. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157282. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157283. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157284. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157285. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157286. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157287. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157288. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157289. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157290. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157291. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157292. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157293. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157294. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157295. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157296. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157297. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157298. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157299. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157300. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157301. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157302. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157303. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157304. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157305. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157306. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157307. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157308. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157309. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157310. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157311. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157312. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157313. };
  157314. static float vwin4096[2048] = {
  157315. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157316. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157317. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157318. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157319. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157320. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157321. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157322. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157323. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157324. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157325. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157326. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157327. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157328. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157329. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157330. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157331. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157332. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157333. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157334. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157335. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157336. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157337. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157338. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157339. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157340. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157341. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157342. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157343. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157344. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157345. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157346. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157347. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157348. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157349. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157350. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157351. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157352. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157353. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157354. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157355. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157356. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157357. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157358. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157359. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157360. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157361. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157362. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157363. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157364. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157365. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157366. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157367. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157368. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157369. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157370. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157371. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157372. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157373. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157374. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157375. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157376. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157377. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157378. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157379. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157380. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157381. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157382. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157383. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157384. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157385. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157386. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157387. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157388. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157389. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157390. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157391. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157392. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157393. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157394. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157395. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157396. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157397. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157398. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157399. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157400. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157401. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157402. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157403. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157404. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157405. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157406. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157407. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157408. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157409. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157410. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157411. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157412. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157413. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157414. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157415. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157416. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157417. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157418. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157419. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157420. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157421. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157422. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157423. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157424. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157425. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157426. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157427. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157428. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157429. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157430. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157431. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157432. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157433. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157434. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157435. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157436. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157437. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157438. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157439. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157440. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157441. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157442. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157443. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157444. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157445. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157446. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157447. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157448. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157449. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157450. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157451. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157452. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157453. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157454. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157455. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157456. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157457. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157458. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157459. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157460. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157461. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157462. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157463. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157464. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157465. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157466. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157467. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157468. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157469. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157470. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157471. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157472. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157473. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157474. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157475. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157476. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157477. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157478. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157479. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157480. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157481. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157482. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157483. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157484. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157485. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157486. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157487. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157488. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157489. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157490. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157491. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157492. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157493. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157494. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157495. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157496. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157497. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157498. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157499. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157500. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157501. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157502. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157503. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157504. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157505. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157506. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157507. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157508. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157509. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157510. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157511. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157512. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157513. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157514. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157515. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157516. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157517. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157518. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157519. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157520. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157521. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157522. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157523. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157524. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157525. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157526. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157527. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157528. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157529. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157530. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157531. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157532. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157533. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157534. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157535. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157536. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157537. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157538. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157539. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157540. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157541. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157542. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157543. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157544. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157545. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157546. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157547. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157548. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157549. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157550. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157551. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157552. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157553. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157554. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157555. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157556. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157557. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157558. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157559. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157560. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157561. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157562. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157563. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157564. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157565. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157566. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157567. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157568. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157569. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157570. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157571. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157572. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157573. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157574. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157575. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157576. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157577. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157578. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157579. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157580. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157581. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157582. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157583. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157584. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157585. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157586. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157587. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157588. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157589. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157590. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157591. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157592. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157593. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157594. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157595. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157596. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157597. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157598. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157599. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157600. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157601. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157602. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157603. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157604. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157605. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157606. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157607. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157608. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157609. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157610. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157611. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157612. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157613. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157614. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157615. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157616. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157617. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157618. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157619. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157620. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157621. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157622. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157623. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157624. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157625. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157626. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157627. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157628. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157629. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157630. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157631. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157632. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157633. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157634. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157635. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157636. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157637. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157638. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157639. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157640. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157641. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157642. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157643. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157644. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157645. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157646. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157647. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157648. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157649. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157650. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157651. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157652. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157653. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157654. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157655. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157656. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157657. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157658. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157659. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157660. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157661. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157662. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157663. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157664. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157665. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157666. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157667. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157668. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157669. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157670. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157671. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157672. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157673. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157674. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157675. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157676. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157677. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157678. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157679. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157680. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157681. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157682. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157683. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157684. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157685. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157686. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157687. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157688. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157689. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157690. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157691. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157692. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157693. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157694. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157695. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157696. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157697. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157698. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157699. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157700. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157701. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157702. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157703. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157704. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157705. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157706. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157707. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157708. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157709. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157710. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157711. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157712. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157713. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157714. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157715. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157716. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157717. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157718. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157719. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157720. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157721. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157722. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157723. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157724. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157725. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157726. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157727. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157728. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157729. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157730. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157731. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157732. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157733. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157734. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157735. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157736. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157737. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157738. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157739. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157740. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157741. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157742. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157743. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157744. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157745. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157746. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157747. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157748. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157749. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157750. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157751. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157752. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157753. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157754. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157755. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157756. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157757. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157758. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157759. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157760. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157761. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157762. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157763. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157764. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157765. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157766. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157767. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157768. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157769. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157770. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157771. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157772. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157773. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157774. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157775. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157776. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157777. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157778. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157779. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157780. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157781. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157782. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157783. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157784. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157785. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157786. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157787. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157788. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157789. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157790. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157791. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157792. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157793. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157794. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157795. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157796. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157797. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157798. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157799. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157800. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157801. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157802. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157803. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157804. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157805. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157806. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157807. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157808. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157809. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157810. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157811. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157812. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157813. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157814. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157815. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157816. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157817. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157818. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157819. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157820. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157821. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157822. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157823. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157824. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157825. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157826. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157827. };
  157828. static float vwin8192[4096] = {
  157829. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157830. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157831. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157832. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157833. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157834. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157835. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157836. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157837. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157838. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157839. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157840. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157841. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157842. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157843. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157844. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157845. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157846. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157847. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157848. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157849. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157850. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157851. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157852. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157853. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157854. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157855. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157856. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157857. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157858. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157859. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157860. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157861. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157862. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157863. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157864. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157865. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157866. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157867. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157868. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157869. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157870. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157871. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157872. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157873. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157874. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157875. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157876. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157877. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157878. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157879. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157880. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157881. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157882. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157883. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157884. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157885. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157886. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157887. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157888. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157889. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157890. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157891. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157892. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157893. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157894. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157895. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157896. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157897. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157898. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157899. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157900. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157901. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157902. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157903. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157904. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157905. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157906. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157907. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157908. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157909. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157910. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157911. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157912. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157913. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157914. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157915. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157916. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157917. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157918. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157919. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157920. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157921. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157922. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157923. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157924. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157925. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157926. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157927. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157928. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157929. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157930. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157931. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157932. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157933. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157934. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157935. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157936. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157937. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157938. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157939. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157940. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157941. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157942. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157943. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157944. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157945. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157946. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157947. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157948. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157949. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157950. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157951. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157952. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157953. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157954. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157955. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157956. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157957. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157958. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157959. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157960. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157961. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157962. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157963. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157964. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157965. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157966. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157967. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157968. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157969. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157970. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157971. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157972. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157973. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157974. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157975. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157976. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157977. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157978. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157979. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157980. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157981. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157982. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157983. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157984. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157985. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157986. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157987. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157988. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157989. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157990. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157991. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157992. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157993. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157994. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157995. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157996. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157997. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157998. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157999. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158000. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158001. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158002. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158003. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158004. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158005. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158006. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158007. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158008. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158009. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158010. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158011. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158012. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158013. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158014. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158015. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158016. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158017. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158018. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158019. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158020. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158021. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158022. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158023. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158024. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158025. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158026. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158027. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158028. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158029. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158030. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158031. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158032. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158033. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158034. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158035. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158036. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158037. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158038. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158039. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158040. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158041. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158042. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158043. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158044. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158045. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158046. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158047. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158048. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158049. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158050. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158051. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158052. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158053. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158054. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158055. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158056. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158057. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158058. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158059. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158060. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158061. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158062. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158063. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158064. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158065. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158066. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158067. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158068. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158069. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158070. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158071. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158072. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158073. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158074. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158075. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158076. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158077. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158078. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158079. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158080. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158081. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158082. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158083. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158084. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158085. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158086. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158087. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158088. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158089. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158090. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158091. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158092. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158093. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158094. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158095. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158096. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158097. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158098. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158099. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158100. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158101. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158102. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158103. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158104. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158105. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158106. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158107. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158108. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158109. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158110. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158111. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158112. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158113. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158114. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158115. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158116. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158117. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158118. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158119. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158120. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158121. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158122. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158123. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158124. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158125. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158126. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158127. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158128. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158129. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158130. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158131. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158132. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158133. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158134. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158135. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158136. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158137. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158138. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158139. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158140. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158141. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158142. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158143. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158144. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158145. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158146. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158147. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158148. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158149. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158150. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158151. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158152. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158153. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158154. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158155. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158156. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158157. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158158. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158159. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158160. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158161. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158162. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158163. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158164. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158165. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158166. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158167. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158168. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158169. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158170. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158171. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158172. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158173. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158174. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158175. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158176. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158177. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158178. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158179. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158180. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158181. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158182. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158183. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158184. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158185. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158186. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158187. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158188. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158189. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158190. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158191. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158192. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158193. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158194. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158195. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158196. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158197. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158198. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158199. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158200. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158201. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158202. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158203. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158204. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158205. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158206. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158207. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158208. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158209. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158210. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158211. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158212. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158213. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158214. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158215. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158216. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158217. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158218. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158219. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158220. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158221. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158222. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158223. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158224. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158225. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158226. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158227. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158228. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158229. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158230. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158231. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158232. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158233. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158234. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158235. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158236. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158237. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158238. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158239. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158240. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158241. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158242. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158243. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158244. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158245. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158246. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158247. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158248. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158249. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158250. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158251. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158252. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158253. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158254. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158255. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158256. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158257. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158258. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158259. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158260. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158261. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158262. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158263. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158264. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158265. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158266. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158267. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158268. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158269. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158270. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158271. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158272. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158273. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158274. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158275. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158276. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158277. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158278. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158279. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158280. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158281. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158282. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158283. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158284. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158285. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158286. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158287. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158288. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158289. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158290. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158291. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158292. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158293. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158294. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158295. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158296. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158297. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158298. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158299. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158300. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158301. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158302. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158303. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158304. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158305. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158306. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158307. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158308. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158309. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158310. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158311. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158312. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158313. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158314. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158315. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158316. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158317. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158318. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158319. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158320. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158321. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158322. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158323. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158324. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158325. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158326. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158327. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158328. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158329. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158330. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158331. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158332. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158333. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158334. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158335. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158336. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158337. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158338. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158339. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158340. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158341. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158342. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158343. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158344. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158345. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158346. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158347. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158348. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158349. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158350. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158351. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158352. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158353. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158354. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158355. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158356. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158357. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158358. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158359. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158360. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158361. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158362. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158363. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158364. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158365. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158366. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158367. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158368. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158369. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158370. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158371. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158372. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158373. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158374. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158375. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158376. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158377. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158378. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158379. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158380. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158381. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158382. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158383. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158384. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158385. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158386. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158387. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158388. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158389. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158390. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158391. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158392. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158393. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158394. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158395. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158396. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158397. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158398. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158399. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158400. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158401. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158402. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158403. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158404. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158405. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158406. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158407. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158408. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158409. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158410. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158411. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158412. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158413. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158414. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158415. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158416. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158417. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158418. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158419. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158420. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158421. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158422. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158423. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158424. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158425. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158426. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158427. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158428. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158429. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158430. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158431. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158432. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158433. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158434. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158435. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158436. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158437. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158438. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158439. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158440. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158441. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158442. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158443. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158444. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158445. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158446. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158447. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158448. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158449. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158450. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158451. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158452. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158453. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158454. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158455. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158456. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158457. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158458. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158459. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158460. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158461. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158462. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158463. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158464. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158465. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158466. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158467. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158468. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158469. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158470. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158471. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158472. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158473. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158474. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158475. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158476. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158477. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158478. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158479. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158480. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158481. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158482. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158483. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158484. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158485. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158486. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158487. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158488. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158489. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158490. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158491. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158492. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158493. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158494. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158495. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158496. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158497. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158498. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158499. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158500. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158501. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158502. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158503. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158504. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158505. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158506. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158507. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158508. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158509. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158510. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158511. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158512. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158513. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158514. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158515. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158516. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158517. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158518. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158519. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158520. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158521. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158522. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158523. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158524. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158525. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158526. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158527. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158528. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158529. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158530. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158531. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158532. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158533. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158534. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158535. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158536. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158537. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158538. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158539. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158540. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158541. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158542. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158543. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158544. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158545. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158546. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158547. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158548. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158549. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158550. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158551. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158552. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158553. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158554. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158555. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158556. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158557. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158558. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158559. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158560. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158561. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158562. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158563. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158564. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158565. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158566. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158567. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158568. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158569. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158570. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158571. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158572. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158573. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158574. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158575. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158576. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158577. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158578. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158579. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158580. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158581. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158582. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158583. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158584. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158585. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158586. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158587. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158588. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158589. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158590. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158591. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158592. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158593. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158594. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158595. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158596. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158597. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158598. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158599. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158600. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158601. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158602. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158603. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158604. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158605. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158606. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158607. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158608. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158609. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158610. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158611. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158612. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158613. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158614. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158615. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158616. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158617. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158618. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158619. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158620. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158621. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158622. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158623. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158624. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158625. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158626. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158627. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158628. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158629. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158630. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158631. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158632. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158633. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158634. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158635. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158636. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158637. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158638. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158639. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158640. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158641. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158642. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158643. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158644. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158645. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158646. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158647. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158648. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158649. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158650. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158651. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158652. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158653. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158654. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158655. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158656. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158657. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158658. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158659. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158660. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158661. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158662. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158663. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158664. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158665. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158666. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158667. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158668. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158669. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158670. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158671. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158672. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158673. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158674. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158675. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158676. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158677. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158678. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158679. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158680. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158681. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158682. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158683. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158684. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158685. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158686. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158687. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158688. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158689. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158690. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158691. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158692. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158693. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158694. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158695. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158696. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158697. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158698. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158699. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158700. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158701. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158702. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158703. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158704. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158705. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158706. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158707. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158708. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158709. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158710. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158711. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158712. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158713. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158714. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158715. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158716. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158717. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158718. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158719. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158720. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158721. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158722. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158723. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158724. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158725. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158726. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158727. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158728. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158729. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158730. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158731. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158732. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158733. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158734. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158735. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158736. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158737. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158738. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158739. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158740. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158741. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158742. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158743. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158744. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158745. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158746. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158747. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158748. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158749. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158750. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158751. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158752. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158753. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158754. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158755. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158756. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158757. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158758. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158759. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158760. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158761. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158762. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158763. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158764. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158765. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158766. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158767. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158768. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158769. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158770. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158771. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158772. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158773. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158774. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158775. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158776. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158777. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158778. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158779. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158780. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158781. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158782. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158783. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158784. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158785. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158786. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158787. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158788. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158789. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158790. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158791. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158792. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158793. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158794. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158795. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158796. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158797. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158798. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158799. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158800. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158801. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158802. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158803. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158804. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158805. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158806. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158807. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158808. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158809. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158810. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158811. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158812. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158813. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158814. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158815. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158816. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158817. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158818. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158819. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158820. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158821. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158822. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158823. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158824. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158825. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158826. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158827. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158828. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158829. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158830. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158831. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158832. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158833. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158834. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158835. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158836. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158837. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158838. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158839. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158840. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158841. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158842. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158843. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158844. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158845. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158846. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158847. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158848. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158849. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158850. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158851. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158852. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158853. };
  158854. static float *vwin[8] = {
  158855. vwin64,
  158856. vwin128,
  158857. vwin256,
  158858. vwin512,
  158859. vwin1024,
  158860. vwin2048,
  158861. vwin4096,
  158862. vwin8192,
  158863. };
  158864. float *_vorbis_window_get(int n){
  158865. return vwin[n];
  158866. }
  158867. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158868. int lW,int W,int nW){
  158869. lW=(W?lW:0);
  158870. nW=(W?nW:0);
  158871. {
  158872. float *windowLW=vwin[winno[lW]];
  158873. float *windowNW=vwin[winno[nW]];
  158874. long n=blocksizes[W];
  158875. long ln=blocksizes[lW];
  158876. long rn=blocksizes[nW];
  158877. long leftbegin=n/4-ln/4;
  158878. long leftend=leftbegin+ln/2;
  158879. long rightbegin=n/2+n/4-rn/4;
  158880. long rightend=rightbegin+rn/2;
  158881. int i,p;
  158882. for(i=0;i<leftbegin;i++)
  158883. d[i]=0.f;
  158884. for(p=0;i<leftend;i++,p++)
  158885. d[i]*=windowLW[p];
  158886. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158887. d[i]*=windowNW[p];
  158888. for(;i<n;i++)
  158889. d[i]=0.f;
  158890. }
  158891. }
  158892. #endif
  158893. /*** End of inlined file: window.c ***/
  158894. #else
  158895. #include <vorbis/vorbisenc.h>
  158896. #include <vorbis/codec.h>
  158897. #include <vorbis/vorbisfile.h>
  158898. #endif
  158899. }
  158900. #undef max
  158901. #undef min
  158902. BEGIN_JUCE_NAMESPACE
  158903. static const char* const oggFormatName = "Ogg-Vorbis file";
  158904. static const char* const oggExtensions[] = { ".ogg", 0 };
  158905. class OggReader : public AudioFormatReader
  158906. {
  158907. OggVorbisNamespace::OggVorbis_File ovFile;
  158908. OggVorbisNamespace::ov_callbacks callbacks;
  158909. AudioSampleBuffer reservoir;
  158910. int reservoirStart, samplesInReservoir;
  158911. public:
  158912. OggReader (InputStream* const inp)
  158913. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158914. reservoir (2, 4096),
  158915. reservoirStart (0),
  158916. samplesInReservoir (0)
  158917. {
  158918. using namespace OggVorbisNamespace;
  158919. sampleRate = 0;
  158920. usesFloatingPointData = true;
  158921. callbacks.read_func = &oggReadCallback;
  158922. callbacks.seek_func = &oggSeekCallback;
  158923. callbacks.close_func = &oggCloseCallback;
  158924. callbacks.tell_func = &oggTellCallback;
  158925. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158926. if (err == 0)
  158927. {
  158928. vorbis_info* info = ov_info (&ovFile, -1);
  158929. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158930. numChannels = info->channels;
  158931. bitsPerSample = 16;
  158932. sampleRate = info->rate;
  158933. reservoir.setSize (numChannels,
  158934. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158935. }
  158936. }
  158937. ~OggReader()
  158938. {
  158939. OggVorbisNamespace::ov_clear (&ovFile);
  158940. }
  158941. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158942. int64 startSampleInFile, int numSamples)
  158943. {
  158944. while (numSamples > 0)
  158945. {
  158946. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158947. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158948. {
  158949. // got a few samples overlapping, so use them before seeking..
  158950. const int numToUse = jmin (numSamples, numAvailable);
  158951. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158952. if (destSamples[i] != 0)
  158953. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158954. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158955. sizeof (float) * numToUse);
  158956. startSampleInFile += numToUse;
  158957. numSamples -= numToUse;
  158958. startOffsetInDestBuffer += numToUse;
  158959. if (numSamples == 0)
  158960. break;
  158961. }
  158962. if (startSampleInFile < reservoirStart
  158963. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158964. {
  158965. // buffer miss, so refill the reservoir
  158966. int bitStream = 0;
  158967. reservoirStart = jmax (0, (int) startSampleInFile);
  158968. samplesInReservoir = reservoir.getNumSamples();
  158969. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158970. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158971. int offset = 0;
  158972. int numToRead = samplesInReservoir;
  158973. while (numToRead > 0)
  158974. {
  158975. float** dataIn = 0;
  158976. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158977. if (samps <= 0)
  158978. break;
  158979. jassert (samps <= numToRead);
  158980. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158981. {
  158982. memcpy (reservoir.getSampleData (i, offset),
  158983. dataIn[i],
  158984. sizeof (float) * samps);
  158985. }
  158986. numToRead -= samps;
  158987. offset += samps;
  158988. }
  158989. if (numToRead > 0)
  158990. reservoir.clear (offset, numToRead);
  158991. }
  158992. }
  158993. if (numSamples > 0)
  158994. {
  158995. for (int i = numDestChannels; --i >= 0;)
  158996. if (destSamples[i] != 0)
  158997. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158998. sizeof (int) * numSamples);
  158999. }
  159000. return true;
  159001. }
  159002. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159003. {
  159004. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159005. }
  159006. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159007. {
  159008. InputStream* const in = static_cast <InputStream*> (datasource);
  159009. if (whence == SEEK_CUR)
  159010. offset += in->getPosition();
  159011. else if (whence == SEEK_END)
  159012. offset += in->getTotalLength();
  159013. in->setPosition (offset);
  159014. return 0;
  159015. }
  159016. static int oggCloseCallback (void*)
  159017. {
  159018. return 0;
  159019. }
  159020. static long oggTellCallback (void* datasource)
  159021. {
  159022. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159023. }
  159024. private:
  159025. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159026. };
  159027. class OggWriter : public AudioFormatWriter
  159028. {
  159029. OggVorbisNamespace::ogg_stream_state os;
  159030. OggVorbisNamespace::ogg_page og;
  159031. OggVorbisNamespace::ogg_packet op;
  159032. OggVorbisNamespace::vorbis_info vi;
  159033. OggVorbisNamespace::vorbis_comment vc;
  159034. OggVorbisNamespace::vorbis_dsp_state vd;
  159035. OggVorbisNamespace::vorbis_block vb;
  159036. public:
  159037. bool ok;
  159038. OggWriter (OutputStream* const out,
  159039. const double sampleRate,
  159040. const int numChannels,
  159041. const int bitsPerSample,
  159042. const int qualityIndex)
  159043. : AudioFormatWriter (out, TRANS (oggFormatName),
  159044. sampleRate,
  159045. numChannels,
  159046. bitsPerSample)
  159047. {
  159048. using namespace OggVorbisNamespace;
  159049. ok = false;
  159050. vorbis_info_init (&vi);
  159051. if (vorbis_encode_init_vbr (&vi,
  159052. numChannels,
  159053. (int) sampleRate,
  159054. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159055. {
  159056. vorbis_comment_init (&vc);
  159057. if (JUCEApplication::getInstance() != 0)
  159058. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8().getAddress()));
  159059. vorbis_analysis_init (&vd, &vi);
  159060. vorbis_block_init (&vd, &vb);
  159061. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159062. ogg_packet header;
  159063. ogg_packet header_comm;
  159064. ogg_packet header_code;
  159065. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159066. ogg_stream_packetin (&os, &header);
  159067. ogg_stream_packetin (&os, &header_comm);
  159068. ogg_stream_packetin (&os, &header_code);
  159069. for (;;)
  159070. {
  159071. if (ogg_stream_flush (&os, &og) == 0)
  159072. break;
  159073. output->write (og.header, og.header_len);
  159074. output->write (og.body, og.body_len);
  159075. }
  159076. ok = true;
  159077. }
  159078. }
  159079. ~OggWriter()
  159080. {
  159081. using namespace OggVorbisNamespace;
  159082. if (ok)
  159083. {
  159084. // write a zero-length packet to show ogg that we're finished..
  159085. write (0, 0);
  159086. ogg_stream_clear (&os);
  159087. vorbis_block_clear (&vb);
  159088. vorbis_dsp_clear (&vd);
  159089. vorbis_comment_clear (&vc);
  159090. vorbis_info_clear (&vi);
  159091. output->flush();
  159092. }
  159093. else
  159094. {
  159095. vorbis_info_clear (&vi);
  159096. output = 0; // to stop the base class deleting this, as it needs to be returned
  159097. // to the caller of createWriter()
  159098. }
  159099. }
  159100. bool write (const int** samplesToWrite, int numSamples)
  159101. {
  159102. using namespace OggVorbisNamespace;
  159103. if (! ok)
  159104. return false;
  159105. if (numSamples > 0)
  159106. {
  159107. const double gain = 1.0 / 0x80000000u;
  159108. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159109. for (int i = numChannels; --i >= 0;)
  159110. {
  159111. float* const dst = vorbisBuffer[i];
  159112. const int* const src = samplesToWrite [i];
  159113. if (src != 0 && dst != 0)
  159114. {
  159115. for (int j = 0; j < numSamples; ++j)
  159116. dst[j] = (float) (src[j] * gain);
  159117. }
  159118. }
  159119. }
  159120. vorbis_analysis_wrote (&vd, numSamples);
  159121. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159122. {
  159123. vorbis_analysis (&vb, 0);
  159124. vorbis_bitrate_addblock (&vb);
  159125. while (vorbis_bitrate_flushpacket (&vd, &op))
  159126. {
  159127. ogg_stream_packetin (&os, &op);
  159128. for (;;)
  159129. {
  159130. if (ogg_stream_pageout (&os, &og) == 0)
  159131. break;
  159132. output->write (og.header, og.header_len);
  159133. output->write (og.body, og.body_len);
  159134. if (ogg_page_eos (&og))
  159135. break;
  159136. }
  159137. }
  159138. }
  159139. return true;
  159140. }
  159141. private:
  159142. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159143. };
  159144. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159145. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159146. {
  159147. }
  159148. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159149. {
  159150. }
  159151. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159152. {
  159153. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159154. return Array <int> (rates);
  159155. }
  159156. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159157. {
  159158. const int depths[] = { 32, 0 };
  159159. return Array <int> (depths);
  159160. }
  159161. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159162. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159163. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159164. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159165. const bool deleteStreamIfOpeningFails)
  159166. {
  159167. ScopedPointer <OggReader> r (new OggReader (in));
  159168. if (r->sampleRate != 0)
  159169. return r.release();
  159170. if (! deleteStreamIfOpeningFails)
  159171. r->input = 0;
  159172. return 0;
  159173. }
  159174. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159175. double sampleRate,
  159176. unsigned int numChannels,
  159177. int bitsPerSample,
  159178. const StringPairArray& /*metadataValues*/,
  159179. int qualityOptionIndex)
  159180. {
  159181. ScopedPointer <OggWriter> w (new OggWriter (out,
  159182. sampleRate,
  159183. numChannels,
  159184. bitsPerSample,
  159185. qualityOptionIndex));
  159186. return w->ok ? w.release() : 0;
  159187. }
  159188. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159189. {
  159190. StringArray s;
  159191. s.add ("Low Quality");
  159192. s.add ("Medium Quality");
  159193. s.add ("High Quality");
  159194. return s;
  159195. }
  159196. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159197. {
  159198. FileInputStream* const in = source.createInputStream();
  159199. if (in != 0)
  159200. {
  159201. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159202. if (r != 0)
  159203. {
  159204. const int64 numSamps = r->lengthInSamples;
  159205. r = 0;
  159206. const int64 fileNumSamps = source.getSize() / 4;
  159207. const double ratio = numSamps / (double) fileNumSamps;
  159208. if (ratio > 12.0)
  159209. return 0;
  159210. else if (ratio > 6.0)
  159211. return 1;
  159212. else
  159213. return 2;
  159214. }
  159215. }
  159216. return 1;
  159217. }
  159218. END_JUCE_NAMESPACE
  159219. #endif
  159220. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159221. #endif
  159222. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159223. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159224. #if JUCE_MSVC
  159225. #pragma warning (push)
  159226. #endif
  159227. namespace jpeglibNamespace
  159228. {
  159229. #if JUCE_INCLUDE_JPEGLIB_CODE
  159230. #if JUCE_MINGW
  159231. typedef unsigned char boolean;
  159232. #endif
  159233. #define JPEG_INTERNALS
  159234. #undef FAR
  159235. /*** Start of inlined file: jpeglib.h ***/
  159236. #ifndef JPEGLIB_H
  159237. #define JPEGLIB_H
  159238. /*
  159239. * First we include the configuration files that record how this
  159240. * installation of the JPEG library is set up. jconfig.h can be
  159241. * generated automatically for many systems. jmorecfg.h contains
  159242. * manual configuration options that most people need not worry about.
  159243. */
  159244. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159245. /*** Start of inlined file: jconfig.h ***/
  159246. /* see jconfig.doc for explanations */
  159247. // disable all the warnings under MSVC
  159248. #ifdef _MSC_VER
  159249. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159250. #endif
  159251. #ifdef __BORLANDC__
  159252. #pragma warn -8057
  159253. #pragma warn -8019
  159254. #pragma warn -8004
  159255. #pragma warn -8008
  159256. #endif
  159257. #define HAVE_PROTOTYPES
  159258. #define HAVE_UNSIGNED_CHAR
  159259. #define HAVE_UNSIGNED_SHORT
  159260. /* #define void char */
  159261. /* #define const */
  159262. #undef CHAR_IS_UNSIGNED
  159263. #define HAVE_STDDEF_H
  159264. #define HAVE_STDLIB_H
  159265. #undef NEED_BSD_STRINGS
  159266. #undef NEED_SYS_TYPES_H
  159267. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159268. #undef NEED_SHORT_EXTERNAL_NAMES
  159269. #undef INCOMPLETE_TYPES_BROKEN
  159270. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159271. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159272. typedef unsigned char boolean;
  159273. #endif
  159274. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159275. #ifdef JPEG_INTERNALS
  159276. #undef RIGHT_SHIFT_IS_UNSIGNED
  159277. #endif /* JPEG_INTERNALS */
  159278. #ifdef JPEG_CJPEG_DJPEG
  159279. #define BMP_SUPPORTED /* BMP image file format */
  159280. #define GIF_SUPPORTED /* GIF image file format */
  159281. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159282. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159283. #define TARGA_SUPPORTED /* Targa image file format */
  159284. #define TWO_FILE_COMMANDLINE /* optional */
  159285. #define USE_SETMODE /* Microsoft has setmode() */
  159286. #undef NEED_SIGNAL_CATCHER
  159287. #undef DONT_USE_B_MODE
  159288. #undef PROGRESS_REPORT /* optional */
  159289. #endif /* JPEG_CJPEG_DJPEG */
  159290. /*** End of inlined file: jconfig.h ***/
  159291. /* widely used configuration options */
  159292. #endif
  159293. /*** Start of inlined file: jmorecfg.h ***/
  159294. /*
  159295. * Define BITS_IN_JSAMPLE as either
  159296. * 8 for 8-bit sample values (the usual setting)
  159297. * 12 for 12-bit sample values
  159298. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159299. * JPEG standard, and the IJG code does not support anything else!
  159300. * We do not support run-time selection of data precision, sorry.
  159301. */
  159302. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159303. /*
  159304. * Maximum number of components (color channels) allowed in JPEG image.
  159305. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159306. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159307. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159308. * really short on memory. (Each allowed component costs a hundred or so
  159309. * bytes of storage, whether actually used in an image or not.)
  159310. */
  159311. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159312. /*
  159313. * Basic data types.
  159314. * You may need to change these if you have a machine with unusual data
  159315. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159316. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159317. * but it had better be at least 16.
  159318. */
  159319. /* Representation of a single sample (pixel element value).
  159320. * We frequently allocate large arrays of these, so it's important to keep
  159321. * them small. But if you have memory to burn and access to char or short
  159322. * arrays is very slow on your hardware, you might want to change these.
  159323. */
  159324. #if BITS_IN_JSAMPLE == 8
  159325. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159326. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159327. */
  159328. #ifdef HAVE_UNSIGNED_CHAR
  159329. typedef unsigned char JSAMPLE;
  159330. #define GETJSAMPLE(value) ((int) (value))
  159331. #else /* not HAVE_UNSIGNED_CHAR */
  159332. typedef char JSAMPLE;
  159333. #ifdef CHAR_IS_UNSIGNED
  159334. #define GETJSAMPLE(value) ((int) (value))
  159335. #else
  159336. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159337. #endif /* CHAR_IS_UNSIGNED */
  159338. #endif /* HAVE_UNSIGNED_CHAR */
  159339. #define MAXJSAMPLE 255
  159340. #define CENTERJSAMPLE 128
  159341. #endif /* BITS_IN_JSAMPLE == 8 */
  159342. #if BITS_IN_JSAMPLE == 12
  159343. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159344. * On nearly all machines "short" will do nicely.
  159345. */
  159346. typedef short JSAMPLE;
  159347. #define GETJSAMPLE(value) ((int) (value))
  159348. #define MAXJSAMPLE 4095
  159349. #define CENTERJSAMPLE 2048
  159350. #endif /* BITS_IN_JSAMPLE == 12 */
  159351. /* Representation of a DCT frequency coefficient.
  159352. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159353. * Again, we allocate large arrays of these, but you can change to int
  159354. * if you have memory to burn and "short" is really slow.
  159355. */
  159356. typedef short JCOEF;
  159357. /* Compressed datastreams are represented as arrays of JOCTET.
  159358. * These must be EXACTLY 8 bits wide, at least once they are written to
  159359. * external storage. Note that when using the stdio data source/destination
  159360. * managers, this is also the data type passed to fread/fwrite.
  159361. */
  159362. #ifdef HAVE_UNSIGNED_CHAR
  159363. typedef unsigned char JOCTET;
  159364. #define GETJOCTET(value) (value)
  159365. #else /* not HAVE_UNSIGNED_CHAR */
  159366. typedef char JOCTET;
  159367. #ifdef CHAR_IS_UNSIGNED
  159368. #define GETJOCTET(value) (value)
  159369. #else
  159370. #define GETJOCTET(value) ((value) & 0xFF)
  159371. #endif /* CHAR_IS_UNSIGNED */
  159372. #endif /* HAVE_UNSIGNED_CHAR */
  159373. /* These typedefs are used for various table entries and so forth.
  159374. * They must be at least as wide as specified; but making them too big
  159375. * won't cost a huge amount of memory, so we don't provide special
  159376. * extraction code like we did for JSAMPLE. (In other words, these
  159377. * typedefs live at a different point on the speed/space tradeoff curve.)
  159378. */
  159379. /* UINT8 must hold at least the values 0..255. */
  159380. #ifdef HAVE_UNSIGNED_CHAR
  159381. typedef unsigned char UINT8;
  159382. #else /* not HAVE_UNSIGNED_CHAR */
  159383. #ifdef CHAR_IS_UNSIGNED
  159384. typedef char UINT8;
  159385. #else /* not CHAR_IS_UNSIGNED */
  159386. typedef short UINT8;
  159387. #endif /* CHAR_IS_UNSIGNED */
  159388. #endif /* HAVE_UNSIGNED_CHAR */
  159389. /* UINT16 must hold at least the values 0..65535. */
  159390. #ifdef HAVE_UNSIGNED_SHORT
  159391. typedef unsigned short UINT16;
  159392. #else /* not HAVE_UNSIGNED_SHORT */
  159393. typedef unsigned int UINT16;
  159394. #endif /* HAVE_UNSIGNED_SHORT */
  159395. /* INT16 must hold at least the values -32768..32767. */
  159396. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159397. typedef short INT16;
  159398. #endif
  159399. /* INT32 must hold at least signed 32-bit values. */
  159400. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159401. typedef long INT32;
  159402. #endif
  159403. /* Datatype used for image dimensions. The JPEG standard only supports
  159404. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159405. * "unsigned int" is sufficient on all machines. However, if you need to
  159406. * handle larger images and you don't mind deviating from the spec, you
  159407. * can change this datatype.
  159408. */
  159409. typedef unsigned int JDIMENSION;
  159410. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159411. /* These macros are used in all function definitions and extern declarations.
  159412. * You could modify them if you need to change function linkage conventions;
  159413. * in particular, you'll need to do that to make the library a Windows DLL.
  159414. * Another application is to make all functions global for use with debuggers
  159415. * or code profilers that require it.
  159416. */
  159417. /* a function called through method pointers: */
  159418. #define METHODDEF(type) static type
  159419. /* a function used only in its module: */
  159420. #define LOCAL(type) static type
  159421. /* a function referenced thru EXTERNs: */
  159422. #define GLOBAL(type) type
  159423. /* a reference to a GLOBAL function: */
  159424. #define EXTERN(type) extern type
  159425. /* This macro is used to declare a "method", that is, a function pointer.
  159426. * We want to supply prototype parameters if the compiler can cope.
  159427. * Note that the arglist parameter must be parenthesized!
  159428. * Again, you can customize this if you need special linkage keywords.
  159429. */
  159430. #ifdef HAVE_PROTOTYPES
  159431. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159432. #else
  159433. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159434. #endif
  159435. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159436. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159437. * by just saying "FAR *" where such a pointer is needed. In a few places
  159438. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159439. */
  159440. #ifdef NEED_FAR_POINTERS
  159441. #define FAR far
  159442. #else
  159443. #define FAR
  159444. #endif
  159445. /*
  159446. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159447. * in standard header files. Or you may have conflicts with application-
  159448. * specific header files that you want to include together with these files.
  159449. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159450. */
  159451. #ifndef HAVE_BOOLEAN
  159452. typedef int boolean;
  159453. #endif
  159454. #ifndef FALSE /* in case these macros already exist */
  159455. #define FALSE 0 /* values of boolean */
  159456. #endif
  159457. #ifndef TRUE
  159458. #define TRUE 1
  159459. #endif
  159460. /*
  159461. * The remaining options affect code selection within the JPEG library,
  159462. * but they don't need to be visible to most applications using the library.
  159463. * To minimize application namespace pollution, the symbols won't be
  159464. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159465. */
  159466. #ifdef JPEG_INTERNALS
  159467. #define JPEG_INTERNAL_OPTIONS
  159468. #endif
  159469. #ifdef JPEG_INTERNAL_OPTIONS
  159470. /*
  159471. * These defines indicate whether to include various optional functions.
  159472. * Undefining some of these symbols will produce a smaller but less capable
  159473. * library. Note that you can leave certain source files out of the
  159474. * compilation/linking process if you've #undef'd the corresponding symbols.
  159475. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159476. */
  159477. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159478. /* Capability options common to encoder and decoder: */
  159479. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159480. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159481. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159482. /* Encoder capability options: */
  159483. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159484. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159485. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159486. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159487. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159488. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159489. * precision, so jchuff.c normally uses entropy optimization to compute
  159490. * usable tables for higher precision. If you don't want to do optimization,
  159491. * you'll have to supply different default Huffman tables.
  159492. * The exact same statements apply for progressive JPEG: the default tables
  159493. * don't work for progressive mode. (This may get fixed, however.)
  159494. */
  159495. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159496. /* Decoder capability options: */
  159497. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159498. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159499. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159500. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159501. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159502. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159503. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159504. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159505. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159506. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159507. /* more capability options later, no doubt */
  159508. /*
  159509. * Ordering of RGB data in scanlines passed to or from the application.
  159510. * If your application wants to deal with data in the order B,G,R, just
  159511. * change these macros. You can also deal with formats such as R,G,B,X
  159512. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159513. * the offsets will also change the order in which colormap data is organized.
  159514. * RESTRICTIONS:
  159515. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159516. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159517. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159518. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159519. * is not 3 (they don't understand about dummy color components!). So you
  159520. * can't use color quantization if you change that value.
  159521. */
  159522. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159523. #define RGB_GREEN 1 /* Offset of Green */
  159524. #define RGB_BLUE 2 /* Offset of Blue */
  159525. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159526. /* Definitions for speed-related optimizations. */
  159527. /* If your compiler supports inline functions, define INLINE
  159528. * as the inline keyword; otherwise define it as empty.
  159529. */
  159530. #ifndef INLINE
  159531. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159532. #define INLINE __inline__
  159533. #endif
  159534. #ifndef INLINE
  159535. #define INLINE /* default is to define it as empty */
  159536. #endif
  159537. #endif
  159538. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159539. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159540. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159541. */
  159542. #ifndef MULTIPLIER
  159543. #define MULTIPLIER int /* type for fastest integer multiply */
  159544. #endif
  159545. /* FAST_FLOAT should be either float or double, whichever is done faster
  159546. * by your compiler. (Note that this type is only used in the floating point
  159547. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159548. * Typically, float is faster in ANSI C compilers, while double is faster in
  159549. * pre-ANSI compilers (because they insist on converting to double anyway).
  159550. * The code below therefore chooses float if we have ANSI-style prototypes.
  159551. */
  159552. #ifndef FAST_FLOAT
  159553. #ifdef HAVE_PROTOTYPES
  159554. #define FAST_FLOAT float
  159555. #else
  159556. #define FAST_FLOAT double
  159557. #endif
  159558. #endif
  159559. #endif /* JPEG_INTERNAL_OPTIONS */
  159560. /*** End of inlined file: jmorecfg.h ***/
  159561. /* seldom changed options */
  159562. /* Version ID for the JPEG library.
  159563. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159564. */
  159565. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159566. /* Various constants determining the sizes of things.
  159567. * All of these are specified by the JPEG standard, so don't change them
  159568. * if you want to be compatible.
  159569. */
  159570. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159571. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159572. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159573. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159574. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159575. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159576. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159577. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159578. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159579. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159580. * to handle it. We even let you do this from the jconfig.h file. However,
  159581. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159582. * sometimes emits noncompliant files doesn't mean you should too.
  159583. */
  159584. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159585. #ifndef D_MAX_BLOCKS_IN_MCU
  159586. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159587. #endif
  159588. /* Data structures for images (arrays of samples and of DCT coefficients).
  159589. * On 80x86 machines, the image arrays are too big for near pointers,
  159590. * but the pointer arrays can fit in near memory.
  159591. */
  159592. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159593. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159594. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159595. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159596. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159597. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159598. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159599. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159600. /* Types for JPEG compression parameters and working tables. */
  159601. /* DCT coefficient quantization tables. */
  159602. typedef struct {
  159603. /* This array gives the coefficient quantizers in natural array order
  159604. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159605. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159606. */
  159607. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159608. /* This field is used only during compression. It's initialized FALSE when
  159609. * the table is created, and set TRUE when it's been output to the file.
  159610. * You could suppress output of a table by setting this to TRUE.
  159611. * (See jpeg_suppress_tables for an example.)
  159612. */
  159613. boolean sent_table; /* TRUE when table has been output */
  159614. } JQUANT_TBL;
  159615. /* Huffman coding tables. */
  159616. typedef struct {
  159617. /* These two fields directly represent the contents of a JPEG DHT marker */
  159618. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159619. /* length k bits; bits[0] is unused */
  159620. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159621. /* This field is used only during compression. It's initialized FALSE when
  159622. * the table is created, and set TRUE when it's been output to the file.
  159623. * You could suppress output of a table by setting this to TRUE.
  159624. * (See jpeg_suppress_tables for an example.)
  159625. */
  159626. boolean sent_table; /* TRUE when table has been output */
  159627. } JHUFF_TBL;
  159628. /* Basic info about one component (color channel). */
  159629. typedef struct {
  159630. /* These values are fixed over the whole image. */
  159631. /* For compression, they must be supplied by parameter setup; */
  159632. /* for decompression, they are read from the SOF marker. */
  159633. int component_id; /* identifier for this component (0..255) */
  159634. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159635. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159636. int v_samp_factor; /* vertical sampling factor (1..4) */
  159637. int quant_tbl_no; /* quantization table selector (0..3) */
  159638. /* These values may vary between scans. */
  159639. /* For compression, they must be supplied by parameter setup; */
  159640. /* for decompression, they are read from the SOS marker. */
  159641. /* The decompressor output side may not use these variables. */
  159642. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159643. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159644. /* Remaining fields should be treated as private by applications. */
  159645. /* These values are computed during compression or decompression startup: */
  159646. /* Component's size in DCT blocks.
  159647. * Any dummy blocks added to complete an MCU are not counted; therefore
  159648. * these values do not depend on whether a scan is interleaved or not.
  159649. */
  159650. JDIMENSION width_in_blocks;
  159651. JDIMENSION height_in_blocks;
  159652. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159653. * For decompression this is the size of the output from one DCT block,
  159654. * reflecting any scaling we choose to apply during the IDCT step.
  159655. * Values of 1,2,4,8 are likely to be supported. Note that different
  159656. * components may receive different IDCT scalings.
  159657. */
  159658. int DCT_scaled_size;
  159659. /* The downsampled dimensions are the component's actual, unpadded number
  159660. * of samples at the main buffer (preprocessing/compression interface), thus
  159661. * downsampled_width = ceil(image_width * Hi/Hmax)
  159662. * and similarly for height. For decompression, IDCT scaling is included, so
  159663. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159664. */
  159665. JDIMENSION downsampled_width; /* actual width in samples */
  159666. JDIMENSION downsampled_height; /* actual height in samples */
  159667. /* This flag is used only for decompression. In cases where some of the
  159668. * components will be ignored (eg grayscale output from YCbCr image),
  159669. * we can skip most computations for the unused components.
  159670. */
  159671. boolean component_needed; /* do we need the value of this component? */
  159672. /* These values are computed before starting a scan of the component. */
  159673. /* The decompressor output side may not use these variables. */
  159674. int MCU_width; /* number of blocks per MCU, horizontally */
  159675. int MCU_height; /* number of blocks per MCU, vertically */
  159676. int MCU_blocks; /* MCU_width * MCU_height */
  159677. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159678. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159679. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159680. /* Saved quantization table for component; NULL if none yet saved.
  159681. * See jdinput.c comments about the need for this information.
  159682. * This field is currently used only for decompression.
  159683. */
  159684. JQUANT_TBL * quant_table;
  159685. /* Private per-component storage for DCT or IDCT subsystem. */
  159686. void * dct_table;
  159687. } jpeg_component_info;
  159688. /* The script for encoding a multiple-scan file is an array of these: */
  159689. typedef struct {
  159690. int comps_in_scan; /* number of components encoded in this scan */
  159691. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159692. int Ss, Se; /* progressive JPEG spectral selection parms */
  159693. int Ah, Al; /* progressive JPEG successive approx. parms */
  159694. } jpeg_scan_info;
  159695. /* The decompressor can save APPn and COM markers in a list of these: */
  159696. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159697. struct jpeg_marker_struct {
  159698. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159699. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159700. unsigned int original_length; /* # bytes of data in the file */
  159701. unsigned int data_length; /* # bytes of data saved at data[] */
  159702. JOCTET FAR * data; /* the data contained in the marker */
  159703. /* the marker length word is not counted in data_length or original_length */
  159704. };
  159705. /* Known color spaces. */
  159706. typedef enum {
  159707. JCS_UNKNOWN, /* error/unspecified */
  159708. JCS_GRAYSCALE, /* monochrome */
  159709. JCS_RGB, /* red/green/blue */
  159710. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159711. JCS_CMYK, /* C/M/Y/K */
  159712. JCS_YCCK /* Y/Cb/Cr/K */
  159713. } J_COLOR_SPACE;
  159714. /* DCT/IDCT algorithm options. */
  159715. typedef enum {
  159716. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159717. JDCT_IFAST, /* faster, less accurate integer method */
  159718. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159719. } J_DCT_METHOD;
  159720. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159721. #define JDCT_DEFAULT JDCT_ISLOW
  159722. #endif
  159723. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159724. #define JDCT_FASTEST JDCT_IFAST
  159725. #endif
  159726. /* Dithering options for decompression. */
  159727. typedef enum {
  159728. JDITHER_NONE, /* no dithering */
  159729. JDITHER_ORDERED, /* simple ordered dither */
  159730. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159731. } J_DITHER_MODE;
  159732. /* Common fields between JPEG compression and decompression master structs. */
  159733. #define jpeg_common_fields \
  159734. struct jpeg_error_mgr * err; /* Error handler module */\
  159735. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159736. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159737. void * client_data; /* Available for use by application */\
  159738. boolean is_decompressor; /* So common code can tell which is which */\
  159739. int global_state /* For checking call sequence validity */
  159740. /* Routines that are to be used by both halves of the library are declared
  159741. * to receive a pointer to this structure. There are no actual instances of
  159742. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159743. */
  159744. struct jpeg_common_struct {
  159745. jpeg_common_fields; /* Fields common to both master struct types */
  159746. /* Additional fields follow in an actual jpeg_compress_struct or
  159747. * jpeg_decompress_struct. All three structs must agree on these
  159748. * initial fields! (This would be a lot cleaner in C++.)
  159749. */
  159750. };
  159751. typedef struct jpeg_common_struct * j_common_ptr;
  159752. typedef struct jpeg_compress_struct * j_compress_ptr;
  159753. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159754. /* Master record for a compression instance */
  159755. struct jpeg_compress_struct {
  159756. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159757. /* Destination for compressed data */
  159758. struct jpeg_destination_mgr * dest;
  159759. /* Description of source image --- these fields must be filled in by
  159760. * outer application before starting compression. in_color_space must
  159761. * be correct before you can even call jpeg_set_defaults().
  159762. */
  159763. JDIMENSION image_width; /* input image width */
  159764. JDIMENSION image_height; /* input image height */
  159765. int input_components; /* # of color components in input image */
  159766. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159767. double input_gamma; /* image gamma of input image */
  159768. /* Compression parameters --- these fields must be set before calling
  159769. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159770. * initialize everything to reasonable defaults, then changing anything
  159771. * the application specifically wants to change. That way you won't get
  159772. * burnt when new parameters are added. Also note that there are several
  159773. * helper routines to simplify changing parameters.
  159774. */
  159775. int data_precision; /* bits of precision in image data */
  159776. int num_components; /* # of color components in JPEG image */
  159777. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159778. jpeg_component_info * comp_info;
  159779. /* comp_info[i] describes component that appears i'th in SOF */
  159780. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159781. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159782. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159783. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159784. /* ptrs to Huffman coding tables, or NULL if not defined */
  159785. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159786. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159787. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159788. int num_scans; /* # of entries in scan_info array */
  159789. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159790. /* The default value of scan_info is NULL, which causes a single-scan
  159791. * sequential JPEG file to be emitted. To create a multi-scan file,
  159792. * set num_scans and scan_info to point to an array of scan definitions.
  159793. */
  159794. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159795. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159796. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159797. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159798. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159799. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159800. /* The restart interval can be specified in absolute MCUs by setting
  159801. * restart_interval, or in MCU rows by setting restart_in_rows
  159802. * (in which case the correct restart_interval will be figured
  159803. * for each scan).
  159804. */
  159805. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159806. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159807. /* Parameters controlling emission of special markers. */
  159808. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159809. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159810. UINT8 JFIF_minor_version;
  159811. /* These three values are not used by the JPEG code, merely copied */
  159812. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159813. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159814. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159815. UINT8 density_unit; /* JFIF code for pixel size units */
  159816. UINT16 X_density; /* Horizontal pixel density */
  159817. UINT16 Y_density; /* Vertical pixel density */
  159818. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159819. /* State variable: index of next scanline to be written to
  159820. * jpeg_write_scanlines(). Application may use this to control its
  159821. * processing loop, e.g., "while (next_scanline < image_height)".
  159822. */
  159823. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159824. /* Remaining fields are known throughout compressor, but generally
  159825. * should not be touched by a surrounding application.
  159826. */
  159827. /*
  159828. * These fields are computed during compression startup
  159829. */
  159830. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159831. int max_h_samp_factor; /* largest h_samp_factor */
  159832. int max_v_samp_factor; /* largest v_samp_factor */
  159833. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159834. /* The coefficient controller receives data in units of MCU rows as defined
  159835. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159836. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159837. * "iMCU" (interleaved MCU) row.
  159838. */
  159839. /*
  159840. * These fields are valid during any one scan.
  159841. * They describe the components and MCUs actually appearing in the scan.
  159842. */
  159843. int comps_in_scan; /* # of JPEG components in this scan */
  159844. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159845. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159846. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159847. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159848. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159849. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159850. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159851. /* i'th block in an MCU */
  159852. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159853. /*
  159854. * Links to compression subobjects (methods and private variables of modules)
  159855. */
  159856. struct jpeg_comp_master * master;
  159857. struct jpeg_c_main_controller * main;
  159858. struct jpeg_c_prep_controller * prep;
  159859. struct jpeg_c_coef_controller * coef;
  159860. struct jpeg_marker_writer * marker;
  159861. struct jpeg_color_converter * cconvert;
  159862. struct jpeg_downsampler * downsample;
  159863. struct jpeg_forward_dct * fdct;
  159864. struct jpeg_entropy_encoder * entropy;
  159865. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159866. int script_space_size;
  159867. };
  159868. /* Master record for a decompression instance */
  159869. struct jpeg_decompress_struct {
  159870. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159871. /* Source of compressed data */
  159872. struct jpeg_source_mgr * src;
  159873. /* Basic description of image --- filled in by jpeg_read_header(). */
  159874. /* Application may inspect these values to decide how to process image. */
  159875. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159876. JDIMENSION image_height; /* nominal image height */
  159877. int num_components; /* # of color components in JPEG image */
  159878. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159879. /* Decompression processing parameters --- these fields must be set before
  159880. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159881. * them to default values.
  159882. */
  159883. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159884. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159885. double output_gamma; /* image gamma wanted in output */
  159886. boolean buffered_image; /* TRUE=multiple output passes */
  159887. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159888. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159889. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159890. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159891. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159892. /* the following are ignored if not quantize_colors: */
  159893. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159894. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159895. int desired_number_of_colors; /* max # colors to use in created colormap */
  159896. /* these are significant only in buffered-image mode: */
  159897. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159898. boolean enable_external_quant;/* enable future use of external colormap */
  159899. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159900. /* Description of actual output image that will be returned to application.
  159901. * These fields are computed by jpeg_start_decompress().
  159902. * You can also use jpeg_calc_output_dimensions() to determine these values
  159903. * in advance of calling jpeg_start_decompress().
  159904. */
  159905. JDIMENSION output_width; /* scaled image width */
  159906. JDIMENSION output_height; /* scaled image height */
  159907. int out_color_components; /* # of color components in out_color_space */
  159908. int output_components; /* # of color components returned */
  159909. /* output_components is 1 (a colormap index) when quantizing colors;
  159910. * otherwise it equals out_color_components.
  159911. */
  159912. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159913. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159914. * high, space and time will be wasted due to unnecessary data copying.
  159915. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159916. */
  159917. /* When quantizing colors, the output colormap is described by these fields.
  159918. * The application can supply a colormap by setting colormap non-NULL before
  159919. * calling jpeg_start_decompress; otherwise a colormap is created during
  159920. * jpeg_start_decompress or jpeg_start_output.
  159921. * The map has out_color_components rows and actual_number_of_colors columns.
  159922. */
  159923. int actual_number_of_colors; /* number of entries in use */
  159924. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159925. /* State variables: these variables indicate the progress of decompression.
  159926. * The application may examine these but must not modify them.
  159927. */
  159928. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159929. * Application may use this to control its processing loop, e.g.,
  159930. * "while (output_scanline < output_height)".
  159931. */
  159932. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159933. /* Current input scan number and number of iMCU rows completed in scan.
  159934. * These indicate the progress of the decompressor input side.
  159935. */
  159936. int input_scan_number; /* Number of SOS markers seen so far */
  159937. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159938. /* The "output scan number" is the notional scan being displayed by the
  159939. * output side. The decompressor will not allow output scan/row number
  159940. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159941. */
  159942. int output_scan_number; /* Nominal scan number being displayed */
  159943. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159944. /* Current progression status. coef_bits[c][i] indicates the precision
  159945. * with which component c's DCT coefficient i (in zigzag order) is known.
  159946. * It is -1 when no data has yet been received, otherwise it is the point
  159947. * transform (shift) value for the most recent scan of the coefficient
  159948. * (thus, 0 at completion of the progression).
  159949. * This pointer is NULL when reading a non-progressive file.
  159950. */
  159951. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159952. /* Internal JPEG parameters --- the application usually need not look at
  159953. * these fields. Note that the decompressor output side may not use
  159954. * any parameters that can change between scans.
  159955. */
  159956. /* Quantization and Huffman tables are carried forward across input
  159957. * datastreams when processing abbreviated JPEG datastreams.
  159958. */
  159959. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159960. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159961. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159962. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159963. /* ptrs to Huffman coding tables, or NULL if not defined */
  159964. /* These parameters are never carried across datastreams, since they
  159965. * are given in SOF/SOS markers or defined to be reset by SOI.
  159966. */
  159967. int data_precision; /* bits of precision in image data */
  159968. jpeg_component_info * comp_info;
  159969. /* comp_info[i] describes component that appears i'th in SOF */
  159970. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159971. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159972. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159973. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159974. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159975. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159976. /* These fields record data obtained from optional markers recognized by
  159977. * the JPEG library.
  159978. */
  159979. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159980. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159981. UINT8 JFIF_major_version; /* JFIF version number */
  159982. UINT8 JFIF_minor_version;
  159983. UINT8 density_unit; /* JFIF code for pixel size units */
  159984. UINT16 X_density; /* Horizontal pixel density */
  159985. UINT16 Y_density; /* Vertical pixel density */
  159986. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159987. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159988. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159989. /* Aside from the specific data retained from APPn markers known to the
  159990. * library, the uninterpreted contents of any or all APPn and COM markers
  159991. * can be saved in a list for examination by the application.
  159992. */
  159993. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159994. /* Remaining fields are known throughout decompressor, but generally
  159995. * should not be touched by a surrounding application.
  159996. */
  159997. /*
  159998. * These fields are computed during decompression startup
  159999. */
  160000. int max_h_samp_factor; /* largest h_samp_factor */
  160001. int max_v_samp_factor; /* largest v_samp_factor */
  160002. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160003. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160004. /* The coefficient controller's input and output progress is measured in
  160005. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160006. * in fully interleaved JPEG scans, but are used whether the scan is
  160007. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160008. * rows of each component. Therefore, the IDCT output contains
  160009. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160010. */
  160011. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160012. /*
  160013. * These fields are valid during any one scan.
  160014. * They describe the components and MCUs actually appearing in the scan.
  160015. * Note that the decompressor output side must not use these fields.
  160016. */
  160017. int comps_in_scan; /* # of JPEG components in this scan */
  160018. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160019. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160020. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160021. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160022. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160023. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160024. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160025. /* i'th block in an MCU */
  160026. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160027. /* This field is shared between entropy decoder and marker parser.
  160028. * It is either zero or the code of a JPEG marker that has been
  160029. * read from the data source, but has not yet been processed.
  160030. */
  160031. int unread_marker;
  160032. /*
  160033. * Links to decompression subobjects (methods, private variables of modules)
  160034. */
  160035. struct jpeg_decomp_master * master;
  160036. struct jpeg_d_main_controller * main;
  160037. struct jpeg_d_coef_controller * coef;
  160038. struct jpeg_d_post_controller * post;
  160039. struct jpeg_input_controller * inputctl;
  160040. struct jpeg_marker_reader * marker;
  160041. struct jpeg_entropy_decoder * entropy;
  160042. struct jpeg_inverse_dct * idct;
  160043. struct jpeg_upsampler * upsample;
  160044. struct jpeg_color_deconverter * cconvert;
  160045. struct jpeg_color_quantizer * cquantize;
  160046. };
  160047. /* "Object" declarations for JPEG modules that may be supplied or called
  160048. * directly by the surrounding application.
  160049. * As with all objects in the JPEG library, these structs only define the
  160050. * publicly visible methods and state variables of a module. Additional
  160051. * private fields may exist after the public ones.
  160052. */
  160053. /* Error handler object */
  160054. struct jpeg_error_mgr {
  160055. /* Error exit handler: does not return to caller */
  160056. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160057. /* Conditionally emit a trace or warning message */
  160058. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160059. /* Routine that actually outputs a trace or error message */
  160060. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160061. /* Format a message string for the most recent JPEG error or message */
  160062. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160063. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160064. /* Reset error state variables at start of a new image */
  160065. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160066. /* The message ID code and any parameters are saved here.
  160067. * A message can have one string parameter or up to 8 int parameters.
  160068. */
  160069. int msg_code;
  160070. #define JMSG_STR_PARM_MAX 80
  160071. union {
  160072. int i[8];
  160073. char s[JMSG_STR_PARM_MAX];
  160074. } msg_parm;
  160075. /* Standard state variables for error facility */
  160076. int trace_level; /* max msg_level that will be displayed */
  160077. /* For recoverable corrupt-data errors, we emit a warning message,
  160078. * but keep going unless emit_message chooses to abort. emit_message
  160079. * should count warnings in num_warnings. The surrounding application
  160080. * can check for bad data by seeing if num_warnings is nonzero at the
  160081. * end of processing.
  160082. */
  160083. long num_warnings; /* number of corrupt-data warnings */
  160084. /* These fields point to the table(s) of error message strings.
  160085. * An application can change the table pointer to switch to a different
  160086. * message list (typically, to change the language in which errors are
  160087. * reported). Some applications may wish to add additional error codes
  160088. * that will be handled by the JPEG library error mechanism; the second
  160089. * table pointer is used for this purpose.
  160090. *
  160091. * First table includes all errors generated by JPEG library itself.
  160092. * Error code 0 is reserved for a "no such error string" message.
  160093. */
  160094. const char * const * jpeg_message_table; /* Library errors */
  160095. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160096. /* Second table can be added by application (see cjpeg/djpeg for example).
  160097. * It contains strings numbered first_addon_message..last_addon_message.
  160098. */
  160099. const char * const * addon_message_table; /* Non-library errors */
  160100. int first_addon_message; /* code for first string in addon table */
  160101. int last_addon_message; /* code for last string in addon table */
  160102. };
  160103. /* Progress monitor object */
  160104. struct jpeg_progress_mgr {
  160105. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160106. long pass_counter; /* work units completed in this pass */
  160107. long pass_limit; /* total number of work units in this pass */
  160108. int completed_passes; /* passes completed so far */
  160109. int total_passes; /* total number of passes expected */
  160110. };
  160111. /* Data destination object for compression */
  160112. struct jpeg_destination_mgr {
  160113. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160114. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160115. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160116. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160117. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160118. };
  160119. /* Data source object for decompression */
  160120. struct jpeg_source_mgr {
  160121. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160122. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160123. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160124. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160125. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160126. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160127. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160128. };
  160129. /* Memory manager object.
  160130. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160131. * and "really big" objects (virtual arrays with backing store if needed).
  160132. * The memory manager does not allow individual objects to be freed; rather,
  160133. * each created object is assigned to a pool, and whole pools can be freed
  160134. * at once. This is faster and more convenient than remembering exactly what
  160135. * to free, especially where malloc()/free() are not too speedy.
  160136. * NB: alloc routines never return NULL. They exit to error_exit if not
  160137. * successful.
  160138. */
  160139. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160140. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160141. #define JPOOL_NUMPOOLS 2
  160142. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160143. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160144. struct jpeg_memory_mgr {
  160145. /* Method pointers */
  160146. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160147. size_t sizeofobject));
  160148. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160149. size_t sizeofobject));
  160150. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160151. JDIMENSION samplesperrow,
  160152. JDIMENSION numrows));
  160153. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160154. JDIMENSION blocksperrow,
  160155. JDIMENSION numrows));
  160156. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160157. int pool_id,
  160158. boolean pre_zero,
  160159. JDIMENSION samplesperrow,
  160160. JDIMENSION numrows,
  160161. JDIMENSION maxaccess));
  160162. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160163. int pool_id,
  160164. boolean pre_zero,
  160165. JDIMENSION blocksperrow,
  160166. JDIMENSION numrows,
  160167. JDIMENSION maxaccess));
  160168. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160169. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160170. jvirt_sarray_ptr ptr,
  160171. JDIMENSION start_row,
  160172. JDIMENSION num_rows,
  160173. boolean writable));
  160174. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160175. jvirt_barray_ptr ptr,
  160176. JDIMENSION start_row,
  160177. JDIMENSION num_rows,
  160178. boolean writable));
  160179. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160180. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160181. /* Limit on memory allocation for this JPEG object. (Note that this is
  160182. * merely advisory, not a guaranteed maximum; it only affects the space
  160183. * used for virtual-array buffers.) May be changed by outer application
  160184. * after creating the JPEG object.
  160185. */
  160186. long max_memory_to_use;
  160187. /* Maximum allocation request accepted by alloc_large. */
  160188. long max_alloc_chunk;
  160189. };
  160190. /* Routine signature for application-supplied marker processing methods.
  160191. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160192. */
  160193. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160194. /* Declarations for routines called by application.
  160195. * The JPP macro hides prototype parameters from compilers that can't cope.
  160196. * Note JPP requires double parentheses.
  160197. */
  160198. #ifdef HAVE_PROTOTYPES
  160199. #define JPP(arglist) arglist
  160200. #else
  160201. #define JPP(arglist) ()
  160202. #endif
  160203. /* Short forms of external names for systems with brain-damaged linkers.
  160204. * We shorten external names to be unique in the first six letters, which
  160205. * is good enough for all known systems.
  160206. * (If your compiler itself needs names to be unique in less than 15
  160207. * characters, you are out of luck. Get a better compiler.)
  160208. */
  160209. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160210. #define jpeg_std_error jStdError
  160211. #define jpeg_CreateCompress jCreaCompress
  160212. #define jpeg_CreateDecompress jCreaDecompress
  160213. #define jpeg_destroy_compress jDestCompress
  160214. #define jpeg_destroy_decompress jDestDecompress
  160215. #define jpeg_stdio_dest jStdDest
  160216. #define jpeg_stdio_src jStdSrc
  160217. #define jpeg_set_defaults jSetDefaults
  160218. #define jpeg_set_colorspace jSetColorspace
  160219. #define jpeg_default_colorspace jDefColorspace
  160220. #define jpeg_set_quality jSetQuality
  160221. #define jpeg_set_linear_quality jSetLQuality
  160222. #define jpeg_add_quant_table jAddQuantTable
  160223. #define jpeg_quality_scaling jQualityScaling
  160224. #define jpeg_simple_progression jSimProgress
  160225. #define jpeg_suppress_tables jSuppressTables
  160226. #define jpeg_alloc_quant_table jAlcQTable
  160227. #define jpeg_alloc_huff_table jAlcHTable
  160228. #define jpeg_start_compress jStrtCompress
  160229. #define jpeg_write_scanlines jWrtScanlines
  160230. #define jpeg_finish_compress jFinCompress
  160231. #define jpeg_write_raw_data jWrtRawData
  160232. #define jpeg_write_marker jWrtMarker
  160233. #define jpeg_write_m_header jWrtMHeader
  160234. #define jpeg_write_m_byte jWrtMByte
  160235. #define jpeg_write_tables jWrtTables
  160236. #define jpeg_read_header jReadHeader
  160237. #define jpeg_start_decompress jStrtDecompress
  160238. #define jpeg_read_scanlines jReadScanlines
  160239. #define jpeg_finish_decompress jFinDecompress
  160240. #define jpeg_read_raw_data jReadRawData
  160241. #define jpeg_has_multiple_scans jHasMultScn
  160242. #define jpeg_start_output jStrtOutput
  160243. #define jpeg_finish_output jFinOutput
  160244. #define jpeg_input_complete jInComplete
  160245. #define jpeg_new_colormap jNewCMap
  160246. #define jpeg_consume_input jConsumeInput
  160247. #define jpeg_calc_output_dimensions jCalcDimensions
  160248. #define jpeg_save_markers jSaveMarkers
  160249. #define jpeg_set_marker_processor jSetMarker
  160250. #define jpeg_read_coefficients jReadCoefs
  160251. #define jpeg_write_coefficients jWrtCoefs
  160252. #define jpeg_copy_critical_parameters jCopyCrit
  160253. #define jpeg_abort_compress jAbrtCompress
  160254. #define jpeg_abort_decompress jAbrtDecompress
  160255. #define jpeg_abort jAbort
  160256. #define jpeg_destroy jDestroy
  160257. #define jpeg_resync_to_restart jResyncRestart
  160258. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160259. /* Default error-management setup */
  160260. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160261. JPP((struct jpeg_error_mgr * err));
  160262. /* Initialization of JPEG compression objects.
  160263. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160264. * names that applications should call. These expand to calls on
  160265. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160266. * passed for version mismatch checking.
  160267. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160268. */
  160269. #define jpeg_create_compress(cinfo) \
  160270. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160271. (size_t) sizeof(struct jpeg_compress_struct))
  160272. #define jpeg_create_decompress(cinfo) \
  160273. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160274. (size_t) sizeof(struct jpeg_decompress_struct))
  160275. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160276. int version, size_t structsize));
  160277. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160278. int version, size_t structsize));
  160279. /* Destruction of JPEG compression objects */
  160280. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160281. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160282. /* Standard data source and destination managers: stdio streams. */
  160283. /* Caller is responsible for opening the file before and closing after. */
  160284. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160285. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160286. /* Default parameter setup for compression */
  160287. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160288. /* Compression parameter setup aids */
  160289. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160290. J_COLOR_SPACE colorspace));
  160291. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160292. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160293. boolean force_baseline));
  160294. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160295. int scale_factor,
  160296. boolean force_baseline));
  160297. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160298. const unsigned int *basic_table,
  160299. int scale_factor,
  160300. boolean force_baseline));
  160301. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160302. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160303. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160304. boolean suppress));
  160305. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160306. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160307. /* Main entry points for compression */
  160308. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160309. boolean write_all_tables));
  160310. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160311. JSAMPARRAY scanlines,
  160312. JDIMENSION num_lines));
  160313. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160314. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160315. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160316. JSAMPIMAGE data,
  160317. JDIMENSION num_lines));
  160318. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160319. EXTERN(void) jpeg_write_marker
  160320. JPP((j_compress_ptr cinfo, int marker,
  160321. const JOCTET * dataptr, unsigned int datalen));
  160322. /* Same, but piecemeal. */
  160323. EXTERN(void) jpeg_write_m_header
  160324. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160325. EXTERN(void) jpeg_write_m_byte
  160326. JPP((j_compress_ptr cinfo, int val));
  160327. /* Alternate compression function: just write an abbreviated table file */
  160328. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160329. /* Decompression startup: read start of JPEG datastream to see what's there */
  160330. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160331. boolean require_image));
  160332. /* Return value is one of: */
  160333. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160334. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160335. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160336. /* If you pass require_image = TRUE (normal case), you need not check for
  160337. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160338. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160339. * give a suspension return (the stdio source module doesn't).
  160340. */
  160341. /* Main entry points for decompression */
  160342. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160343. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160344. JSAMPARRAY scanlines,
  160345. JDIMENSION max_lines));
  160346. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160347. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160348. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160349. JSAMPIMAGE data,
  160350. JDIMENSION max_lines));
  160351. /* Additional entry points for buffered-image mode. */
  160352. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160353. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160354. int scan_number));
  160355. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160356. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160357. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160358. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160359. /* Return value is one of: */
  160360. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160361. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160362. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160363. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160364. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160365. /* Precalculate output dimensions for current decompression parameters. */
  160366. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160367. /* Control saving of COM and APPn markers into marker_list. */
  160368. EXTERN(void) jpeg_save_markers
  160369. JPP((j_decompress_ptr cinfo, int marker_code,
  160370. unsigned int length_limit));
  160371. /* Install a special processing method for COM or APPn markers. */
  160372. EXTERN(void) jpeg_set_marker_processor
  160373. JPP((j_decompress_ptr cinfo, int marker_code,
  160374. jpeg_marker_parser_method routine));
  160375. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160376. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160377. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160378. jvirt_barray_ptr * coef_arrays));
  160379. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160380. j_compress_ptr dstinfo));
  160381. /* If you choose to abort compression or decompression before completing
  160382. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160383. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160384. * if you're done with the JPEG object, but if you want to clean it up and
  160385. * reuse it, call this:
  160386. */
  160387. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160388. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160389. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160390. * flavor of JPEG object. These may be more convenient in some places.
  160391. */
  160392. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160393. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160394. /* Default restart-marker-resync procedure for use by data source modules */
  160395. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160396. int desired));
  160397. /* These marker codes are exported since applications and data source modules
  160398. * are likely to want to use them.
  160399. */
  160400. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160401. #define JPEG_EOI 0xD9 /* EOI marker code */
  160402. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160403. #define JPEG_COM 0xFE /* COM marker code */
  160404. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160405. * for structure definitions that are never filled in, keep it quiet by
  160406. * supplying dummy definitions for the various substructures.
  160407. */
  160408. #ifdef INCOMPLETE_TYPES_BROKEN
  160409. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160410. struct jvirt_sarray_control { long dummy; };
  160411. struct jvirt_barray_control { long dummy; };
  160412. struct jpeg_comp_master { long dummy; };
  160413. struct jpeg_c_main_controller { long dummy; };
  160414. struct jpeg_c_prep_controller { long dummy; };
  160415. struct jpeg_c_coef_controller { long dummy; };
  160416. struct jpeg_marker_writer { long dummy; };
  160417. struct jpeg_color_converter { long dummy; };
  160418. struct jpeg_downsampler { long dummy; };
  160419. struct jpeg_forward_dct { long dummy; };
  160420. struct jpeg_entropy_encoder { long dummy; };
  160421. struct jpeg_decomp_master { long dummy; };
  160422. struct jpeg_d_main_controller { long dummy; };
  160423. struct jpeg_d_coef_controller { long dummy; };
  160424. struct jpeg_d_post_controller { long dummy; };
  160425. struct jpeg_input_controller { long dummy; };
  160426. struct jpeg_marker_reader { long dummy; };
  160427. struct jpeg_entropy_decoder { long dummy; };
  160428. struct jpeg_inverse_dct { long dummy; };
  160429. struct jpeg_upsampler { long dummy; };
  160430. struct jpeg_color_deconverter { long dummy; };
  160431. struct jpeg_color_quantizer { long dummy; };
  160432. #endif /* JPEG_INTERNALS */
  160433. #endif /* INCOMPLETE_TYPES_BROKEN */
  160434. /*
  160435. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160436. * The internal structure declarations are read only when that is true.
  160437. * Applications using the library should not include jpegint.h, but may wish
  160438. * to include jerror.h.
  160439. */
  160440. #ifdef JPEG_INTERNALS
  160441. /*** Start of inlined file: jpegint.h ***/
  160442. /* Declarations for both compression & decompression */
  160443. typedef enum { /* Operating modes for buffer controllers */
  160444. JBUF_PASS_THRU, /* Plain stripwise operation */
  160445. /* Remaining modes require a full-image buffer to have been created */
  160446. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160447. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160448. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160449. } J_BUF_MODE;
  160450. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160451. #define CSTATE_START 100 /* after create_compress */
  160452. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160453. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160454. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160455. #define DSTATE_START 200 /* after create_decompress */
  160456. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160457. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160458. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160459. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160460. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160461. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160462. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160463. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160464. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160465. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160466. /* Declarations for compression modules */
  160467. /* Master control module */
  160468. struct jpeg_comp_master {
  160469. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160470. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160471. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160472. /* State variables made visible to other modules */
  160473. boolean call_pass_startup; /* True if pass_startup must be called */
  160474. boolean is_last_pass; /* True during last pass */
  160475. };
  160476. /* Main buffer control (downsampled-data buffer) */
  160477. struct jpeg_c_main_controller {
  160478. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160479. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160480. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160481. JDIMENSION in_rows_avail));
  160482. };
  160483. /* Compression preprocessing (downsampling input buffer control) */
  160484. struct jpeg_c_prep_controller {
  160485. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160486. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160487. JSAMPARRAY input_buf,
  160488. JDIMENSION *in_row_ctr,
  160489. JDIMENSION in_rows_avail,
  160490. JSAMPIMAGE output_buf,
  160491. JDIMENSION *out_row_group_ctr,
  160492. JDIMENSION out_row_groups_avail));
  160493. };
  160494. /* Coefficient buffer control */
  160495. struct jpeg_c_coef_controller {
  160496. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160497. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160498. JSAMPIMAGE input_buf));
  160499. };
  160500. /* Colorspace conversion */
  160501. struct jpeg_color_converter {
  160502. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160503. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160504. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160505. JDIMENSION output_row, int num_rows));
  160506. };
  160507. /* Downsampling */
  160508. struct jpeg_downsampler {
  160509. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160510. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160511. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160512. JSAMPIMAGE output_buf,
  160513. JDIMENSION out_row_group_index));
  160514. boolean need_context_rows; /* TRUE if need rows above & below */
  160515. };
  160516. /* Forward DCT (also controls coefficient quantization) */
  160517. struct jpeg_forward_dct {
  160518. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160519. /* perhaps this should be an array??? */
  160520. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160521. jpeg_component_info * compptr,
  160522. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160523. JDIMENSION start_row, JDIMENSION start_col,
  160524. JDIMENSION num_blocks));
  160525. };
  160526. /* Entropy encoding */
  160527. struct jpeg_entropy_encoder {
  160528. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160529. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160530. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160531. };
  160532. /* Marker writing */
  160533. struct jpeg_marker_writer {
  160534. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160535. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160536. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160537. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160538. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160539. /* These routines are exported to allow insertion of extra markers */
  160540. /* Probably only COM and APPn markers should be written this way */
  160541. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160542. unsigned int datalen));
  160543. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160544. };
  160545. /* Declarations for decompression modules */
  160546. /* Master control module */
  160547. struct jpeg_decomp_master {
  160548. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160549. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160550. /* State variables made visible to other modules */
  160551. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160552. };
  160553. /* Input control module */
  160554. struct jpeg_input_controller {
  160555. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160556. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160557. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160558. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160559. /* State variables made visible to other modules */
  160560. boolean has_multiple_scans; /* True if file has multiple scans */
  160561. boolean eoi_reached; /* True when EOI has been consumed */
  160562. };
  160563. /* Main buffer control (downsampled-data buffer) */
  160564. struct jpeg_d_main_controller {
  160565. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160566. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160567. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160568. JDIMENSION out_rows_avail));
  160569. };
  160570. /* Coefficient buffer control */
  160571. struct jpeg_d_coef_controller {
  160572. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160573. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160574. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160575. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160576. JSAMPIMAGE output_buf));
  160577. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160578. jvirt_barray_ptr *coef_arrays;
  160579. };
  160580. /* Decompression postprocessing (color quantization buffer control) */
  160581. struct jpeg_d_post_controller {
  160582. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160583. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160584. JSAMPIMAGE input_buf,
  160585. JDIMENSION *in_row_group_ctr,
  160586. JDIMENSION in_row_groups_avail,
  160587. JSAMPARRAY output_buf,
  160588. JDIMENSION *out_row_ctr,
  160589. JDIMENSION out_rows_avail));
  160590. };
  160591. /* Marker reading & parsing */
  160592. struct jpeg_marker_reader {
  160593. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160594. /* Read markers until SOS or EOI.
  160595. * Returns same codes as are defined for jpeg_consume_input:
  160596. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160597. */
  160598. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160599. /* Read a restart marker --- exported for use by entropy decoder only */
  160600. jpeg_marker_parser_method read_restart_marker;
  160601. /* State of marker reader --- nominally internal, but applications
  160602. * supplying COM or APPn handlers might like to know the state.
  160603. */
  160604. boolean saw_SOI; /* found SOI? */
  160605. boolean saw_SOF; /* found SOF? */
  160606. int next_restart_num; /* next restart number expected (0-7) */
  160607. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160608. };
  160609. /* Entropy decoding */
  160610. struct jpeg_entropy_decoder {
  160611. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160612. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160613. JBLOCKROW *MCU_data));
  160614. /* This is here to share code between baseline and progressive decoders; */
  160615. /* other modules probably should not use it */
  160616. boolean insufficient_data; /* set TRUE after emitting warning */
  160617. };
  160618. /* Inverse DCT (also performs dequantization) */
  160619. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160620. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160621. JCOEFPTR coef_block,
  160622. JSAMPARRAY output_buf, JDIMENSION output_col));
  160623. struct jpeg_inverse_dct {
  160624. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160625. /* It is useful to allow each component to have a separate IDCT method. */
  160626. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160627. };
  160628. /* Upsampling (note that upsampler must also call color converter) */
  160629. struct jpeg_upsampler {
  160630. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160631. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160632. JSAMPIMAGE input_buf,
  160633. JDIMENSION *in_row_group_ctr,
  160634. JDIMENSION in_row_groups_avail,
  160635. JSAMPARRAY output_buf,
  160636. JDIMENSION *out_row_ctr,
  160637. JDIMENSION out_rows_avail));
  160638. boolean need_context_rows; /* TRUE if need rows above & below */
  160639. };
  160640. /* Colorspace conversion */
  160641. struct jpeg_color_deconverter {
  160642. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160643. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160644. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160645. JSAMPARRAY output_buf, int num_rows));
  160646. };
  160647. /* Color quantization or color precision reduction */
  160648. struct jpeg_color_quantizer {
  160649. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160650. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160651. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160652. int num_rows));
  160653. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160654. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160655. };
  160656. /* Miscellaneous useful macros */
  160657. #undef MAX
  160658. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160659. #undef MIN
  160660. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160661. /* We assume that right shift corresponds to signed division by 2 with
  160662. * rounding towards minus infinity. This is correct for typical "arithmetic
  160663. * shift" instructions that shift in copies of the sign bit. But some
  160664. * C compilers implement >> with an unsigned shift. For these machines you
  160665. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160666. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160667. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160668. * included in the variables of any routine using RIGHT_SHIFT.
  160669. */
  160670. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160671. #define SHIFT_TEMPS INT32 shift_temp;
  160672. #define RIGHT_SHIFT(x,shft) \
  160673. ((shift_temp = (x)) < 0 ? \
  160674. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160675. (shift_temp >> (shft)))
  160676. #else
  160677. #define SHIFT_TEMPS
  160678. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160679. #endif
  160680. /* Short forms of external names for systems with brain-damaged linkers. */
  160681. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160682. #define jinit_compress_master jICompress
  160683. #define jinit_c_master_control jICMaster
  160684. #define jinit_c_main_controller jICMainC
  160685. #define jinit_c_prep_controller jICPrepC
  160686. #define jinit_c_coef_controller jICCoefC
  160687. #define jinit_color_converter jICColor
  160688. #define jinit_downsampler jIDownsampler
  160689. #define jinit_forward_dct jIFDCT
  160690. #define jinit_huff_encoder jIHEncoder
  160691. #define jinit_phuff_encoder jIPHEncoder
  160692. #define jinit_marker_writer jIMWriter
  160693. #define jinit_master_decompress jIDMaster
  160694. #define jinit_d_main_controller jIDMainC
  160695. #define jinit_d_coef_controller jIDCoefC
  160696. #define jinit_d_post_controller jIDPostC
  160697. #define jinit_input_controller jIInCtlr
  160698. #define jinit_marker_reader jIMReader
  160699. #define jinit_huff_decoder jIHDecoder
  160700. #define jinit_phuff_decoder jIPHDecoder
  160701. #define jinit_inverse_dct jIIDCT
  160702. #define jinit_upsampler jIUpsampler
  160703. #define jinit_color_deconverter jIDColor
  160704. #define jinit_1pass_quantizer jI1Quant
  160705. #define jinit_2pass_quantizer jI2Quant
  160706. #define jinit_merged_upsampler jIMUpsampler
  160707. #define jinit_memory_mgr jIMemMgr
  160708. #define jdiv_round_up jDivRound
  160709. #define jround_up jRound
  160710. #define jcopy_sample_rows jCopySamples
  160711. #define jcopy_block_row jCopyBlocks
  160712. #define jzero_far jZeroFar
  160713. #define jpeg_zigzag_order jZIGTable
  160714. #define jpeg_natural_order jZAGTable
  160715. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160716. /* Compression module initialization routines */
  160717. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160718. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160719. boolean transcode_only));
  160720. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160721. boolean need_full_buffer));
  160722. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160723. boolean need_full_buffer));
  160724. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160725. boolean need_full_buffer));
  160726. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160727. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160728. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160729. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160730. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160731. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160732. /* Decompression module initialization routines */
  160733. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160734. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160735. boolean need_full_buffer));
  160736. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160737. boolean need_full_buffer));
  160738. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160739. boolean need_full_buffer));
  160740. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160741. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160742. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160743. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160744. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160745. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160746. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160747. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160748. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160749. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160750. /* Memory manager initialization */
  160751. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160752. /* Utility routines in jutils.c */
  160753. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160754. EXTERN(long) jround_up JPP((long a, long b));
  160755. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160756. JSAMPARRAY output_array, int dest_row,
  160757. int num_rows, JDIMENSION num_cols));
  160758. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160759. JDIMENSION num_blocks));
  160760. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160761. /* Constant tables in jutils.c */
  160762. #if 0 /* This table is not actually needed in v6a */
  160763. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160764. #endif
  160765. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160766. /* Suppress undefined-structure complaints if necessary. */
  160767. #ifdef INCOMPLETE_TYPES_BROKEN
  160768. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160769. struct jvirt_sarray_control { long dummy; };
  160770. struct jvirt_barray_control { long dummy; };
  160771. #endif
  160772. #endif /* INCOMPLETE_TYPES_BROKEN */
  160773. /*** End of inlined file: jpegint.h ***/
  160774. /* fetch private declarations */
  160775. /*** Start of inlined file: jerror.h ***/
  160776. /*
  160777. * To define the enum list of message codes, include this file without
  160778. * defining macro JMESSAGE. To create a message string table, include it
  160779. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160780. */
  160781. #ifndef JMESSAGE
  160782. #ifndef JERROR_H
  160783. /* First time through, define the enum list */
  160784. #define JMAKE_ENUM_LIST
  160785. #else
  160786. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160787. #define JMESSAGE(code,string)
  160788. #endif /* JERROR_H */
  160789. #endif /* JMESSAGE */
  160790. #ifdef JMAKE_ENUM_LIST
  160791. typedef enum {
  160792. #define JMESSAGE(code,string) code ,
  160793. #endif /* JMAKE_ENUM_LIST */
  160794. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160795. /* For maintenance convenience, list is alphabetical by message code name */
  160796. JMESSAGE(JERR_ARITH_NOTIMPL,
  160797. "Sorry, there are legal restrictions on arithmetic coding")
  160798. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160799. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160800. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160801. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160802. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160803. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160804. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160805. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160806. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160807. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160808. JMESSAGE(JERR_BAD_LIB_VERSION,
  160809. "Wrong JPEG library version: library is %d, caller expects %d")
  160810. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160811. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160812. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160813. JMESSAGE(JERR_BAD_PROGRESSION,
  160814. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160815. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160816. "Invalid progressive parameters at scan script entry %d")
  160817. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160818. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160819. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160820. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160821. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160822. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160823. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160824. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160825. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160826. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160827. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160828. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160829. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160830. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160831. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160832. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160833. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160834. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160835. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160836. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160837. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160838. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160839. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160840. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160841. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160842. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160843. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160844. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160845. "Cannot transcode due to multiple use of quantization table %d")
  160846. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160847. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160848. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160849. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160850. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160851. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160852. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160853. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160854. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160855. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160856. JMESSAGE(JERR_QUANT_COMPONENTS,
  160857. "Cannot quantize more than %d color components")
  160858. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160859. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160860. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160861. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160862. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160863. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160864. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160865. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160866. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160867. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160868. JMESSAGE(JERR_TFILE_WRITE,
  160869. "Write failed on temporary file --- out of disk space?")
  160870. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160871. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160872. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160873. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160874. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160875. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160876. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160877. JMESSAGE(JMSG_VERSION, JVERSION)
  160878. JMESSAGE(JTRC_16BIT_TABLES,
  160879. "Caution: quantization tables are too coarse for baseline JPEG")
  160880. JMESSAGE(JTRC_ADOBE,
  160881. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160882. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160883. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160884. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160885. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160886. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160887. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160888. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160889. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160890. JMESSAGE(JTRC_EOI, "End Of Image")
  160891. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160892. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160893. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160894. "Warning: thumbnail image size does not match data length %u")
  160895. JMESSAGE(JTRC_JFIF_EXTENSION,
  160896. "JFIF extension marker: type 0x%02x, length %u")
  160897. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160898. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160899. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160900. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160901. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160902. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160903. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160904. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160905. JMESSAGE(JTRC_RST, "RST%d")
  160906. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160907. "Smoothing not supported with nonstandard sampling ratios")
  160908. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160909. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160910. JMESSAGE(JTRC_SOI, "Start of Image")
  160911. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160912. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160913. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160914. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160915. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160916. JMESSAGE(JTRC_THUMB_JPEG,
  160917. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160918. JMESSAGE(JTRC_THUMB_PALETTE,
  160919. "JFIF extension marker: palette thumbnail image, length %u")
  160920. JMESSAGE(JTRC_THUMB_RGB,
  160921. "JFIF extension marker: RGB thumbnail image, length %u")
  160922. JMESSAGE(JTRC_UNKNOWN_IDS,
  160923. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160924. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160925. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160926. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160927. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160928. "Inconsistent progression sequence for component %d coefficient %d")
  160929. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160930. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160931. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160932. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160933. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160934. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160935. JMESSAGE(JWRN_MUST_RESYNC,
  160936. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160937. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160938. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160939. #ifdef JMAKE_ENUM_LIST
  160940. JMSG_LASTMSGCODE
  160941. } J_MESSAGE_CODE;
  160942. #undef JMAKE_ENUM_LIST
  160943. #endif /* JMAKE_ENUM_LIST */
  160944. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160945. #undef JMESSAGE
  160946. #ifndef JERROR_H
  160947. #define JERROR_H
  160948. /* Macros to simplify using the error and trace message stuff */
  160949. /* The first parameter is either type of cinfo pointer */
  160950. /* Fatal errors (print message and exit) */
  160951. #define ERREXIT(cinfo,code) \
  160952. ((cinfo)->err->msg_code = (code), \
  160953. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160954. #define ERREXIT1(cinfo,code,p1) \
  160955. ((cinfo)->err->msg_code = (code), \
  160956. (cinfo)->err->msg_parm.i[0] = (p1), \
  160957. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160958. #define ERREXIT2(cinfo,code,p1,p2) \
  160959. ((cinfo)->err->msg_code = (code), \
  160960. (cinfo)->err->msg_parm.i[0] = (p1), \
  160961. (cinfo)->err->msg_parm.i[1] = (p2), \
  160962. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160963. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160964. ((cinfo)->err->msg_code = (code), \
  160965. (cinfo)->err->msg_parm.i[0] = (p1), \
  160966. (cinfo)->err->msg_parm.i[1] = (p2), \
  160967. (cinfo)->err->msg_parm.i[2] = (p3), \
  160968. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160969. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160970. ((cinfo)->err->msg_code = (code), \
  160971. (cinfo)->err->msg_parm.i[0] = (p1), \
  160972. (cinfo)->err->msg_parm.i[1] = (p2), \
  160973. (cinfo)->err->msg_parm.i[2] = (p3), \
  160974. (cinfo)->err->msg_parm.i[3] = (p4), \
  160975. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160976. #define ERREXITS(cinfo,code,str) \
  160977. ((cinfo)->err->msg_code = (code), \
  160978. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160979. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160980. #define MAKESTMT(stuff) do { stuff } while (0)
  160981. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160982. #define WARNMS(cinfo,code) \
  160983. ((cinfo)->err->msg_code = (code), \
  160984. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160985. #define WARNMS1(cinfo,code,p1) \
  160986. ((cinfo)->err->msg_code = (code), \
  160987. (cinfo)->err->msg_parm.i[0] = (p1), \
  160988. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160989. #define WARNMS2(cinfo,code,p1,p2) \
  160990. ((cinfo)->err->msg_code = (code), \
  160991. (cinfo)->err->msg_parm.i[0] = (p1), \
  160992. (cinfo)->err->msg_parm.i[1] = (p2), \
  160993. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160994. /* Informational/debugging messages */
  160995. #define TRACEMS(cinfo,lvl,code) \
  160996. ((cinfo)->err->msg_code = (code), \
  160997. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160998. #define TRACEMS1(cinfo,lvl,code,p1) \
  160999. ((cinfo)->err->msg_code = (code), \
  161000. (cinfo)->err->msg_parm.i[0] = (p1), \
  161001. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161002. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161003. ((cinfo)->err->msg_code = (code), \
  161004. (cinfo)->err->msg_parm.i[0] = (p1), \
  161005. (cinfo)->err->msg_parm.i[1] = (p2), \
  161006. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161007. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161008. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161009. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161010. (cinfo)->err->msg_code = (code); \
  161011. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161012. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161013. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161014. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161015. (cinfo)->err->msg_code = (code); \
  161016. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161017. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161018. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161019. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161020. _mp[4] = (p5); \
  161021. (cinfo)->err->msg_code = (code); \
  161022. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161023. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161024. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161025. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161026. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161027. (cinfo)->err->msg_code = (code); \
  161028. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161029. #define TRACEMSS(cinfo,lvl,code,str) \
  161030. ((cinfo)->err->msg_code = (code), \
  161031. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161032. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161033. #endif /* JERROR_H */
  161034. /*** End of inlined file: jerror.h ***/
  161035. /* fetch error codes too */
  161036. #endif
  161037. #endif /* JPEGLIB_H */
  161038. /*** End of inlined file: jpeglib.h ***/
  161039. /*** Start of inlined file: jcapimin.c ***/
  161040. #define JPEG_INTERNALS
  161041. /*** Start of inlined file: jinclude.h ***/
  161042. /* Include auto-config file to find out which system include files we need. */
  161043. #ifndef __jinclude_h__
  161044. #define __jinclude_h__
  161045. /*** Start of inlined file: jconfig.h ***/
  161046. /* see jconfig.doc for explanations */
  161047. // disable all the warnings under MSVC
  161048. #ifdef _MSC_VER
  161049. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161050. #endif
  161051. #ifdef __BORLANDC__
  161052. #pragma warn -8057
  161053. #pragma warn -8019
  161054. #pragma warn -8004
  161055. #pragma warn -8008
  161056. #endif
  161057. #define HAVE_PROTOTYPES
  161058. #define HAVE_UNSIGNED_CHAR
  161059. #define HAVE_UNSIGNED_SHORT
  161060. /* #define void char */
  161061. /* #define const */
  161062. #undef CHAR_IS_UNSIGNED
  161063. #define HAVE_STDDEF_H
  161064. #define HAVE_STDLIB_H
  161065. #undef NEED_BSD_STRINGS
  161066. #undef NEED_SYS_TYPES_H
  161067. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161068. #undef NEED_SHORT_EXTERNAL_NAMES
  161069. #undef INCOMPLETE_TYPES_BROKEN
  161070. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161071. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161072. typedef unsigned char boolean;
  161073. #endif
  161074. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161075. #ifdef JPEG_INTERNALS
  161076. #undef RIGHT_SHIFT_IS_UNSIGNED
  161077. #endif /* JPEG_INTERNALS */
  161078. #ifdef JPEG_CJPEG_DJPEG
  161079. #define BMP_SUPPORTED /* BMP image file format */
  161080. #define GIF_SUPPORTED /* GIF image file format */
  161081. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161082. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161083. #define TARGA_SUPPORTED /* Targa image file format */
  161084. #define TWO_FILE_COMMANDLINE /* optional */
  161085. #define USE_SETMODE /* Microsoft has setmode() */
  161086. #undef NEED_SIGNAL_CATCHER
  161087. #undef DONT_USE_B_MODE
  161088. #undef PROGRESS_REPORT /* optional */
  161089. #endif /* JPEG_CJPEG_DJPEG */
  161090. /*** End of inlined file: jconfig.h ***/
  161091. /* auto configuration options */
  161092. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161093. /*
  161094. * We need the NULL macro and size_t typedef.
  161095. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161096. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161097. * pull in <sys/types.h> as well.
  161098. * Note that the core JPEG library does not require <stdio.h>;
  161099. * only the default error handler and data source/destination modules do.
  161100. * But we must pull it in because of the references to FILE in jpeglib.h.
  161101. * You can remove those references if you want to compile without <stdio.h>.
  161102. */
  161103. #ifdef HAVE_STDDEF_H
  161104. #include <stddef.h>
  161105. #endif
  161106. #ifdef HAVE_STDLIB_H
  161107. #include <stdlib.h>
  161108. #endif
  161109. #ifdef NEED_SYS_TYPES_H
  161110. #include <sys/types.h>
  161111. #endif
  161112. #include <stdio.h>
  161113. /*
  161114. * We need memory copying and zeroing functions, plus strncpy().
  161115. * ANSI and System V implementations declare these in <string.h>.
  161116. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161117. * Some systems may declare memset and memcpy in <memory.h>.
  161118. *
  161119. * NOTE: we assume the size parameters to these functions are of type size_t.
  161120. * Change the casts in these macros if not!
  161121. */
  161122. #ifdef NEED_BSD_STRINGS
  161123. #include <strings.h>
  161124. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161125. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161126. #else /* not BSD, assume ANSI/SysV string lib */
  161127. #include <string.h>
  161128. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161129. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161130. #endif
  161131. /*
  161132. * In ANSI C, and indeed any rational implementation, size_t is also the
  161133. * type returned by sizeof(). However, it seems there are some irrational
  161134. * implementations out there, in which sizeof() returns an int even though
  161135. * size_t is defined as long or unsigned long. To ensure consistent results
  161136. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161137. */
  161138. #define SIZEOF(object) ((size_t) sizeof(object))
  161139. /*
  161140. * The modules that use fread() and fwrite() always invoke them through
  161141. * these macros. On some systems you may need to twiddle the argument casts.
  161142. * CAUTION: argument order is different from underlying functions!
  161143. */
  161144. #define JFREAD(file,buf,sizeofbuf) \
  161145. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161146. #define JFWRITE(file,buf,sizeofbuf) \
  161147. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161148. typedef enum { /* JPEG marker codes */
  161149. M_SOF0 = 0xc0,
  161150. M_SOF1 = 0xc1,
  161151. M_SOF2 = 0xc2,
  161152. M_SOF3 = 0xc3,
  161153. M_SOF5 = 0xc5,
  161154. M_SOF6 = 0xc6,
  161155. M_SOF7 = 0xc7,
  161156. M_JPG = 0xc8,
  161157. M_SOF9 = 0xc9,
  161158. M_SOF10 = 0xca,
  161159. M_SOF11 = 0xcb,
  161160. M_SOF13 = 0xcd,
  161161. M_SOF14 = 0xce,
  161162. M_SOF15 = 0xcf,
  161163. M_DHT = 0xc4,
  161164. M_DAC = 0xcc,
  161165. M_RST0 = 0xd0,
  161166. M_RST1 = 0xd1,
  161167. M_RST2 = 0xd2,
  161168. M_RST3 = 0xd3,
  161169. M_RST4 = 0xd4,
  161170. M_RST5 = 0xd5,
  161171. M_RST6 = 0xd6,
  161172. M_RST7 = 0xd7,
  161173. M_SOI = 0xd8,
  161174. M_EOI = 0xd9,
  161175. M_SOS = 0xda,
  161176. M_DQT = 0xdb,
  161177. M_DNL = 0xdc,
  161178. M_DRI = 0xdd,
  161179. M_DHP = 0xde,
  161180. M_EXP = 0xdf,
  161181. M_APP0 = 0xe0,
  161182. M_APP1 = 0xe1,
  161183. M_APP2 = 0xe2,
  161184. M_APP3 = 0xe3,
  161185. M_APP4 = 0xe4,
  161186. M_APP5 = 0xe5,
  161187. M_APP6 = 0xe6,
  161188. M_APP7 = 0xe7,
  161189. M_APP8 = 0xe8,
  161190. M_APP9 = 0xe9,
  161191. M_APP10 = 0xea,
  161192. M_APP11 = 0xeb,
  161193. M_APP12 = 0xec,
  161194. M_APP13 = 0xed,
  161195. M_APP14 = 0xee,
  161196. M_APP15 = 0xef,
  161197. M_JPG0 = 0xf0,
  161198. M_JPG13 = 0xfd,
  161199. M_COM = 0xfe,
  161200. M_TEM = 0x01,
  161201. M_ERROR = 0x100
  161202. } JPEG_MARKER;
  161203. /*
  161204. * Figure F.12: extend sign bit.
  161205. * On some machines, a shift and add will be faster than a table lookup.
  161206. */
  161207. #ifdef AVOID_TABLES
  161208. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161209. #else
  161210. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161211. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161212. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161213. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161214. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161215. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161216. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161217. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161218. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161219. #endif /* AVOID_TABLES */
  161220. #endif
  161221. /*** End of inlined file: jinclude.h ***/
  161222. /*
  161223. * Initialization of a JPEG compression object.
  161224. * The error manager must already be set up (in case memory manager fails).
  161225. */
  161226. GLOBAL(void)
  161227. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161228. {
  161229. int i;
  161230. /* Guard against version mismatches between library and caller. */
  161231. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161232. if (version != JPEG_LIB_VERSION)
  161233. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161234. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161235. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161236. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161237. /* For debugging purposes, we zero the whole master structure.
  161238. * But the application has already set the err pointer, and may have set
  161239. * client_data, so we have to save and restore those fields.
  161240. * Note: if application hasn't set client_data, tools like Purify may
  161241. * complain here.
  161242. */
  161243. {
  161244. struct jpeg_error_mgr * err = cinfo->err;
  161245. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161246. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161247. cinfo->err = err;
  161248. cinfo->client_data = client_data;
  161249. }
  161250. cinfo->is_decompressor = FALSE;
  161251. /* Initialize a memory manager instance for this object */
  161252. jinit_memory_mgr((j_common_ptr) cinfo);
  161253. /* Zero out pointers to permanent structures. */
  161254. cinfo->progress = NULL;
  161255. cinfo->dest = NULL;
  161256. cinfo->comp_info = NULL;
  161257. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161258. cinfo->quant_tbl_ptrs[i] = NULL;
  161259. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161260. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161261. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161262. }
  161263. cinfo->script_space = NULL;
  161264. cinfo->input_gamma = 1.0; /* in case application forgets */
  161265. /* OK, I'm ready */
  161266. cinfo->global_state = CSTATE_START;
  161267. }
  161268. /*
  161269. * Destruction of a JPEG compression object
  161270. */
  161271. GLOBAL(void)
  161272. jpeg_destroy_compress (j_compress_ptr cinfo)
  161273. {
  161274. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161275. }
  161276. /*
  161277. * Abort processing of a JPEG compression operation,
  161278. * but don't destroy the object itself.
  161279. */
  161280. GLOBAL(void)
  161281. jpeg_abort_compress (j_compress_ptr cinfo)
  161282. {
  161283. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161284. }
  161285. /*
  161286. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161287. * Marks all currently defined tables as already written (if suppress)
  161288. * or not written (if !suppress). This will control whether they get emitted
  161289. * by a subsequent jpeg_start_compress call.
  161290. *
  161291. * This routine is exported for use by applications that want to produce
  161292. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161293. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161294. * jcparam.o would be linked whether the application used it or not.
  161295. */
  161296. GLOBAL(void)
  161297. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161298. {
  161299. int i;
  161300. JQUANT_TBL * qtbl;
  161301. JHUFF_TBL * htbl;
  161302. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161303. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161304. qtbl->sent_table = suppress;
  161305. }
  161306. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161307. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161308. htbl->sent_table = suppress;
  161309. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161310. htbl->sent_table = suppress;
  161311. }
  161312. }
  161313. /*
  161314. * Finish JPEG compression.
  161315. *
  161316. * If a multipass operating mode was selected, this may do a great deal of
  161317. * work including most of the actual output.
  161318. */
  161319. GLOBAL(void)
  161320. jpeg_finish_compress (j_compress_ptr cinfo)
  161321. {
  161322. JDIMENSION iMCU_row;
  161323. if (cinfo->global_state == CSTATE_SCANNING ||
  161324. cinfo->global_state == CSTATE_RAW_OK) {
  161325. /* Terminate first pass */
  161326. if (cinfo->next_scanline < cinfo->image_height)
  161327. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161328. (*cinfo->master->finish_pass) (cinfo);
  161329. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161330. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161331. /* Perform any remaining passes */
  161332. while (! cinfo->master->is_last_pass) {
  161333. (*cinfo->master->prepare_for_pass) (cinfo);
  161334. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161335. if (cinfo->progress != NULL) {
  161336. cinfo->progress->pass_counter = (long) iMCU_row;
  161337. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161338. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161339. }
  161340. /* We bypass the main controller and invoke coef controller directly;
  161341. * all work is being done from the coefficient buffer.
  161342. */
  161343. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161344. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161345. }
  161346. (*cinfo->master->finish_pass) (cinfo);
  161347. }
  161348. /* Write EOI, do final cleanup */
  161349. (*cinfo->marker->write_file_trailer) (cinfo);
  161350. (*cinfo->dest->term_destination) (cinfo);
  161351. /* We can use jpeg_abort to release memory and reset global_state */
  161352. jpeg_abort((j_common_ptr) cinfo);
  161353. }
  161354. /*
  161355. * Write a special marker.
  161356. * This is only recommended for writing COM or APPn markers.
  161357. * Must be called after jpeg_start_compress() and before
  161358. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161359. */
  161360. GLOBAL(void)
  161361. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161362. const JOCTET *dataptr, unsigned int datalen)
  161363. {
  161364. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161365. if (cinfo->next_scanline != 0 ||
  161366. (cinfo->global_state != CSTATE_SCANNING &&
  161367. cinfo->global_state != CSTATE_RAW_OK &&
  161368. cinfo->global_state != CSTATE_WRCOEFS))
  161369. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161370. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161371. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161372. while (datalen--) {
  161373. (*write_marker_byte) (cinfo, *dataptr);
  161374. dataptr++;
  161375. }
  161376. }
  161377. /* Same, but piecemeal. */
  161378. GLOBAL(void)
  161379. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161380. {
  161381. if (cinfo->next_scanline != 0 ||
  161382. (cinfo->global_state != CSTATE_SCANNING &&
  161383. cinfo->global_state != CSTATE_RAW_OK &&
  161384. cinfo->global_state != CSTATE_WRCOEFS))
  161385. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161386. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161387. }
  161388. GLOBAL(void)
  161389. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161390. {
  161391. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161392. }
  161393. /*
  161394. * Alternate compression function: just write an abbreviated table file.
  161395. * Before calling this, all parameters and a data destination must be set up.
  161396. *
  161397. * To produce a pair of files containing abbreviated tables and abbreviated
  161398. * image data, one would proceed as follows:
  161399. *
  161400. * initialize JPEG object
  161401. * set JPEG parameters
  161402. * set destination to table file
  161403. * jpeg_write_tables(cinfo);
  161404. * set destination to image file
  161405. * jpeg_start_compress(cinfo, FALSE);
  161406. * write data...
  161407. * jpeg_finish_compress(cinfo);
  161408. *
  161409. * jpeg_write_tables has the side effect of marking all tables written
  161410. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161411. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161412. */
  161413. GLOBAL(void)
  161414. jpeg_write_tables (j_compress_ptr cinfo)
  161415. {
  161416. if (cinfo->global_state != CSTATE_START)
  161417. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161418. /* (Re)initialize error mgr and destination modules */
  161419. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161420. (*cinfo->dest->init_destination) (cinfo);
  161421. /* Initialize the marker writer ... bit of a crock to do it here. */
  161422. jinit_marker_writer(cinfo);
  161423. /* Write them tables! */
  161424. (*cinfo->marker->write_tables_only) (cinfo);
  161425. /* And clean up. */
  161426. (*cinfo->dest->term_destination) (cinfo);
  161427. /*
  161428. * In library releases up through v6a, we called jpeg_abort() here to free
  161429. * any working memory allocated by the destination manager and marker
  161430. * writer. Some applications had a problem with that: they allocated space
  161431. * of their own from the library memory manager, and didn't want it to go
  161432. * away during write_tables. So now we do nothing. This will cause a
  161433. * memory leak if an app calls write_tables repeatedly without doing a full
  161434. * compression cycle or otherwise resetting the JPEG object. However, that
  161435. * seems less bad than unexpectedly freeing memory in the normal case.
  161436. * An app that prefers the old behavior can call jpeg_abort for itself after
  161437. * each call to jpeg_write_tables().
  161438. */
  161439. }
  161440. /*** End of inlined file: jcapimin.c ***/
  161441. /*** Start of inlined file: jcapistd.c ***/
  161442. #define JPEG_INTERNALS
  161443. /*
  161444. * Compression initialization.
  161445. * Before calling this, all parameters and a data destination must be set up.
  161446. *
  161447. * We require a write_all_tables parameter as a failsafe check when writing
  161448. * multiple datastreams from the same compression object. Since prior runs
  161449. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161450. * would emit an abbreviated stream (no tables) by default. This may be what
  161451. * is wanted, but for safety's sake it should not be the default behavior:
  161452. * programmers should have to make a deliberate choice to emit abbreviated
  161453. * images. Therefore the documentation and examples should encourage people
  161454. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161455. * wrong thing.
  161456. */
  161457. GLOBAL(void)
  161458. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161459. {
  161460. if (cinfo->global_state != CSTATE_START)
  161461. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161462. if (write_all_tables)
  161463. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161464. /* (Re)initialize error mgr and destination modules */
  161465. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161466. (*cinfo->dest->init_destination) (cinfo);
  161467. /* Perform master selection of active modules */
  161468. jinit_compress_master(cinfo);
  161469. /* Set up for the first pass */
  161470. (*cinfo->master->prepare_for_pass) (cinfo);
  161471. /* Ready for application to drive first pass through jpeg_write_scanlines
  161472. * or jpeg_write_raw_data.
  161473. */
  161474. cinfo->next_scanline = 0;
  161475. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161476. }
  161477. /*
  161478. * Write some scanlines of data to the JPEG compressor.
  161479. *
  161480. * The return value will be the number of lines actually written.
  161481. * This should be less than the supplied num_lines only in case that
  161482. * the data destination module has requested suspension of the compressor,
  161483. * or if more than image_height scanlines are passed in.
  161484. *
  161485. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161486. * this likely signals an application programmer error. However,
  161487. * excess scanlines passed in the last valid call are *silently* ignored,
  161488. * so that the application need not adjust num_lines for end-of-image
  161489. * when using a multiple-scanline buffer.
  161490. */
  161491. GLOBAL(JDIMENSION)
  161492. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161493. JDIMENSION num_lines)
  161494. {
  161495. JDIMENSION row_ctr, rows_left;
  161496. if (cinfo->global_state != CSTATE_SCANNING)
  161497. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161498. if (cinfo->next_scanline >= cinfo->image_height)
  161499. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161500. /* Call progress monitor hook if present */
  161501. if (cinfo->progress != NULL) {
  161502. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161503. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161504. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161505. }
  161506. /* Give master control module another chance if this is first call to
  161507. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161508. * delayed so that application can write COM, etc, markers between
  161509. * jpeg_start_compress and jpeg_write_scanlines.
  161510. */
  161511. if (cinfo->master->call_pass_startup)
  161512. (*cinfo->master->pass_startup) (cinfo);
  161513. /* Ignore any extra scanlines at bottom of image. */
  161514. rows_left = cinfo->image_height - cinfo->next_scanline;
  161515. if (num_lines > rows_left)
  161516. num_lines = rows_left;
  161517. row_ctr = 0;
  161518. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161519. cinfo->next_scanline += row_ctr;
  161520. return row_ctr;
  161521. }
  161522. /*
  161523. * Alternate entry point to write raw data.
  161524. * Processes exactly one iMCU row per call, unless suspended.
  161525. */
  161526. GLOBAL(JDIMENSION)
  161527. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161528. JDIMENSION num_lines)
  161529. {
  161530. JDIMENSION lines_per_iMCU_row;
  161531. if (cinfo->global_state != CSTATE_RAW_OK)
  161532. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161533. if (cinfo->next_scanline >= cinfo->image_height) {
  161534. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161535. return 0;
  161536. }
  161537. /* Call progress monitor hook if present */
  161538. if (cinfo->progress != NULL) {
  161539. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161540. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161541. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161542. }
  161543. /* Give master control module another chance if this is first call to
  161544. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161545. * delayed so that application can write COM, etc, markers between
  161546. * jpeg_start_compress and jpeg_write_raw_data.
  161547. */
  161548. if (cinfo->master->call_pass_startup)
  161549. (*cinfo->master->pass_startup) (cinfo);
  161550. /* Verify that at least one iMCU row has been passed. */
  161551. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161552. if (num_lines < lines_per_iMCU_row)
  161553. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161554. /* Directly compress the row. */
  161555. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161556. /* If compressor did not consume the whole row, suspend processing. */
  161557. return 0;
  161558. }
  161559. /* OK, we processed one iMCU row. */
  161560. cinfo->next_scanline += lines_per_iMCU_row;
  161561. return lines_per_iMCU_row;
  161562. }
  161563. /*** End of inlined file: jcapistd.c ***/
  161564. /*** Start of inlined file: jccoefct.c ***/
  161565. #define JPEG_INTERNALS
  161566. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161567. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161568. * step is run during the first pass, and subsequent passes need only read
  161569. * the buffered coefficients.
  161570. */
  161571. #ifdef ENTROPY_OPT_SUPPORTED
  161572. #define FULL_COEF_BUFFER_SUPPORTED
  161573. #else
  161574. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161575. #define FULL_COEF_BUFFER_SUPPORTED
  161576. #endif
  161577. #endif
  161578. /* Private buffer controller object */
  161579. typedef struct {
  161580. struct jpeg_c_coef_controller pub; /* public fields */
  161581. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161582. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161583. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161584. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161585. /* For single-pass compression, it's sufficient to buffer just one MCU
  161586. * (although this may prove a bit slow in practice). We allocate a
  161587. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161588. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161589. * it's not really very big; this is to keep the module interfaces unchanged
  161590. * when a large coefficient buffer is necessary.)
  161591. * In multi-pass modes, this array points to the current MCU's blocks
  161592. * within the virtual arrays.
  161593. */
  161594. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161595. /* In multi-pass modes, we need a virtual block array for each component. */
  161596. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161597. } my_coef_controller;
  161598. typedef my_coef_controller * my_coef_ptr;
  161599. /* Forward declarations */
  161600. METHODDEF(boolean) compress_data
  161601. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161602. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161603. METHODDEF(boolean) compress_first_pass
  161604. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161605. METHODDEF(boolean) compress_output
  161606. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161607. #endif
  161608. LOCAL(void)
  161609. start_iMCU_row (j_compress_ptr cinfo)
  161610. /* Reset within-iMCU-row counters for a new row */
  161611. {
  161612. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161613. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161614. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161615. * But at the bottom of the image, process only what's left.
  161616. */
  161617. if (cinfo->comps_in_scan > 1) {
  161618. coef->MCU_rows_per_iMCU_row = 1;
  161619. } else {
  161620. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161621. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161622. else
  161623. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161624. }
  161625. coef->mcu_ctr = 0;
  161626. coef->MCU_vert_offset = 0;
  161627. }
  161628. /*
  161629. * Initialize for a processing pass.
  161630. */
  161631. METHODDEF(void)
  161632. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161633. {
  161634. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161635. coef->iMCU_row_num = 0;
  161636. start_iMCU_row(cinfo);
  161637. switch (pass_mode) {
  161638. case JBUF_PASS_THRU:
  161639. if (coef->whole_image[0] != NULL)
  161640. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161641. coef->pub.compress_data = compress_data;
  161642. break;
  161643. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161644. case JBUF_SAVE_AND_PASS:
  161645. if (coef->whole_image[0] == NULL)
  161646. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161647. coef->pub.compress_data = compress_first_pass;
  161648. break;
  161649. case JBUF_CRANK_DEST:
  161650. if (coef->whole_image[0] == NULL)
  161651. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161652. coef->pub.compress_data = compress_output;
  161653. break;
  161654. #endif
  161655. default:
  161656. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161657. break;
  161658. }
  161659. }
  161660. /*
  161661. * Process some data in the single-pass case.
  161662. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161663. * per call, ie, v_samp_factor block rows for each component in the image.
  161664. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161665. *
  161666. * NB: input_buf contains a plane for each component in image,
  161667. * which we index according to the component's SOF position.
  161668. */
  161669. METHODDEF(boolean)
  161670. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161671. {
  161672. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161673. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161674. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161675. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161676. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161677. JDIMENSION ypos, xpos;
  161678. jpeg_component_info *compptr;
  161679. /* Loop to write as much as one whole iMCU row */
  161680. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161681. yoffset++) {
  161682. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161683. MCU_col_num++) {
  161684. /* Determine where data comes from in input_buf and do the DCT thing.
  161685. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161686. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161687. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161688. * specially. The data in them does not matter for image reconstruction,
  161689. * so we fill them with values that will encode to the smallest amount of
  161690. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161691. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161692. */
  161693. blkn = 0;
  161694. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161695. compptr = cinfo->cur_comp_info[ci];
  161696. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161697. : compptr->last_col_width;
  161698. xpos = MCU_col_num * compptr->MCU_sample_width;
  161699. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161700. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161701. if (coef->iMCU_row_num < last_iMCU_row ||
  161702. yoffset+yindex < compptr->last_row_height) {
  161703. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161704. input_buf[compptr->component_index],
  161705. coef->MCU_buffer[blkn],
  161706. ypos, xpos, (JDIMENSION) blockcnt);
  161707. if (blockcnt < compptr->MCU_width) {
  161708. /* Create some dummy blocks at the right edge of the image. */
  161709. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161710. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161711. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161712. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161713. }
  161714. }
  161715. } else {
  161716. /* Create a row of dummy blocks at the bottom of the image. */
  161717. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161718. compptr->MCU_width * SIZEOF(JBLOCK));
  161719. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161720. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161721. }
  161722. }
  161723. blkn += compptr->MCU_width;
  161724. ypos += DCTSIZE;
  161725. }
  161726. }
  161727. /* Try to write the MCU. In event of a suspension failure, we will
  161728. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161729. */
  161730. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161731. /* Suspension forced; update state counters and exit */
  161732. coef->MCU_vert_offset = yoffset;
  161733. coef->mcu_ctr = MCU_col_num;
  161734. return FALSE;
  161735. }
  161736. }
  161737. /* Completed an MCU row, but perhaps not an iMCU row */
  161738. coef->mcu_ctr = 0;
  161739. }
  161740. /* Completed the iMCU row, advance counters for next one */
  161741. coef->iMCU_row_num++;
  161742. start_iMCU_row(cinfo);
  161743. return TRUE;
  161744. }
  161745. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161746. /*
  161747. * Process some data in the first pass of a multi-pass case.
  161748. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161749. * per call, ie, v_samp_factor block rows for each component in the image.
  161750. * This amount of data is read from the source buffer, DCT'd and quantized,
  161751. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161752. * as needed at the right and lower edges. (The dummy blocks are constructed
  161753. * in the virtual arrays, which have been padded appropriately.) This makes
  161754. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161755. *
  161756. * We must also emit the data to the entropy encoder. This is conveniently
  161757. * done by calling compress_output() after we've loaded the current strip
  161758. * of the virtual arrays.
  161759. *
  161760. * NB: input_buf contains a plane for each component in image. All
  161761. * components are DCT'd and loaded into the virtual arrays in this pass.
  161762. * However, it may be that only a subset of the components are emitted to
  161763. * the entropy encoder during this first pass; be careful about looking
  161764. * at the scan-dependent variables (MCU dimensions, etc).
  161765. */
  161766. METHODDEF(boolean)
  161767. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161768. {
  161769. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161770. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161771. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161772. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161773. JCOEF lastDC;
  161774. jpeg_component_info *compptr;
  161775. JBLOCKARRAY buffer;
  161776. JBLOCKROW thisblockrow, lastblockrow;
  161777. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161778. ci++, compptr++) {
  161779. /* Align the virtual buffer for this component. */
  161780. buffer = (*cinfo->mem->access_virt_barray)
  161781. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161782. coef->iMCU_row_num * compptr->v_samp_factor,
  161783. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161784. /* Count non-dummy DCT block rows in this iMCU row. */
  161785. if (coef->iMCU_row_num < last_iMCU_row)
  161786. block_rows = compptr->v_samp_factor;
  161787. else {
  161788. /* NB: can't use last_row_height here, since may not be set! */
  161789. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161790. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161791. }
  161792. blocks_across = compptr->width_in_blocks;
  161793. h_samp_factor = compptr->h_samp_factor;
  161794. /* Count number of dummy blocks to be added at the right margin. */
  161795. ndummy = (int) (blocks_across % h_samp_factor);
  161796. if (ndummy > 0)
  161797. ndummy = h_samp_factor - ndummy;
  161798. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161799. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161800. */
  161801. for (block_row = 0; block_row < block_rows; block_row++) {
  161802. thisblockrow = buffer[block_row];
  161803. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161804. input_buf[ci], thisblockrow,
  161805. (JDIMENSION) (block_row * DCTSIZE),
  161806. (JDIMENSION) 0, blocks_across);
  161807. if (ndummy > 0) {
  161808. /* Create dummy blocks at the right edge of the image. */
  161809. thisblockrow += blocks_across; /* => first dummy block */
  161810. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161811. lastDC = thisblockrow[-1][0];
  161812. for (bi = 0; bi < ndummy; bi++) {
  161813. thisblockrow[bi][0] = lastDC;
  161814. }
  161815. }
  161816. }
  161817. /* If at end of image, create dummy block rows as needed.
  161818. * The tricky part here is that within each MCU, we want the DC values
  161819. * of the dummy blocks to match the last real block's DC value.
  161820. * This squeezes a few more bytes out of the resulting file...
  161821. */
  161822. if (coef->iMCU_row_num == last_iMCU_row) {
  161823. blocks_across += ndummy; /* include lower right corner */
  161824. MCUs_across = blocks_across / h_samp_factor;
  161825. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161826. block_row++) {
  161827. thisblockrow = buffer[block_row];
  161828. lastblockrow = buffer[block_row-1];
  161829. jzero_far((void FAR *) thisblockrow,
  161830. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161831. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161832. lastDC = lastblockrow[h_samp_factor-1][0];
  161833. for (bi = 0; bi < h_samp_factor; bi++) {
  161834. thisblockrow[bi][0] = lastDC;
  161835. }
  161836. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161837. lastblockrow += h_samp_factor;
  161838. }
  161839. }
  161840. }
  161841. }
  161842. /* NB: compress_output will increment iMCU_row_num if successful.
  161843. * A suspension return will result in redoing all the work above next time.
  161844. */
  161845. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161846. return compress_output(cinfo, input_buf);
  161847. }
  161848. /*
  161849. * Process some data in subsequent passes of a multi-pass case.
  161850. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161851. * per call, ie, v_samp_factor block rows for each component in the scan.
  161852. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161853. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161854. *
  161855. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161856. */
  161857. METHODDEF(boolean)
  161858. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161859. {
  161860. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161861. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161862. int blkn, ci, xindex, yindex, yoffset;
  161863. JDIMENSION start_col;
  161864. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161865. JBLOCKROW buffer_ptr;
  161866. jpeg_component_info *compptr;
  161867. /* Align the virtual buffers for the components used in this scan.
  161868. * NB: during first pass, this is safe only because the buffers will
  161869. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161870. */
  161871. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161872. compptr = cinfo->cur_comp_info[ci];
  161873. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161874. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161875. coef->iMCU_row_num * compptr->v_samp_factor,
  161876. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161877. }
  161878. /* Loop to process one whole iMCU row */
  161879. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161880. yoffset++) {
  161881. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161882. MCU_col_num++) {
  161883. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161884. blkn = 0; /* index of current DCT block within MCU */
  161885. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161886. compptr = cinfo->cur_comp_info[ci];
  161887. start_col = MCU_col_num * compptr->MCU_width;
  161888. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161889. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161890. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161891. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161892. }
  161893. }
  161894. }
  161895. /* Try to write the MCU. */
  161896. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161897. /* Suspension forced; update state counters and exit */
  161898. coef->MCU_vert_offset = yoffset;
  161899. coef->mcu_ctr = MCU_col_num;
  161900. return FALSE;
  161901. }
  161902. }
  161903. /* Completed an MCU row, but perhaps not an iMCU row */
  161904. coef->mcu_ctr = 0;
  161905. }
  161906. /* Completed the iMCU row, advance counters for next one */
  161907. coef->iMCU_row_num++;
  161908. start_iMCU_row(cinfo);
  161909. return TRUE;
  161910. }
  161911. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161912. /*
  161913. * Initialize coefficient buffer controller.
  161914. */
  161915. GLOBAL(void)
  161916. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161917. {
  161918. my_coef_ptr coef;
  161919. coef = (my_coef_ptr)
  161920. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161921. SIZEOF(my_coef_controller));
  161922. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161923. coef->pub.start_pass = start_pass_coef;
  161924. /* Create the coefficient buffer. */
  161925. if (need_full_buffer) {
  161926. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161927. /* Allocate a full-image virtual array for each component, */
  161928. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161929. int ci;
  161930. jpeg_component_info *compptr;
  161931. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161932. ci++, compptr++) {
  161933. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161934. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161935. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161936. (long) compptr->h_samp_factor),
  161937. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161938. (long) compptr->v_samp_factor),
  161939. (JDIMENSION) compptr->v_samp_factor);
  161940. }
  161941. #else
  161942. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161943. #endif
  161944. } else {
  161945. /* We only need a single-MCU buffer. */
  161946. JBLOCKROW buffer;
  161947. int i;
  161948. buffer = (JBLOCKROW)
  161949. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161950. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161951. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161952. coef->MCU_buffer[i] = buffer + i;
  161953. }
  161954. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161955. }
  161956. }
  161957. /*** End of inlined file: jccoefct.c ***/
  161958. /*** Start of inlined file: jccolor.c ***/
  161959. #define JPEG_INTERNALS
  161960. /* Private subobject */
  161961. typedef struct {
  161962. struct jpeg_color_converter pub; /* public fields */
  161963. /* Private state for RGB->YCC conversion */
  161964. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161965. } my_color_converter;
  161966. typedef my_color_converter * my_cconvert_ptr;
  161967. /**************** RGB -> YCbCr conversion: most common case **************/
  161968. /*
  161969. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161970. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161971. * The conversion equations to be implemented are therefore
  161972. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161973. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161974. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161975. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161976. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161977. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161978. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161979. * were not represented exactly. Now we sacrifice exact representation of
  161980. * maximum red and maximum blue in order to get exact grayscales.
  161981. *
  161982. * To avoid floating-point arithmetic, we represent the fractional constants
  161983. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161984. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161985. *
  161986. * For even more speed, we avoid doing any multiplications in the inner loop
  161987. * by precalculating the constants times R,G,B for all possible values.
  161988. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161989. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161990. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161991. * colorspace anyway.
  161992. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161993. * in the tables to save adding them separately in the inner loop.
  161994. */
  161995. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161996. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161997. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161998. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161999. /* We allocate one big table and divide it up into eight parts, instead of
  162000. * doing eight alloc_small requests. This lets us use a single table base
  162001. * address, which can be held in a register in the inner loops on many
  162002. * machines (more than can hold all eight addresses, anyway).
  162003. */
  162004. #define R_Y_OFF 0 /* offset to R => Y section */
  162005. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162006. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162007. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162008. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162009. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162010. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162011. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162012. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162013. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162014. /*
  162015. * Initialize for RGB->YCC colorspace conversion.
  162016. */
  162017. METHODDEF(void)
  162018. rgb_ycc_start (j_compress_ptr cinfo)
  162019. {
  162020. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162021. INT32 * rgb_ycc_tab;
  162022. INT32 i;
  162023. /* Allocate and fill in the conversion tables. */
  162024. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162025. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162026. (TABLE_SIZE * SIZEOF(INT32)));
  162027. for (i = 0; i <= MAXJSAMPLE; i++) {
  162028. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162029. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162030. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162031. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162032. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162033. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162034. * This ensures that the maximum output will round to MAXJSAMPLE
  162035. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162036. */
  162037. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162038. /* B=>Cb and R=>Cr tables are the same
  162039. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162040. */
  162041. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162042. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162043. }
  162044. }
  162045. /*
  162046. * Convert some rows of samples to the JPEG colorspace.
  162047. *
  162048. * Note that we change from the application's interleaved-pixel format
  162049. * to our internal noninterleaved, one-plane-per-component format.
  162050. * The input buffer is therefore three times as wide as the output buffer.
  162051. *
  162052. * A starting row offset is provided only for the output buffer. The caller
  162053. * can easily adjust the passed input_buf value to accommodate any row
  162054. * offset required on that side.
  162055. */
  162056. METHODDEF(void)
  162057. rgb_ycc_convert (j_compress_ptr cinfo,
  162058. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162059. JDIMENSION output_row, int num_rows)
  162060. {
  162061. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162062. register int r, g, b;
  162063. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162064. register JSAMPROW inptr;
  162065. register JSAMPROW outptr0, outptr1, outptr2;
  162066. register JDIMENSION col;
  162067. JDIMENSION num_cols = cinfo->image_width;
  162068. while (--num_rows >= 0) {
  162069. inptr = *input_buf++;
  162070. outptr0 = output_buf[0][output_row];
  162071. outptr1 = output_buf[1][output_row];
  162072. outptr2 = output_buf[2][output_row];
  162073. output_row++;
  162074. for (col = 0; col < num_cols; col++) {
  162075. r = GETJSAMPLE(inptr[RGB_RED]);
  162076. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162077. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162078. inptr += RGB_PIXELSIZE;
  162079. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162080. * must be too; we do not need an explicit range-limiting operation.
  162081. * Hence the value being shifted is never negative, and we don't
  162082. * need the general RIGHT_SHIFT macro.
  162083. */
  162084. /* Y */
  162085. outptr0[col] = (JSAMPLE)
  162086. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162087. >> SCALEBITS);
  162088. /* Cb */
  162089. outptr1[col] = (JSAMPLE)
  162090. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162091. >> SCALEBITS);
  162092. /* Cr */
  162093. outptr2[col] = (JSAMPLE)
  162094. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162095. >> SCALEBITS);
  162096. }
  162097. }
  162098. }
  162099. /**************** Cases other than RGB -> YCbCr **************/
  162100. /*
  162101. * Convert some rows of samples to the JPEG colorspace.
  162102. * This version handles RGB->grayscale conversion, which is the same
  162103. * as the RGB->Y portion of RGB->YCbCr.
  162104. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162105. */
  162106. METHODDEF(void)
  162107. rgb_gray_convert (j_compress_ptr cinfo,
  162108. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162109. JDIMENSION output_row, int num_rows)
  162110. {
  162111. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162112. register int r, g, b;
  162113. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162114. register JSAMPROW inptr;
  162115. register JSAMPROW outptr;
  162116. register JDIMENSION col;
  162117. JDIMENSION num_cols = cinfo->image_width;
  162118. while (--num_rows >= 0) {
  162119. inptr = *input_buf++;
  162120. outptr = output_buf[0][output_row];
  162121. output_row++;
  162122. for (col = 0; col < num_cols; col++) {
  162123. r = GETJSAMPLE(inptr[RGB_RED]);
  162124. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162125. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162126. inptr += RGB_PIXELSIZE;
  162127. /* Y */
  162128. outptr[col] = (JSAMPLE)
  162129. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162130. >> SCALEBITS);
  162131. }
  162132. }
  162133. }
  162134. /*
  162135. * Convert some rows of samples to the JPEG colorspace.
  162136. * This version handles Adobe-style CMYK->YCCK conversion,
  162137. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162138. * conversion as above, while passing K (black) unchanged.
  162139. * We assume rgb_ycc_start has been called.
  162140. */
  162141. METHODDEF(void)
  162142. cmyk_ycck_convert (j_compress_ptr cinfo,
  162143. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162144. JDIMENSION output_row, int num_rows)
  162145. {
  162146. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162147. register int r, g, b;
  162148. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162149. register JSAMPROW inptr;
  162150. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162151. register JDIMENSION col;
  162152. JDIMENSION num_cols = cinfo->image_width;
  162153. while (--num_rows >= 0) {
  162154. inptr = *input_buf++;
  162155. outptr0 = output_buf[0][output_row];
  162156. outptr1 = output_buf[1][output_row];
  162157. outptr2 = output_buf[2][output_row];
  162158. outptr3 = output_buf[3][output_row];
  162159. output_row++;
  162160. for (col = 0; col < num_cols; col++) {
  162161. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162162. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162163. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162164. /* K passes through as-is */
  162165. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162166. inptr += 4;
  162167. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162168. * must be too; we do not need an explicit range-limiting operation.
  162169. * Hence the value being shifted is never negative, and we don't
  162170. * need the general RIGHT_SHIFT macro.
  162171. */
  162172. /* Y */
  162173. outptr0[col] = (JSAMPLE)
  162174. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162175. >> SCALEBITS);
  162176. /* Cb */
  162177. outptr1[col] = (JSAMPLE)
  162178. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162179. >> SCALEBITS);
  162180. /* Cr */
  162181. outptr2[col] = (JSAMPLE)
  162182. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162183. >> SCALEBITS);
  162184. }
  162185. }
  162186. }
  162187. /*
  162188. * Convert some rows of samples to the JPEG colorspace.
  162189. * This version handles grayscale output with no conversion.
  162190. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162191. */
  162192. METHODDEF(void)
  162193. grayscale_convert (j_compress_ptr cinfo,
  162194. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162195. JDIMENSION output_row, int num_rows)
  162196. {
  162197. register JSAMPROW inptr;
  162198. register JSAMPROW outptr;
  162199. register JDIMENSION col;
  162200. JDIMENSION num_cols = cinfo->image_width;
  162201. int instride = cinfo->input_components;
  162202. while (--num_rows >= 0) {
  162203. inptr = *input_buf++;
  162204. outptr = output_buf[0][output_row];
  162205. output_row++;
  162206. for (col = 0; col < num_cols; col++) {
  162207. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162208. inptr += instride;
  162209. }
  162210. }
  162211. }
  162212. /*
  162213. * Convert some rows of samples to the JPEG colorspace.
  162214. * This version handles multi-component colorspaces without conversion.
  162215. * We assume input_components == num_components.
  162216. */
  162217. METHODDEF(void)
  162218. null_convert (j_compress_ptr cinfo,
  162219. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162220. JDIMENSION output_row, int num_rows)
  162221. {
  162222. register JSAMPROW inptr;
  162223. register JSAMPROW outptr;
  162224. register JDIMENSION col;
  162225. register int ci;
  162226. int nc = cinfo->num_components;
  162227. JDIMENSION num_cols = cinfo->image_width;
  162228. while (--num_rows >= 0) {
  162229. /* It seems fastest to make a separate pass for each component. */
  162230. for (ci = 0; ci < nc; ci++) {
  162231. inptr = *input_buf;
  162232. outptr = output_buf[ci][output_row];
  162233. for (col = 0; col < num_cols; col++) {
  162234. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162235. inptr += nc;
  162236. }
  162237. }
  162238. input_buf++;
  162239. output_row++;
  162240. }
  162241. }
  162242. /*
  162243. * Empty method for start_pass.
  162244. */
  162245. METHODDEF(void)
  162246. null_method (j_compress_ptr)
  162247. {
  162248. /* no work needed */
  162249. }
  162250. /*
  162251. * Module initialization routine for input colorspace conversion.
  162252. */
  162253. GLOBAL(void)
  162254. jinit_color_converter (j_compress_ptr cinfo)
  162255. {
  162256. my_cconvert_ptr cconvert;
  162257. cconvert = (my_cconvert_ptr)
  162258. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162259. SIZEOF(my_color_converter));
  162260. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162261. /* set start_pass to null method until we find out differently */
  162262. cconvert->pub.start_pass = null_method;
  162263. /* Make sure input_components agrees with in_color_space */
  162264. switch (cinfo->in_color_space) {
  162265. case JCS_GRAYSCALE:
  162266. if (cinfo->input_components != 1)
  162267. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162268. break;
  162269. case JCS_RGB:
  162270. #if RGB_PIXELSIZE != 3
  162271. if (cinfo->input_components != RGB_PIXELSIZE)
  162272. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162273. break;
  162274. #endif /* else share code with YCbCr */
  162275. case JCS_YCbCr:
  162276. if (cinfo->input_components != 3)
  162277. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162278. break;
  162279. case JCS_CMYK:
  162280. case JCS_YCCK:
  162281. if (cinfo->input_components != 4)
  162282. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162283. break;
  162284. default: /* JCS_UNKNOWN can be anything */
  162285. if (cinfo->input_components < 1)
  162286. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162287. break;
  162288. }
  162289. /* Check num_components, set conversion method based on requested space */
  162290. switch (cinfo->jpeg_color_space) {
  162291. case JCS_GRAYSCALE:
  162292. if (cinfo->num_components != 1)
  162293. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162294. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162295. cconvert->pub.color_convert = grayscale_convert;
  162296. else if (cinfo->in_color_space == JCS_RGB) {
  162297. cconvert->pub.start_pass = rgb_ycc_start;
  162298. cconvert->pub.color_convert = rgb_gray_convert;
  162299. } else if (cinfo->in_color_space == JCS_YCbCr)
  162300. cconvert->pub.color_convert = grayscale_convert;
  162301. else
  162302. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162303. break;
  162304. case JCS_RGB:
  162305. if (cinfo->num_components != 3)
  162306. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162307. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162308. cconvert->pub.color_convert = null_convert;
  162309. else
  162310. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162311. break;
  162312. case JCS_YCbCr:
  162313. if (cinfo->num_components != 3)
  162314. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162315. if (cinfo->in_color_space == JCS_RGB) {
  162316. cconvert->pub.start_pass = rgb_ycc_start;
  162317. cconvert->pub.color_convert = rgb_ycc_convert;
  162318. } else if (cinfo->in_color_space == JCS_YCbCr)
  162319. cconvert->pub.color_convert = null_convert;
  162320. else
  162321. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162322. break;
  162323. case JCS_CMYK:
  162324. if (cinfo->num_components != 4)
  162325. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162326. if (cinfo->in_color_space == JCS_CMYK)
  162327. cconvert->pub.color_convert = null_convert;
  162328. else
  162329. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162330. break;
  162331. case JCS_YCCK:
  162332. if (cinfo->num_components != 4)
  162333. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162334. if (cinfo->in_color_space == JCS_CMYK) {
  162335. cconvert->pub.start_pass = rgb_ycc_start;
  162336. cconvert->pub.color_convert = cmyk_ycck_convert;
  162337. } else if (cinfo->in_color_space == JCS_YCCK)
  162338. cconvert->pub.color_convert = null_convert;
  162339. else
  162340. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162341. break;
  162342. default: /* allow null conversion of JCS_UNKNOWN */
  162343. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162344. cinfo->num_components != cinfo->input_components)
  162345. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162346. cconvert->pub.color_convert = null_convert;
  162347. break;
  162348. }
  162349. }
  162350. /*** End of inlined file: jccolor.c ***/
  162351. #undef FIX
  162352. /*** Start of inlined file: jcdctmgr.c ***/
  162353. #define JPEG_INTERNALS
  162354. /*** Start of inlined file: jdct.h ***/
  162355. /*
  162356. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162357. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162358. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162359. * implementations use an array of type FAST_FLOAT, instead.)
  162360. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162361. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162362. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162363. * convention improves accuracy in integer implementations and saves some
  162364. * work in floating-point ones.
  162365. * Quantization of the output coefficients is done by jcdctmgr.c.
  162366. */
  162367. #ifndef __jdct_h__
  162368. #define __jdct_h__
  162369. #if BITS_IN_JSAMPLE == 8
  162370. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162371. #else
  162372. typedef INT32 DCTELEM; /* must have 32 bits */
  162373. #endif
  162374. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162375. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162376. /*
  162377. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162378. * to an output sample array. The routine must dequantize the input data as
  162379. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162380. * pointed to by compptr->dct_table. The output data is to be placed into the
  162381. * sample array starting at a specified column. (Any row offset needed will
  162382. * be applied to the array pointer before it is passed to the IDCT code.)
  162383. * Note that the number of samples emitted by the IDCT routine is
  162384. * DCT_scaled_size * DCT_scaled_size.
  162385. */
  162386. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162387. /*
  162388. * Each IDCT routine has its own ideas about the best dct_table element type.
  162389. */
  162390. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162391. #if BITS_IN_JSAMPLE == 8
  162392. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162393. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162394. #else
  162395. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162396. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162397. #endif
  162398. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162399. /*
  162400. * Each IDCT routine is responsible for range-limiting its results and
  162401. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162402. * be quite far out of range if the input data is corrupt, so a bulletproof
  162403. * range-limiting step is required. We use a mask-and-table-lookup method
  162404. * to do the combined operations quickly. See the comments with
  162405. * prepare_range_limit_table (in jdmaster.c) for more info.
  162406. */
  162407. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162408. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162409. /* Short forms of external names for systems with brain-damaged linkers. */
  162410. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162411. #define jpeg_fdct_islow jFDislow
  162412. #define jpeg_fdct_ifast jFDifast
  162413. #define jpeg_fdct_float jFDfloat
  162414. #define jpeg_idct_islow jRDislow
  162415. #define jpeg_idct_ifast jRDifast
  162416. #define jpeg_idct_float jRDfloat
  162417. #define jpeg_idct_4x4 jRD4x4
  162418. #define jpeg_idct_2x2 jRD2x2
  162419. #define jpeg_idct_1x1 jRD1x1
  162420. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162421. /* Extern declarations for the forward and inverse DCT routines. */
  162422. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162423. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162424. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162425. EXTERN(void) jpeg_idct_islow
  162426. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162427. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162428. EXTERN(void) jpeg_idct_ifast
  162429. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162430. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162431. EXTERN(void) jpeg_idct_float
  162432. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162433. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162434. EXTERN(void) jpeg_idct_4x4
  162435. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162436. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162437. EXTERN(void) jpeg_idct_2x2
  162438. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162439. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162440. EXTERN(void) jpeg_idct_1x1
  162441. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162442. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162443. /*
  162444. * Macros for handling fixed-point arithmetic; these are used by many
  162445. * but not all of the DCT/IDCT modules.
  162446. *
  162447. * All values are expected to be of type INT32.
  162448. * Fractional constants are scaled left by CONST_BITS bits.
  162449. * CONST_BITS is defined within each module using these macros,
  162450. * and may differ from one module to the next.
  162451. */
  162452. #define ONE ((INT32) 1)
  162453. #define CONST_SCALE (ONE << CONST_BITS)
  162454. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162455. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162456. * thus causing a lot of useless floating-point operations at run time.
  162457. */
  162458. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162459. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162460. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162461. * the fudge factor is correct for either sign of X.
  162462. */
  162463. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162464. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162465. * This macro is used only when the two inputs will actually be no more than
  162466. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162467. * full 32x32 multiply. This provides a useful speedup on many machines.
  162468. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162469. * in C, but some C compilers will do the right thing if you provide the
  162470. * correct combination of casts.
  162471. */
  162472. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162473. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162474. #endif
  162475. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162476. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162477. #endif
  162478. #ifndef MULTIPLY16C16 /* default definition */
  162479. #define MULTIPLY16C16(var,const) ((var) * (const))
  162480. #endif
  162481. /* Same except both inputs are variables. */
  162482. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162483. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162484. #endif
  162485. #ifndef MULTIPLY16V16 /* default definition */
  162486. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162487. #endif
  162488. #endif
  162489. /*** End of inlined file: jdct.h ***/
  162490. /* Private declarations for DCT subsystem */
  162491. /* Private subobject for this module */
  162492. typedef struct {
  162493. struct jpeg_forward_dct pub; /* public fields */
  162494. /* Pointer to the DCT routine actually in use */
  162495. forward_DCT_method_ptr do_dct;
  162496. /* The actual post-DCT divisors --- not identical to the quant table
  162497. * entries, because of scaling (especially for an unnormalized DCT).
  162498. * Each table is given in normal array order.
  162499. */
  162500. DCTELEM * divisors[NUM_QUANT_TBLS];
  162501. #ifdef DCT_FLOAT_SUPPORTED
  162502. /* Same as above for the floating-point case. */
  162503. float_DCT_method_ptr do_float_dct;
  162504. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162505. #endif
  162506. } my_fdct_controller;
  162507. typedef my_fdct_controller * my_fdct_ptr;
  162508. /*
  162509. * Initialize for a processing pass.
  162510. * Verify that all referenced Q-tables are present, and set up
  162511. * the divisor table for each one.
  162512. * In the current implementation, DCT of all components is done during
  162513. * the first pass, even if only some components will be output in the
  162514. * first scan. Hence all components should be examined here.
  162515. */
  162516. METHODDEF(void)
  162517. start_pass_fdctmgr (j_compress_ptr cinfo)
  162518. {
  162519. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162520. int ci, qtblno, i;
  162521. jpeg_component_info *compptr;
  162522. JQUANT_TBL * qtbl;
  162523. DCTELEM * dtbl;
  162524. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162525. ci++, compptr++) {
  162526. qtblno = compptr->quant_tbl_no;
  162527. /* Make sure specified quantization table is present */
  162528. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162529. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162530. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162531. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162532. /* Compute divisors for this quant table */
  162533. /* We may do this more than once for same table, but it's not a big deal */
  162534. switch (cinfo->dct_method) {
  162535. #ifdef DCT_ISLOW_SUPPORTED
  162536. case JDCT_ISLOW:
  162537. /* For LL&M IDCT method, divisors are equal to raw quantization
  162538. * coefficients multiplied by 8 (to counteract scaling).
  162539. */
  162540. if (fdct->divisors[qtblno] == NULL) {
  162541. fdct->divisors[qtblno] = (DCTELEM *)
  162542. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162543. DCTSIZE2 * SIZEOF(DCTELEM));
  162544. }
  162545. dtbl = fdct->divisors[qtblno];
  162546. for (i = 0; i < DCTSIZE2; i++) {
  162547. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162548. }
  162549. break;
  162550. #endif
  162551. #ifdef DCT_IFAST_SUPPORTED
  162552. case JDCT_IFAST:
  162553. {
  162554. /* For AA&N IDCT method, divisors are equal to quantization
  162555. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162556. * scalefactor[0] = 1
  162557. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162558. * We apply a further scale factor of 8.
  162559. */
  162560. #define CONST_BITS 14
  162561. static const INT16 aanscales[DCTSIZE2] = {
  162562. /* precomputed values scaled up by 14 bits */
  162563. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162564. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162565. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162566. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162567. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162568. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162569. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162570. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162571. };
  162572. SHIFT_TEMPS
  162573. if (fdct->divisors[qtblno] == NULL) {
  162574. fdct->divisors[qtblno] = (DCTELEM *)
  162575. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162576. DCTSIZE2 * SIZEOF(DCTELEM));
  162577. }
  162578. dtbl = fdct->divisors[qtblno];
  162579. for (i = 0; i < DCTSIZE2; i++) {
  162580. dtbl[i] = (DCTELEM)
  162581. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162582. (INT32) aanscales[i]),
  162583. CONST_BITS-3);
  162584. }
  162585. }
  162586. break;
  162587. #endif
  162588. #ifdef DCT_FLOAT_SUPPORTED
  162589. case JDCT_FLOAT:
  162590. {
  162591. /* For float AA&N IDCT method, divisors are equal to quantization
  162592. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162593. * scalefactor[0] = 1
  162594. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162595. * We apply a further scale factor of 8.
  162596. * What's actually stored is 1/divisor so that the inner loop can
  162597. * use a multiplication rather than a division.
  162598. */
  162599. FAST_FLOAT * fdtbl;
  162600. int row, col;
  162601. static const double aanscalefactor[DCTSIZE] = {
  162602. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162603. 1.0, 0.785694958, 0.541196100, 0.275899379
  162604. };
  162605. if (fdct->float_divisors[qtblno] == NULL) {
  162606. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162607. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162608. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162609. }
  162610. fdtbl = fdct->float_divisors[qtblno];
  162611. i = 0;
  162612. for (row = 0; row < DCTSIZE; row++) {
  162613. for (col = 0; col < DCTSIZE; col++) {
  162614. fdtbl[i] = (FAST_FLOAT)
  162615. (1.0 / (((double) qtbl->quantval[i] *
  162616. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162617. i++;
  162618. }
  162619. }
  162620. }
  162621. break;
  162622. #endif
  162623. default:
  162624. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162625. break;
  162626. }
  162627. }
  162628. }
  162629. /*
  162630. * Perform forward DCT on one or more blocks of a component.
  162631. *
  162632. * The input samples are taken from the sample_data[] array starting at
  162633. * position start_row/start_col, and moving to the right for any additional
  162634. * blocks. The quantized coefficients are returned in coef_blocks[].
  162635. */
  162636. METHODDEF(void)
  162637. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162638. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162639. JDIMENSION start_row, JDIMENSION start_col,
  162640. JDIMENSION num_blocks)
  162641. /* This version is used for integer DCT implementations. */
  162642. {
  162643. /* This routine is heavily used, so it's worth coding it tightly. */
  162644. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162645. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162646. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162647. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162648. JDIMENSION bi;
  162649. sample_data += start_row; /* fold in the vertical offset once */
  162650. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162651. /* Load data into workspace, applying unsigned->signed conversion */
  162652. { register DCTELEM *workspaceptr;
  162653. register JSAMPROW elemptr;
  162654. register int elemr;
  162655. workspaceptr = workspace;
  162656. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162657. elemptr = sample_data[elemr] + start_col;
  162658. #if DCTSIZE == 8 /* unroll the inner loop */
  162659. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162660. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162661. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162662. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162663. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162664. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162665. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162666. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162667. #else
  162668. { register int elemc;
  162669. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162670. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162671. }
  162672. }
  162673. #endif
  162674. }
  162675. }
  162676. /* Perform the DCT */
  162677. (*do_dct) (workspace);
  162678. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162679. { register DCTELEM temp, qval;
  162680. register int i;
  162681. register JCOEFPTR output_ptr = coef_blocks[bi];
  162682. for (i = 0; i < DCTSIZE2; i++) {
  162683. qval = divisors[i];
  162684. temp = workspace[i];
  162685. /* Divide the coefficient value by qval, ensuring proper rounding.
  162686. * Since C does not specify the direction of rounding for negative
  162687. * quotients, we have to force the dividend positive for portability.
  162688. *
  162689. * In most files, at least half of the output values will be zero
  162690. * (at default quantization settings, more like three-quarters...)
  162691. * so we should ensure that this case is fast. On many machines,
  162692. * a comparison is enough cheaper than a divide to make a special test
  162693. * a win. Since both inputs will be nonnegative, we need only test
  162694. * for a < b to discover whether a/b is 0.
  162695. * If your machine's division is fast enough, define FAST_DIVIDE.
  162696. */
  162697. #ifdef FAST_DIVIDE
  162698. #define DIVIDE_BY(a,b) a /= b
  162699. #else
  162700. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162701. #endif
  162702. if (temp < 0) {
  162703. temp = -temp;
  162704. temp += qval>>1; /* for rounding */
  162705. DIVIDE_BY(temp, qval);
  162706. temp = -temp;
  162707. } else {
  162708. temp += qval>>1; /* for rounding */
  162709. DIVIDE_BY(temp, qval);
  162710. }
  162711. output_ptr[i] = (JCOEF) temp;
  162712. }
  162713. }
  162714. }
  162715. }
  162716. #ifdef DCT_FLOAT_SUPPORTED
  162717. METHODDEF(void)
  162718. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162719. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162720. JDIMENSION start_row, JDIMENSION start_col,
  162721. JDIMENSION num_blocks)
  162722. /* This version is used for floating-point DCT implementations. */
  162723. {
  162724. /* This routine is heavily used, so it's worth coding it tightly. */
  162725. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162726. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162727. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162728. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162729. JDIMENSION bi;
  162730. sample_data += start_row; /* fold in the vertical offset once */
  162731. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162732. /* Load data into workspace, applying unsigned->signed conversion */
  162733. { register FAST_FLOAT *workspaceptr;
  162734. register JSAMPROW elemptr;
  162735. register int elemr;
  162736. workspaceptr = workspace;
  162737. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162738. elemptr = sample_data[elemr] + start_col;
  162739. #if DCTSIZE == 8 /* unroll the inner loop */
  162740. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162741. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162742. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162743. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162744. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162745. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162746. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162747. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162748. #else
  162749. { register int elemc;
  162750. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162751. *workspaceptr++ = (FAST_FLOAT)
  162752. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162753. }
  162754. }
  162755. #endif
  162756. }
  162757. }
  162758. /* Perform the DCT */
  162759. (*do_dct) (workspace);
  162760. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162761. { register FAST_FLOAT temp;
  162762. register int i;
  162763. register JCOEFPTR output_ptr = coef_blocks[bi];
  162764. for (i = 0; i < DCTSIZE2; i++) {
  162765. /* Apply the quantization and scaling factor */
  162766. temp = workspace[i] * divisors[i];
  162767. /* Round to nearest integer.
  162768. * Since C does not specify the direction of rounding for negative
  162769. * quotients, we have to force the dividend positive for portability.
  162770. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162771. * code should work for either 16-bit or 32-bit ints.
  162772. */
  162773. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162774. }
  162775. }
  162776. }
  162777. }
  162778. #endif /* DCT_FLOAT_SUPPORTED */
  162779. /*
  162780. * Initialize FDCT manager.
  162781. */
  162782. GLOBAL(void)
  162783. jinit_forward_dct (j_compress_ptr cinfo)
  162784. {
  162785. my_fdct_ptr fdct;
  162786. int i;
  162787. fdct = (my_fdct_ptr)
  162788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162789. SIZEOF(my_fdct_controller));
  162790. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162791. fdct->pub.start_pass = start_pass_fdctmgr;
  162792. switch (cinfo->dct_method) {
  162793. #ifdef DCT_ISLOW_SUPPORTED
  162794. case JDCT_ISLOW:
  162795. fdct->pub.forward_DCT = forward_DCT;
  162796. fdct->do_dct = jpeg_fdct_islow;
  162797. break;
  162798. #endif
  162799. #ifdef DCT_IFAST_SUPPORTED
  162800. case JDCT_IFAST:
  162801. fdct->pub.forward_DCT = forward_DCT;
  162802. fdct->do_dct = jpeg_fdct_ifast;
  162803. break;
  162804. #endif
  162805. #ifdef DCT_FLOAT_SUPPORTED
  162806. case JDCT_FLOAT:
  162807. fdct->pub.forward_DCT = forward_DCT_float;
  162808. fdct->do_float_dct = jpeg_fdct_float;
  162809. break;
  162810. #endif
  162811. default:
  162812. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162813. break;
  162814. }
  162815. /* Mark divisor tables unallocated */
  162816. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162817. fdct->divisors[i] = NULL;
  162818. #ifdef DCT_FLOAT_SUPPORTED
  162819. fdct->float_divisors[i] = NULL;
  162820. #endif
  162821. }
  162822. }
  162823. /*** End of inlined file: jcdctmgr.c ***/
  162824. #undef CONST_BITS
  162825. /*** Start of inlined file: jchuff.c ***/
  162826. #define JPEG_INTERNALS
  162827. /*** Start of inlined file: jchuff.h ***/
  162828. /* The legal range of a DCT coefficient is
  162829. * -1024 .. +1023 for 8-bit data;
  162830. * -16384 .. +16383 for 12-bit data.
  162831. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162832. */
  162833. #ifndef _jchuff_h_
  162834. #define _jchuff_h_
  162835. #if BITS_IN_JSAMPLE == 8
  162836. #define MAX_COEF_BITS 10
  162837. #else
  162838. #define MAX_COEF_BITS 14
  162839. #endif
  162840. /* Derived data constructed for each Huffman table */
  162841. typedef struct {
  162842. unsigned int ehufco[256]; /* code for each symbol */
  162843. char ehufsi[256]; /* length of code for each symbol */
  162844. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162845. } c_derived_tbl;
  162846. /* Short forms of external names for systems with brain-damaged linkers. */
  162847. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162848. #define jpeg_make_c_derived_tbl jMkCDerived
  162849. #define jpeg_gen_optimal_table jGenOptTbl
  162850. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162851. /* Expand a Huffman table definition into the derived format */
  162852. EXTERN(void) jpeg_make_c_derived_tbl
  162853. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162854. c_derived_tbl ** pdtbl));
  162855. /* Generate an optimal table definition given the specified counts */
  162856. EXTERN(void) jpeg_gen_optimal_table
  162857. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162858. #endif
  162859. /*** End of inlined file: jchuff.h ***/
  162860. /* Declarations shared with jcphuff.c */
  162861. /* Expanded entropy encoder object for Huffman encoding.
  162862. *
  162863. * The savable_state subrecord contains fields that change within an MCU,
  162864. * but must not be updated permanently until we complete the MCU.
  162865. */
  162866. typedef struct {
  162867. INT32 put_buffer; /* current bit-accumulation buffer */
  162868. int put_bits; /* # of bits now in it */
  162869. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162870. } savable_state;
  162871. /* This macro is to work around compilers with missing or broken
  162872. * structure assignment. You'll need to fix this code if you have
  162873. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162874. */
  162875. #ifndef NO_STRUCT_ASSIGN
  162876. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162877. #else
  162878. #if MAX_COMPS_IN_SCAN == 4
  162879. #define ASSIGN_STATE(dest,src) \
  162880. ((dest).put_buffer = (src).put_buffer, \
  162881. (dest).put_bits = (src).put_bits, \
  162882. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162883. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162884. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162885. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162886. #endif
  162887. #endif
  162888. typedef struct {
  162889. struct jpeg_entropy_encoder pub; /* public fields */
  162890. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162891. /* These fields are NOT loaded into local working state. */
  162892. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162893. int next_restart_num; /* next restart number to write (0-7) */
  162894. /* Pointers to derived tables (these workspaces have image lifespan) */
  162895. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162896. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162897. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162898. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162899. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162900. #endif
  162901. } huff_entropy_encoder;
  162902. typedef huff_entropy_encoder * huff_entropy_ptr;
  162903. /* Working state while writing an MCU.
  162904. * This struct contains all the fields that are needed by subroutines.
  162905. */
  162906. typedef struct {
  162907. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162908. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162909. savable_state cur; /* Current bit buffer & DC state */
  162910. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162911. } working_state;
  162912. /* Forward declarations */
  162913. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162914. JBLOCKROW *MCU_data));
  162915. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162916. #ifdef ENTROPY_OPT_SUPPORTED
  162917. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162918. JBLOCKROW *MCU_data));
  162919. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162920. #endif
  162921. /*
  162922. * Initialize for a Huffman-compressed scan.
  162923. * If gather_statistics is TRUE, we do not output anything during the scan,
  162924. * just count the Huffman symbols used and generate Huffman code tables.
  162925. */
  162926. METHODDEF(void)
  162927. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162928. {
  162929. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162930. int ci, dctbl, actbl;
  162931. jpeg_component_info * compptr;
  162932. if (gather_statistics) {
  162933. #ifdef ENTROPY_OPT_SUPPORTED
  162934. entropy->pub.encode_mcu = encode_mcu_gather;
  162935. entropy->pub.finish_pass = finish_pass_gather;
  162936. #else
  162937. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162938. #endif
  162939. } else {
  162940. entropy->pub.encode_mcu = encode_mcu_huff;
  162941. entropy->pub.finish_pass = finish_pass_huff;
  162942. }
  162943. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162944. compptr = cinfo->cur_comp_info[ci];
  162945. dctbl = compptr->dc_tbl_no;
  162946. actbl = compptr->ac_tbl_no;
  162947. if (gather_statistics) {
  162948. #ifdef ENTROPY_OPT_SUPPORTED
  162949. /* Check for invalid table indexes */
  162950. /* (make_c_derived_tbl does this in the other path) */
  162951. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162952. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162953. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162954. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162955. /* Allocate and zero the statistics tables */
  162956. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162957. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162958. entropy->dc_count_ptrs[dctbl] = (long *)
  162959. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162960. 257 * SIZEOF(long));
  162961. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162962. if (entropy->ac_count_ptrs[actbl] == NULL)
  162963. entropy->ac_count_ptrs[actbl] = (long *)
  162964. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162965. 257 * SIZEOF(long));
  162966. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162967. #endif
  162968. } else {
  162969. /* Compute derived values for Huffman tables */
  162970. /* We may do this more than once for a table, but it's not expensive */
  162971. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162972. & entropy->dc_derived_tbls[dctbl]);
  162973. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162974. & entropy->ac_derived_tbls[actbl]);
  162975. }
  162976. /* Initialize DC predictions to 0 */
  162977. entropy->saved.last_dc_val[ci] = 0;
  162978. }
  162979. /* Initialize bit buffer to empty */
  162980. entropy->saved.put_buffer = 0;
  162981. entropy->saved.put_bits = 0;
  162982. /* Initialize restart stuff */
  162983. entropy->restarts_to_go = cinfo->restart_interval;
  162984. entropy->next_restart_num = 0;
  162985. }
  162986. /*
  162987. * Compute the derived values for a Huffman table.
  162988. * This routine also performs some validation checks on the table.
  162989. *
  162990. * Note this is also used by jcphuff.c.
  162991. */
  162992. GLOBAL(void)
  162993. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162994. c_derived_tbl ** pdtbl)
  162995. {
  162996. JHUFF_TBL *htbl;
  162997. c_derived_tbl *dtbl;
  162998. int p, i, l, lastp, si, maxsymbol;
  162999. char huffsize[257];
  163000. unsigned int huffcode[257];
  163001. unsigned int code;
  163002. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163003. * paralleling the order of the symbols themselves in htbl->huffval[].
  163004. */
  163005. /* Find the input Huffman table */
  163006. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163007. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163008. htbl =
  163009. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163010. if (htbl == NULL)
  163011. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163012. /* Allocate a workspace if we haven't already done so. */
  163013. if (*pdtbl == NULL)
  163014. *pdtbl = (c_derived_tbl *)
  163015. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163016. SIZEOF(c_derived_tbl));
  163017. dtbl = *pdtbl;
  163018. /* Figure C.1: make table of Huffman code length for each symbol */
  163019. p = 0;
  163020. for (l = 1; l <= 16; l++) {
  163021. i = (int) htbl->bits[l];
  163022. if (i < 0 || p + i > 256) /* protect against table overrun */
  163023. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163024. while (i--)
  163025. huffsize[p++] = (char) l;
  163026. }
  163027. huffsize[p] = 0;
  163028. lastp = p;
  163029. /* Figure C.2: generate the codes themselves */
  163030. /* We also validate that the counts represent a legal Huffman code tree. */
  163031. code = 0;
  163032. si = huffsize[0];
  163033. p = 0;
  163034. while (huffsize[p]) {
  163035. while (((int) huffsize[p]) == si) {
  163036. huffcode[p++] = code;
  163037. code++;
  163038. }
  163039. /* code is now 1 more than the last code used for codelength si; but
  163040. * it must still fit in si bits, since no code is allowed to be all ones.
  163041. */
  163042. if (((INT32) code) >= (((INT32) 1) << si))
  163043. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163044. code <<= 1;
  163045. si++;
  163046. }
  163047. /* Figure C.3: generate encoding tables */
  163048. /* These are code and size indexed by symbol value */
  163049. /* Set all codeless symbols to have code length 0;
  163050. * this lets us detect duplicate VAL entries here, and later
  163051. * allows emit_bits to detect any attempt to emit such symbols.
  163052. */
  163053. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163054. /* This is also a convenient place to check for out-of-range
  163055. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163056. * but only 0..15 for DC. (We could constrain them further
  163057. * based on data depth and mode, but this seems enough.)
  163058. */
  163059. maxsymbol = isDC ? 15 : 255;
  163060. for (p = 0; p < lastp; p++) {
  163061. i = htbl->huffval[p];
  163062. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163063. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163064. dtbl->ehufco[i] = huffcode[p];
  163065. dtbl->ehufsi[i] = huffsize[p];
  163066. }
  163067. }
  163068. /* Outputting bytes to the file */
  163069. /* Emit a byte, taking 'action' if must suspend. */
  163070. #define emit_byte(state,val,action) \
  163071. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163072. if (--(state)->free_in_buffer == 0) \
  163073. if (! dump_buffer(state)) \
  163074. { action; } }
  163075. LOCAL(boolean)
  163076. dump_buffer (working_state * state)
  163077. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163078. {
  163079. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163080. if (! (*dest->empty_output_buffer) (state->cinfo))
  163081. return FALSE;
  163082. /* After a successful buffer dump, must reset buffer pointers */
  163083. state->next_output_byte = dest->next_output_byte;
  163084. state->free_in_buffer = dest->free_in_buffer;
  163085. return TRUE;
  163086. }
  163087. /* Outputting bits to the file */
  163088. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163089. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163090. * in one call, and we never retain more than 7 bits in put_buffer
  163091. * between calls, so 24 bits are sufficient.
  163092. */
  163093. INLINE
  163094. LOCAL(boolean)
  163095. emit_bits (working_state * state, unsigned int code, int size)
  163096. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163097. {
  163098. /* This routine is heavily used, so it's worth coding tightly. */
  163099. register INT32 put_buffer = (INT32) code;
  163100. register int put_bits = state->cur.put_bits;
  163101. /* if size is 0, caller used an invalid Huffman table entry */
  163102. if (size == 0)
  163103. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163104. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163105. put_bits += size; /* new number of bits in buffer */
  163106. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163107. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163108. while (put_bits >= 8) {
  163109. int c = (int) ((put_buffer >> 16) & 0xFF);
  163110. emit_byte(state, c, return FALSE);
  163111. if (c == 0xFF) { /* need to stuff a zero byte? */
  163112. emit_byte(state, 0, return FALSE);
  163113. }
  163114. put_buffer <<= 8;
  163115. put_bits -= 8;
  163116. }
  163117. state->cur.put_buffer = put_buffer; /* update state variables */
  163118. state->cur.put_bits = put_bits;
  163119. return TRUE;
  163120. }
  163121. LOCAL(boolean)
  163122. flush_bits (working_state * state)
  163123. {
  163124. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163125. return FALSE;
  163126. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163127. state->cur.put_bits = 0;
  163128. return TRUE;
  163129. }
  163130. /* Encode a single block's worth of coefficients */
  163131. LOCAL(boolean)
  163132. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163133. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163134. {
  163135. register int temp, temp2;
  163136. register int nbits;
  163137. register int k, r, i;
  163138. /* Encode the DC coefficient difference per section F.1.2.1 */
  163139. temp = temp2 = block[0] - last_dc_val;
  163140. if (temp < 0) {
  163141. temp = -temp; /* temp is abs value of input */
  163142. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163143. /* This code assumes we are on a two's complement machine */
  163144. temp2--;
  163145. }
  163146. /* Find the number of bits needed for the magnitude of the coefficient */
  163147. nbits = 0;
  163148. while (temp) {
  163149. nbits++;
  163150. temp >>= 1;
  163151. }
  163152. /* Check for out-of-range coefficient values.
  163153. * Since we're encoding a difference, the range limit is twice as much.
  163154. */
  163155. if (nbits > MAX_COEF_BITS+1)
  163156. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163157. /* Emit the Huffman-coded symbol for the number of bits */
  163158. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163159. return FALSE;
  163160. /* Emit that number of bits of the value, if positive, */
  163161. /* or the complement of its magnitude, if negative. */
  163162. if (nbits) /* emit_bits rejects calls with size 0 */
  163163. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163164. return FALSE;
  163165. /* Encode the AC coefficients per section F.1.2.2 */
  163166. r = 0; /* r = run length of zeros */
  163167. for (k = 1; k < DCTSIZE2; k++) {
  163168. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163169. r++;
  163170. } else {
  163171. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163172. while (r > 15) {
  163173. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163174. return FALSE;
  163175. r -= 16;
  163176. }
  163177. temp2 = temp;
  163178. if (temp < 0) {
  163179. temp = -temp; /* temp is abs value of input */
  163180. /* This code assumes we are on a two's complement machine */
  163181. temp2--;
  163182. }
  163183. /* Find the number of bits needed for the magnitude of the coefficient */
  163184. nbits = 1; /* there must be at least one 1 bit */
  163185. while ((temp >>= 1))
  163186. nbits++;
  163187. /* Check for out-of-range coefficient values */
  163188. if (nbits > MAX_COEF_BITS)
  163189. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163190. /* Emit Huffman symbol for run length / number of bits */
  163191. i = (r << 4) + nbits;
  163192. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163193. return FALSE;
  163194. /* Emit that number of bits of the value, if positive, */
  163195. /* or the complement of its magnitude, if negative. */
  163196. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163197. return FALSE;
  163198. r = 0;
  163199. }
  163200. }
  163201. /* If the last coef(s) were zero, emit an end-of-block code */
  163202. if (r > 0)
  163203. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163204. return FALSE;
  163205. return TRUE;
  163206. }
  163207. /*
  163208. * Emit a restart marker & resynchronize predictions.
  163209. */
  163210. LOCAL(boolean)
  163211. emit_restart (working_state * state, int restart_num)
  163212. {
  163213. int ci;
  163214. if (! flush_bits(state))
  163215. return FALSE;
  163216. emit_byte(state, 0xFF, return FALSE);
  163217. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163218. /* Re-initialize DC predictions to 0 */
  163219. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163220. state->cur.last_dc_val[ci] = 0;
  163221. /* The restart counter is not updated until we successfully write the MCU. */
  163222. return TRUE;
  163223. }
  163224. /*
  163225. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163226. */
  163227. METHODDEF(boolean)
  163228. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163229. {
  163230. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163231. working_state state;
  163232. int blkn, ci;
  163233. jpeg_component_info * compptr;
  163234. /* Load up working state */
  163235. state.next_output_byte = cinfo->dest->next_output_byte;
  163236. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163237. ASSIGN_STATE(state.cur, entropy->saved);
  163238. state.cinfo = cinfo;
  163239. /* Emit restart marker if needed */
  163240. if (cinfo->restart_interval) {
  163241. if (entropy->restarts_to_go == 0)
  163242. if (! emit_restart(&state, entropy->next_restart_num))
  163243. return FALSE;
  163244. }
  163245. /* Encode the MCU data blocks */
  163246. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163247. ci = cinfo->MCU_membership[blkn];
  163248. compptr = cinfo->cur_comp_info[ci];
  163249. if (! encode_one_block(&state,
  163250. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163251. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163252. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163253. return FALSE;
  163254. /* Update last_dc_val */
  163255. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163256. }
  163257. /* Completed MCU, so update state */
  163258. cinfo->dest->next_output_byte = state.next_output_byte;
  163259. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163260. ASSIGN_STATE(entropy->saved, state.cur);
  163261. /* Update restart-interval state too */
  163262. if (cinfo->restart_interval) {
  163263. if (entropy->restarts_to_go == 0) {
  163264. entropy->restarts_to_go = cinfo->restart_interval;
  163265. entropy->next_restart_num++;
  163266. entropy->next_restart_num &= 7;
  163267. }
  163268. entropy->restarts_to_go--;
  163269. }
  163270. return TRUE;
  163271. }
  163272. /*
  163273. * Finish up at the end of a Huffman-compressed scan.
  163274. */
  163275. METHODDEF(void)
  163276. finish_pass_huff (j_compress_ptr cinfo)
  163277. {
  163278. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163279. working_state state;
  163280. /* Load up working state ... flush_bits needs it */
  163281. state.next_output_byte = cinfo->dest->next_output_byte;
  163282. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163283. ASSIGN_STATE(state.cur, entropy->saved);
  163284. state.cinfo = cinfo;
  163285. /* Flush out the last data */
  163286. if (! flush_bits(&state))
  163287. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163288. /* Update state */
  163289. cinfo->dest->next_output_byte = state.next_output_byte;
  163290. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163291. ASSIGN_STATE(entropy->saved, state.cur);
  163292. }
  163293. /*
  163294. * Huffman coding optimization.
  163295. *
  163296. * We first scan the supplied data and count the number of uses of each symbol
  163297. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163298. * Then we build a Huffman coding tree for the observed counts.
  163299. * Symbols which are not needed at all for the particular image are not
  163300. * assigned any code, which saves space in the DHT marker as well as in
  163301. * the compressed data.
  163302. */
  163303. #ifdef ENTROPY_OPT_SUPPORTED
  163304. /* Process a single block's worth of coefficients */
  163305. LOCAL(void)
  163306. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163307. long dc_counts[], long ac_counts[])
  163308. {
  163309. register int temp;
  163310. register int nbits;
  163311. register int k, r;
  163312. /* Encode the DC coefficient difference per section F.1.2.1 */
  163313. temp = block[0] - last_dc_val;
  163314. if (temp < 0)
  163315. temp = -temp;
  163316. /* Find the number of bits needed for the magnitude of the coefficient */
  163317. nbits = 0;
  163318. while (temp) {
  163319. nbits++;
  163320. temp >>= 1;
  163321. }
  163322. /* Check for out-of-range coefficient values.
  163323. * Since we're encoding a difference, the range limit is twice as much.
  163324. */
  163325. if (nbits > MAX_COEF_BITS+1)
  163326. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163327. /* Count the Huffman symbol for the number of bits */
  163328. dc_counts[nbits]++;
  163329. /* Encode the AC coefficients per section F.1.2.2 */
  163330. r = 0; /* r = run length of zeros */
  163331. for (k = 1; k < DCTSIZE2; k++) {
  163332. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163333. r++;
  163334. } else {
  163335. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163336. while (r > 15) {
  163337. ac_counts[0xF0]++;
  163338. r -= 16;
  163339. }
  163340. /* Find the number of bits needed for the magnitude of the coefficient */
  163341. if (temp < 0)
  163342. temp = -temp;
  163343. /* Find the number of bits needed for the magnitude of the coefficient */
  163344. nbits = 1; /* there must be at least one 1 bit */
  163345. while ((temp >>= 1))
  163346. nbits++;
  163347. /* Check for out-of-range coefficient values */
  163348. if (nbits > MAX_COEF_BITS)
  163349. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163350. /* Count Huffman symbol for run length / number of bits */
  163351. ac_counts[(r << 4) + nbits]++;
  163352. r = 0;
  163353. }
  163354. }
  163355. /* If the last coef(s) were zero, emit an end-of-block code */
  163356. if (r > 0)
  163357. ac_counts[0]++;
  163358. }
  163359. /*
  163360. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163361. * No data is actually output, so no suspension return is possible.
  163362. */
  163363. METHODDEF(boolean)
  163364. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163365. {
  163366. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163367. int blkn, ci;
  163368. jpeg_component_info * compptr;
  163369. /* Take care of restart intervals if needed */
  163370. if (cinfo->restart_interval) {
  163371. if (entropy->restarts_to_go == 0) {
  163372. /* Re-initialize DC predictions to 0 */
  163373. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163374. entropy->saved.last_dc_val[ci] = 0;
  163375. /* Update restart state */
  163376. entropy->restarts_to_go = cinfo->restart_interval;
  163377. }
  163378. entropy->restarts_to_go--;
  163379. }
  163380. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163381. ci = cinfo->MCU_membership[blkn];
  163382. compptr = cinfo->cur_comp_info[ci];
  163383. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163384. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163385. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163386. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163387. }
  163388. return TRUE;
  163389. }
  163390. /*
  163391. * Generate the best Huffman code table for the given counts, fill htbl.
  163392. * Note this is also used by jcphuff.c.
  163393. *
  163394. * The JPEG standard requires that no symbol be assigned a codeword of all
  163395. * one bits (so that padding bits added at the end of a compressed segment
  163396. * can't look like a valid code). Because of the canonical ordering of
  163397. * codewords, this just means that there must be an unused slot in the
  163398. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163399. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163400. * with count 1. In theory that's not optimal; giving it count zero but
  163401. * including it in the symbol set anyway should give a better Huffman code.
  163402. * But the theoretically better code actually seems to come out worse in
  163403. * practice, because it produces more all-ones bytes (which incur stuffed
  163404. * zero bytes in the final file). In any case the difference is tiny.
  163405. *
  163406. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163407. * If some symbols have a very small but nonzero probability, the Huffman tree
  163408. * must be adjusted to meet the code length restriction. We currently use
  163409. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163410. * optimal; it may not choose the best possible limited-length code. But
  163411. * typically only very-low-frequency symbols will be given less-than-optimal
  163412. * lengths, so the code is almost optimal. Experimental comparisons against
  163413. * an optimal limited-length-code algorithm indicate that the difference is
  163414. * microscopic --- usually less than a hundredth of a percent of total size.
  163415. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163416. */
  163417. GLOBAL(void)
  163418. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163419. {
  163420. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163421. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163422. int codesize[257]; /* codesize[k] = code length of symbol k */
  163423. int others[257]; /* next symbol in current branch of tree */
  163424. int c1, c2;
  163425. int p, i, j;
  163426. long v;
  163427. /* This algorithm is explained in section K.2 of the JPEG standard */
  163428. MEMZERO(bits, SIZEOF(bits));
  163429. MEMZERO(codesize, SIZEOF(codesize));
  163430. for (i = 0; i < 257; i++)
  163431. others[i] = -1; /* init links to empty */
  163432. freq[256] = 1; /* make sure 256 has a nonzero count */
  163433. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163434. * that no real symbol is given code-value of all ones, because 256
  163435. * will be placed last in the largest codeword category.
  163436. */
  163437. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163438. for (;;) {
  163439. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163440. /* In case of ties, take the larger symbol number */
  163441. c1 = -1;
  163442. v = 1000000000L;
  163443. for (i = 0; i <= 256; i++) {
  163444. if (freq[i] && freq[i] <= v) {
  163445. v = freq[i];
  163446. c1 = i;
  163447. }
  163448. }
  163449. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163450. /* In case of ties, take the larger symbol number */
  163451. c2 = -1;
  163452. v = 1000000000L;
  163453. for (i = 0; i <= 256; i++) {
  163454. if (freq[i] && freq[i] <= v && i != c1) {
  163455. v = freq[i];
  163456. c2 = i;
  163457. }
  163458. }
  163459. /* Done if we've merged everything into one frequency */
  163460. if (c2 < 0)
  163461. break;
  163462. /* Else merge the two counts/trees */
  163463. freq[c1] += freq[c2];
  163464. freq[c2] = 0;
  163465. /* Increment the codesize of everything in c1's tree branch */
  163466. codesize[c1]++;
  163467. while (others[c1] >= 0) {
  163468. c1 = others[c1];
  163469. codesize[c1]++;
  163470. }
  163471. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163472. /* Increment the codesize of everything in c2's tree branch */
  163473. codesize[c2]++;
  163474. while (others[c2] >= 0) {
  163475. c2 = others[c2];
  163476. codesize[c2]++;
  163477. }
  163478. }
  163479. /* Now count the number of symbols of each code length */
  163480. for (i = 0; i <= 256; i++) {
  163481. if (codesize[i]) {
  163482. /* The JPEG standard seems to think that this can't happen, */
  163483. /* but I'm paranoid... */
  163484. if (codesize[i] > MAX_CLEN)
  163485. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163486. bits[codesize[i]]++;
  163487. }
  163488. }
  163489. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163490. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163491. * Here is what the JPEG spec says about how this next bit works:
  163492. * Since symbols are paired for the longest Huffman code, the symbols are
  163493. * removed from this length category two at a time. The prefix for the pair
  163494. * (which is one bit shorter) is allocated to one of the pair; then,
  163495. * skipping the BITS entry for that prefix length, a code word from the next
  163496. * shortest nonzero BITS entry is converted into a prefix for two code words
  163497. * one bit longer.
  163498. */
  163499. for (i = MAX_CLEN; i > 16; i--) {
  163500. while (bits[i] > 0) {
  163501. j = i - 2; /* find length of new prefix to be used */
  163502. while (bits[j] == 0)
  163503. j--;
  163504. bits[i] -= 2; /* remove two symbols */
  163505. bits[i-1]++; /* one goes in this length */
  163506. bits[j+1] += 2; /* two new symbols in this length */
  163507. bits[j]--; /* symbol of this length is now a prefix */
  163508. }
  163509. }
  163510. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163511. while (bits[i] == 0) /* find largest codelength still in use */
  163512. i--;
  163513. bits[i]--;
  163514. /* Return final symbol counts (only for lengths 0..16) */
  163515. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163516. /* Return a list of the symbols sorted by code length */
  163517. /* It's not real clear to me why we don't need to consider the codelength
  163518. * changes made above, but the JPEG spec seems to think this works.
  163519. */
  163520. p = 0;
  163521. for (i = 1; i <= MAX_CLEN; i++) {
  163522. for (j = 0; j <= 255; j++) {
  163523. if (codesize[j] == i) {
  163524. htbl->huffval[p] = (UINT8) j;
  163525. p++;
  163526. }
  163527. }
  163528. }
  163529. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163530. htbl->sent_table = FALSE;
  163531. }
  163532. /*
  163533. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163534. */
  163535. METHODDEF(void)
  163536. finish_pass_gather (j_compress_ptr cinfo)
  163537. {
  163538. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163539. int ci, dctbl, actbl;
  163540. jpeg_component_info * compptr;
  163541. JHUFF_TBL **htblptr;
  163542. boolean did_dc[NUM_HUFF_TBLS];
  163543. boolean did_ac[NUM_HUFF_TBLS];
  163544. /* It's important not to apply jpeg_gen_optimal_table more than once
  163545. * per table, because it clobbers the input frequency counts!
  163546. */
  163547. MEMZERO(did_dc, SIZEOF(did_dc));
  163548. MEMZERO(did_ac, SIZEOF(did_ac));
  163549. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163550. compptr = cinfo->cur_comp_info[ci];
  163551. dctbl = compptr->dc_tbl_no;
  163552. actbl = compptr->ac_tbl_no;
  163553. if (! did_dc[dctbl]) {
  163554. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163555. if (*htblptr == NULL)
  163556. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163557. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163558. did_dc[dctbl] = TRUE;
  163559. }
  163560. if (! did_ac[actbl]) {
  163561. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163562. if (*htblptr == NULL)
  163563. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163564. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163565. did_ac[actbl] = TRUE;
  163566. }
  163567. }
  163568. }
  163569. #endif /* ENTROPY_OPT_SUPPORTED */
  163570. /*
  163571. * Module initialization routine for Huffman entropy encoding.
  163572. */
  163573. GLOBAL(void)
  163574. jinit_huff_encoder (j_compress_ptr cinfo)
  163575. {
  163576. huff_entropy_ptr entropy;
  163577. int i;
  163578. entropy = (huff_entropy_ptr)
  163579. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163580. SIZEOF(huff_entropy_encoder));
  163581. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163582. entropy->pub.start_pass = start_pass_huff;
  163583. /* Mark tables unallocated */
  163584. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163585. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163586. #ifdef ENTROPY_OPT_SUPPORTED
  163587. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163588. #endif
  163589. }
  163590. }
  163591. /*** End of inlined file: jchuff.c ***/
  163592. #undef emit_byte
  163593. /*** Start of inlined file: jcinit.c ***/
  163594. #define JPEG_INTERNALS
  163595. /*
  163596. * Master selection of compression modules.
  163597. * This is done once at the start of processing an image. We determine
  163598. * which modules will be used and give them appropriate initialization calls.
  163599. */
  163600. GLOBAL(void)
  163601. jinit_compress_master (j_compress_ptr cinfo)
  163602. {
  163603. /* Initialize master control (includes parameter checking/processing) */
  163604. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163605. /* Preprocessing */
  163606. if (! cinfo->raw_data_in) {
  163607. jinit_color_converter(cinfo);
  163608. jinit_downsampler(cinfo);
  163609. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163610. }
  163611. /* Forward DCT */
  163612. jinit_forward_dct(cinfo);
  163613. /* Entropy encoding: either Huffman or arithmetic coding. */
  163614. if (cinfo->arith_code) {
  163615. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163616. } else {
  163617. if (cinfo->progressive_mode) {
  163618. #ifdef C_PROGRESSIVE_SUPPORTED
  163619. jinit_phuff_encoder(cinfo);
  163620. #else
  163621. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163622. #endif
  163623. } else
  163624. jinit_huff_encoder(cinfo);
  163625. }
  163626. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163627. jinit_c_coef_controller(cinfo,
  163628. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163629. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163630. jinit_marker_writer(cinfo);
  163631. /* We can now tell the memory manager to allocate virtual arrays. */
  163632. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163633. /* Write the datastream header (SOI) immediately.
  163634. * Frame and scan headers are postponed till later.
  163635. * This lets application insert special markers after the SOI.
  163636. */
  163637. (*cinfo->marker->write_file_header) (cinfo);
  163638. }
  163639. /*** End of inlined file: jcinit.c ***/
  163640. /*** Start of inlined file: jcmainct.c ***/
  163641. #define JPEG_INTERNALS
  163642. /* Note: currently, there is no operating mode in which a full-image buffer
  163643. * is needed at this step. If there were, that mode could not be used with
  163644. * "raw data" input, since this module is bypassed in that case. However,
  163645. * we've left the code here for possible use in special applications.
  163646. */
  163647. #undef FULL_MAIN_BUFFER_SUPPORTED
  163648. /* Private buffer controller object */
  163649. typedef struct {
  163650. struct jpeg_c_main_controller pub; /* public fields */
  163651. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163652. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163653. boolean suspended; /* remember if we suspended output */
  163654. J_BUF_MODE pass_mode; /* current operating mode */
  163655. /* If using just a strip buffer, this points to the entire set of buffers
  163656. * (we allocate one for each component). In the full-image case, this
  163657. * points to the currently accessible strips of the virtual arrays.
  163658. */
  163659. JSAMPARRAY buffer[MAX_COMPONENTS];
  163660. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163661. /* If using full-image storage, this array holds pointers to virtual-array
  163662. * control blocks for each component. Unused if not full-image storage.
  163663. */
  163664. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163665. #endif
  163666. } my_main_controller;
  163667. typedef my_main_controller * my_main_ptr;
  163668. /* Forward declarations */
  163669. METHODDEF(void) process_data_simple_main
  163670. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163671. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163672. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163673. METHODDEF(void) process_data_buffer_main
  163674. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163675. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163676. #endif
  163677. /*
  163678. * Initialize for a processing pass.
  163679. */
  163680. METHODDEF(void)
  163681. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163682. {
  163683. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163684. /* Do nothing in raw-data mode. */
  163685. if (cinfo->raw_data_in)
  163686. return;
  163687. main_->cur_iMCU_row = 0; /* initialize counters */
  163688. main_->rowgroup_ctr = 0;
  163689. main_->suspended = FALSE;
  163690. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163691. switch (pass_mode) {
  163692. case JBUF_PASS_THRU:
  163693. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163694. if (main_->whole_image[0] != NULL)
  163695. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163696. #endif
  163697. main_->pub.process_data = process_data_simple_main;
  163698. break;
  163699. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163700. case JBUF_SAVE_SOURCE:
  163701. case JBUF_CRANK_DEST:
  163702. case JBUF_SAVE_AND_PASS:
  163703. if (main_->whole_image[0] == NULL)
  163704. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163705. main_->pub.process_data = process_data_buffer_main;
  163706. break;
  163707. #endif
  163708. default:
  163709. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163710. break;
  163711. }
  163712. }
  163713. /*
  163714. * Process some data.
  163715. * This routine handles the simple pass-through mode,
  163716. * where we have only a strip buffer.
  163717. */
  163718. METHODDEF(void)
  163719. process_data_simple_main (j_compress_ptr cinfo,
  163720. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163721. JDIMENSION in_rows_avail)
  163722. {
  163723. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163724. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163725. /* Read input data if we haven't filled the main buffer yet */
  163726. if (main_->rowgroup_ctr < DCTSIZE)
  163727. (*cinfo->prep->pre_process_data) (cinfo,
  163728. input_buf, in_row_ctr, in_rows_avail,
  163729. main_->buffer, &main_->rowgroup_ctr,
  163730. (JDIMENSION) DCTSIZE);
  163731. /* If we don't have a full iMCU row buffered, return to application for
  163732. * more data. Note that preprocessor will always pad to fill the iMCU row
  163733. * at the bottom of the image.
  163734. */
  163735. if (main_->rowgroup_ctr != DCTSIZE)
  163736. return;
  163737. /* Send the completed row to the compressor */
  163738. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163739. /* If compressor did not consume the whole row, then we must need to
  163740. * suspend processing and return to the application. In this situation
  163741. * we pretend we didn't yet consume the last input row; otherwise, if
  163742. * it happened to be the last row of the image, the application would
  163743. * think we were done.
  163744. */
  163745. if (! main_->suspended) {
  163746. (*in_row_ctr)--;
  163747. main_->suspended = TRUE;
  163748. }
  163749. return;
  163750. }
  163751. /* We did finish the row. Undo our little suspension hack if a previous
  163752. * call suspended; then mark the main buffer empty.
  163753. */
  163754. if (main_->suspended) {
  163755. (*in_row_ctr)++;
  163756. main_->suspended = FALSE;
  163757. }
  163758. main_->rowgroup_ctr = 0;
  163759. main_->cur_iMCU_row++;
  163760. }
  163761. }
  163762. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163763. /*
  163764. * Process some data.
  163765. * This routine handles all of the modes that use a full-size buffer.
  163766. */
  163767. METHODDEF(void)
  163768. process_data_buffer_main (j_compress_ptr cinfo,
  163769. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163770. JDIMENSION in_rows_avail)
  163771. {
  163772. my_main_ptr main = (my_main_ptr) cinfo->main;
  163773. int ci;
  163774. jpeg_component_info *compptr;
  163775. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163776. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163777. /* Realign the virtual buffers if at the start of an iMCU row. */
  163778. if (main->rowgroup_ctr == 0) {
  163779. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163780. ci++, compptr++) {
  163781. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163782. ((j_common_ptr) cinfo, main->whole_image[ci],
  163783. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163784. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163785. }
  163786. /* In a read pass, pretend we just read some source data. */
  163787. if (! writing) {
  163788. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163789. main->rowgroup_ctr = DCTSIZE;
  163790. }
  163791. }
  163792. /* If a write pass, read input data until the current iMCU row is full. */
  163793. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163794. if (writing) {
  163795. (*cinfo->prep->pre_process_data) (cinfo,
  163796. input_buf, in_row_ctr, in_rows_avail,
  163797. main->buffer, &main->rowgroup_ctr,
  163798. (JDIMENSION) DCTSIZE);
  163799. /* Return to application if we need more data to fill the iMCU row. */
  163800. if (main->rowgroup_ctr < DCTSIZE)
  163801. return;
  163802. }
  163803. /* Emit data, unless this is a sink-only pass. */
  163804. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163805. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163806. /* If compressor did not consume the whole row, then we must need to
  163807. * suspend processing and return to the application. In this situation
  163808. * we pretend we didn't yet consume the last input row; otherwise, if
  163809. * it happened to be the last row of the image, the application would
  163810. * think we were done.
  163811. */
  163812. if (! main->suspended) {
  163813. (*in_row_ctr)--;
  163814. main->suspended = TRUE;
  163815. }
  163816. return;
  163817. }
  163818. /* We did finish the row. Undo our little suspension hack if a previous
  163819. * call suspended; then mark the main buffer empty.
  163820. */
  163821. if (main->suspended) {
  163822. (*in_row_ctr)++;
  163823. main->suspended = FALSE;
  163824. }
  163825. }
  163826. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163827. main->rowgroup_ctr = 0;
  163828. main->cur_iMCU_row++;
  163829. }
  163830. }
  163831. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163832. /*
  163833. * Initialize main buffer controller.
  163834. */
  163835. GLOBAL(void)
  163836. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163837. {
  163838. my_main_ptr main_;
  163839. int ci;
  163840. jpeg_component_info *compptr;
  163841. main_ = (my_main_ptr)
  163842. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163843. SIZEOF(my_main_controller));
  163844. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163845. main_->pub.start_pass = start_pass_main;
  163846. /* We don't need to create a buffer in raw-data mode. */
  163847. if (cinfo->raw_data_in)
  163848. return;
  163849. /* Create the buffer. It holds downsampled data, so each component
  163850. * may be of a different size.
  163851. */
  163852. if (need_full_buffer) {
  163853. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163854. /* Allocate a full-image virtual array for each component */
  163855. /* Note we pad the bottom to a multiple of the iMCU height */
  163856. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163857. ci++, compptr++) {
  163858. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163859. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163860. compptr->width_in_blocks * DCTSIZE,
  163861. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163862. (long) compptr->v_samp_factor) * DCTSIZE,
  163863. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163864. }
  163865. #else
  163866. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163867. #endif
  163868. } else {
  163869. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163870. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163871. #endif
  163872. /* Allocate a strip buffer for each component */
  163873. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163874. ci++, compptr++) {
  163875. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163876. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163877. compptr->width_in_blocks * DCTSIZE,
  163878. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163879. }
  163880. }
  163881. }
  163882. /*** End of inlined file: jcmainct.c ***/
  163883. /*** Start of inlined file: jcmarker.c ***/
  163884. #define JPEG_INTERNALS
  163885. /* Private state */
  163886. typedef struct {
  163887. struct jpeg_marker_writer pub; /* public fields */
  163888. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163889. } my_marker_writer;
  163890. typedef my_marker_writer * my_marker_ptr;
  163891. /*
  163892. * Basic output routines.
  163893. *
  163894. * Note that we do not support suspension while writing a marker.
  163895. * Therefore, an application using suspension must ensure that there is
  163896. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163897. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163898. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163899. * modes are not supported at all with suspension, so those two are the only
  163900. * points where markers will be written.
  163901. */
  163902. LOCAL(void)
  163903. emit_byte (j_compress_ptr cinfo, int val)
  163904. /* Emit a byte */
  163905. {
  163906. struct jpeg_destination_mgr * dest = cinfo->dest;
  163907. *(dest->next_output_byte)++ = (JOCTET) val;
  163908. if (--dest->free_in_buffer == 0) {
  163909. if (! (*dest->empty_output_buffer) (cinfo))
  163910. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163911. }
  163912. }
  163913. LOCAL(void)
  163914. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163915. /* Emit a marker code */
  163916. {
  163917. emit_byte(cinfo, 0xFF);
  163918. emit_byte(cinfo, (int) mark);
  163919. }
  163920. LOCAL(void)
  163921. emit_2bytes (j_compress_ptr cinfo, int value)
  163922. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163923. {
  163924. emit_byte(cinfo, (value >> 8) & 0xFF);
  163925. emit_byte(cinfo, value & 0xFF);
  163926. }
  163927. /*
  163928. * Routines to write specific marker types.
  163929. */
  163930. LOCAL(int)
  163931. emit_dqt (j_compress_ptr cinfo, int index)
  163932. /* Emit a DQT marker */
  163933. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163934. {
  163935. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163936. int prec;
  163937. int i;
  163938. if (qtbl == NULL)
  163939. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163940. prec = 0;
  163941. for (i = 0; i < DCTSIZE2; i++) {
  163942. if (qtbl->quantval[i] > 255)
  163943. prec = 1;
  163944. }
  163945. if (! qtbl->sent_table) {
  163946. emit_marker(cinfo, M_DQT);
  163947. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163948. emit_byte(cinfo, index + (prec<<4));
  163949. for (i = 0; i < DCTSIZE2; i++) {
  163950. /* The table entries must be emitted in zigzag order. */
  163951. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163952. if (prec)
  163953. emit_byte(cinfo, (int) (qval >> 8));
  163954. emit_byte(cinfo, (int) (qval & 0xFF));
  163955. }
  163956. qtbl->sent_table = TRUE;
  163957. }
  163958. return prec;
  163959. }
  163960. LOCAL(void)
  163961. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163962. /* Emit a DHT marker */
  163963. {
  163964. JHUFF_TBL * htbl;
  163965. int length, i;
  163966. if (is_ac) {
  163967. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163968. index += 0x10; /* output index has AC bit set */
  163969. } else {
  163970. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163971. }
  163972. if (htbl == NULL)
  163973. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163974. if (! htbl->sent_table) {
  163975. emit_marker(cinfo, M_DHT);
  163976. length = 0;
  163977. for (i = 1; i <= 16; i++)
  163978. length += htbl->bits[i];
  163979. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163980. emit_byte(cinfo, index);
  163981. for (i = 1; i <= 16; i++)
  163982. emit_byte(cinfo, htbl->bits[i]);
  163983. for (i = 0; i < length; i++)
  163984. emit_byte(cinfo, htbl->huffval[i]);
  163985. htbl->sent_table = TRUE;
  163986. }
  163987. }
  163988. LOCAL(void)
  163989. emit_dac (j_compress_ptr)
  163990. /* Emit a DAC marker */
  163991. /* Since the useful info is so small, we want to emit all the tables in */
  163992. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163993. {
  163994. #ifdef C_ARITH_CODING_SUPPORTED
  163995. char dc_in_use[NUM_ARITH_TBLS];
  163996. char ac_in_use[NUM_ARITH_TBLS];
  163997. int length, i;
  163998. jpeg_component_info *compptr;
  163999. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164000. dc_in_use[i] = ac_in_use[i] = 0;
  164001. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164002. compptr = cinfo->cur_comp_info[i];
  164003. dc_in_use[compptr->dc_tbl_no] = 1;
  164004. ac_in_use[compptr->ac_tbl_no] = 1;
  164005. }
  164006. length = 0;
  164007. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164008. length += dc_in_use[i] + ac_in_use[i];
  164009. emit_marker(cinfo, M_DAC);
  164010. emit_2bytes(cinfo, length*2 + 2);
  164011. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164012. if (dc_in_use[i]) {
  164013. emit_byte(cinfo, i);
  164014. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164015. }
  164016. if (ac_in_use[i]) {
  164017. emit_byte(cinfo, i + 0x10);
  164018. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164019. }
  164020. }
  164021. #endif /* C_ARITH_CODING_SUPPORTED */
  164022. }
  164023. LOCAL(void)
  164024. emit_dri (j_compress_ptr cinfo)
  164025. /* Emit a DRI marker */
  164026. {
  164027. emit_marker(cinfo, M_DRI);
  164028. emit_2bytes(cinfo, 4); /* fixed length */
  164029. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164030. }
  164031. LOCAL(void)
  164032. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164033. /* Emit a SOF marker */
  164034. {
  164035. int ci;
  164036. jpeg_component_info *compptr;
  164037. emit_marker(cinfo, code);
  164038. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164039. /* Make sure image isn't bigger than SOF field can handle */
  164040. if ((long) cinfo->image_height > 65535L ||
  164041. (long) cinfo->image_width > 65535L)
  164042. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164043. emit_byte(cinfo, cinfo->data_precision);
  164044. emit_2bytes(cinfo, (int) cinfo->image_height);
  164045. emit_2bytes(cinfo, (int) cinfo->image_width);
  164046. emit_byte(cinfo, cinfo->num_components);
  164047. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164048. ci++, compptr++) {
  164049. emit_byte(cinfo, compptr->component_id);
  164050. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164051. emit_byte(cinfo, compptr->quant_tbl_no);
  164052. }
  164053. }
  164054. LOCAL(void)
  164055. emit_sos (j_compress_ptr cinfo)
  164056. /* Emit a SOS marker */
  164057. {
  164058. int i, td, ta;
  164059. jpeg_component_info *compptr;
  164060. emit_marker(cinfo, M_SOS);
  164061. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164062. emit_byte(cinfo, cinfo->comps_in_scan);
  164063. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164064. compptr = cinfo->cur_comp_info[i];
  164065. emit_byte(cinfo, compptr->component_id);
  164066. td = compptr->dc_tbl_no;
  164067. ta = compptr->ac_tbl_no;
  164068. if (cinfo->progressive_mode) {
  164069. /* Progressive mode: only DC or only AC tables are used in one scan;
  164070. * furthermore, Huffman coding of DC refinement uses no table at all.
  164071. * We emit 0 for unused field(s); this is recommended by the P&M text
  164072. * but does not seem to be specified in the standard.
  164073. */
  164074. if (cinfo->Ss == 0) {
  164075. ta = 0; /* DC scan */
  164076. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164077. td = 0; /* no DC table either */
  164078. } else {
  164079. td = 0; /* AC scan */
  164080. }
  164081. }
  164082. emit_byte(cinfo, (td << 4) + ta);
  164083. }
  164084. emit_byte(cinfo, cinfo->Ss);
  164085. emit_byte(cinfo, cinfo->Se);
  164086. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164087. }
  164088. LOCAL(void)
  164089. emit_jfif_app0 (j_compress_ptr cinfo)
  164090. /* Emit a JFIF-compliant APP0 marker */
  164091. {
  164092. /*
  164093. * Length of APP0 block (2 bytes)
  164094. * Block ID (4 bytes - ASCII "JFIF")
  164095. * Zero byte (1 byte to terminate the ID string)
  164096. * Version Major, Minor (2 bytes - major first)
  164097. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164098. * Xdpu (2 bytes - dots per unit horizontal)
  164099. * Ydpu (2 bytes - dots per unit vertical)
  164100. * Thumbnail X size (1 byte)
  164101. * Thumbnail Y size (1 byte)
  164102. */
  164103. emit_marker(cinfo, M_APP0);
  164104. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164105. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164106. emit_byte(cinfo, 0x46);
  164107. emit_byte(cinfo, 0x49);
  164108. emit_byte(cinfo, 0x46);
  164109. emit_byte(cinfo, 0);
  164110. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164111. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164112. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164113. emit_2bytes(cinfo, (int) cinfo->X_density);
  164114. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164115. emit_byte(cinfo, 0); /* No thumbnail image */
  164116. emit_byte(cinfo, 0);
  164117. }
  164118. LOCAL(void)
  164119. emit_adobe_app14 (j_compress_ptr cinfo)
  164120. /* Emit an Adobe APP14 marker */
  164121. {
  164122. /*
  164123. * Length of APP14 block (2 bytes)
  164124. * Block ID (5 bytes - ASCII "Adobe")
  164125. * Version Number (2 bytes - currently 100)
  164126. * Flags0 (2 bytes - currently 0)
  164127. * Flags1 (2 bytes - currently 0)
  164128. * Color transform (1 byte)
  164129. *
  164130. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164131. * now in circulation seem to use Version = 100, so that's what we write.
  164132. *
  164133. * We write the color transform byte as 1 if the JPEG color space is
  164134. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164135. * whether the encoder performed a transformation, which is pretty useless.
  164136. */
  164137. emit_marker(cinfo, M_APP14);
  164138. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164139. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164140. emit_byte(cinfo, 0x64);
  164141. emit_byte(cinfo, 0x6F);
  164142. emit_byte(cinfo, 0x62);
  164143. emit_byte(cinfo, 0x65);
  164144. emit_2bytes(cinfo, 100); /* Version */
  164145. emit_2bytes(cinfo, 0); /* Flags0 */
  164146. emit_2bytes(cinfo, 0); /* Flags1 */
  164147. switch (cinfo->jpeg_color_space) {
  164148. case JCS_YCbCr:
  164149. emit_byte(cinfo, 1); /* Color transform = 1 */
  164150. break;
  164151. case JCS_YCCK:
  164152. emit_byte(cinfo, 2); /* Color transform = 2 */
  164153. break;
  164154. default:
  164155. emit_byte(cinfo, 0); /* Color transform = 0 */
  164156. break;
  164157. }
  164158. }
  164159. /*
  164160. * These routines allow writing an arbitrary marker with parameters.
  164161. * The only intended use is to emit COM or APPn markers after calling
  164162. * write_file_header and before calling write_frame_header.
  164163. * Other uses are not guaranteed to produce desirable results.
  164164. * Counting the parameter bytes properly is the caller's responsibility.
  164165. */
  164166. METHODDEF(void)
  164167. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164168. /* Emit an arbitrary marker header */
  164169. {
  164170. if (datalen > (unsigned int) 65533) /* safety check */
  164171. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164172. emit_marker(cinfo, (JPEG_MARKER) marker);
  164173. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164174. }
  164175. METHODDEF(void)
  164176. write_marker_byte (j_compress_ptr cinfo, int val)
  164177. /* Emit one byte of marker parameters following write_marker_header */
  164178. {
  164179. emit_byte(cinfo, val);
  164180. }
  164181. /*
  164182. * Write datastream header.
  164183. * This consists of an SOI and optional APPn markers.
  164184. * We recommend use of the JFIF marker, but not the Adobe marker,
  164185. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164186. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164187. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164188. * Note that an application can write additional header markers after
  164189. * jpeg_start_compress returns.
  164190. */
  164191. METHODDEF(void)
  164192. write_file_header (j_compress_ptr cinfo)
  164193. {
  164194. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164195. emit_marker(cinfo, M_SOI); /* first the SOI */
  164196. /* SOI is defined to reset restart interval to 0 */
  164197. marker->last_restart_interval = 0;
  164198. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164199. emit_jfif_app0(cinfo);
  164200. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164201. emit_adobe_app14(cinfo);
  164202. }
  164203. /*
  164204. * Write frame header.
  164205. * This consists of DQT and SOFn markers.
  164206. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164207. * This avoids compatibility problems with incorrect implementations that
  164208. * try to error-check the quant table numbers as soon as they see the SOF.
  164209. */
  164210. METHODDEF(void)
  164211. write_frame_header (j_compress_ptr cinfo)
  164212. {
  164213. int ci, prec;
  164214. boolean is_baseline;
  164215. jpeg_component_info *compptr;
  164216. /* Emit DQT for each quantization table.
  164217. * Note that emit_dqt() suppresses any duplicate tables.
  164218. */
  164219. prec = 0;
  164220. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164221. ci++, compptr++) {
  164222. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164223. }
  164224. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164225. /* Check for a non-baseline specification.
  164226. * Note we assume that Huffman table numbers won't be changed later.
  164227. */
  164228. if (cinfo->arith_code || cinfo->progressive_mode ||
  164229. cinfo->data_precision != 8) {
  164230. is_baseline = FALSE;
  164231. } else {
  164232. is_baseline = TRUE;
  164233. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164234. ci++, compptr++) {
  164235. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164236. is_baseline = FALSE;
  164237. }
  164238. if (prec && is_baseline) {
  164239. is_baseline = FALSE;
  164240. /* If it's baseline except for quantizer size, warn the user */
  164241. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164242. }
  164243. }
  164244. /* Emit the proper SOF marker */
  164245. if (cinfo->arith_code) {
  164246. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164247. } else {
  164248. if (cinfo->progressive_mode)
  164249. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164250. else if (is_baseline)
  164251. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164252. else
  164253. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164254. }
  164255. }
  164256. /*
  164257. * Write scan header.
  164258. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164259. * Compressed data will be written following the SOS.
  164260. */
  164261. METHODDEF(void)
  164262. write_scan_header (j_compress_ptr cinfo)
  164263. {
  164264. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164265. int i;
  164266. jpeg_component_info *compptr;
  164267. if (cinfo->arith_code) {
  164268. /* Emit arith conditioning info. We may have some duplication
  164269. * if the file has multiple scans, but it's so small it's hardly
  164270. * worth worrying about.
  164271. */
  164272. emit_dac(cinfo);
  164273. } else {
  164274. /* Emit Huffman tables.
  164275. * Note that emit_dht() suppresses any duplicate tables.
  164276. */
  164277. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164278. compptr = cinfo->cur_comp_info[i];
  164279. if (cinfo->progressive_mode) {
  164280. /* Progressive mode: only DC or only AC tables are used in one scan */
  164281. if (cinfo->Ss == 0) {
  164282. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164283. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164284. } else {
  164285. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164286. }
  164287. } else {
  164288. /* Sequential mode: need both DC and AC tables */
  164289. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164290. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164291. }
  164292. }
  164293. }
  164294. /* Emit DRI if required --- note that DRI value could change for each scan.
  164295. * We avoid wasting space with unnecessary DRIs, however.
  164296. */
  164297. if (cinfo->restart_interval != marker->last_restart_interval) {
  164298. emit_dri(cinfo);
  164299. marker->last_restart_interval = cinfo->restart_interval;
  164300. }
  164301. emit_sos(cinfo);
  164302. }
  164303. /*
  164304. * Write datastream trailer.
  164305. */
  164306. METHODDEF(void)
  164307. write_file_trailer (j_compress_ptr cinfo)
  164308. {
  164309. emit_marker(cinfo, M_EOI);
  164310. }
  164311. /*
  164312. * Write an abbreviated table-specification datastream.
  164313. * This consists of SOI, DQT and DHT tables, and EOI.
  164314. * Any table that is defined and not marked sent_table = TRUE will be
  164315. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164316. */
  164317. METHODDEF(void)
  164318. write_tables_only (j_compress_ptr cinfo)
  164319. {
  164320. int i;
  164321. emit_marker(cinfo, M_SOI);
  164322. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164323. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164324. (void) emit_dqt(cinfo, i);
  164325. }
  164326. if (! cinfo->arith_code) {
  164327. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164328. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164329. emit_dht(cinfo, i, FALSE);
  164330. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164331. emit_dht(cinfo, i, TRUE);
  164332. }
  164333. }
  164334. emit_marker(cinfo, M_EOI);
  164335. }
  164336. /*
  164337. * Initialize the marker writer module.
  164338. */
  164339. GLOBAL(void)
  164340. jinit_marker_writer (j_compress_ptr cinfo)
  164341. {
  164342. my_marker_ptr marker;
  164343. /* Create the subobject */
  164344. marker = (my_marker_ptr)
  164345. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164346. SIZEOF(my_marker_writer));
  164347. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164348. /* Initialize method pointers */
  164349. marker->pub.write_file_header = write_file_header;
  164350. marker->pub.write_frame_header = write_frame_header;
  164351. marker->pub.write_scan_header = write_scan_header;
  164352. marker->pub.write_file_trailer = write_file_trailer;
  164353. marker->pub.write_tables_only = write_tables_only;
  164354. marker->pub.write_marker_header = write_marker_header;
  164355. marker->pub.write_marker_byte = write_marker_byte;
  164356. /* Initialize private state */
  164357. marker->last_restart_interval = 0;
  164358. }
  164359. /*** End of inlined file: jcmarker.c ***/
  164360. /*** Start of inlined file: jcmaster.c ***/
  164361. #define JPEG_INTERNALS
  164362. /* Private state */
  164363. typedef enum {
  164364. main_pass, /* input data, also do first output step */
  164365. huff_opt_pass, /* Huffman code optimization pass */
  164366. output_pass /* data output pass */
  164367. } c_pass_type;
  164368. typedef struct {
  164369. struct jpeg_comp_master pub; /* public fields */
  164370. c_pass_type pass_type; /* the type of the current pass */
  164371. int pass_number; /* # of passes completed */
  164372. int total_passes; /* total # of passes needed */
  164373. int scan_number; /* current index in scan_info[] */
  164374. } my_comp_master;
  164375. typedef my_comp_master * my_master_ptr;
  164376. /*
  164377. * Support routines that do various essential calculations.
  164378. */
  164379. LOCAL(void)
  164380. initial_setup (j_compress_ptr cinfo)
  164381. /* Do computations that are needed before master selection phase */
  164382. {
  164383. int ci;
  164384. jpeg_component_info *compptr;
  164385. long samplesperrow;
  164386. JDIMENSION jd_samplesperrow;
  164387. /* Sanity check on image dimensions */
  164388. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164389. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164390. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164391. /* Make sure image isn't bigger than I can handle */
  164392. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164393. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164394. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164395. /* Width of an input scanline must be representable as JDIMENSION. */
  164396. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164397. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164398. if ((long) jd_samplesperrow != samplesperrow)
  164399. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164400. /* For now, precision must match compiled-in value... */
  164401. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164402. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164403. /* Check that number of components won't exceed internal array sizes */
  164404. if (cinfo->num_components > MAX_COMPONENTS)
  164405. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164406. MAX_COMPONENTS);
  164407. /* Compute maximum sampling factors; check factor validity */
  164408. cinfo->max_h_samp_factor = 1;
  164409. cinfo->max_v_samp_factor = 1;
  164410. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164411. ci++, compptr++) {
  164412. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164413. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164414. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164415. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164416. compptr->h_samp_factor);
  164417. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164418. compptr->v_samp_factor);
  164419. }
  164420. /* Compute dimensions of components */
  164421. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164422. ci++, compptr++) {
  164423. /* Fill in the correct component_index value; don't rely on application */
  164424. compptr->component_index = ci;
  164425. /* For compression, we never do DCT scaling. */
  164426. compptr->DCT_scaled_size = DCTSIZE;
  164427. /* Size in DCT blocks */
  164428. compptr->width_in_blocks = (JDIMENSION)
  164429. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164430. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164431. compptr->height_in_blocks = (JDIMENSION)
  164432. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164433. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164434. /* Size in samples */
  164435. compptr->downsampled_width = (JDIMENSION)
  164436. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164437. (long) cinfo->max_h_samp_factor);
  164438. compptr->downsampled_height = (JDIMENSION)
  164439. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164440. (long) cinfo->max_v_samp_factor);
  164441. /* Mark component needed (this flag isn't actually used for compression) */
  164442. compptr->component_needed = TRUE;
  164443. }
  164444. /* Compute number of fully interleaved MCU rows (number of times that
  164445. * main controller will call coefficient controller).
  164446. */
  164447. cinfo->total_iMCU_rows = (JDIMENSION)
  164448. jdiv_round_up((long) cinfo->image_height,
  164449. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164450. }
  164451. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164452. LOCAL(void)
  164453. validate_script (j_compress_ptr cinfo)
  164454. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164455. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164456. */
  164457. {
  164458. const jpeg_scan_info * scanptr;
  164459. int scanno, ncomps, ci, coefi, thisi;
  164460. int Ss, Se, Ah, Al;
  164461. boolean component_sent[MAX_COMPONENTS];
  164462. #ifdef C_PROGRESSIVE_SUPPORTED
  164463. int * last_bitpos_ptr;
  164464. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164465. /* -1 until that coefficient has been seen; then last Al for it */
  164466. #endif
  164467. if (cinfo->num_scans <= 0)
  164468. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164469. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164470. * for progressive JPEG, no scan can have this.
  164471. */
  164472. scanptr = cinfo->scan_info;
  164473. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164474. #ifdef C_PROGRESSIVE_SUPPORTED
  164475. cinfo->progressive_mode = TRUE;
  164476. last_bitpos_ptr = & last_bitpos[0][0];
  164477. for (ci = 0; ci < cinfo->num_components; ci++)
  164478. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164479. *last_bitpos_ptr++ = -1;
  164480. #else
  164481. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164482. #endif
  164483. } else {
  164484. cinfo->progressive_mode = FALSE;
  164485. for (ci = 0; ci < cinfo->num_components; ci++)
  164486. component_sent[ci] = FALSE;
  164487. }
  164488. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164489. /* Validate component indexes */
  164490. ncomps = scanptr->comps_in_scan;
  164491. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164492. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164493. for (ci = 0; ci < ncomps; ci++) {
  164494. thisi = scanptr->component_index[ci];
  164495. if (thisi < 0 || thisi >= cinfo->num_components)
  164496. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164497. /* Components must appear in SOF order within each scan */
  164498. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164499. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164500. }
  164501. /* Validate progression parameters */
  164502. Ss = scanptr->Ss;
  164503. Se = scanptr->Se;
  164504. Ah = scanptr->Ah;
  164505. Al = scanptr->Al;
  164506. if (cinfo->progressive_mode) {
  164507. #ifdef C_PROGRESSIVE_SUPPORTED
  164508. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164509. * seems wrong: the upper bound ought to depend on data precision.
  164510. * Perhaps they really meant 0..N+1 for N-bit precision.
  164511. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164512. * out-of-range reconstructed DC values during the first DC scan,
  164513. * which might cause problems for some decoders.
  164514. */
  164515. #if BITS_IN_JSAMPLE == 8
  164516. #define MAX_AH_AL 10
  164517. #else
  164518. #define MAX_AH_AL 13
  164519. #endif
  164520. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164521. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164522. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164523. if (Ss == 0) {
  164524. if (Se != 0) /* DC and AC together not OK */
  164525. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164526. } else {
  164527. if (ncomps != 1) /* AC scans must be for only one component */
  164528. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164529. }
  164530. for (ci = 0; ci < ncomps; ci++) {
  164531. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164532. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164533. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164534. for (coefi = Ss; coefi <= Se; coefi++) {
  164535. if (last_bitpos_ptr[coefi] < 0) {
  164536. /* first scan of this coefficient */
  164537. if (Ah != 0)
  164538. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164539. } else {
  164540. /* not first scan */
  164541. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164542. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164543. }
  164544. last_bitpos_ptr[coefi] = Al;
  164545. }
  164546. }
  164547. #endif
  164548. } else {
  164549. /* For sequential JPEG, all progression parameters must be these: */
  164550. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164551. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164552. /* Make sure components are not sent twice */
  164553. for (ci = 0; ci < ncomps; ci++) {
  164554. thisi = scanptr->component_index[ci];
  164555. if (component_sent[thisi])
  164556. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164557. component_sent[thisi] = TRUE;
  164558. }
  164559. }
  164560. }
  164561. /* Now verify that everything got sent. */
  164562. if (cinfo->progressive_mode) {
  164563. #ifdef C_PROGRESSIVE_SUPPORTED
  164564. /* For progressive mode, we only check that at least some DC data
  164565. * got sent for each component; the spec does not require that all bits
  164566. * of all coefficients be transmitted. Would it be wiser to enforce
  164567. * transmission of all coefficient bits??
  164568. */
  164569. for (ci = 0; ci < cinfo->num_components; ci++) {
  164570. if (last_bitpos[ci][0] < 0)
  164571. ERREXIT(cinfo, JERR_MISSING_DATA);
  164572. }
  164573. #endif
  164574. } else {
  164575. for (ci = 0; ci < cinfo->num_components; ci++) {
  164576. if (! component_sent[ci])
  164577. ERREXIT(cinfo, JERR_MISSING_DATA);
  164578. }
  164579. }
  164580. }
  164581. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164582. LOCAL(void)
  164583. select_scan_parameters (j_compress_ptr cinfo)
  164584. /* Set up the scan parameters for the current scan */
  164585. {
  164586. int ci;
  164587. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164588. if (cinfo->scan_info != NULL) {
  164589. /* Prepare for current scan --- the script is already validated */
  164590. my_master_ptr master = (my_master_ptr) cinfo->master;
  164591. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164592. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164593. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164594. cinfo->cur_comp_info[ci] =
  164595. &cinfo->comp_info[scanptr->component_index[ci]];
  164596. }
  164597. cinfo->Ss = scanptr->Ss;
  164598. cinfo->Se = scanptr->Se;
  164599. cinfo->Ah = scanptr->Ah;
  164600. cinfo->Al = scanptr->Al;
  164601. }
  164602. else
  164603. #endif
  164604. {
  164605. /* Prepare for single sequential-JPEG scan containing all components */
  164606. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164607. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164608. MAX_COMPS_IN_SCAN);
  164609. cinfo->comps_in_scan = cinfo->num_components;
  164610. for (ci = 0; ci < cinfo->num_components; ci++) {
  164611. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164612. }
  164613. cinfo->Ss = 0;
  164614. cinfo->Se = DCTSIZE2-1;
  164615. cinfo->Ah = 0;
  164616. cinfo->Al = 0;
  164617. }
  164618. }
  164619. LOCAL(void)
  164620. per_scan_setup (j_compress_ptr cinfo)
  164621. /* Do computations that are needed before processing a JPEG scan */
  164622. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164623. {
  164624. int ci, mcublks, tmp;
  164625. jpeg_component_info *compptr;
  164626. if (cinfo->comps_in_scan == 1) {
  164627. /* Noninterleaved (single-component) scan */
  164628. compptr = cinfo->cur_comp_info[0];
  164629. /* Overall image size in MCUs */
  164630. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164631. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164632. /* For noninterleaved scan, always one block per MCU */
  164633. compptr->MCU_width = 1;
  164634. compptr->MCU_height = 1;
  164635. compptr->MCU_blocks = 1;
  164636. compptr->MCU_sample_width = DCTSIZE;
  164637. compptr->last_col_width = 1;
  164638. /* For noninterleaved scans, it is convenient to define last_row_height
  164639. * as the number of block rows present in the last iMCU row.
  164640. */
  164641. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164642. if (tmp == 0) tmp = compptr->v_samp_factor;
  164643. compptr->last_row_height = tmp;
  164644. /* Prepare array describing MCU composition */
  164645. cinfo->blocks_in_MCU = 1;
  164646. cinfo->MCU_membership[0] = 0;
  164647. } else {
  164648. /* Interleaved (multi-component) scan */
  164649. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164650. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164651. MAX_COMPS_IN_SCAN);
  164652. /* Overall image size in MCUs */
  164653. cinfo->MCUs_per_row = (JDIMENSION)
  164654. jdiv_round_up((long) cinfo->image_width,
  164655. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164656. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164657. jdiv_round_up((long) cinfo->image_height,
  164658. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164659. cinfo->blocks_in_MCU = 0;
  164660. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164661. compptr = cinfo->cur_comp_info[ci];
  164662. /* Sampling factors give # of blocks of component in each MCU */
  164663. compptr->MCU_width = compptr->h_samp_factor;
  164664. compptr->MCU_height = compptr->v_samp_factor;
  164665. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164666. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164667. /* Figure number of non-dummy blocks in last MCU column & row */
  164668. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164669. if (tmp == 0) tmp = compptr->MCU_width;
  164670. compptr->last_col_width = tmp;
  164671. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164672. if (tmp == 0) tmp = compptr->MCU_height;
  164673. compptr->last_row_height = tmp;
  164674. /* Prepare array describing MCU composition */
  164675. mcublks = compptr->MCU_blocks;
  164676. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164677. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164678. while (mcublks-- > 0) {
  164679. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164680. }
  164681. }
  164682. }
  164683. /* Convert restart specified in rows to actual MCU count. */
  164684. /* Note that count must fit in 16 bits, so we provide limiting. */
  164685. if (cinfo->restart_in_rows > 0) {
  164686. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164687. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164688. }
  164689. }
  164690. /*
  164691. * Per-pass setup.
  164692. * This is called at the beginning of each pass. We determine which modules
  164693. * will be active during this pass and give them appropriate start_pass calls.
  164694. * We also set is_last_pass to indicate whether any more passes will be
  164695. * required.
  164696. */
  164697. METHODDEF(void)
  164698. prepare_for_pass (j_compress_ptr cinfo)
  164699. {
  164700. my_master_ptr master = (my_master_ptr) cinfo->master;
  164701. switch (master->pass_type) {
  164702. case main_pass:
  164703. /* Initial pass: will collect input data, and do either Huffman
  164704. * optimization or data output for the first scan.
  164705. */
  164706. select_scan_parameters(cinfo);
  164707. per_scan_setup(cinfo);
  164708. if (! cinfo->raw_data_in) {
  164709. (*cinfo->cconvert->start_pass) (cinfo);
  164710. (*cinfo->downsample->start_pass) (cinfo);
  164711. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164712. }
  164713. (*cinfo->fdct->start_pass) (cinfo);
  164714. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164715. (*cinfo->coef->start_pass) (cinfo,
  164716. (master->total_passes > 1 ?
  164717. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164718. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164719. if (cinfo->optimize_coding) {
  164720. /* No immediate data output; postpone writing frame/scan headers */
  164721. master->pub.call_pass_startup = FALSE;
  164722. } else {
  164723. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164724. master->pub.call_pass_startup = TRUE;
  164725. }
  164726. break;
  164727. #ifdef ENTROPY_OPT_SUPPORTED
  164728. case huff_opt_pass:
  164729. /* Do Huffman optimization for a scan after the first one. */
  164730. select_scan_parameters(cinfo);
  164731. per_scan_setup(cinfo);
  164732. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164733. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164734. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164735. master->pub.call_pass_startup = FALSE;
  164736. break;
  164737. }
  164738. /* Special case: Huffman DC refinement scans need no Huffman table
  164739. * and therefore we can skip the optimization pass for them.
  164740. */
  164741. master->pass_type = output_pass;
  164742. master->pass_number++;
  164743. /*FALLTHROUGH*/
  164744. #endif
  164745. case output_pass:
  164746. /* Do a data-output pass. */
  164747. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164748. if (! cinfo->optimize_coding) {
  164749. select_scan_parameters(cinfo);
  164750. per_scan_setup(cinfo);
  164751. }
  164752. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164753. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164754. /* We emit frame/scan headers now */
  164755. if (master->scan_number == 0)
  164756. (*cinfo->marker->write_frame_header) (cinfo);
  164757. (*cinfo->marker->write_scan_header) (cinfo);
  164758. master->pub.call_pass_startup = FALSE;
  164759. break;
  164760. default:
  164761. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164762. }
  164763. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164764. /* Set up progress monitor's pass info if present */
  164765. if (cinfo->progress != NULL) {
  164766. cinfo->progress->completed_passes = master->pass_number;
  164767. cinfo->progress->total_passes = master->total_passes;
  164768. }
  164769. }
  164770. /*
  164771. * Special start-of-pass hook.
  164772. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164773. * In single-pass processing, we need this hook because we don't want to
  164774. * write frame/scan headers during jpeg_start_compress; we want to let the
  164775. * application write COM markers etc. between jpeg_start_compress and the
  164776. * jpeg_write_scanlines loop.
  164777. * In multi-pass processing, this routine is not used.
  164778. */
  164779. METHODDEF(void)
  164780. pass_startup (j_compress_ptr cinfo)
  164781. {
  164782. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164783. (*cinfo->marker->write_frame_header) (cinfo);
  164784. (*cinfo->marker->write_scan_header) (cinfo);
  164785. }
  164786. /*
  164787. * Finish up at end of pass.
  164788. */
  164789. METHODDEF(void)
  164790. finish_pass_master (j_compress_ptr cinfo)
  164791. {
  164792. my_master_ptr master = (my_master_ptr) cinfo->master;
  164793. /* The entropy coder always needs an end-of-pass call,
  164794. * either to analyze statistics or to flush its output buffer.
  164795. */
  164796. (*cinfo->entropy->finish_pass) (cinfo);
  164797. /* Update state for next pass */
  164798. switch (master->pass_type) {
  164799. case main_pass:
  164800. /* next pass is either output of scan 0 (after optimization)
  164801. * or output of scan 1 (if no optimization).
  164802. */
  164803. master->pass_type = output_pass;
  164804. if (! cinfo->optimize_coding)
  164805. master->scan_number++;
  164806. break;
  164807. case huff_opt_pass:
  164808. /* next pass is always output of current scan */
  164809. master->pass_type = output_pass;
  164810. break;
  164811. case output_pass:
  164812. /* next pass is either optimization or output of next scan */
  164813. if (cinfo->optimize_coding)
  164814. master->pass_type = huff_opt_pass;
  164815. master->scan_number++;
  164816. break;
  164817. }
  164818. master->pass_number++;
  164819. }
  164820. /*
  164821. * Initialize master compression control.
  164822. */
  164823. GLOBAL(void)
  164824. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164825. {
  164826. my_master_ptr master;
  164827. master = (my_master_ptr)
  164828. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164829. SIZEOF(my_comp_master));
  164830. cinfo->master = (struct jpeg_comp_master *) master;
  164831. master->pub.prepare_for_pass = prepare_for_pass;
  164832. master->pub.pass_startup = pass_startup;
  164833. master->pub.finish_pass = finish_pass_master;
  164834. master->pub.is_last_pass = FALSE;
  164835. /* Validate parameters, determine derived values */
  164836. initial_setup(cinfo);
  164837. if (cinfo->scan_info != NULL) {
  164838. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164839. validate_script(cinfo);
  164840. #else
  164841. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164842. #endif
  164843. } else {
  164844. cinfo->progressive_mode = FALSE;
  164845. cinfo->num_scans = 1;
  164846. }
  164847. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164848. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164849. /* Initialize my private state */
  164850. if (transcode_only) {
  164851. /* no main pass in transcoding */
  164852. if (cinfo->optimize_coding)
  164853. master->pass_type = huff_opt_pass;
  164854. else
  164855. master->pass_type = output_pass;
  164856. } else {
  164857. /* for normal compression, first pass is always this type: */
  164858. master->pass_type = main_pass;
  164859. }
  164860. master->scan_number = 0;
  164861. master->pass_number = 0;
  164862. if (cinfo->optimize_coding)
  164863. master->total_passes = cinfo->num_scans * 2;
  164864. else
  164865. master->total_passes = cinfo->num_scans;
  164866. }
  164867. /*** End of inlined file: jcmaster.c ***/
  164868. /*** Start of inlined file: jcomapi.c ***/
  164869. #define JPEG_INTERNALS
  164870. /*
  164871. * Abort processing of a JPEG compression or decompression operation,
  164872. * but don't destroy the object itself.
  164873. *
  164874. * For this, we merely clean up all the nonpermanent memory pools.
  164875. * Note that temp files (virtual arrays) are not allowed to belong to
  164876. * the permanent pool, so we will be able to close all temp files here.
  164877. * Closing a data source or destination, if necessary, is the application's
  164878. * responsibility.
  164879. */
  164880. GLOBAL(void)
  164881. jpeg_abort (j_common_ptr cinfo)
  164882. {
  164883. int pool;
  164884. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164885. if (cinfo->mem == NULL)
  164886. return;
  164887. /* Releasing pools in reverse order might help avoid fragmentation
  164888. * with some (brain-damaged) malloc libraries.
  164889. */
  164890. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164891. (*cinfo->mem->free_pool) (cinfo, pool);
  164892. }
  164893. /* Reset overall state for possible reuse of object */
  164894. if (cinfo->is_decompressor) {
  164895. cinfo->global_state = DSTATE_START;
  164896. /* Try to keep application from accessing now-deleted marker list.
  164897. * A bit kludgy to do it here, but this is the most central place.
  164898. */
  164899. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164900. } else {
  164901. cinfo->global_state = CSTATE_START;
  164902. }
  164903. }
  164904. /*
  164905. * Destruction of a JPEG object.
  164906. *
  164907. * Everything gets deallocated except the master jpeg_compress_struct itself
  164908. * and the error manager struct. Both of these are supplied by the application
  164909. * and must be freed, if necessary, by the application. (Often they are on
  164910. * the stack and so don't need to be freed anyway.)
  164911. * Closing a data source or destination, if necessary, is the application's
  164912. * responsibility.
  164913. */
  164914. GLOBAL(void)
  164915. jpeg_destroy (j_common_ptr cinfo)
  164916. {
  164917. /* We need only tell the memory manager to release everything. */
  164918. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164919. if (cinfo->mem != NULL)
  164920. (*cinfo->mem->self_destruct) (cinfo);
  164921. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164922. cinfo->global_state = 0; /* mark it destroyed */
  164923. }
  164924. /*
  164925. * Convenience routines for allocating quantization and Huffman tables.
  164926. * (Would jutils.c be a more reasonable place to put these?)
  164927. */
  164928. GLOBAL(JQUANT_TBL *)
  164929. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164930. {
  164931. JQUANT_TBL *tbl;
  164932. tbl = (JQUANT_TBL *)
  164933. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164934. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164935. return tbl;
  164936. }
  164937. GLOBAL(JHUFF_TBL *)
  164938. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164939. {
  164940. JHUFF_TBL *tbl;
  164941. tbl = (JHUFF_TBL *)
  164942. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164943. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164944. return tbl;
  164945. }
  164946. /*** End of inlined file: jcomapi.c ***/
  164947. /*** Start of inlined file: jcparam.c ***/
  164948. #define JPEG_INTERNALS
  164949. /*
  164950. * Quantization table setup routines
  164951. */
  164952. GLOBAL(void)
  164953. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164954. const unsigned int *basic_table,
  164955. int scale_factor, boolean force_baseline)
  164956. /* Define a quantization table equal to the basic_table times
  164957. * a scale factor (given as a percentage).
  164958. * If force_baseline is TRUE, the computed quantization table entries
  164959. * are limited to 1..255 for JPEG baseline compatibility.
  164960. */
  164961. {
  164962. JQUANT_TBL ** qtblptr;
  164963. int i;
  164964. long temp;
  164965. /* Safety check to ensure start_compress not called yet. */
  164966. if (cinfo->global_state != CSTATE_START)
  164967. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164968. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164969. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164970. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164971. if (*qtblptr == NULL)
  164972. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164973. for (i = 0; i < DCTSIZE2; i++) {
  164974. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164975. /* limit the values to the valid range */
  164976. if (temp <= 0L) temp = 1L;
  164977. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164978. if (force_baseline && temp > 255L)
  164979. temp = 255L; /* limit to baseline range if requested */
  164980. (*qtblptr)->quantval[i] = (UINT16) temp;
  164981. }
  164982. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164983. (*qtblptr)->sent_table = FALSE;
  164984. }
  164985. GLOBAL(void)
  164986. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164987. boolean force_baseline)
  164988. /* Set or change the 'quality' (quantization) setting, using default tables
  164989. * and a straight percentage-scaling quality scale. In most cases it's better
  164990. * to use jpeg_set_quality (below); this entry point is provided for
  164991. * applications that insist on a linear percentage scaling.
  164992. */
  164993. {
  164994. /* These are the sample quantization tables given in JPEG spec section K.1.
  164995. * The spec says that the values given produce "good" quality, and
  164996. * when divided by 2, "very good" quality.
  164997. */
  164998. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164999. 16, 11, 10, 16, 24, 40, 51, 61,
  165000. 12, 12, 14, 19, 26, 58, 60, 55,
  165001. 14, 13, 16, 24, 40, 57, 69, 56,
  165002. 14, 17, 22, 29, 51, 87, 80, 62,
  165003. 18, 22, 37, 56, 68, 109, 103, 77,
  165004. 24, 35, 55, 64, 81, 104, 113, 92,
  165005. 49, 64, 78, 87, 103, 121, 120, 101,
  165006. 72, 92, 95, 98, 112, 100, 103, 99
  165007. };
  165008. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165009. 17, 18, 24, 47, 99, 99, 99, 99,
  165010. 18, 21, 26, 66, 99, 99, 99, 99,
  165011. 24, 26, 56, 99, 99, 99, 99, 99,
  165012. 47, 66, 99, 99, 99, 99, 99, 99,
  165013. 99, 99, 99, 99, 99, 99, 99, 99,
  165014. 99, 99, 99, 99, 99, 99, 99, 99,
  165015. 99, 99, 99, 99, 99, 99, 99, 99,
  165016. 99, 99, 99, 99, 99, 99, 99, 99
  165017. };
  165018. /* Set up two quantization tables using the specified scaling */
  165019. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165020. scale_factor, force_baseline);
  165021. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165022. scale_factor, force_baseline);
  165023. }
  165024. GLOBAL(int)
  165025. jpeg_quality_scaling (int quality)
  165026. /* Convert a user-specified quality rating to a percentage scaling factor
  165027. * for an underlying quantization table, using our recommended scaling curve.
  165028. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165029. */
  165030. {
  165031. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165032. if (quality <= 0) quality = 1;
  165033. if (quality > 100) quality = 100;
  165034. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165035. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165036. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165037. * to make all the table entries 1 (hence, minimum quantization loss).
  165038. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165039. */
  165040. if (quality < 50)
  165041. quality = 5000 / quality;
  165042. else
  165043. quality = 200 - quality*2;
  165044. return quality;
  165045. }
  165046. GLOBAL(void)
  165047. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165048. /* Set or change the 'quality' (quantization) setting, using default tables.
  165049. * This is the standard quality-adjusting entry point for typical user
  165050. * interfaces; only those who want detailed control over quantization tables
  165051. * would use the preceding three routines directly.
  165052. */
  165053. {
  165054. /* Convert user 0-100 rating to percentage scaling */
  165055. quality = jpeg_quality_scaling(quality);
  165056. /* Set up standard quality tables */
  165057. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165058. }
  165059. /*
  165060. * Huffman table setup routines
  165061. */
  165062. LOCAL(void)
  165063. add_huff_table (j_compress_ptr cinfo,
  165064. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165065. /* Define a Huffman table */
  165066. {
  165067. int nsymbols, len;
  165068. if (*htblptr == NULL)
  165069. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165070. /* Copy the number-of-symbols-of-each-code-length counts */
  165071. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165072. /* Validate the counts. We do this here mainly so we can copy the right
  165073. * number of symbols from the val[] array, without risking marching off
  165074. * the end of memory. jchuff.c will do a more thorough test later.
  165075. */
  165076. nsymbols = 0;
  165077. for (len = 1; len <= 16; len++)
  165078. nsymbols += bits[len];
  165079. if (nsymbols < 1 || nsymbols > 256)
  165080. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165081. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165082. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165083. (*htblptr)->sent_table = FALSE;
  165084. }
  165085. LOCAL(void)
  165086. std_huff_tables (j_compress_ptr cinfo)
  165087. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165088. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165089. {
  165090. static const UINT8 bits_dc_luminance[17] =
  165091. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165092. static const UINT8 val_dc_luminance[] =
  165093. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165094. static const UINT8 bits_dc_chrominance[17] =
  165095. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165096. static const UINT8 val_dc_chrominance[] =
  165097. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165098. static const UINT8 bits_ac_luminance[17] =
  165099. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165100. static const UINT8 val_ac_luminance[] =
  165101. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165102. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165103. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165104. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165105. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165106. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165107. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165108. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165109. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165110. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165111. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165112. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165113. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165114. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165115. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165116. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165117. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165118. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165119. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165120. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165121. 0xf9, 0xfa };
  165122. static const UINT8 bits_ac_chrominance[17] =
  165123. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165124. static const UINT8 val_ac_chrominance[] =
  165125. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165126. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165127. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165128. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165129. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165130. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165131. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165132. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165133. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165134. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165135. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165136. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165137. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165138. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165139. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165140. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165141. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165142. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165143. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165144. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165145. 0xf9, 0xfa };
  165146. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165147. bits_dc_luminance, val_dc_luminance);
  165148. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165149. bits_ac_luminance, val_ac_luminance);
  165150. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165151. bits_dc_chrominance, val_dc_chrominance);
  165152. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165153. bits_ac_chrominance, val_ac_chrominance);
  165154. }
  165155. /*
  165156. * Default parameter setup for compression.
  165157. *
  165158. * Applications that don't choose to use this routine must do their
  165159. * own setup of all these parameters. Alternately, you can call this
  165160. * to establish defaults and then alter parameters selectively. This
  165161. * is the recommended approach since, if we add any new parameters,
  165162. * your code will still work (they'll be set to reasonable defaults).
  165163. */
  165164. GLOBAL(void)
  165165. jpeg_set_defaults (j_compress_ptr cinfo)
  165166. {
  165167. int i;
  165168. /* Safety check to ensure start_compress not called yet. */
  165169. if (cinfo->global_state != CSTATE_START)
  165170. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165171. /* Allocate comp_info array large enough for maximum component count.
  165172. * Array is made permanent in case application wants to compress
  165173. * multiple images at same param settings.
  165174. */
  165175. if (cinfo->comp_info == NULL)
  165176. cinfo->comp_info = (jpeg_component_info *)
  165177. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165178. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165179. /* Initialize everything not dependent on the color space */
  165180. cinfo->data_precision = BITS_IN_JSAMPLE;
  165181. /* Set up two quantization tables using default quality of 75 */
  165182. jpeg_set_quality(cinfo, 75, TRUE);
  165183. /* Set up two Huffman tables */
  165184. std_huff_tables(cinfo);
  165185. /* Initialize default arithmetic coding conditioning */
  165186. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165187. cinfo->arith_dc_L[i] = 0;
  165188. cinfo->arith_dc_U[i] = 1;
  165189. cinfo->arith_ac_K[i] = 5;
  165190. }
  165191. /* Default is no multiple-scan output */
  165192. cinfo->scan_info = NULL;
  165193. cinfo->num_scans = 0;
  165194. /* Expect normal source image, not raw downsampled data */
  165195. cinfo->raw_data_in = FALSE;
  165196. /* Use Huffman coding, not arithmetic coding, by default */
  165197. cinfo->arith_code = FALSE;
  165198. /* By default, don't do extra passes to optimize entropy coding */
  165199. cinfo->optimize_coding = FALSE;
  165200. /* The standard Huffman tables are only valid for 8-bit data precision.
  165201. * If the precision is higher, force optimization on so that usable
  165202. * tables will be computed. This test can be removed if default tables
  165203. * are supplied that are valid for the desired precision.
  165204. */
  165205. if (cinfo->data_precision > 8)
  165206. cinfo->optimize_coding = TRUE;
  165207. /* By default, use the simpler non-cosited sampling alignment */
  165208. cinfo->CCIR601_sampling = FALSE;
  165209. /* No input smoothing */
  165210. cinfo->smoothing_factor = 0;
  165211. /* DCT algorithm preference */
  165212. cinfo->dct_method = JDCT_DEFAULT;
  165213. /* No restart markers */
  165214. cinfo->restart_interval = 0;
  165215. cinfo->restart_in_rows = 0;
  165216. /* Fill in default JFIF marker parameters. Note that whether the marker
  165217. * will actually be written is determined by jpeg_set_colorspace.
  165218. *
  165219. * By default, the library emits JFIF version code 1.01.
  165220. * An application that wants to emit JFIF 1.02 extension markers should set
  165221. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165222. * to 1.02, but there may still be some decoders in use that will complain
  165223. * about that; saying 1.01 should minimize compatibility problems.
  165224. */
  165225. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165226. cinfo->JFIF_minor_version = 1;
  165227. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165228. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165229. cinfo->Y_density = 1;
  165230. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165231. jpeg_default_colorspace(cinfo);
  165232. }
  165233. /*
  165234. * Select an appropriate JPEG colorspace for in_color_space.
  165235. */
  165236. GLOBAL(void)
  165237. jpeg_default_colorspace (j_compress_ptr cinfo)
  165238. {
  165239. switch (cinfo->in_color_space) {
  165240. case JCS_GRAYSCALE:
  165241. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165242. break;
  165243. case JCS_RGB:
  165244. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165245. break;
  165246. case JCS_YCbCr:
  165247. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165248. break;
  165249. case JCS_CMYK:
  165250. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165251. break;
  165252. case JCS_YCCK:
  165253. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165254. break;
  165255. case JCS_UNKNOWN:
  165256. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165257. break;
  165258. default:
  165259. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165260. }
  165261. }
  165262. /*
  165263. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165264. */
  165265. GLOBAL(void)
  165266. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165267. {
  165268. jpeg_component_info * compptr;
  165269. int ci;
  165270. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165271. (compptr = &cinfo->comp_info[index], \
  165272. compptr->component_id = (id), \
  165273. compptr->h_samp_factor = (hsamp), \
  165274. compptr->v_samp_factor = (vsamp), \
  165275. compptr->quant_tbl_no = (quant), \
  165276. compptr->dc_tbl_no = (dctbl), \
  165277. compptr->ac_tbl_no = (actbl) )
  165278. /* Safety check to ensure start_compress not called yet. */
  165279. if (cinfo->global_state != CSTATE_START)
  165280. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165281. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165282. * tables 1 for chrominance components.
  165283. */
  165284. cinfo->jpeg_color_space = colorspace;
  165285. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165286. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165287. switch (colorspace) {
  165288. case JCS_GRAYSCALE:
  165289. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165290. cinfo->num_components = 1;
  165291. /* JFIF specifies component ID 1 */
  165292. SET_COMP(0, 1, 1,1, 0, 0,0);
  165293. break;
  165294. case JCS_RGB:
  165295. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165296. cinfo->num_components = 3;
  165297. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165298. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165299. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165300. break;
  165301. case JCS_YCbCr:
  165302. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165303. cinfo->num_components = 3;
  165304. /* JFIF specifies component IDs 1,2,3 */
  165305. /* We default to 2x2 subsamples of chrominance */
  165306. SET_COMP(0, 1, 2,2, 0, 0,0);
  165307. SET_COMP(1, 2, 1,1, 1, 1,1);
  165308. SET_COMP(2, 3, 1,1, 1, 1,1);
  165309. break;
  165310. case JCS_CMYK:
  165311. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165312. cinfo->num_components = 4;
  165313. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165314. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165315. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165316. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165317. break;
  165318. case JCS_YCCK:
  165319. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165320. cinfo->num_components = 4;
  165321. SET_COMP(0, 1, 2,2, 0, 0,0);
  165322. SET_COMP(1, 2, 1,1, 1, 1,1);
  165323. SET_COMP(2, 3, 1,1, 1, 1,1);
  165324. SET_COMP(3, 4, 2,2, 0, 0,0);
  165325. break;
  165326. case JCS_UNKNOWN:
  165327. cinfo->num_components = cinfo->input_components;
  165328. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165329. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165330. MAX_COMPONENTS);
  165331. for (ci = 0; ci < cinfo->num_components; ci++) {
  165332. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165333. }
  165334. break;
  165335. default:
  165336. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165337. }
  165338. }
  165339. #ifdef C_PROGRESSIVE_SUPPORTED
  165340. LOCAL(jpeg_scan_info *)
  165341. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165342. int Ss, int Se, int Ah, int Al)
  165343. /* Support routine: generate one scan for specified component */
  165344. {
  165345. scanptr->comps_in_scan = 1;
  165346. scanptr->component_index[0] = ci;
  165347. scanptr->Ss = Ss;
  165348. scanptr->Se = Se;
  165349. scanptr->Ah = Ah;
  165350. scanptr->Al = Al;
  165351. scanptr++;
  165352. return scanptr;
  165353. }
  165354. LOCAL(jpeg_scan_info *)
  165355. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165356. int Ss, int Se, int Ah, int Al)
  165357. /* Support routine: generate one scan for each component */
  165358. {
  165359. int ci;
  165360. for (ci = 0; ci < ncomps; ci++) {
  165361. scanptr->comps_in_scan = 1;
  165362. scanptr->component_index[0] = ci;
  165363. scanptr->Ss = Ss;
  165364. scanptr->Se = Se;
  165365. scanptr->Ah = Ah;
  165366. scanptr->Al = Al;
  165367. scanptr++;
  165368. }
  165369. return scanptr;
  165370. }
  165371. LOCAL(jpeg_scan_info *)
  165372. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165373. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165374. {
  165375. int ci;
  165376. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165377. /* Single interleaved DC scan */
  165378. scanptr->comps_in_scan = ncomps;
  165379. for (ci = 0; ci < ncomps; ci++)
  165380. scanptr->component_index[ci] = ci;
  165381. scanptr->Ss = scanptr->Se = 0;
  165382. scanptr->Ah = Ah;
  165383. scanptr->Al = Al;
  165384. scanptr++;
  165385. } else {
  165386. /* Noninterleaved DC scan for each component */
  165387. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165388. }
  165389. return scanptr;
  165390. }
  165391. /*
  165392. * Create a recommended progressive-JPEG script.
  165393. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165394. */
  165395. GLOBAL(void)
  165396. jpeg_simple_progression (j_compress_ptr cinfo)
  165397. {
  165398. int ncomps = cinfo->num_components;
  165399. int nscans;
  165400. jpeg_scan_info * scanptr;
  165401. /* Safety check to ensure start_compress not called yet. */
  165402. if (cinfo->global_state != CSTATE_START)
  165403. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165404. /* Figure space needed for script. Calculation must match code below! */
  165405. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165406. /* Custom script for YCbCr color images. */
  165407. nscans = 10;
  165408. } else {
  165409. /* All-purpose script for other color spaces. */
  165410. if (ncomps > MAX_COMPS_IN_SCAN)
  165411. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165412. else
  165413. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165414. }
  165415. /* Allocate space for script.
  165416. * We need to put it in the permanent pool in case the application performs
  165417. * multiple compressions without changing the settings. To avoid a memory
  165418. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165419. * object, we try to re-use previously allocated space, and we allocate
  165420. * enough space to handle YCbCr even if initially asked for grayscale.
  165421. */
  165422. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165423. cinfo->script_space_size = MAX(nscans, 10);
  165424. cinfo->script_space = (jpeg_scan_info *)
  165425. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165426. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165427. }
  165428. scanptr = cinfo->script_space;
  165429. cinfo->scan_info = scanptr;
  165430. cinfo->num_scans = nscans;
  165431. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165432. /* Custom script for YCbCr color images. */
  165433. /* Initial DC scan */
  165434. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165435. /* Initial AC scan: get some luma data out in a hurry */
  165436. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165437. /* Chroma data is too small to be worth expending many scans on */
  165438. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165439. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165440. /* Complete spectral selection for luma AC */
  165441. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165442. /* Refine next bit of luma AC */
  165443. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165444. /* Finish DC successive approximation */
  165445. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165446. /* Finish AC successive approximation */
  165447. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165448. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165449. /* Luma bottom bit comes last since it's usually largest scan */
  165450. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165451. } else {
  165452. /* All-purpose script for other color spaces. */
  165453. /* Successive approximation first pass */
  165454. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165455. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165456. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165457. /* Successive approximation second pass */
  165458. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165459. /* Successive approximation final pass */
  165460. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165461. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165462. }
  165463. }
  165464. #endif /* C_PROGRESSIVE_SUPPORTED */
  165465. /*** End of inlined file: jcparam.c ***/
  165466. /*** Start of inlined file: jcphuff.c ***/
  165467. #define JPEG_INTERNALS
  165468. #ifdef C_PROGRESSIVE_SUPPORTED
  165469. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165470. typedef struct {
  165471. struct jpeg_entropy_encoder pub; /* public fields */
  165472. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165473. boolean gather_statistics;
  165474. /* Bit-level coding status.
  165475. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165476. */
  165477. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165478. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165479. INT32 put_buffer; /* current bit-accumulation buffer */
  165480. int put_bits; /* # of bits now in it */
  165481. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165482. /* Coding status for DC components */
  165483. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165484. /* Coding status for AC components */
  165485. int ac_tbl_no; /* the table number of the single component */
  165486. unsigned int EOBRUN; /* run length of EOBs */
  165487. unsigned int BE; /* # of buffered correction bits before MCU */
  165488. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165489. /* packing correction bits tightly would save some space but cost time... */
  165490. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165491. int next_restart_num; /* next restart number to write (0-7) */
  165492. /* Pointers to derived tables (these workspaces have image lifespan).
  165493. * Since any one scan codes only DC or only AC, we only need one set
  165494. * of tables, not one for DC and one for AC.
  165495. */
  165496. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165497. /* Statistics tables for optimization; again, one set is enough */
  165498. long * count_ptrs[NUM_HUFF_TBLS];
  165499. } phuff_entropy_encoder;
  165500. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165501. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165502. * buffer can hold. Larger sizes may slightly improve compression, but
  165503. * 1000 is already well into the realm of overkill.
  165504. * The minimum safe size is 64 bits.
  165505. */
  165506. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165507. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165508. * We assume that int right shift is unsigned if INT32 right shift is,
  165509. * which should be safe.
  165510. */
  165511. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165512. #define ISHIFT_TEMPS int ishift_temp;
  165513. #define IRIGHT_SHIFT(x,shft) \
  165514. ((ishift_temp = (x)) < 0 ? \
  165515. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165516. (ishift_temp >> (shft)))
  165517. #else
  165518. #define ISHIFT_TEMPS
  165519. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165520. #endif
  165521. /* Forward declarations */
  165522. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165523. JBLOCKROW *MCU_data));
  165524. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165525. JBLOCKROW *MCU_data));
  165526. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165527. JBLOCKROW *MCU_data));
  165528. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165529. JBLOCKROW *MCU_data));
  165530. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165531. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165532. /*
  165533. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165534. */
  165535. METHODDEF(void)
  165536. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165537. {
  165538. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165539. boolean is_DC_band;
  165540. int ci, tbl;
  165541. jpeg_component_info * compptr;
  165542. entropy->cinfo = cinfo;
  165543. entropy->gather_statistics = gather_statistics;
  165544. is_DC_band = (cinfo->Ss == 0);
  165545. /* We assume jcmaster.c already validated the scan parameters. */
  165546. /* Select execution routines */
  165547. if (cinfo->Ah == 0) {
  165548. if (is_DC_band)
  165549. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165550. else
  165551. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165552. } else {
  165553. if (is_DC_band)
  165554. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165555. else {
  165556. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165557. /* AC refinement needs a correction bit buffer */
  165558. if (entropy->bit_buffer == NULL)
  165559. entropy->bit_buffer = (char *)
  165560. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165561. MAX_CORR_BITS * SIZEOF(char));
  165562. }
  165563. }
  165564. if (gather_statistics)
  165565. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165566. else
  165567. entropy->pub.finish_pass = finish_pass_phuff;
  165568. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165569. * for AC coefficients.
  165570. */
  165571. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165572. compptr = cinfo->cur_comp_info[ci];
  165573. /* Initialize DC predictions to 0 */
  165574. entropy->last_dc_val[ci] = 0;
  165575. /* Get table index */
  165576. if (is_DC_band) {
  165577. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165578. continue;
  165579. tbl = compptr->dc_tbl_no;
  165580. } else {
  165581. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165582. }
  165583. if (gather_statistics) {
  165584. /* Check for invalid table index */
  165585. /* (make_c_derived_tbl does this in the other path) */
  165586. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165587. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165588. /* Allocate and zero the statistics tables */
  165589. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165590. if (entropy->count_ptrs[tbl] == NULL)
  165591. entropy->count_ptrs[tbl] = (long *)
  165592. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165593. 257 * SIZEOF(long));
  165594. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165595. } else {
  165596. /* Compute derived values for Huffman table */
  165597. /* We may do this more than once for a table, but it's not expensive */
  165598. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165599. & entropy->derived_tbls[tbl]);
  165600. }
  165601. }
  165602. /* Initialize AC stuff */
  165603. entropy->EOBRUN = 0;
  165604. entropy->BE = 0;
  165605. /* Initialize bit buffer to empty */
  165606. entropy->put_buffer = 0;
  165607. entropy->put_bits = 0;
  165608. /* Initialize restart stuff */
  165609. entropy->restarts_to_go = cinfo->restart_interval;
  165610. entropy->next_restart_num = 0;
  165611. }
  165612. /* Outputting bytes to the file.
  165613. * NB: these must be called only when actually outputting,
  165614. * that is, entropy->gather_statistics == FALSE.
  165615. */
  165616. /* Emit a byte */
  165617. #define emit_byte(entropy,val) \
  165618. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165619. if (--(entropy)->free_in_buffer == 0) \
  165620. dump_buffer_p(entropy); }
  165621. LOCAL(void)
  165622. dump_buffer_p (phuff_entropy_ptr entropy)
  165623. /* Empty the output buffer; we do not support suspension in this module. */
  165624. {
  165625. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165626. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165627. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165628. /* After a successful buffer dump, must reset buffer pointers */
  165629. entropy->next_output_byte = dest->next_output_byte;
  165630. entropy->free_in_buffer = dest->free_in_buffer;
  165631. }
  165632. /* Outputting bits to the file */
  165633. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165634. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165635. * in one call, and we never retain more than 7 bits in put_buffer
  165636. * between calls, so 24 bits are sufficient.
  165637. */
  165638. INLINE
  165639. LOCAL(void)
  165640. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165641. /* Emit some bits, unless we are in gather mode */
  165642. {
  165643. /* This routine is heavily used, so it's worth coding tightly. */
  165644. register INT32 put_buffer = (INT32) code;
  165645. register int put_bits = entropy->put_bits;
  165646. /* if size is 0, caller used an invalid Huffman table entry */
  165647. if (size == 0)
  165648. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165649. if (entropy->gather_statistics)
  165650. return; /* do nothing if we're only getting stats */
  165651. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165652. put_bits += size; /* new number of bits in buffer */
  165653. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165654. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165655. while (put_bits >= 8) {
  165656. int c = (int) ((put_buffer >> 16) & 0xFF);
  165657. emit_byte(entropy, c);
  165658. if (c == 0xFF) { /* need to stuff a zero byte? */
  165659. emit_byte(entropy, 0);
  165660. }
  165661. put_buffer <<= 8;
  165662. put_bits -= 8;
  165663. }
  165664. entropy->put_buffer = put_buffer; /* update variables */
  165665. entropy->put_bits = put_bits;
  165666. }
  165667. LOCAL(void)
  165668. flush_bits_p (phuff_entropy_ptr entropy)
  165669. {
  165670. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165671. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165672. entropy->put_bits = 0;
  165673. }
  165674. /*
  165675. * Emit (or just count) a Huffman symbol.
  165676. */
  165677. INLINE
  165678. LOCAL(void)
  165679. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165680. {
  165681. if (entropy->gather_statistics)
  165682. entropy->count_ptrs[tbl_no][symbol]++;
  165683. else {
  165684. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165685. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165686. }
  165687. }
  165688. /*
  165689. * Emit bits from a correction bit buffer.
  165690. */
  165691. LOCAL(void)
  165692. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165693. unsigned int nbits)
  165694. {
  165695. if (entropy->gather_statistics)
  165696. return; /* no real work */
  165697. while (nbits > 0) {
  165698. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165699. bufstart++;
  165700. nbits--;
  165701. }
  165702. }
  165703. /*
  165704. * Emit any pending EOBRUN symbol.
  165705. */
  165706. LOCAL(void)
  165707. emit_eobrun (phuff_entropy_ptr entropy)
  165708. {
  165709. register int temp, nbits;
  165710. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165711. temp = entropy->EOBRUN;
  165712. nbits = 0;
  165713. while ((temp >>= 1))
  165714. nbits++;
  165715. /* safety check: shouldn't happen given limited correction-bit buffer */
  165716. if (nbits > 14)
  165717. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165718. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165719. if (nbits)
  165720. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165721. entropy->EOBRUN = 0;
  165722. /* Emit any buffered correction bits */
  165723. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165724. entropy->BE = 0;
  165725. }
  165726. }
  165727. /*
  165728. * Emit a restart marker & resynchronize predictions.
  165729. */
  165730. LOCAL(void)
  165731. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165732. {
  165733. int ci;
  165734. emit_eobrun(entropy);
  165735. if (! entropy->gather_statistics) {
  165736. flush_bits_p(entropy);
  165737. emit_byte(entropy, 0xFF);
  165738. emit_byte(entropy, JPEG_RST0 + restart_num);
  165739. }
  165740. if (entropy->cinfo->Ss == 0) {
  165741. /* Re-initialize DC predictions to 0 */
  165742. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165743. entropy->last_dc_val[ci] = 0;
  165744. } else {
  165745. /* Re-initialize all AC-related fields to 0 */
  165746. entropy->EOBRUN = 0;
  165747. entropy->BE = 0;
  165748. }
  165749. }
  165750. /*
  165751. * MCU encoding for DC initial scan (either spectral selection,
  165752. * or first pass of successive approximation).
  165753. */
  165754. METHODDEF(boolean)
  165755. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165756. {
  165757. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165758. register int temp, temp2;
  165759. register int nbits;
  165760. int blkn, ci;
  165761. int Al = cinfo->Al;
  165762. JBLOCKROW block;
  165763. jpeg_component_info * compptr;
  165764. ISHIFT_TEMPS
  165765. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165766. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165767. /* Emit restart marker if needed */
  165768. if (cinfo->restart_interval)
  165769. if (entropy->restarts_to_go == 0)
  165770. emit_restart_p(entropy, entropy->next_restart_num);
  165771. /* Encode the MCU data blocks */
  165772. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165773. block = MCU_data[blkn];
  165774. ci = cinfo->MCU_membership[blkn];
  165775. compptr = cinfo->cur_comp_info[ci];
  165776. /* Compute the DC value after the required point transform by Al.
  165777. * This is simply an arithmetic right shift.
  165778. */
  165779. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165780. /* DC differences are figured on the point-transformed values. */
  165781. temp = temp2 - entropy->last_dc_val[ci];
  165782. entropy->last_dc_val[ci] = temp2;
  165783. /* Encode the DC coefficient difference per section G.1.2.1 */
  165784. temp2 = temp;
  165785. if (temp < 0) {
  165786. temp = -temp; /* temp is abs value of input */
  165787. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165788. /* This code assumes we are on a two's complement machine */
  165789. temp2--;
  165790. }
  165791. /* Find the number of bits needed for the magnitude of the coefficient */
  165792. nbits = 0;
  165793. while (temp) {
  165794. nbits++;
  165795. temp >>= 1;
  165796. }
  165797. /* Check for out-of-range coefficient values.
  165798. * Since we're encoding a difference, the range limit is twice as much.
  165799. */
  165800. if (nbits > MAX_COEF_BITS+1)
  165801. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165802. /* Count/emit the Huffman-coded symbol for the number of bits */
  165803. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165804. /* Emit that number of bits of the value, if positive, */
  165805. /* or the complement of its magnitude, if negative. */
  165806. if (nbits) /* emit_bits rejects calls with size 0 */
  165807. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165808. }
  165809. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165810. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165811. /* Update restart-interval state too */
  165812. if (cinfo->restart_interval) {
  165813. if (entropy->restarts_to_go == 0) {
  165814. entropy->restarts_to_go = cinfo->restart_interval;
  165815. entropy->next_restart_num++;
  165816. entropy->next_restart_num &= 7;
  165817. }
  165818. entropy->restarts_to_go--;
  165819. }
  165820. return TRUE;
  165821. }
  165822. /*
  165823. * MCU encoding for AC initial scan (either spectral selection,
  165824. * or first pass of successive approximation).
  165825. */
  165826. METHODDEF(boolean)
  165827. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165828. {
  165829. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165830. register int temp, temp2;
  165831. register int nbits;
  165832. register int r, k;
  165833. int Se = cinfo->Se;
  165834. int Al = cinfo->Al;
  165835. JBLOCKROW block;
  165836. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165837. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165838. /* Emit restart marker if needed */
  165839. if (cinfo->restart_interval)
  165840. if (entropy->restarts_to_go == 0)
  165841. emit_restart_p(entropy, entropy->next_restart_num);
  165842. /* Encode the MCU data block */
  165843. block = MCU_data[0];
  165844. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165845. r = 0; /* r = run length of zeros */
  165846. for (k = cinfo->Ss; k <= Se; k++) {
  165847. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165848. r++;
  165849. continue;
  165850. }
  165851. /* We must apply the point transform by Al. For AC coefficients this
  165852. * is an integer division with rounding towards 0. To do this portably
  165853. * in C, we shift after obtaining the absolute value; so the code is
  165854. * interwoven with finding the abs value (temp) and output bits (temp2).
  165855. */
  165856. if (temp < 0) {
  165857. temp = -temp; /* temp is abs value of input */
  165858. temp >>= Al; /* apply the point transform */
  165859. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165860. temp2 = ~temp;
  165861. } else {
  165862. temp >>= Al; /* apply the point transform */
  165863. temp2 = temp;
  165864. }
  165865. /* Watch out for case that nonzero coef is zero after point transform */
  165866. if (temp == 0) {
  165867. r++;
  165868. continue;
  165869. }
  165870. /* Emit any pending EOBRUN */
  165871. if (entropy->EOBRUN > 0)
  165872. emit_eobrun(entropy);
  165873. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165874. while (r > 15) {
  165875. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165876. r -= 16;
  165877. }
  165878. /* Find the number of bits needed for the magnitude of the coefficient */
  165879. nbits = 1; /* there must be at least one 1 bit */
  165880. while ((temp >>= 1))
  165881. nbits++;
  165882. /* Check for out-of-range coefficient values */
  165883. if (nbits > MAX_COEF_BITS)
  165884. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165885. /* Count/emit Huffman symbol for run length / number of bits */
  165886. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165887. /* Emit that number of bits of the value, if positive, */
  165888. /* or the complement of its magnitude, if negative. */
  165889. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165890. r = 0; /* reset zero run length */
  165891. }
  165892. if (r > 0) { /* If there are trailing zeroes, */
  165893. entropy->EOBRUN++; /* count an EOB */
  165894. if (entropy->EOBRUN == 0x7FFF)
  165895. emit_eobrun(entropy); /* force it out to avoid overflow */
  165896. }
  165897. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165898. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165899. /* Update restart-interval state too */
  165900. if (cinfo->restart_interval) {
  165901. if (entropy->restarts_to_go == 0) {
  165902. entropy->restarts_to_go = cinfo->restart_interval;
  165903. entropy->next_restart_num++;
  165904. entropy->next_restart_num &= 7;
  165905. }
  165906. entropy->restarts_to_go--;
  165907. }
  165908. return TRUE;
  165909. }
  165910. /*
  165911. * MCU encoding for DC successive approximation refinement scan.
  165912. * Note: we assume such scans can be multi-component, although the spec
  165913. * is not very clear on the point.
  165914. */
  165915. METHODDEF(boolean)
  165916. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165917. {
  165918. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165919. register int temp;
  165920. int blkn;
  165921. int Al = cinfo->Al;
  165922. JBLOCKROW block;
  165923. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165924. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165925. /* Emit restart marker if needed */
  165926. if (cinfo->restart_interval)
  165927. if (entropy->restarts_to_go == 0)
  165928. emit_restart_p(entropy, entropy->next_restart_num);
  165929. /* Encode the MCU data blocks */
  165930. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165931. block = MCU_data[blkn];
  165932. /* We simply emit the Al'th bit of the DC coefficient value. */
  165933. temp = (*block)[0];
  165934. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165935. }
  165936. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165937. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165938. /* Update restart-interval state too */
  165939. if (cinfo->restart_interval) {
  165940. if (entropy->restarts_to_go == 0) {
  165941. entropy->restarts_to_go = cinfo->restart_interval;
  165942. entropy->next_restart_num++;
  165943. entropy->next_restart_num &= 7;
  165944. }
  165945. entropy->restarts_to_go--;
  165946. }
  165947. return TRUE;
  165948. }
  165949. /*
  165950. * MCU encoding for AC successive approximation refinement scan.
  165951. */
  165952. METHODDEF(boolean)
  165953. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165954. {
  165955. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165956. register int temp;
  165957. register int r, k;
  165958. int EOB;
  165959. char *BR_buffer;
  165960. unsigned int BR;
  165961. int Se = cinfo->Se;
  165962. int Al = cinfo->Al;
  165963. JBLOCKROW block;
  165964. int absvalues[DCTSIZE2];
  165965. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165966. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165967. /* Emit restart marker if needed */
  165968. if (cinfo->restart_interval)
  165969. if (entropy->restarts_to_go == 0)
  165970. emit_restart_p(entropy, entropy->next_restart_num);
  165971. /* Encode the MCU data block */
  165972. block = MCU_data[0];
  165973. /* It is convenient to make a pre-pass to determine the transformed
  165974. * coefficients' absolute values and the EOB position.
  165975. */
  165976. EOB = 0;
  165977. for (k = cinfo->Ss; k <= Se; k++) {
  165978. temp = (*block)[jpeg_natural_order[k]];
  165979. /* We must apply the point transform by Al. For AC coefficients this
  165980. * is an integer division with rounding towards 0. To do this portably
  165981. * in C, we shift after obtaining the absolute value.
  165982. */
  165983. if (temp < 0)
  165984. temp = -temp; /* temp is abs value of input */
  165985. temp >>= Al; /* apply the point transform */
  165986. absvalues[k] = temp; /* save abs value for main pass */
  165987. if (temp == 1)
  165988. EOB = k; /* EOB = index of last newly-nonzero coef */
  165989. }
  165990. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165991. r = 0; /* r = run length of zeros */
  165992. BR = 0; /* BR = count of buffered bits added now */
  165993. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165994. for (k = cinfo->Ss; k <= Se; k++) {
  165995. if ((temp = absvalues[k]) == 0) {
  165996. r++;
  165997. continue;
  165998. }
  165999. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166000. while (r > 15 && k <= EOB) {
  166001. /* emit any pending EOBRUN and the BE correction bits */
  166002. emit_eobrun(entropy);
  166003. /* Emit ZRL */
  166004. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166005. r -= 16;
  166006. /* Emit buffered correction bits that must be associated with ZRL */
  166007. emit_buffered_bits(entropy, BR_buffer, BR);
  166008. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166009. BR = 0;
  166010. }
  166011. /* If the coef was previously nonzero, it only needs a correction bit.
  166012. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166013. * that we also need to test r > 15. But if r > 15, we can only get here
  166014. * if k > EOB, which implies that this coefficient is not 1.
  166015. */
  166016. if (temp > 1) {
  166017. /* The correction bit is the next bit of the absolute value. */
  166018. BR_buffer[BR++] = (char) (temp & 1);
  166019. continue;
  166020. }
  166021. /* Emit any pending EOBRUN and the BE correction bits */
  166022. emit_eobrun(entropy);
  166023. /* Count/emit Huffman symbol for run length / number of bits */
  166024. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166025. /* Emit output bit for newly-nonzero coef */
  166026. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166027. emit_bits_p(entropy, (unsigned int) temp, 1);
  166028. /* Emit buffered correction bits that must be associated with this code */
  166029. emit_buffered_bits(entropy, BR_buffer, BR);
  166030. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166031. BR = 0;
  166032. r = 0; /* reset zero run length */
  166033. }
  166034. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166035. entropy->EOBRUN++; /* count an EOB */
  166036. entropy->BE += BR; /* concat my correction bits to older ones */
  166037. /* We force out the EOB if we risk either:
  166038. * 1. overflow of the EOB counter;
  166039. * 2. overflow of the correction bit buffer during the next MCU.
  166040. */
  166041. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166042. emit_eobrun(entropy);
  166043. }
  166044. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166045. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166046. /* Update restart-interval state too */
  166047. if (cinfo->restart_interval) {
  166048. if (entropy->restarts_to_go == 0) {
  166049. entropy->restarts_to_go = cinfo->restart_interval;
  166050. entropy->next_restart_num++;
  166051. entropy->next_restart_num &= 7;
  166052. }
  166053. entropy->restarts_to_go--;
  166054. }
  166055. return TRUE;
  166056. }
  166057. /*
  166058. * Finish up at the end of a Huffman-compressed progressive scan.
  166059. */
  166060. METHODDEF(void)
  166061. finish_pass_phuff (j_compress_ptr cinfo)
  166062. {
  166063. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166064. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166065. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166066. /* Flush out any buffered data */
  166067. emit_eobrun(entropy);
  166068. flush_bits_p(entropy);
  166069. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166070. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166071. }
  166072. /*
  166073. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166074. */
  166075. METHODDEF(void)
  166076. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166077. {
  166078. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166079. boolean is_DC_band;
  166080. int ci, tbl;
  166081. jpeg_component_info * compptr;
  166082. JHUFF_TBL **htblptr;
  166083. boolean did[NUM_HUFF_TBLS];
  166084. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166085. emit_eobrun(entropy);
  166086. is_DC_band = (cinfo->Ss == 0);
  166087. /* It's important not to apply jpeg_gen_optimal_table more than once
  166088. * per table, because it clobbers the input frequency counts!
  166089. */
  166090. MEMZERO(did, SIZEOF(did));
  166091. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166092. compptr = cinfo->cur_comp_info[ci];
  166093. if (is_DC_band) {
  166094. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166095. continue;
  166096. tbl = compptr->dc_tbl_no;
  166097. } else {
  166098. tbl = compptr->ac_tbl_no;
  166099. }
  166100. if (! did[tbl]) {
  166101. if (is_DC_band)
  166102. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166103. else
  166104. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166105. if (*htblptr == NULL)
  166106. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166107. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166108. did[tbl] = TRUE;
  166109. }
  166110. }
  166111. }
  166112. /*
  166113. * Module initialization routine for progressive Huffman entropy encoding.
  166114. */
  166115. GLOBAL(void)
  166116. jinit_phuff_encoder (j_compress_ptr cinfo)
  166117. {
  166118. phuff_entropy_ptr entropy;
  166119. int i;
  166120. entropy = (phuff_entropy_ptr)
  166121. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166122. SIZEOF(phuff_entropy_encoder));
  166123. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166124. entropy->pub.start_pass = start_pass_phuff;
  166125. /* Mark tables unallocated */
  166126. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166127. entropy->derived_tbls[i] = NULL;
  166128. entropy->count_ptrs[i] = NULL;
  166129. }
  166130. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166131. }
  166132. #endif /* C_PROGRESSIVE_SUPPORTED */
  166133. /*** End of inlined file: jcphuff.c ***/
  166134. /*** Start of inlined file: jcprepct.c ***/
  166135. #define JPEG_INTERNALS
  166136. /* At present, jcsample.c can request context rows only for smoothing.
  166137. * In the future, we might also need context rows for CCIR601 sampling
  166138. * or other more-complex downsampling procedures. The code to support
  166139. * context rows should be compiled only if needed.
  166140. */
  166141. #ifdef INPUT_SMOOTHING_SUPPORTED
  166142. #define CONTEXT_ROWS_SUPPORTED
  166143. #endif
  166144. /*
  166145. * For the simple (no-context-row) case, we just need to buffer one
  166146. * row group's worth of pixels for the downsampling step. At the bottom of
  166147. * the image, we pad to a full row group by replicating the last pixel row.
  166148. * The downsampler's last output row is then replicated if needed to pad
  166149. * out to a full iMCU row.
  166150. *
  166151. * When providing context rows, we must buffer three row groups' worth of
  166152. * pixels. Three row groups are physically allocated, but the row pointer
  166153. * arrays are made five row groups high, with the extra pointers above and
  166154. * below "wrapping around" to point to the last and first real row groups.
  166155. * This allows the downsampler to access the proper context rows.
  166156. * At the top and bottom of the image, we create dummy context rows by
  166157. * copying the first or last real pixel row. This copying could be avoided
  166158. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166159. * trouble on the compression side.
  166160. */
  166161. /* Private buffer controller object */
  166162. typedef struct {
  166163. struct jpeg_c_prep_controller pub; /* public fields */
  166164. /* Downsampling input buffer. This buffer holds color-converted data
  166165. * until we have enough to do a downsample step.
  166166. */
  166167. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166168. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166169. int next_buf_row; /* index of next row to store in color_buf */
  166170. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166171. int this_row_group; /* starting row index of group to process */
  166172. int next_buf_stop; /* downsample when we reach this index */
  166173. #endif
  166174. } my_prep_controller;
  166175. typedef my_prep_controller * my_prep_ptr;
  166176. /*
  166177. * Initialize for a processing pass.
  166178. */
  166179. METHODDEF(void)
  166180. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166181. {
  166182. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166183. if (pass_mode != JBUF_PASS_THRU)
  166184. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166185. /* Initialize total-height counter for detecting bottom of image */
  166186. prep->rows_to_go = cinfo->image_height;
  166187. /* Mark the conversion buffer empty */
  166188. prep->next_buf_row = 0;
  166189. #ifdef CONTEXT_ROWS_SUPPORTED
  166190. /* Preset additional state variables for context mode.
  166191. * These aren't used in non-context mode, so we needn't test which mode.
  166192. */
  166193. prep->this_row_group = 0;
  166194. /* Set next_buf_stop to stop after two row groups have been read in. */
  166195. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166196. #endif
  166197. }
  166198. /*
  166199. * Expand an image vertically from height input_rows to height output_rows,
  166200. * by duplicating the bottom row.
  166201. */
  166202. LOCAL(void)
  166203. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166204. int input_rows, int output_rows)
  166205. {
  166206. register int row;
  166207. for (row = input_rows; row < output_rows; row++) {
  166208. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166209. 1, num_cols);
  166210. }
  166211. }
  166212. /*
  166213. * Process some data in the simple no-context case.
  166214. *
  166215. * Preprocessor output data is counted in "row groups". A row group
  166216. * is defined to be v_samp_factor sample rows of each component.
  166217. * Downsampling will produce this much data from each max_v_samp_factor
  166218. * input rows.
  166219. */
  166220. METHODDEF(void)
  166221. pre_process_data (j_compress_ptr cinfo,
  166222. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166223. JDIMENSION in_rows_avail,
  166224. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166225. JDIMENSION out_row_groups_avail)
  166226. {
  166227. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166228. int numrows, ci;
  166229. JDIMENSION inrows;
  166230. jpeg_component_info * compptr;
  166231. while (*in_row_ctr < in_rows_avail &&
  166232. *out_row_group_ctr < out_row_groups_avail) {
  166233. /* Do color conversion to fill the conversion buffer. */
  166234. inrows = in_rows_avail - *in_row_ctr;
  166235. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166236. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166237. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166238. prep->color_buf,
  166239. (JDIMENSION) prep->next_buf_row,
  166240. numrows);
  166241. *in_row_ctr += numrows;
  166242. prep->next_buf_row += numrows;
  166243. prep->rows_to_go -= numrows;
  166244. /* If at bottom of image, pad to fill the conversion buffer. */
  166245. if (prep->rows_to_go == 0 &&
  166246. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166247. for (ci = 0; ci < cinfo->num_components; ci++) {
  166248. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166249. prep->next_buf_row, cinfo->max_v_samp_factor);
  166250. }
  166251. prep->next_buf_row = cinfo->max_v_samp_factor;
  166252. }
  166253. /* If we've filled the conversion buffer, empty it. */
  166254. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166255. (*cinfo->downsample->downsample) (cinfo,
  166256. prep->color_buf, (JDIMENSION) 0,
  166257. output_buf, *out_row_group_ctr);
  166258. prep->next_buf_row = 0;
  166259. (*out_row_group_ctr)++;
  166260. }
  166261. /* If at bottom of image, pad the output to a full iMCU height.
  166262. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166263. */
  166264. if (prep->rows_to_go == 0 &&
  166265. *out_row_group_ctr < out_row_groups_avail) {
  166266. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166267. ci++, compptr++) {
  166268. expand_bottom_edge(output_buf[ci],
  166269. compptr->width_in_blocks * DCTSIZE,
  166270. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166271. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166272. }
  166273. *out_row_group_ctr = out_row_groups_avail;
  166274. break; /* can exit outer loop without test */
  166275. }
  166276. }
  166277. }
  166278. #ifdef CONTEXT_ROWS_SUPPORTED
  166279. /*
  166280. * Process some data in the context case.
  166281. */
  166282. METHODDEF(void)
  166283. pre_process_context (j_compress_ptr cinfo,
  166284. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166285. JDIMENSION in_rows_avail,
  166286. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166287. JDIMENSION out_row_groups_avail)
  166288. {
  166289. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166290. int numrows, ci;
  166291. int buf_height = cinfo->max_v_samp_factor * 3;
  166292. JDIMENSION inrows;
  166293. while (*out_row_group_ctr < out_row_groups_avail) {
  166294. if (*in_row_ctr < in_rows_avail) {
  166295. /* Do color conversion to fill the conversion buffer. */
  166296. inrows = in_rows_avail - *in_row_ctr;
  166297. numrows = prep->next_buf_stop - prep->next_buf_row;
  166298. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166299. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166300. prep->color_buf,
  166301. (JDIMENSION) prep->next_buf_row,
  166302. numrows);
  166303. /* Pad at top of image, if first time through */
  166304. if (prep->rows_to_go == cinfo->image_height) {
  166305. for (ci = 0; ci < cinfo->num_components; ci++) {
  166306. int row;
  166307. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166308. jcopy_sample_rows(prep->color_buf[ci], 0,
  166309. prep->color_buf[ci], -row,
  166310. 1, cinfo->image_width);
  166311. }
  166312. }
  166313. }
  166314. *in_row_ctr += numrows;
  166315. prep->next_buf_row += numrows;
  166316. prep->rows_to_go -= numrows;
  166317. } else {
  166318. /* Return for more data, unless we are at the bottom of the image. */
  166319. if (prep->rows_to_go != 0)
  166320. break;
  166321. /* When at bottom of image, pad to fill the conversion buffer. */
  166322. if (prep->next_buf_row < prep->next_buf_stop) {
  166323. for (ci = 0; ci < cinfo->num_components; ci++) {
  166324. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166325. prep->next_buf_row, prep->next_buf_stop);
  166326. }
  166327. prep->next_buf_row = prep->next_buf_stop;
  166328. }
  166329. }
  166330. /* If we've gotten enough data, downsample a row group. */
  166331. if (prep->next_buf_row == prep->next_buf_stop) {
  166332. (*cinfo->downsample->downsample) (cinfo,
  166333. prep->color_buf,
  166334. (JDIMENSION) prep->this_row_group,
  166335. output_buf, *out_row_group_ctr);
  166336. (*out_row_group_ctr)++;
  166337. /* Advance pointers with wraparound as necessary. */
  166338. prep->this_row_group += cinfo->max_v_samp_factor;
  166339. if (prep->this_row_group >= buf_height)
  166340. prep->this_row_group = 0;
  166341. if (prep->next_buf_row >= buf_height)
  166342. prep->next_buf_row = 0;
  166343. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166344. }
  166345. }
  166346. }
  166347. /*
  166348. * Create the wrapped-around downsampling input buffer needed for context mode.
  166349. */
  166350. LOCAL(void)
  166351. create_context_buffer (j_compress_ptr cinfo)
  166352. {
  166353. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166354. int rgroup_height = cinfo->max_v_samp_factor;
  166355. int ci, i;
  166356. jpeg_component_info * compptr;
  166357. JSAMPARRAY true_buffer, fake_buffer;
  166358. /* Grab enough space for fake row pointers for all the components;
  166359. * we need five row groups' worth of pointers for each component.
  166360. */
  166361. fake_buffer = (JSAMPARRAY)
  166362. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166363. (cinfo->num_components * 5 * rgroup_height) *
  166364. SIZEOF(JSAMPROW));
  166365. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166366. ci++, compptr++) {
  166367. /* Allocate the actual buffer space (3 row groups) for this component.
  166368. * We make the buffer wide enough to allow the downsampler to edge-expand
  166369. * horizontally within the buffer, if it so chooses.
  166370. */
  166371. true_buffer = (*cinfo->mem->alloc_sarray)
  166372. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166373. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166374. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166375. (JDIMENSION) (3 * rgroup_height));
  166376. /* Copy true buffer row pointers into the middle of the fake row array */
  166377. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166378. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166379. /* Fill in the above and below wraparound pointers */
  166380. for (i = 0; i < rgroup_height; i++) {
  166381. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166382. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166383. }
  166384. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166385. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166386. }
  166387. }
  166388. #endif /* CONTEXT_ROWS_SUPPORTED */
  166389. /*
  166390. * Initialize preprocessing controller.
  166391. */
  166392. GLOBAL(void)
  166393. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166394. {
  166395. my_prep_ptr prep;
  166396. int ci;
  166397. jpeg_component_info * compptr;
  166398. if (need_full_buffer) /* safety check */
  166399. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166400. prep = (my_prep_ptr)
  166401. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166402. SIZEOF(my_prep_controller));
  166403. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166404. prep->pub.start_pass = start_pass_prep;
  166405. /* Allocate the color conversion buffer.
  166406. * We make the buffer wide enough to allow the downsampler to edge-expand
  166407. * horizontally within the buffer, if it so chooses.
  166408. */
  166409. if (cinfo->downsample->need_context_rows) {
  166410. /* Set up to provide context rows */
  166411. #ifdef CONTEXT_ROWS_SUPPORTED
  166412. prep->pub.pre_process_data = pre_process_context;
  166413. create_context_buffer(cinfo);
  166414. #else
  166415. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166416. #endif
  166417. } else {
  166418. /* No context, just make it tall enough for one row group */
  166419. prep->pub.pre_process_data = pre_process_data;
  166420. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166421. ci++, compptr++) {
  166422. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166423. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166424. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166425. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166426. (JDIMENSION) cinfo->max_v_samp_factor);
  166427. }
  166428. }
  166429. }
  166430. /*** End of inlined file: jcprepct.c ***/
  166431. /*** Start of inlined file: jcsample.c ***/
  166432. #define JPEG_INTERNALS
  166433. /* Pointer to routine to downsample a single component */
  166434. typedef JMETHOD(void, downsample1_ptr,
  166435. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166436. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166437. /* Private subobject */
  166438. typedef struct {
  166439. struct jpeg_downsampler pub; /* public fields */
  166440. /* Downsampling method pointers, one per component */
  166441. downsample1_ptr methods[MAX_COMPONENTS];
  166442. } my_downsampler;
  166443. typedef my_downsampler * my_downsample_ptr;
  166444. /*
  166445. * Initialize for a downsampling pass.
  166446. */
  166447. METHODDEF(void)
  166448. start_pass_downsample (j_compress_ptr)
  166449. {
  166450. /* no work for now */
  166451. }
  166452. /*
  166453. * Expand a component horizontally from width input_cols to width output_cols,
  166454. * by duplicating the rightmost samples.
  166455. */
  166456. LOCAL(void)
  166457. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166458. JDIMENSION input_cols, JDIMENSION output_cols)
  166459. {
  166460. register JSAMPROW ptr;
  166461. register JSAMPLE pixval;
  166462. register int count;
  166463. int row;
  166464. int numcols = (int) (output_cols - input_cols);
  166465. if (numcols > 0) {
  166466. for (row = 0; row < num_rows; row++) {
  166467. ptr = image_data[row] + input_cols;
  166468. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166469. for (count = numcols; count > 0; count--)
  166470. *ptr++ = pixval;
  166471. }
  166472. }
  166473. }
  166474. /*
  166475. * Do downsampling for a whole row group (all components).
  166476. *
  166477. * In this version we simply downsample each component independently.
  166478. */
  166479. METHODDEF(void)
  166480. sep_downsample (j_compress_ptr cinfo,
  166481. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166482. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166483. {
  166484. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166485. int ci;
  166486. jpeg_component_info * compptr;
  166487. JSAMPARRAY in_ptr, out_ptr;
  166488. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166489. ci++, compptr++) {
  166490. in_ptr = input_buf[ci] + in_row_index;
  166491. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166492. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166493. }
  166494. }
  166495. /*
  166496. * Downsample pixel values of a single component.
  166497. * One row group is processed per call.
  166498. * This version handles arbitrary integral sampling ratios, without smoothing.
  166499. * Note that this version is not actually used for customary sampling ratios.
  166500. */
  166501. METHODDEF(void)
  166502. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166503. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166504. {
  166505. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166506. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166507. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166508. JSAMPROW inptr, outptr;
  166509. INT32 outvalue;
  166510. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166511. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166512. numpix = h_expand * v_expand;
  166513. numpix2 = numpix/2;
  166514. /* Expand input data enough to let all the output samples be generated
  166515. * by the standard loop. Special-casing padded output would be more
  166516. * efficient.
  166517. */
  166518. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166519. cinfo->image_width, output_cols * h_expand);
  166520. inrow = 0;
  166521. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166522. outptr = output_data[outrow];
  166523. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166524. outcol++, outcol_h += h_expand) {
  166525. outvalue = 0;
  166526. for (v = 0; v < v_expand; v++) {
  166527. inptr = input_data[inrow+v] + outcol_h;
  166528. for (h = 0; h < h_expand; h++) {
  166529. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166530. }
  166531. }
  166532. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166533. }
  166534. inrow += v_expand;
  166535. }
  166536. }
  166537. /*
  166538. * Downsample pixel values of a single component.
  166539. * This version handles the special case of a full-size component,
  166540. * without smoothing.
  166541. */
  166542. METHODDEF(void)
  166543. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166544. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166545. {
  166546. /* Copy the data */
  166547. jcopy_sample_rows(input_data, 0, output_data, 0,
  166548. cinfo->max_v_samp_factor, cinfo->image_width);
  166549. /* Edge-expand */
  166550. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166551. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166552. }
  166553. /*
  166554. * Downsample pixel values of a single component.
  166555. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166556. * without smoothing.
  166557. *
  166558. * A note about the "bias" calculations: when rounding fractional values to
  166559. * integer, we do not want to always round 0.5 up to the next integer.
  166560. * If we did that, we'd introduce a noticeable bias towards larger values.
  166561. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166562. * alternate pixel locations (a simple ordered dither pattern).
  166563. */
  166564. METHODDEF(void)
  166565. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166566. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166567. {
  166568. int outrow;
  166569. JDIMENSION outcol;
  166570. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166571. register JSAMPROW inptr, outptr;
  166572. register int bias;
  166573. /* Expand input data enough to let all the output samples be generated
  166574. * by the standard loop. Special-casing padded output would be more
  166575. * efficient.
  166576. */
  166577. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166578. cinfo->image_width, output_cols * 2);
  166579. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166580. outptr = output_data[outrow];
  166581. inptr = input_data[outrow];
  166582. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166583. for (outcol = 0; outcol < output_cols; outcol++) {
  166584. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166585. + bias) >> 1);
  166586. bias ^= 1; /* 0=>1, 1=>0 */
  166587. inptr += 2;
  166588. }
  166589. }
  166590. }
  166591. /*
  166592. * Downsample pixel values of a single component.
  166593. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166594. * without smoothing.
  166595. */
  166596. METHODDEF(void)
  166597. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166598. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166599. {
  166600. int inrow, outrow;
  166601. JDIMENSION outcol;
  166602. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166603. register JSAMPROW inptr0, inptr1, outptr;
  166604. register int bias;
  166605. /* Expand input data enough to let all the output samples be generated
  166606. * by the standard loop. Special-casing padded output would be more
  166607. * efficient.
  166608. */
  166609. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166610. cinfo->image_width, output_cols * 2);
  166611. inrow = 0;
  166612. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166613. outptr = output_data[outrow];
  166614. inptr0 = input_data[inrow];
  166615. inptr1 = input_data[inrow+1];
  166616. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166617. for (outcol = 0; outcol < output_cols; outcol++) {
  166618. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166619. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166620. + bias) >> 2);
  166621. bias ^= 3; /* 1=>2, 2=>1 */
  166622. inptr0 += 2; inptr1 += 2;
  166623. }
  166624. inrow += 2;
  166625. }
  166626. }
  166627. #ifdef INPUT_SMOOTHING_SUPPORTED
  166628. /*
  166629. * Downsample pixel values of a single component.
  166630. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166631. * with smoothing. One row of context is required.
  166632. */
  166633. METHODDEF(void)
  166634. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166635. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166636. {
  166637. int inrow, outrow;
  166638. JDIMENSION colctr;
  166639. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166640. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166641. INT32 membersum, neighsum, memberscale, neighscale;
  166642. /* Expand input data enough to let all the output samples be generated
  166643. * by the standard loop. Special-casing padded output would be more
  166644. * efficient.
  166645. */
  166646. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166647. cinfo->image_width, output_cols * 2);
  166648. /* We don't bother to form the individual "smoothed" input pixel values;
  166649. * we can directly compute the output which is the average of the four
  166650. * smoothed values. Each of the four member pixels contributes a fraction
  166651. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166652. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166653. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166654. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166655. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166656. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166657. * factors are scaled by 2^16 = 65536.
  166658. * Also recall that SF = smoothing_factor / 1024.
  166659. */
  166660. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166661. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166662. inrow = 0;
  166663. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166664. outptr = output_data[outrow];
  166665. inptr0 = input_data[inrow];
  166666. inptr1 = input_data[inrow+1];
  166667. above_ptr = input_data[inrow-1];
  166668. below_ptr = input_data[inrow+2];
  166669. /* Special case for first column: pretend column -1 is same as column 0 */
  166670. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166671. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166672. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166673. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166674. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166675. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166676. neighsum += neighsum;
  166677. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166678. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166679. membersum = membersum * memberscale + neighsum * neighscale;
  166680. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166681. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166682. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166683. /* sum of pixels directly mapped to this output element */
  166684. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166685. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166686. /* sum of edge-neighbor pixels */
  166687. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166688. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166689. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166690. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166691. /* The edge-neighbors count twice as much as corner-neighbors */
  166692. neighsum += neighsum;
  166693. /* Add in the corner-neighbors */
  166694. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166695. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166696. /* form final output scaled up by 2^16 */
  166697. membersum = membersum * memberscale + neighsum * neighscale;
  166698. /* round, descale and output it */
  166699. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166700. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166701. }
  166702. /* Special case for last column */
  166703. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166704. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166705. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166706. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166707. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166708. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166709. neighsum += neighsum;
  166710. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166711. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166712. membersum = membersum * memberscale + neighsum * neighscale;
  166713. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166714. inrow += 2;
  166715. }
  166716. }
  166717. /*
  166718. * Downsample pixel values of a single component.
  166719. * This version handles the special case of a full-size component,
  166720. * with smoothing. One row of context is required.
  166721. */
  166722. METHODDEF(void)
  166723. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166724. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166725. {
  166726. int outrow;
  166727. JDIMENSION colctr;
  166728. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166729. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166730. INT32 membersum, neighsum, memberscale, neighscale;
  166731. int colsum, lastcolsum, nextcolsum;
  166732. /* Expand input data enough to let all the output samples be generated
  166733. * by the standard loop. Special-casing padded output would be more
  166734. * efficient.
  166735. */
  166736. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166737. cinfo->image_width, output_cols);
  166738. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166739. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166740. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166741. * Also recall that SF = smoothing_factor / 1024.
  166742. */
  166743. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166744. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166745. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166746. outptr = output_data[outrow];
  166747. inptr = input_data[outrow];
  166748. above_ptr = input_data[outrow-1];
  166749. below_ptr = input_data[outrow+1];
  166750. /* Special case for first column */
  166751. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166752. GETJSAMPLE(*inptr);
  166753. membersum = GETJSAMPLE(*inptr++);
  166754. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166755. GETJSAMPLE(*inptr);
  166756. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166757. membersum = membersum * memberscale + neighsum * neighscale;
  166758. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166759. lastcolsum = colsum; colsum = nextcolsum;
  166760. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166761. membersum = GETJSAMPLE(*inptr++);
  166762. above_ptr++; below_ptr++;
  166763. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166764. GETJSAMPLE(*inptr);
  166765. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166766. membersum = membersum * memberscale + neighsum * neighscale;
  166767. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166768. lastcolsum = colsum; colsum = nextcolsum;
  166769. }
  166770. /* Special case for last column */
  166771. membersum = GETJSAMPLE(*inptr);
  166772. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166773. membersum = membersum * memberscale + neighsum * neighscale;
  166774. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166775. }
  166776. }
  166777. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166778. /*
  166779. * Module initialization routine for downsampling.
  166780. * Note that we must select a routine for each component.
  166781. */
  166782. GLOBAL(void)
  166783. jinit_downsampler (j_compress_ptr cinfo)
  166784. {
  166785. my_downsample_ptr downsample;
  166786. int ci;
  166787. jpeg_component_info * compptr;
  166788. boolean smoothok = TRUE;
  166789. downsample = (my_downsample_ptr)
  166790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166791. SIZEOF(my_downsampler));
  166792. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166793. downsample->pub.start_pass = start_pass_downsample;
  166794. downsample->pub.downsample = sep_downsample;
  166795. downsample->pub.need_context_rows = FALSE;
  166796. if (cinfo->CCIR601_sampling)
  166797. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166798. /* Verify we can handle the sampling factors, and set up method pointers */
  166799. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166800. ci++, compptr++) {
  166801. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166802. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166803. #ifdef INPUT_SMOOTHING_SUPPORTED
  166804. if (cinfo->smoothing_factor) {
  166805. downsample->methods[ci] = fullsize_smooth_downsample;
  166806. downsample->pub.need_context_rows = TRUE;
  166807. } else
  166808. #endif
  166809. downsample->methods[ci] = fullsize_downsample;
  166810. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166811. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166812. smoothok = FALSE;
  166813. downsample->methods[ci] = h2v1_downsample;
  166814. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166815. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166816. #ifdef INPUT_SMOOTHING_SUPPORTED
  166817. if (cinfo->smoothing_factor) {
  166818. downsample->methods[ci] = h2v2_smooth_downsample;
  166819. downsample->pub.need_context_rows = TRUE;
  166820. } else
  166821. #endif
  166822. downsample->methods[ci] = h2v2_downsample;
  166823. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166824. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166825. smoothok = FALSE;
  166826. downsample->methods[ci] = int_downsample;
  166827. } else
  166828. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166829. }
  166830. #ifdef INPUT_SMOOTHING_SUPPORTED
  166831. if (cinfo->smoothing_factor && !smoothok)
  166832. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166833. #endif
  166834. }
  166835. /*** End of inlined file: jcsample.c ***/
  166836. /*** Start of inlined file: jctrans.c ***/
  166837. #define JPEG_INTERNALS
  166838. /* Forward declarations */
  166839. LOCAL(void) transencode_master_selection
  166840. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166841. LOCAL(void) transencode_coef_controller
  166842. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166843. /*
  166844. * Compression initialization for writing raw-coefficient data.
  166845. * Before calling this, all parameters and a data destination must be set up.
  166846. * Call jpeg_finish_compress() to actually write the data.
  166847. *
  166848. * The number of passed virtual arrays must match cinfo->num_components.
  166849. * Note that the virtual arrays need not be filled or even realized at
  166850. * the time write_coefficients is called; indeed, if the virtual arrays
  166851. * were requested from this compression object's memory manager, they
  166852. * typically will be realized during this routine and filled afterwards.
  166853. */
  166854. GLOBAL(void)
  166855. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166856. {
  166857. if (cinfo->global_state != CSTATE_START)
  166858. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166859. /* Mark all tables to be written */
  166860. jpeg_suppress_tables(cinfo, FALSE);
  166861. /* (Re)initialize error mgr and destination modules */
  166862. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166863. (*cinfo->dest->init_destination) (cinfo);
  166864. /* Perform master selection of active modules */
  166865. transencode_master_selection(cinfo, coef_arrays);
  166866. /* Wait for jpeg_finish_compress() call */
  166867. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166868. cinfo->global_state = CSTATE_WRCOEFS;
  166869. }
  166870. /*
  166871. * Initialize the compression object with default parameters,
  166872. * then copy from the source object all parameters needed for lossless
  166873. * transcoding. Parameters that can be varied without loss (such as
  166874. * scan script and Huffman optimization) are left in their default states.
  166875. */
  166876. GLOBAL(void)
  166877. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166878. j_compress_ptr dstinfo)
  166879. {
  166880. JQUANT_TBL ** qtblptr;
  166881. jpeg_component_info *incomp, *outcomp;
  166882. JQUANT_TBL *c_quant, *slot_quant;
  166883. int tblno, ci, coefi;
  166884. /* Safety check to ensure start_compress not called yet. */
  166885. if (dstinfo->global_state != CSTATE_START)
  166886. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166887. /* Copy fundamental image dimensions */
  166888. dstinfo->image_width = srcinfo->image_width;
  166889. dstinfo->image_height = srcinfo->image_height;
  166890. dstinfo->input_components = srcinfo->num_components;
  166891. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166892. /* Initialize all parameters to default values */
  166893. jpeg_set_defaults(dstinfo);
  166894. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166895. * Fix it to get the right header markers for the image colorspace.
  166896. */
  166897. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166898. dstinfo->data_precision = srcinfo->data_precision;
  166899. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166900. /* Copy the source's quantization tables. */
  166901. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166902. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166903. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166904. if (*qtblptr == NULL)
  166905. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166906. MEMCOPY((*qtblptr)->quantval,
  166907. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166908. SIZEOF((*qtblptr)->quantval));
  166909. (*qtblptr)->sent_table = FALSE;
  166910. }
  166911. }
  166912. /* Copy the source's per-component info.
  166913. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166914. */
  166915. dstinfo->num_components = srcinfo->num_components;
  166916. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166917. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166918. MAX_COMPONENTS);
  166919. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166920. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166921. outcomp->component_id = incomp->component_id;
  166922. outcomp->h_samp_factor = incomp->h_samp_factor;
  166923. outcomp->v_samp_factor = incomp->v_samp_factor;
  166924. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166925. /* Make sure saved quantization table for component matches the qtable
  166926. * slot. If not, the input file re-used this qtable slot.
  166927. * IJG encoder currently cannot duplicate this.
  166928. */
  166929. tblno = outcomp->quant_tbl_no;
  166930. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166931. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166932. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166933. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166934. c_quant = incomp->quant_table;
  166935. if (c_quant != NULL) {
  166936. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166937. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166938. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166939. }
  166940. }
  166941. /* Note: we do not copy the source's Huffman table assignments;
  166942. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166943. */
  166944. }
  166945. /* Also copy JFIF version and resolution information, if available.
  166946. * Strictly speaking this isn't "critical" info, but it's nearly
  166947. * always appropriate to copy it if available. In particular,
  166948. * if the application chooses to copy JFIF 1.02 extension markers from
  166949. * the source file, we need to copy the version to make sure we don't
  166950. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166951. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166952. */
  166953. if (srcinfo->saw_JFIF_marker) {
  166954. if (srcinfo->JFIF_major_version == 1) {
  166955. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166956. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166957. }
  166958. dstinfo->density_unit = srcinfo->density_unit;
  166959. dstinfo->X_density = srcinfo->X_density;
  166960. dstinfo->Y_density = srcinfo->Y_density;
  166961. }
  166962. }
  166963. /*
  166964. * Master selection of compression modules for transcoding.
  166965. * This substitutes for jcinit.c's initialization of the full compressor.
  166966. */
  166967. LOCAL(void)
  166968. transencode_master_selection (j_compress_ptr cinfo,
  166969. jvirt_barray_ptr * coef_arrays)
  166970. {
  166971. /* Although we don't actually use input_components for transcoding,
  166972. * jcmaster.c's initial_setup will complain if input_components is 0.
  166973. */
  166974. cinfo->input_components = 1;
  166975. /* Initialize master control (includes parameter checking/processing) */
  166976. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166977. /* Entropy encoding: either Huffman or arithmetic coding. */
  166978. if (cinfo->arith_code) {
  166979. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166980. } else {
  166981. if (cinfo->progressive_mode) {
  166982. #ifdef C_PROGRESSIVE_SUPPORTED
  166983. jinit_phuff_encoder(cinfo);
  166984. #else
  166985. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166986. #endif
  166987. } else
  166988. jinit_huff_encoder(cinfo);
  166989. }
  166990. /* We need a special coefficient buffer controller. */
  166991. transencode_coef_controller(cinfo, coef_arrays);
  166992. jinit_marker_writer(cinfo);
  166993. /* We can now tell the memory manager to allocate virtual arrays. */
  166994. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166995. /* Write the datastream header (SOI, JFIF) immediately.
  166996. * Frame and scan headers are postponed till later.
  166997. * This lets application insert special markers after the SOI.
  166998. */
  166999. (*cinfo->marker->write_file_header) (cinfo);
  167000. }
  167001. /*
  167002. * The rest of this file is a special implementation of the coefficient
  167003. * buffer controller. This is similar to jccoefct.c, but it handles only
  167004. * output from presupplied virtual arrays. Furthermore, we generate any
  167005. * dummy padding blocks on-the-fly rather than expecting them to be present
  167006. * in the arrays.
  167007. */
  167008. /* Private buffer controller object */
  167009. typedef struct {
  167010. struct jpeg_c_coef_controller pub; /* public fields */
  167011. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167012. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167013. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167014. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167015. /* Virtual block array for each component. */
  167016. jvirt_barray_ptr * whole_image;
  167017. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167018. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167019. } my_coef_controller2;
  167020. typedef my_coef_controller2 * my_coef_ptr2;
  167021. LOCAL(void)
  167022. start_iMCU_row2 (j_compress_ptr cinfo)
  167023. /* Reset within-iMCU-row counters for a new row */
  167024. {
  167025. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167026. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167027. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167028. * But at the bottom of the image, process only what's left.
  167029. */
  167030. if (cinfo->comps_in_scan > 1) {
  167031. coef->MCU_rows_per_iMCU_row = 1;
  167032. } else {
  167033. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167034. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167035. else
  167036. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167037. }
  167038. coef->mcu_ctr = 0;
  167039. coef->MCU_vert_offset = 0;
  167040. }
  167041. /*
  167042. * Initialize for a processing pass.
  167043. */
  167044. METHODDEF(void)
  167045. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167046. {
  167047. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167048. if (pass_mode != JBUF_CRANK_DEST)
  167049. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167050. coef->iMCU_row_num = 0;
  167051. start_iMCU_row2(cinfo);
  167052. }
  167053. /*
  167054. * Process some data.
  167055. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167056. * per call, ie, v_samp_factor block rows for each component in the scan.
  167057. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167058. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167059. *
  167060. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167061. */
  167062. METHODDEF(boolean)
  167063. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167064. {
  167065. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167066. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167067. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167068. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167069. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167070. JDIMENSION start_col;
  167071. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167072. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167073. JBLOCKROW buffer_ptr;
  167074. jpeg_component_info *compptr;
  167075. /* Align the virtual buffers for the components used in this scan. */
  167076. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167077. compptr = cinfo->cur_comp_info[ci];
  167078. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167079. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167080. coef->iMCU_row_num * compptr->v_samp_factor,
  167081. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167082. }
  167083. /* Loop to process one whole iMCU row */
  167084. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167085. yoffset++) {
  167086. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167087. MCU_col_num++) {
  167088. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167089. blkn = 0; /* index of current DCT block within MCU */
  167090. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167091. compptr = cinfo->cur_comp_info[ci];
  167092. start_col = MCU_col_num * compptr->MCU_width;
  167093. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167094. : compptr->last_col_width;
  167095. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167096. if (coef->iMCU_row_num < last_iMCU_row ||
  167097. yindex+yoffset < compptr->last_row_height) {
  167098. /* Fill in pointers to real blocks in this row */
  167099. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167100. for (xindex = 0; xindex < blockcnt; xindex++)
  167101. MCU_buffer[blkn++] = buffer_ptr++;
  167102. } else {
  167103. /* At bottom of image, need a whole row of dummy blocks */
  167104. xindex = 0;
  167105. }
  167106. /* Fill in any dummy blocks needed in this row.
  167107. * Dummy blocks are filled in the same way as in jccoefct.c:
  167108. * all zeroes in the AC entries, DC entries equal to previous
  167109. * block's DC value. The init routine has already zeroed the
  167110. * AC entries, so we need only set the DC entries correctly.
  167111. */
  167112. for (; xindex < compptr->MCU_width; xindex++) {
  167113. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167114. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167115. blkn++;
  167116. }
  167117. }
  167118. }
  167119. /* Try to write the MCU. */
  167120. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167121. /* Suspension forced; update state counters and exit */
  167122. coef->MCU_vert_offset = yoffset;
  167123. coef->mcu_ctr = MCU_col_num;
  167124. return FALSE;
  167125. }
  167126. }
  167127. /* Completed an MCU row, but perhaps not an iMCU row */
  167128. coef->mcu_ctr = 0;
  167129. }
  167130. /* Completed the iMCU row, advance counters for next one */
  167131. coef->iMCU_row_num++;
  167132. start_iMCU_row2(cinfo);
  167133. return TRUE;
  167134. }
  167135. /*
  167136. * Initialize coefficient buffer controller.
  167137. *
  167138. * Each passed coefficient array must be the right size for that
  167139. * coefficient: width_in_blocks wide and height_in_blocks high,
  167140. * with unitheight at least v_samp_factor.
  167141. */
  167142. LOCAL(void)
  167143. transencode_coef_controller (j_compress_ptr cinfo,
  167144. jvirt_barray_ptr * coef_arrays)
  167145. {
  167146. my_coef_ptr2 coef;
  167147. JBLOCKROW buffer;
  167148. int i;
  167149. coef = (my_coef_ptr2)
  167150. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167151. SIZEOF(my_coef_controller2));
  167152. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167153. coef->pub.start_pass = start_pass_coef2;
  167154. coef->pub.compress_data = compress_output2;
  167155. /* Save pointer to virtual arrays */
  167156. coef->whole_image = coef_arrays;
  167157. /* Allocate and pre-zero space for dummy DCT blocks. */
  167158. buffer = (JBLOCKROW)
  167159. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167160. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167161. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167162. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167163. coef->dummy_buffer[i] = buffer + i;
  167164. }
  167165. }
  167166. /*** End of inlined file: jctrans.c ***/
  167167. /*** Start of inlined file: jdapistd.c ***/
  167168. #define JPEG_INTERNALS
  167169. /* Forward declarations */
  167170. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167171. /*
  167172. * Decompression initialization.
  167173. * jpeg_read_header must be completed before calling this.
  167174. *
  167175. * If a multipass operating mode was selected, this will do all but the
  167176. * last pass, and thus may take a great deal of time.
  167177. *
  167178. * Returns FALSE if suspended. The return value need be inspected only if
  167179. * a suspending data source is used.
  167180. */
  167181. GLOBAL(boolean)
  167182. jpeg_start_decompress (j_decompress_ptr cinfo)
  167183. {
  167184. if (cinfo->global_state == DSTATE_READY) {
  167185. /* First call: initialize master control, select active modules */
  167186. jinit_master_decompress(cinfo);
  167187. if (cinfo->buffered_image) {
  167188. /* No more work here; expecting jpeg_start_output next */
  167189. cinfo->global_state = DSTATE_BUFIMAGE;
  167190. return TRUE;
  167191. }
  167192. cinfo->global_state = DSTATE_PRELOAD;
  167193. }
  167194. if (cinfo->global_state == DSTATE_PRELOAD) {
  167195. /* If file has multiple scans, absorb them all into the coef buffer */
  167196. if (cinfo->inputctl->has_multiple_scans) {
  167197. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167198. for (;;) {
  167199. int retcode;
  167200. /* Call progress monitor hook if present */
  167201. if (cinfo->progress != NULL)
  167202. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167203. /* Absorb some more input */
  167204. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167205. if (retcode == JPEG_SUSPENDED)
  167206. return FALSE;
  167207. if (retcode == JPEG_REACHED_EOI)
  167208. break;
  167209. /* Advance progress counter if appropriate */
  167210. if (cinfo->progress != NULL &&
  167211. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167212. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167213. /* jdmaster underestimated number of scans; ratchet up one scan */
  167214. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167215. }
  167216. }
  167217. }
  167218. #else
  167219. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167220. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167221. }
  167222. cinfo->output_scan_number = cinfo->input_scan_number;
  167223. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167224. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167225. /* Perform any dummy output passes, and set up for the final pass */
  167226. return output_pass_setup(cinfo);
  167227. }
  167228. /*
  167229. * Set up for an output pass, and perform any dummy pass(es) needed.
  167230. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167231. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167232. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167233. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167234. */
  167235. LOCAL(boolean)
  167236. output_pass_setup (j_decompress_ptr cinfo)
  167237. {
  167238. if (cinfo->global_state != DSTATE_PRESCAN) {
  167239. /* First call: do pass setup */
  167240. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167241. cinfo->output_scanline = 0;
  167242. cinfo->global_state = DSTATE_PRESCAN;
  167243. }
  167244. /* Loop over any required dummy passes */
  167245. while (cinfo->master->is_dummy_pass) {
  167246. #ifdef QUANT_2PASS_SUPPORTED
  167247. /* Crank through the dummy pass */
  167248. while (cinfo->output_scanline < cinfo->output_height) {
  167249. JDIMENSION last_scanline;
  167250. /* Call progress monitor hook if present */
  167251. if (cinfo->progress != NULL) {
  167252. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167253. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167254. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167255. }
  167256. /* Process some data */
  167257. last_scanline = cinfo->output_scanline;
  167258. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167259. &cinfo->output_scanline, (JDIMENSION) 0);
  167260. if (cinfo->output_scanline == last_scanline)
  167261. return FALSE; /* No progress made, must suspend */
  167262. }
  167263. /* Finish up dummy pass, and set up for another one */
  167264. (*cinfo->master->finish_output_pass) (cinfo);
  167265. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167266. cinfo->output_scanline = 0;
  167267. #else
  167268. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167269. #endif /* QUANT_2PASS_SUPPORTED */
  167270. }
  167271. /* Ready for application to drive output pass through
  167272. * jpeg_read_scanlines or jpeg_read_raw_data.
  167273. */
  167274. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167275. return TRUE;
  167276. }
  167277. /*
  167278. * Read some scanlines of data from the JPEG decompressor.
  167279. *
  167280. * The return value will be the number of lines actually read.
  167281. * This may be less than the number requested in several cases,
  167282. * including bottom of image, data source suspension, and operating
  167283. * modes that emit multiple scanlines at a time.
  167284. *
  167285. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167286. * this likely signals an application programmer error. However,
  167287. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167288. */
  167289. GLOBAL(JDIMENSION)
  167290. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167291. JDIMENSION max_lines)
  167292. {
  167293. JDIMENSION row_ctr;
  167294. if (cinfo->global_state != DSTATE_SCANNING)
  167295. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167296. if (cinfo->output_scanline >= cinfo->output_height) {
  167297. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167298. return 0;
  167299. }
  167300. /* Call progress monitor hook if present */
  167301. if (cinfo->progress != NULL) {
  167302. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167303. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167304. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167305. }
  167306. /* Process some data */
  167307. row_ctr = 0;
  167308. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167309. cinfo->output_scanline += row_ctr;
  167310. return row_ctr;
  167311. }
  167312. /*
  167313. * Alternate entry point to read raw data.
  167314. * Processes exactly one iMCU row per call, unless suspended.
  167315. */
  167316. GLOBAL(JDIMENSION)
  167317. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167318. JDIMENSION max_lines)
  167319. {
  167320. JDIMENSION lines_per_iMCU_row;
  167321. if (cinfo->global_state != DSTATE_RAW_OK)
  167322. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167323. if (cinfo->output_scanline >= cinfo->output_height) {
  167324. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167325. return 0;
  167326. }
  167327. /* Call progress monitor hook if present */
  167328. if (cinfo->progress != NULL) {
  167329. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167330. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167331. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167332. }
  167333. /* Verify that at least one iMCU row can be returned. */
  167334. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167335. if (max_lines < lines_per_iMCU_row)
  167336. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167337. /* Decompress directly into user's buffer. */
  167338. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167339. return 0; /* suspension forced, can do nothing more */
  167340. /* OK, we processed one iMCU row. */
  167341. cinfo->output_scanline += lines_per_iMCU_row;
  167342. return lines_per_iMCU_row;
  167343. }
  167344. /* Additional entry points for buffered-image mode. */
  167345. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167346. /*
  167347. * Initialize for an output pass in buffered-image mode.
  167348. */
  167349. GLOBAL(boolean)
  167350. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167351. {
  167352. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167353. cinfo->global_state != DSTATE_PRESCAN)
  167354. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167355. /* Limit scan number to valid range */
  167356. if (scan_number <= 0)
  167357. scan_number = 1;
  167358. if (cinfo->inputctl->eoi_reached &&
  167359. scan_number > cinfo->input_scan_number)
  167360. scan_number = cinfo->input_scan_number;
  167361. cinfo->output_scan_number = scan_number;
  167362. /* Perform any dummy output passes, and set up for the real pass */
  167363. return output_pass_setup(cinfo);
  167364. }
  167365. /*
  167366. * Finish up after an output pass in buffered-image mode.
  167367. *
  167368. * Returns FALSE if suspended. The return value need be inspected only if
  167369. * a suspending data source is used.
  167370. */
  167371. GLOBAL(boolean)
  167372. jpeg_finish_output (j_decompress_ptr cinfo)
  167373. {
  167374. if ((cinfo->global_state == DSTATE_SCANNING ||
  167375. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167376. /* Terminate this pass. */
  167377. /* We do not require the whole pass to have been completed. */
  167378. (*cinfo->master->finish_output_pass) (cinfo);
  167379. cinfo->global_state = DSTATE_BUFPOST;
  167380. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167381. /* BUFPOST = repeat call after a suspension, anything else is error */
  167382. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167383. }
  167384. /* Read markers looking for SOS or EOI */
  167385. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167386. ! cinfo->inputctl->eoi_reached) {
  167387. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167388. return FALSE; /* Suspend, come back later */
  167389. }
  167390. cinfo->global_state = DSTATE_BUFIMAGE;
  167391. return TRUE;
  167392. }
  167393. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167394. /*** End of inlined file: jdapistd.c ***/
  167395. /*** Start of inlined file: jdapimin.c ***/
  167396. #define JPEG_INTERNALS
  167397. /*
  167398. * Initialization of a JPEG decompression object.
  167399. * The error manager must already be set up (in case memory manager fails).
  167400. */
  167401. GLOBAL(void)
  167402. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167403. {
  167404. int i;
  167405. /* Guard against version mismatches between library and caller. */
  167406. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167407. if (version != JPEG_LIB_VERSION)
  167408. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167409. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167410. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167411. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167412. /* For debugging purposes, we zero the whole master structure.
  167413. * But the application has already set the err pointer, and may have set
  167414. * client_data, so we have to save and restore those fields.
  167415. * Note: if application hasn't set client_data, tools like Purify may
  167416. * complain here.
  167417. */
  167418. {
  167419. struct jpeg_error_mgr * err = cinfo->err;
  167420. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167421. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167422. cinfo->err = err;
  167423. cinfo->client_data = client_data;
  167424. }
  167425. cinfo->is_decompressor = TRUE;
  167426. /* Initialize a memory manager instance for this object */
  167427. jinit_memory_mgr((j_common_ptr) cinfo);
  167428. /* Zero out pointers to permanent structures. */
  167429. cinfo->progress = NULL;
  167430. cinfo->src = NULL;
  167431. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167432. cinfo->quant_tbl_ptrs[i] = NULL;
  167433. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167434. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167435. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167436. }
  167437. /* Initialize marker processor so application can override methods
  167438. * for COM, APPn markers before calling jpeg_read_header.
  167439. */
  167440. cinfo->marker_list = NULL;
  167441. jinit_marker_reader(cinfo);
  167442. /* And initialize the overall input controller. */
  167443. jinit_input_controller(cinfo);
  167444. /* OK, I'm ready */
  167445. cinfo->global_state = DSTATE_START;
  167446. }
  167447. /*
  167448. * Destruction of a JPEG decompression object
  167449. */
  167450. GLOBAL(void)
  167451. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167452. {
  167453. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167454. }
  167455. /*
  167456. * Abort processing of a JPEG decompression operation,
  167457. * but don't destroy the object itself.
  167458. */
  167459. GLOBAL(void)
  167460. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167461. {
  167462. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167463. }
  167464. /*
  167465. * Set default decompression parameters.
  167466. */
  167467. LOCAL(void)
  167468. default_decompress_parms (j_decompress_ptr cinfo)
  167469. {
  167470. /* Guess the input colorspace, and set output colorspace accordingly. */
  167471. /* (Wish JPEG committee had provided a real way to specify this...) */
  167472. /* Note application may override our guesses. */
  167473. switch (cinfo->num_components) {
  167474. case 1:
  167475. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167476. cinfo->out_color_space = JCS_GRAYSCALE;
  167477. break;
  167478. case 3:
  167479. if (cinfo->saw_JFIF_marker) {
  167480. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167481. } else if (cinfo->saw_Adobe_marker) {
  167482. switch (cinfo->Adobe_transform) {
  167483. case 0:
  167484. cinfo->jpeg_color_space = JCS_RGB;
  167485. break;
  167486. case 1:
  167487. cinfo->jpeg_color_space = JCS_YCbCr;
  167488. break;
  167489. default:
  167490. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167491. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167492. break;
  167493. }
  167494. } else {
  167495. /* Saw no special markers, try to guess from the component IDs */
  167496. int cid0 = cinfo->comp_info[0].component_id;
  167497. int cid1 = cinfo->comp_info[1].component_id;
  167498. int cid2 = cinfo->comp_info[2].component_id;
  167499. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167500. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167501. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167502. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167503. else {
  167504. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167505. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167506. }
  167507. }
  167508. /* Always guess RGB is proper output colorspace. */
  167509. cinfo->out_color_space = JCS_RGB;
  167510. break;
  167511. case 4:
  167512. if (cinfo->saw_Adobe_marker) {
  167513. switch (cinfo->Adobe_transform) {
  167514. case 0:
  167515. cinfo->jpeg_color_space = JCS_CMYK;
  167516. break;
  167517. case 2:
  167518. cinfo->jpeg_color_space = JCS_YCCK;
  167519. break;
  167520. default:
  167521. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167522. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167523. break;
  167524. }
  167525. } else {
  167526. /* No special markers, assume straight CMYK. */
  167527. cinfo->jpeg_color_space = JCS_CMYK;
  167528. }
  167529. cinfo->out_color_space = JCS_CMYK;
  167530. break;
  167531. default:
  167532. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167533. cinfo->out_color_space = JCS_UNKNOWN;
  167534. break;
  167535. }
  167536. /* Set defaults for other decompression parameters. */
  167537. cinfo->scale_num = 1; /* 1:1 scaling */
  167538. cinfo->scale_denom = 1;
  167539. cinfo->output_gamma = 1.0;
  167540. cinfo->buffered_image = FALSE;
  167541. cinfo->raw_data_out = FALSE;
  167542. cinfo->dct_method = JDCT_DEFAULT;
  167543. cinfo->do_fancy_upsampling = TRUE;
  167544. cinfo->do_block_smoothing = TRUE;
  167545. cinfo->quantize_colors = FALSE;
  167546. /* We set these in case application only sets quantize_colors. */
  167547. cinfo->dither_mode = JDITHER_FS;
  167548. #ifdef QUANT_2PASS_SUPPORTED
  167549. cinfo->two_pass_quantize = TRUE;
  167550. #else
  167551. cinfo->two_pass_quantize = FALSE;
  167552. #endif
  167553. cinfo->desired_number_of_colors = 256;
  167554. cinfo->colormap = NULL;
  167555. /* Initialize for no mode change in buffered-image mode. */
  167556. cinfo->enable_1pass_quant = FALSE;
  167557. cinfo->enable_external_quant = FALSE;
  167558. cinfo->enable_2pass_quant = FALSE;
  167559. }
  167560. /*
  167561. * Decompression startup: read start of JPEG datastream to see what's there.
  167562. * Need only initialize JPEG object and supply a data source before calling.
  167563. *
  167564. * This routine will read as far as the first SOS marker (ie, actual start of
  167565. * compressed data), and will save all tables and parameters in the JPEG
  167566. * object. It will also initialize the decompression parameters to default
  167567. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167568. * adjust the decompression parameters and then call jpeg_start_decompress.
  167569. * (Or, if the application only wanted to determine the image parameters,
  167570. * the data need not be decompressed. In that case, call jpeg_abort or
  167571. * jpeg_destroy to release any temporary space.)
  167572. * If an abbreviated (tables only) datastream is presented, the routine will
  167573. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167574. * re-use the JPEG object to read the abbreviated image datastream(s).
  167575. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167576. * The JPEG_SUSPENDED return code only occurs if the data source module
  167577. * requests suspension of the decompressor. In this case the application
  167578. * should load more source data and then re-call jpeg_read_header to resume
  167579. * processing.
  167580. * If a non-suspending data source is used and require_image is TRUE, then the
  167581. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167582. *
  167583. * This routine is now just a front end to jpeg_consume_input, with some
  167584. * extra error checking.
  167585. */
  167586. GLOBAL(int)
  167587. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167588. {
  167589. int retcode;
  167590. if (cinfo->global_state != DSTATE_START &&
  167591. cinfo->global_state != DSTATE_INHEADER)
  167592. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167593. retcode = jpeg_consume_input(cinfo);
  167594. switch (retcode) {
  167595. case JPEG_REACHED_SOS:
  167596. retcode = JPEG_HEADER_OK;
  167597. break;
  167598. case JPEG_REACHED_EOI:
  167599. if (require_image) /* Complain if application wanted an image */
  167600. ERREXIT(cinfo, JERR_NO_IMAGE);
  167601. /* Reset to start state; it would be safer to require the application to
  167602. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167603. * A side effect is to free any temporary memory (there shouldn't be any).
  167604. */
  167605. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167606. retcode = JPEG_HEADER_TABLES_ONLY;
  167607. break;
  167608. case JPEG_SUSPENDED:
  167609. /* no work */
  167610. break;
  167611. }
  167612. return retcode;
  167613. }
  167614. /*
  167615. * Consume data in advance of what the decompressor requires.
  167616. * This can be called at any time once the decompressor object has
  167617. * been created and a data source has been set up.
  167618. *
  167619. * This routine is essentially a state machine that handles a couple
  167620. * of critical state-transition actions, namely initial setup and
  167621. * transition from header scanning to ready-for-start_decompress.
  167622. * All the actual input is done via the input controller's consume_input
  167623. * method.
  167624. */
  167625. GLOBAL(int)
  167626. jpeg_consume_input (j_decompress_ptr cinfo)
  167627. {
  167628. int retcode = JPEG_SUSPENDED;
  167629. /* NB: every possible DSTATE value should be listed in this switch */
  167630. switch (cinfo->global_state) {
  167631. case DSTATE_START:
  167632. /* Start-of-datastream actions: reset appropriate modules */
  167633. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167634. /* Initialize application's data source module */
  167635. (*cinfo->src->init_source) (cinfo);
  167636. cinfo->global_state = DSTATE_INHEADER;
  167637. /*FALLTHROUGH*/
  167638. case DSTATE_INHEADER:
  167639. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167640. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167641. /* Set up default parameters based on header data */
  167642. default_decompress_parms(cinfo);
  167643. /* Set global state: ready for start_decompress */
  167644. cinfo->global_state = DSTATE_READY;
  167645. }
  167646. break;
  167647. case DSTATE_READY:
  167648. /* Can't advance past first SOS until start_decompress is called */
  167649. retcode = JPEG_REACHED_SOS;
  167650. break;
  167651. case DSTATE_PRELOAD:
  167652. case DSTATE_PRESCAN:
  167653. case DSTATE_SCANNING:
  167654. case DSTATE_RAW_OK:
  167655. case DSTATE_BUFIMAGE:
  167656. case DSTATE_BUFPOST:
  167657. case DSTATE_STOPPING:
  167658. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167659. break;
  167660. default:
  167661. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167662. }
  167663. return retcode;
  167664. }
  167665. /*
  167666. * Have we finished reading the input file?
  167667. */
  167668. GLOBAL(boolean)
  167669. jpeg_input_complete (j_decompress_ptr cinfo)
  167670. {
  167671. /* Check for valid jpeg object */
  167672. if (cinfo->global_state < DSTATE_START ||
  167673. cinfo->global_state > DSTATE_STOPPING)
  167674. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167675. return cinfo->inputctl->eoi_reached;
  167676. }
  167677. /*
  167678. * Is there more than one scan?
  167679. */
  167680. GLOBAL(boolean)
  167681. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167682. {
  167683. /* Only valid after jpeg_read_header completes */
  167684. if (cinfo->global_state < DSTATE_READY ||
  167685. cinfo->global_state > DSTATE_STOPPING)
  167686. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167687. return cinfo->inputctl->has_multiple_scans;
  167688. }
  167689. /*
  167690. * Finish JPEG decompression.
  167691. *
  167692. * This will normally just verify the file trailer and release temp storage.
  167693. *
  167694. * Returns FALSE if suspended. The return value need be inspected only if
  167695. * a suspending data source is used.
  167696. */
  167697. GLOBAL(boolean)
  167698. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167699. {
  167700. if ((cinfo->global_state == DSTATE_SCANNING ||
  167701. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167702. /* Terminate final pass of non-buffered mode */
  167703. if (cinfo->output_scanline < cinfo->output_height)
  167704. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167705. (*cinfo->master->finish_output_pass) (cinfo);
  167706. cinfo->global_state = DSTATE_STOPPING;
  167707. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167708. /* Finishing after a buffered-image operation */
  167709. cinfo->global_state = DSTATE_STOPPING;
  167710. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167711. /* STOPPING = repeat call after a suspension, anything else is error */
  167712. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167713. }
  167714. /* Read until EOI */
  167715. while (! cinfo->inputctl->eoi_reached) {
  167716. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167717. return FALSE; /* Suspend, come back later */
  167718. }
  167719. /* Do final cleanup */
  167720. (*cinfo->src->term_source) (cinfo);
  167721. /* We can use jpeg_abort to release memory and reset global_state */
  167722. jpeg_abort((j_common_ptr) cinfo);
  167723. return TRUE;
  167724. }
  167725. /*** End of inlined file: jdapimin.c ***/
  167726. /*** Start of inlined file: jdatasrc.c ***/
  167727. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167728. /*** Start of inlined file: jerror.h ***/
  167729. /*
  167730. * To define the enum list of message codes, include this file without
  167731. * defining macro JMESSAGE. To create a message string table, include it
  167732. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167733. */
  167734. #ifndef JMESSAGE
  167735. #ifndef JERROR_H
  167736. /* First time through, define the enum list */
  167737. #define JMAKE_ENUM_LIST
  167738. #else
  167739. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167740. #define JMESSAGE(code,string)
  167741. #endif /* JERROR_H */
  167742. #endif /* JMESSAGE */
  167743. #ifdef JMAKE_ENUM_LIST
  167744. typedef enum {
  167745. #define JMESSAGE(code,string) code ,
  167746. #endif /* JMAKE_ENUM_LIST */
  167747. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167748. /* For maintenance convenience, list is alphabetical by message code name */
  167749. JMESSAGE(JERR_ARITH_NOTIMPL,
  167750. "Sorry, there are legal restrictions on arithmetic coding")
  167751. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167752. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167753. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167754. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167755. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167756. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167757. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167758. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167759. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167760. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167761. JMESSAGE(JERR_BAD_LIB_VERSION,
  167762. "Wrong JPEG library version: library is %d, caller expects %d")
  167763. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167764. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167765. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167766. JMESSAGE(JERR_BAD_PROGRESSION,
  167767. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167768. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167769. "Invalid progressive parameters at scan script entry %d")
  167770. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167771. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167772. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167773. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167774. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167775. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167776. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167777. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167778. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167779. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167780. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167781. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167782. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167783. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167784. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167785. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167786. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167787. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167788. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167789. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167790. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167791. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167792. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167793. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167794. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167795. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167796. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167797. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167798. "Cannot transcode due to multiple use of quantization table %d")
  167799. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167800. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167801. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167802. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167803. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167804. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167805. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167806. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167807. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167808. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167809. JMESSAGE(JERR_QUANT_COMPONENTS,
  167810. "Cannot quantize more than %d color components")
  167811. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167812. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167813. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167814. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167815. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167816. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167817. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167818. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167819. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167820. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167821. JMESSAGE(JERR_TFILE_WRITE,
  167822. "Write failed on temporary file --- out of disk space?")
  167823. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167824. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167825. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167826. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167827. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167828. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167829. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167830. JMESSAGE(JMSG_VERSION, JVERSION)
  167831. JMESSAGE(JTRC_16BIT_TABLES,
  167832. "Caution: quantization tables are too coarse for baseline JPEG")
  167833. JMESSAGE(JTRC_ADOBE,
  167834. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167835. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167836. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167837. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167838. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167839. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167840. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167841. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167842. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167843. JMESSAGE(JTRC_EOI, "End Of Image")
  167844. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167845. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167846. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167847. "Warning: thumbnail image size does not match data length %u")
  167848. JMESSAGE(JTRC_JFIF_EXTENSION,
  167849. "JFIF extension marker: type 0x%02x, length %u")
  167850. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167851. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167852. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167853. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167854. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167855. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167856. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167857. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167858. JMESSAGE(JTRC_RST, "RST%d")
  167859. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167860. "Smoothing not supported with nonstandard sampling ratios")
  167861. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167862. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167863. JMESSAGE(JTRC_SOI, "Start of Image")
  167864. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167865. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167866. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167867. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167868. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167869. JMESSAGE(JTRC_THUMB_JPEG,
  167870. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167871. JMESSAGE(JTRC_THUMB_PALETTE,
  167872. "JFIF extension marker: palette thumbnail image, length %u")
  167873. JMESSAGE(JTRC_THUMB_RGB,
  167874. "JFIF extension marker: RGB thumbnail image, length %u")
  167875. JMESSAGE(JTRC_UNKNOWN_IDS,
  167876. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167877. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167878. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167879. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167880. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167881. "Inconsistent progression sequence for component %d coefficient %d")
  167882. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167883. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167884. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167885. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167886. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167887. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167888. JMESSAGE(JWRN_MUST_RESYNC,
  167889. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167890. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167891. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167892. #ifdef JMAKE_ENUM_LIST
  167893. JMSG_LASTMSGCODE
  167894. } J_MESSAGE_CODE;
  167895. #undef JMAKE_ENUM_LIST
  167896. #endif /* JMAKE_ENUM_LIST */
  167897. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167898. #undef JMESSAGE
  167899. #ifndef JERROR_H
  167900. #define JERROR_H
  167901. /* Macros to simplify using the error and trace message stuff */
  167902. /* The first parameter is either type of cinfo pointer */
  167903. /* Fatal errors (print message and exit) */
  167904. #define ERREXIT(cinfo,code) \
  167905. ((cinfo)->err->msg_code = (code), \
  167906. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167907. #define ERREXIT1(cinfo,code,p1) \
  167908. ((cinfo)->err->msg_code = (code), \
  167909. (cinfo)->err->msg_parm.i[0] = (p1), \
  167910. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167911. #define ERREXIT2(cinfo,code,p1,p2) \
  167912. ((cinfo)->err->msg_code = (code), \
  167913. (cinfo)->err->msg_parm.i[0] = (p1), \
  167914. (cinfo)->err->msg_parm.i[1] = (p2), \
  167915. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167916. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167917. ((cinfo)->err->msg_code = (code), \
  167918. (cinfo)->err->msg_parm.i[0] = (p1), \
  167919. (cinfo)->err->msg_parm.i[1] = (p2), \
  167920. (cinfo)->err->msg_parm.i[2] = (p3), \
  167921. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167922. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167923. ((cinfo)->err->msg_code = (code), \
  167924. (cinfo)->err->msg_parm.i[0] = (p1), \
  167925. (cinfo)->err->msg_parm.i[1] = (p2), \
  167926. (cinfo)->err->msg_parm.i[2] = (p3), \
  167927. (cinfo)->err->msg_parm.i[3] = (p4), \
  167928. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167929. #define ERREXITS(cinfo,code,str) \
  167930. ((cinfo)->err->msg_code = (code), \
  167931. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167932. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167933. #define MAKESTMT(stuff) do { stuff } while (0)
  167934. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167935. #define WARNMS(cinfo,code) \
  167936. ((cinfo)->err->msg_code = (code), \
  167937. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167938. #define WARNMS1(cinfo,code,p1) \
  167939. ((cinfo)->err->msg_code = (code), \
  167940. (cinfo)->err->msg_parm.i[0] = (p1), \
  167941. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167942. #define WARNMS2(cinfo,code,p1,p2) \
  167943. ((cinfo)->err->msg_code = (code), \
  167944. (cinfo)->err->msg_parm.i[0] = (p1), \
  167945. (cinfo)->err->msg_parm.i[1] = (p2), \
  167946. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167947. /* Informational/debugging messages */
  167948. #define TRACEMS(cinfo,lvl,code) \
  167949. ((cinfo)->err->msg_code = (code), \
  167950. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167951. #define TRACEMS1(cinfo,lvl,code,p1) \
  167952. ((cinfo)->err->msg_code = (code), \
  167953. (cinfo)->err->msg_parm.i[0] = (p1), \
  167954. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167955. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167956. ((cinfo)->err->msg_code = (code), \
  167957. (cinfo)->err->msg_parm.i[0] = (p1), \
  167958. (cinfo)->err->msg_parm.i[1] = (p2), \
  167959. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167960. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167961. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167962. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167963. (cinfo)->err->msg_code = (code); \
  167964. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167965. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167966. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167967. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167968. (cinfo)->err->msg_code = (code); \
  167969. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167970. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167971. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167972. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167973. _mp[4] = (p5); \
  167974. (cinfo)->err->msg_code = (code); \
  167975. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167976. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167977. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167978. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167979. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167980. (cinfo)->err->msg_code = (code); \
  167981. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167982. #define TRACEMSS(cinfo,lvl,code,str) \
  167983. ((cinfo)->err->msg_code = (code), \
  167984. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167985. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167986. #endif /* JERROR_H */
  167987. /*** End of inlined file: jerror.h ***/
  167988. /* Expanded data source object for stdio input */
  167989. typedef struct {
  167990. struct jpeg_source_mgr pub; /* public fields */
  167991. FILE * infile; /* source stream */
  167992. JOCTET * buffer; /* start of buffer */
  167993. boolean start_of_file; /* have we gotten any data yet? */
  167994. } my_source_mgr;
  167995. typedef my_source_mgr * my_src_ptr;
  167996. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167997. /*
  167998. * Initialize source --- called by jpeg_read_header
  167999. * before any data is actually read.
  168000. */
  168001. METHODDEF(void)
  168002. init_source (j_decompress_ptr cinfo)
  168003. {
  168004. my_src_ptr src = (my_src_ptr) cinfo->src;
  168005. /* We reset the empty-input-file flag for each image,
  168006. * but we don't clear the input buffer.
  168007. * This is correct behavior for reading a series of images from one source.
  168008. */
  168009. src->start_of_file = TRUE;
  168010. }
  168011. /*
  168012. * Fill the input buffer --- called whenever buffer is emptied.
  168013. *
  168014. * In typical applications, this should read fresh data into the buffer
  168015. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168016. * reset the pointer & count to the start of the buffer, and return TRUE
  168017. * indicating that the buffer has been reloaded. It is not necessary to
  168018. * fill the buffer entirely, only to obtain at least one more byte.
  168019. *
  168020. * There is no such thing as an EOF return. If the end of the file has been
  168021. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168022. * the buffer. In most cases, generating a warning message and inserting a
  168023. * fake EOI marker is the best course of action --- this will allow the
  168024. * decompressor to output however much of the image is there. However,
  168025. * the resulting error message is misleading if the real problem is an empty
  168026. * input file, so we handle that case specially.
  168027. *
  168028. * In applications that need to be able to suspend compression due to input
  168029. * not being available yet, a FALSE return indicates that no more data can be
  168030. * obtained right now, but more may be forthcoming later. In this situation,
  168031. * the decompressor will return to its caller (with an indication of the
  168032. * number of scanlines it has read, if any). The application should resume
  168033. * decompression after it has loaded more data into the input buffer. Note
  168034. * that there are substantial restrictions on the use of suspension --- see
  168035. * the documentation.
  168036. *
  168037. * When suspending, the decompressor will back up to a convenient restart point
  168038. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168039. * indicate where the restart point will be if the current call returns FALSE.
  168040. * Data beyond this point must be rescanned after resumption, so move it to
  168041. * the front of the buffer rather than discarding it.
  168042. */
  168043. METHODDEF(boolean)
  168044. fill_input_buffer (j_decompress_ptr cinfo)
  168045. {
  168046. my_src_ptr src = (my_src_ptr) cinfo->src;
  168047. size_t nbytes;
  168048. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168049. if (nbytes <= 0) {
  168050. if (src->start_of_file) /* Treat empty input file as fatal error */
  168051. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168052. WARNMS(cinfo, JWRN_JPEG_EOF);
  168053. /* Insert a fake EOI marker */
  168054. src->buffer[0] = (JOCTET) 0xFF;
  168055. src->buffer[1] = (JOCTET) JPEG_EOI;
  168056. nbytes = 2;
  168057. }
  168058. src->pub.next_input_byte = src->buffer;
  168059. src->pub.bytes_in_buffer = nbytes;
  168060. src->start_of_file = FALSE;
  168061. return TRUE;
  168062. }
  168063. /*
  168064. * Skip data --- used to skip over a potentially large amount of
  168065. * uninteresting data (such as an APPn marker).
  168066. *
  168067. * Writers of suspendable-input applications must note that skip_input_data
  168068. * is not granted the right to give a suspension return. If the skip extends
  168069. * beyond the data currently in the buffer, the buffer can be marked empty so
  168070. * that the next read will cause a fill_input_buffer call that can suspend.
  168071. * Arranging for additional bytes to be discarded before reloading the input
  168072. * buffer is the application writer's problem.
  168073. */
  168074. METHODDEF(void)
  168075. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168076. {
  168077. my_src_ptr src = (my_src_ptr) cinfo->src;
  168078. /* Just a dumb implementation for now. Could use fseek() except
  168079. * it doesn't work on pipes. Not clear that being smart is worth
  168080. * any trouble anyway --- large skips are infrequent.
  168081. */
  168082. if (num_bytes > 0) {
  168083. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168084. num_bytes -= (long) src->pub.bytes_in_buffer;
  168085. (void) fill_input_buffer(cinfo);
  168086. /* note we assume that fill_input_buffer will never return FALSE,
  168087. * so suspension need not be handled.
  168088. */
  168089. }
  168090. src->pub.next_input_byte += (size_t) num_bytes;
  168091. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168092. }
  168093. }
  168094. /*
  168095. * An additional method that can be provided by data source modules is the
  168096. * resync_to_restart method for error recovery in the presence of RST markers.
  168097. * For the moment, this source module just uses the default resync method
  168098. * provided by the JPEG library. That method assumes that no backtracking
  168099. * is possible.
  168100. */
  168101. /*
  168102. * Terminate source --- called by jpeg_finish_decompress
  168103. * after all data has been read. Often a no-op.
  168104. *
  168105. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168106. * application must deal with any cleanup that should happen even
  168107. * for error exit.
  168108. */
  168109. METHODDEF(void)
  168110. term_source (j_decompress_ptr)
  168111. {
  168112. /* no work necessary here */
  168113. }
  168114. /*
  168115. * Prepare for input from a stdio stream.
  168116. * The caller must have already opened the stream, and is responsible
  168117. * for closing it after finishing decompression.
  168118. */
  168119. GLOBAL(void)
  168120. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168121. {
  168122. my_src_ptr src;
  168123. /* The source object and input buffer are made permanent so that a series
  168124. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168125. * only before the first one. (If we discarded the buffer at the end of
  168126. * one image, we'd likely lose the start of the next one.)
  168127. * This makes it unsafe to use this manager and a different source
  168128. * manager serially with the same JPEG object. Caveat programmer.
  168129. */
  168130. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168131. cinfo->src = (struct jpeg_source_mgr *)
  168132. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168133. SIZEOF(my_source_mgr));
  168134. src = (my_src_ptr) cinfo->src;
  168135. src->buffer = (JOCTET *)
  168136. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168137. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168138. }
  168139. src = (my_src_ptr) cinfo->src;
  168140. src->pub.init_source = init_source;
  168141. src->pub.fill_input_buffer = fill_input_buffer;
  168142. src->pub.skip_input_data = skip_input_data;
  168143. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168144. src->pub.term_source = term_source;
  168145. src->infile = infile;
  168146. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168147. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168148. }
  168149. /*** End of inlined file: jdatasrc.c ***/
  168150. /*** Start of inlined file: jdcoefct.c ***/
  168151. #define JPEG_INTERNALS
  168152. /* Block smoothing is only applicable for progressive JPEG, so: */
  168153. #ifndef D_PROGRESSIVE_SUPPORTED
  168154. #undef BLOCK_SMOOTHING_SUPPORTED
  168155. #endif
  168156. /* Private buffer controller object */
  168157. typedef struct {
  168158. struct jpeg_d_coef_controller pub; /* public fields */
  168159. /* These variables keep track of the current location of the input side. */
  168160. /* cinfo->input_iMCU_row is also used for this. */
  168161. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168162. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168163. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168164. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168165. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168166. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168167. * and let the entropy decoder write into that workspace each time.
  168168. * (On 80x86, the workspace is FAR even though it's not really very big;
  168169. * this is to keep the module interfaces unchanged when a large coefficient
  168170. * buffer is necessary.)
  168171. * In multi-pass modes, this array points to the current MCU's blocks
  168172. * within the virtual arrays; it is used only by the input side.
  168173. */
  168174. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168175. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168176. /* In multi-pass modes, we need a virtual block array for each component. */
  168177. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168178. #endif
  168179. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168180. /* When doing block smoothing, we latch coefficient Al values here */
  168181. int * coef_bits_latch;
  168182. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168183. #endif
  168184. } my_coef_controller3;
  168185. typedef my_coef_controller3 * my_coef_ptr3;
  168186. /* Forward declarations */
  168187. METHODDEF(int) decompress_onepass
  168188. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168189. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168190. METHODDEF(int) decompress_data
  168191. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168192. #endif
  168193. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168194. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168195. METHODDEF(int) decompress_smooth_data
  168196. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168197. #endif
  168198. LOCAL(void)
  168199. start_iMCU_row3 (j_decompress_ptr cinfo)
  168200. /* Reset within-iMCU-row counters for a new row (input side) */
  168201. {
  168202. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168203. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168204. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168205. * But at the bottom of the image, process only what's left.
  168206. */
  168207. if (cinfo->comps_in_scan > 1) {
  168208. coef->MCU_rows_per_iMCU_row = 1;
  168209. } else {
  168210. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168211. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168212. else
  168213. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168214. }
  168215. coef->MCU_ctr = 0;
  168216. coef->MCU_vert_offset = 0;
  168217. }
  168218. /*
  168219. * Initialize for an input processing pass.
  168220. */
  168221. METHODDEF(void)
  168222. start_input_pass (j_decompress_ptr cinfo)
  168223. {
  168224. cinfo->input_iMCU_row = 0;
  168225. start_iMCU_row3(cinfo);
  168226. }
  168227. /*
  168228. * Initialize for an output processing pass.
  168229. */
  168230. METHODDEF(void)
  168231. start_output_pass (j_decompress_ptr cinfo)
  168232. {
  168233. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168234. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168235. /* If multipass, check to see whether to use block smoothing on this pass */
  168236. if (coef->pub.coef_arrays != NULL) {
  168237. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168238. coef->pub.decompress_data = decompress_smooth_data;
  168239. else
  168240. coef->pub.decompress_data = decompress_data;
  168241. }
  168242. #endif
  168243. cinfo->output_iMCU_row = 0;
  168244. }
  168245. /*
  168246. * Decompress and return some data in the single-pass case.
  168247. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168248. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168249. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168250. *
  168251. * NB: output_buf contains a plane for each component in image,
  168252. * which we index according to the component's SOF position.
  168253. */
  168254. METHODDEF(int)
  168255. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168256. {
  168257. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168258. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168259. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168260. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168261. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168262. JSAMPARRAY output_ptr;
  168263. JDIMENSION start_col, output_col;
  168264. jpeg_component_info *compptr;
  168265. inverse_DCT_method_ptr inverse_DCT;
  168266. /* Loop to process as much as one whole iMCU row */
  168267. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168268. yoffset++) {
  168269. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168270. MCU_col_num++) {
  168271. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168272. jzero_far((void FAR *) coef->MCU_buffer[0],
  168273. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168274. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168275. /* Suspension forced; update state counters and exit */
  168276. coef->MCU_vert_offset = yoffset;
  168277. coef->MCU_ctr = MCU_col_num;
  168278. return JPEG_SUSPENDED;
  168279. }
  168280. /* Determine where data should go in output_buf and do the IDCT thing.
  168281. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168282. * incremented past them!). Note the inner loop relies on having
  168283. * allocated the MCU_buffer[] blocks sequentially.
  168284. */
  168285. blkn = 0; /* index of current DCT block within MCU */
  168286. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168287. compptr = cinfo->cur_comp_info[ci];
  168288. /* Don't bother to IDCT an uninteresting component. */
  168289. if (! compptr->component_needed) {
  168290. blkn += compptr->MCU_blocks;
  168291. continue;
  168292. }
  168293. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168294. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168295. : compptr->last_col_width;
  168296. output_ptr = output_buf[compptr->component_index] +
  168297. yoffset * compptr->DCT_scaled_size;
  168298. start_col = MCU_col_num * compptr->MCU_sample_width;
  168299. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168300. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168301. yoffset+yindex < compptr->last_row_height) {
  168302. output_col = start_col;
  168303. for (xindex = 0; xindex < useful_width; xindex++) {
  168304. (*inverse_DCT) (cinfo, compptr,
  168305. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168306. output_ptr, output_col);
  168307. output_col += compptr->DCT_scaled_size;
  168308. }
  168309. }
  168310. blkn += compptr->MCU_width;
  168311. output_ptr += compptr->DCT_scaled_size;
  168312. }
  168313. }
  168314. }
  168315. /* Completed an MCU row, but perhaps not an iMCU row */
  168316. coef->MCU_ctr = 0;
  168317. }
  168318. /* Completed the iMCU row, advance counters for next one */
  168319. cinfo->output_iMCU_row++;
  168320. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168321. start_iMCU_row3(cinfo);
  168322. return JPEG_ROW_COMPLETED;
  168323. }
  168324. /* Completed the scan */
  168325. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168326. return JPEG_SCAN_COMPLETED;
  168327. }
  168328. /*
  168329. * Dummy consume-input routine for single-pass operation.
  168330. */
  168331. METHODDEF(int)
  168332. dummy_consume_data (j_decompress_ptr)
  168333. {
  168334. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168335. }
  168336. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168337. /*
  168338. * Consume input data and store it in the full-image coefficient buffer.
  168339. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168340. * ie, v_samp_factor block rows for each component in the scan.
  168341. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168342. */
  168343. METHODDEF(int)
  168344. consume_data (j_decompress_ptr cinfo)
  168345. {
  168346. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168347. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168348. int blkn, ci, xindex, yindex, yoffset;
  168349. JDIMENSION start_col;
  168350. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168351. JBLOCKROW buffer_ptr;
  168352. jpeg_component_info *compptr;
  168353. /* Align the virtual buffers for the components used in this scan. */
  168354. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168355. compptr = cinfo->cur_comp_info[ci];
  168356. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168357. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168358. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168359. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168360. /* Note: entropy decoder expects buffer to be zeroed,
  168361. * but this is handled automatically by the memory manager
  168362. * because we requested a pre-zeroed array.
  168363. */
  168364. }
  168365. /* Loop to process one whole iMCU row */
  168366. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168367. yoffset++) {
  168368. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168369. MCU_col_num++) {
  168370. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168371. blkn = 0; /* index of current DCT block within MCU */
  168372. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168373. compptr = cinfo->cur_comp_info[ci];
  168374. start_col = MCU_col_num * compptr->MCU_width;
  168375. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168376. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168377. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168378. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168379. }
  168380. }
  168381. }
  168382. /* Try to fetch the MCU. */
  168383. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168384. /* Suspension forced; update state counters and exit */
  168385. coef->MCU_vert_offset = yoffset;
  168386. coef->MCU_ctr = MCU_col_num;
  168387. return JPEG_SUSPENDED;
  168388. }
  168389. }
  168390. /* Completed an MCU row, but perhaps not an iMCU row */
  168391. coef->MCU_ctr = 0;
  168392. }
  168393. /* Completed the iMCU row, advance counters for next one */
  168394. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168395. start_iMCU_row3(cinfo);
  168396. return JPEG_ROW_COMPLETED;
  168397. }
  168398. /* Completed the scan */
  168399. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168400. return JPEG_SCAN_COMPLETED;
  168401. }
  168402. /*
  168403. * Decompress and return some data in the multi-pass case.
  168404. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168405. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168406. *
  168407. * NB: output_buf contains a plane for each component in image.
  168408. */
  168409. METHODDEF(int)
  168410. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168411. {
  168412. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168413. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168414. JDIMENSION block_num;
  168415. int ci, block_row, block_rows;
  168416. JBLOCKARRAY buffer;
  168417. JBLOCKROW buffer_ptr;
  168418. JSAMPARRAY output_ptr;
  168419. JDIMENSION output_col;
  168420. jpeg_component_info *compptr;
  168421. inverse_DCT_method_ptr inverse_DCT;
  168422. /* Force some input to be done if we are getting ahead of the input. */
  168423. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168424. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168425. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168426. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168427. return JPEG_SUSPENDED;
  168428. }
  168429. /* OK, output from the virtual arrays. */
  168430. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168431. ci++, compptr++) {
  168432. /* Don't bother to IDCT an uninteresting component. */
  168433. if (! compptr->component_needed)
  168434. continue;
  168435. /* Align the virtual buffer for this component. */
  168436. buffer = (*cinfo->mem->access_virt_barray)
  168437. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168438. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168439. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168440. /* Count non-dummy DCT block rows in this iMCU row. */
  168441. if (cinfo->output_iMCU_row < last_iMCU_row)
  168442. block_rows = compptr->v_samp_factor;
  168443. else {
  168444. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168445. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168446. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168447. }
  168448. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168449. output_ptr = output_buf[ci];
  168450. /* Loop over all DCT blocks to be processed. */
  168451. for (block_row = 0; block_row < block_rows; block_row++) {
  168452. buffer_ptr = buffer[block_row];
  168453. output_col = 0;
  168454. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168455. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168456. output_ptr, output_col);
  168457. buffer_ptr++;
  168458. output_col += compptr->DCT_scaled_size;
  168459. }
  168460. output_ptr += compptr->DCT_scaled_size;
  168461. }
  168462. }
  168463. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168464. return JPEG_ROW_COMPLETED;
  168465. return JPEG_SCAN_COMPLETED;
  168466. }
  168467. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168468. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168469. /*
  168470. * This code applies interblock smoothing as described by section K.8
  168471. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168472. * the DC values of a DCT block and its 8 neighboring blocks.
  168473. * We apply smoothing only for progressive JPEG decoding, and only if
  168474. * the coefficients it can estimate are not yet known to full precision.
  168475. */
  168476. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168477. #define Q01_POS 1
  168478. #define Q10_POS 8
  168479. #define Q20_POS 16
  168480. #define Q11_POS 9
  168481. #define Q02_POS 2
  168482. /*
  168483. * Determine whether block smoothing is applicable and safe.
  168484. * We also latch the current states of the coef_bits[] entries for the
  168485. * AC coefficients; otherwise, if the input side of the decompressor
  168486. * advances into a new scan, we might think the coefficients are known
  168487. * more accurately than they really are.
  168488. */
  168489. LOCAL(boolean)
  168490. smoothing_ok (j_decompress_ptr cinfo)
  168491. {
  168492. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168493. boolean smoothing_useful = FALSE;
  168494. int ci, coefi;
  168495. jpeg_component_info *compptr;
  168496. JQUANT_TBL * qtable;
  168497. int * coef_bits;
  168498. int * coef_bits_latch;
  168499. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168500. return FALSE;
  168501. /* Allocate latch area if not already done */
  168502. if (coef->coef_bits_latch == NULL)
  168503. coef->coef_bits_latch = (int *)
  168504. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168505. cinfo->num_components *
  168506. (SAVED_COEFS * SIZEOF(int)));
  168507. coef_bits_latch = coef->coef_bits_latch;
  168508. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168509. ci++, compptr++) {
  168510. /* All components' quantization values must already be latched. */
  168511. if ((qtable = compptr->quant_table) == NULL)
  168512. return FALSE;
  168513. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168514. if (qtable->quantval[0] == 0 ||
  168515. qtable->quantval[Q01_POS] == 0 ||
  168516. qtable->quantval[Q10_POS] == 0 ||
  168517. qtable->quantval[Q20_POS] == 0 ||
  168518. qtable->quantval[Q11_POS] == 0 ||
  168519. qtable->quantval[Q02_POS] == 0)
  168520. return FALSE;
  168521. /* DC values must be at least partly known for all components. */
  168522. coef_bits = cinfo->coef_bits[ci];
  168523. if (coef_bits[0] < 0)
  168524. return FALSE;
  168525. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168526. for (coefi = 1; coefi <= 5; coefi++) {
  168527. coef_bits_latch[coefi] = coef_bits[coefi];
  168528. if (coef_bits[coefi] != 0)
  168529. smoothing_useful = TRUE;
  168530. }
  168531. coef_bits_latch += SAVED_COEFS;
  168532. }
  168533. return smoothing_useful;
  168534. }
  168535. /*
  168536. * Variant of decompress_data for use when doing block smoothing.
  168537. */
  168538. METHODDEF(int)
  168539. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168540. {
  168541. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168542. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168543. JDIMENSION block_num, last_block_column;
  168544. int ci, block_row, block_rows, access_rows;
  168545. JBLOCKARRAY buffer;
  168546. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168547. JSAMPARRAY output_ptr;
  168548. JDIMENSION output_col;
  168549. jpeg_component_info *compptr;
  168550. inverse_DCT_method_ptr inverse_DCT;
  168551. boolean first_row, last_row;
  168552. JBLOCK workspace;
  168553. int *coef_bits;
  168554. JQUANT_TBL *quanttbl;
  168555. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168556. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168557. int Al, pred;
  168558. /* Force some input to be done if we are getting ahead of the input. */
  168559. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168560. ! cinfo->inputctl->eoi_reached) {
  168561. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168562. /* If input is working on current scan, we ordinarily want it to
  168563. * have completed the current row. But if input scan is DC,
  168564. * we want it to keep one row ahead so that next block row's DC
  168565. * values are up to date.
  168566. */
  168567. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168568. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168569. break;
  168570. }
  168571. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168572. return JPEG_SUSPENDED;
  168573. }
  168574. /* OK, output from the virtual arrays. */
  168575. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168576. ci++, compptr++) {
  168577. /* Don't bother to IDCT an uninteresting component. */
  168578. if (! compptr->component_needed)
  168579. continue;
  168580. /* Count non-dummy DCT block rows in this iMCU row. */
  168581. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168582. block_rows = compptr->v_samp_factor;
  168583. access_rows = block_rows * 2; /* this and next iMCU row */
  168584. last_row = FALSE;
  168585. } else {
  168586. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168587. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168588. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168589. access_rows = block_rows; /* this iMCU row only */
  168590. last_row = TRUE;
  168591. }
  168592. /* Align the virtual buffer for this component. */
  168593. if (cinfo->output_iMCU_row > 0) {
  168594. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168595. buffer = (*cinfo->mem->access_virt_barray)
  168596. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168597. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168598. (JDIMENSION) access_rows, FALSE);
  168599. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168600. first_row = FALSE;
  168601. } else {
  168602. buffer = (*cinfo->mem->access_virt_barray)
  168603. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168604. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168605. first_row = TRUE;
  168606. }
  168607. /* Fetch component-dependent info */
  168608. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168609. quanttbl = compptr->quant_table;
  168610. Q00 = quanttbl->quantval[0];
  168611. Q01 = quanttbl->quantval[Q01_POS];
  168612. Q10 = quanttbl->quantval[Q10_POS];
  168613. Q20 = quanttbl->quantval[Q20_POS];
  168614. Q11 = quanttbl->quantval[Q11_POS];
  168615. Q02 = quanttbl->quantval[Q02_POS];
  168616. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168617. output_ptr = output_buf[ci];
  168618. /* Loop over all DCT blocks to be processed. */
  168619. for (block_row = 0; block_row < block_rows; block_row++) {
  168620. buffer_ptr = buffer[block_row];
  168621. if (first_row && block_row == 0)
  168622. prev_block_row = buffer_ptr;
  168623. else
  168624. prev_block_row = buffer[block_row-1];
  168625. if (last_row && block_row == block_rows-1)
  168626. next_block_row = buffer_ptr;
  168627. else
  168628. next_block_row = buffer[block_row+1];
  168629. /* We fetch the surrounding DC values using a sliding-register approach.
  168630. * Initialize all nine here so as to do the right thing on narrow pics.
  168631. */
  168632. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168633. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168634. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168635. output_col = 0;
  168636. last_block_column = compptr->width_in_blocks - 1;
  168637. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168638. /* Fetch current DCT block into workspace so we can modify it. */
  168639. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168640. /* Update DC values */
  168641. if (block_num < last_block_column) {
  168642. DC3 = (int) prev_block_row[1][0];
  168643. DC6 = (int) buffer_ptr[1][0];
  168644. DC9 = (int) next_block_row[1][0];
  168645. }
  168646. /* Compute coefficient estimates per K.8.
  168647. * An estimate is applied only if coefficient is still zero,
  168648. * and is not known to be fully accurate.
  168649. */
  168650. /* AC01 */
  168651. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168652. num = 36 * Q00 * (DC4 - DC6);
  168653. if (num >= 0) {
  168654. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168655. if (Al > 0 && pred >= (1<<Al))
  168656. pred = (1<<Al)-1;
  168657. } else {
  168658. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168659. if (Al > 0 && pred >= (1<<Al))
  168660. pred = (1<<Al)-1;
  168661. pred = -pred;
  168662. }
  168663. workspace[1] = (JCOEF) pred;
  168664. }
  168665. /* AC10 */
  168666. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168667. num = 36 * Q00 * (DC2 - DC8);
  168668. if (num >= 0) {
  168669. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168670. if (Al > 0 && pred >= (1<<Al))
  168671. pred = (1<<Al)-1;
  168672. } else {
  168673. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168674. if (Al > 0 && pred >= (1<<Al))
  168675. pred = (1<<Al)-1;
  168676. pred = -pred;
  168677. }
  168678. workspace[8] = (JCOEF) pred;
  168679. }
  168680. /* AC20 */
  168681. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168682. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168683. if (num >= 0) {
  168684. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168685. if (Al > 0 && pred >= (1<<Al))
  168686. pred = (1<<Al)-1;
  168687. } else {
  168688. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168689. if (Al > 0 && pred >= (1<<Al))
  168690. pred = (1<<Al)-1;
  168691. pred = -pred;
  168692. }
  168693. workspace[16] = (JCOEF) pred;
  168694. }
  168695. /* AC11 */
  168696. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168697. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168698. if (num >= 0) {
  168699. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168700. if (Al > 0 && pred >= (1<<Al))
  168701. pred = (1<<Al)-1;
  168702. } else {
  168703. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168704. if (Al > 0 && pred >= (1<<Al))
  168705. pred = (1<<Al)-1;
  168706. pred = -pred;
  168707. }
  168708. workspace[9] = (JCOEF) pred;
  168709. }
  168710. /* AC02 */
  168711. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168712. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168713. if (num >= 0) {
  168714. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168715. if (Al > 0 && pred >= (1<<Al))
  168716. pred = (1<<Al)-1;
  168717. } else {
  168718. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168719. if (Al > 0 && pred >= (1<<Al))
  168720. pred = (1<<Al)-1;
  168721. pred = -pred;
  168722. }
  168723. workspace[2] = (JCOEF) pred;
  168724. }
  168725. /* OK, do the IDCT */
  168726. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168727. output_ptr, output_col);
  168728. /* Advance for next column */
  168729. DC1 = DC2; DC2 = DC3;
  168730. DC4 = DC5; DC5 = DC6;
  168731. DC7 = DC8; DC8 = DC9;
  168732. buffer_ptr++, prev_block_row++, next_block_row++;
  168733. output_col += compptr->DCT_scaled_size;
  168734. }
  168735. output_ptr += compptr->DCT_scaled_size;
  168736. }
  168737. }
  168738. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168739. return JPEG_ROW_COMPLETED;
  168740. return JPEG_SCAN_COMPLETED;
  168741. }
  168742. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168743. /*
  168744. * Initialize coefficient buffer controller.
  168745. */
  168746. GLOBAL(void)
  168747. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168748. {
  168749. my_coef_ptr3 coef;
  168750. coef = (my_coef_ptr3)
  168751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168752. SIZEOF(my_coef_controller3));
  168753. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168754. coef->pub.start_input_pass = start_input_pass;
  168755. coef->pub.start_output_pass = start_output_pass;
  168756. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168757. coef->coef_bits_latch = NULL;
  168758. #endif
  168759. /* Create the coefficient buffer. */
  168760. if (need_full_buffer) {
  168761. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168762. /* Allocate a full-image virtual array for each component, */
  168763. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168764. /* Note we ask for a pre-zeroed array. */
  168765. int ci, access_rows;
  168766. jpeg_component_info *compptr;
  168767. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168768. ci++, compptr++) {
  168769. access_rows = compptr->v_samp_factor;
  168770. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168771. /* If block smoothing could be used, need a bigger window */
  168772. if (cinfo->progressive_mode)
  168773. access_rows *= 3;
  168774. #endif
  168775. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168776. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168777. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168778. (long) compptr->h_samp_factor),
  168779. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168780. (long) compptr->v_samp_factor),
  168781. (JDIMENSION) access_rows);
  168782. }
  168783. coef->pub.consume_data = consume_data;
  168784. coef->pub.decompress_data = decompress_data;
  168785. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168786. #else
  168787. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168788. #endif
  168789. } else {
  168790. /* We only need a single-MCU buffer. */
  168791. JBLOCKROW buffer;
  168792. int i;
  168793. buffer = (JBLOCKROW)
  168794. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168795. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168796. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168797. coef->MCU_buffer[i] = buffer + i;
  168798. }
  168799. coef->pub.consume_data = dummy_consume_data;
  168800. coef->pub.decompress_data = decompress_onepass;
  168801. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168802. }
  168803. }
  168804. /*** End of inlined file: jdcoefct.c ***/
  168805. #undef FIX
  168806. /*** Start of inlined file: jdcolor.c ***/
  168807. #define JPEG_INTERNALS
  168808. /* Private subobject */
  168809. typedef struct {
  168810. struct jpeg_color_deconverter pub; /* public fields */
  168811. /* Private state for YCC->RGB conversion */
  168812. int * Cr_r_tab; /* => table for Cr to R conversion */
  168813. int * Cb_b_tab; /* => table for Cb to B conversion */
  168814. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168815. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168816. } my_color_deconverter2;
  168817. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168818. /**************** YCbCr -> RGB conversion: most common case **************/
  168819. /*
  168820. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168821. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168822. * The conversion equations to be implemented are therefore
  168823. * R = Y + 1.40200 * Cr
  168824. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168825. * B = Y + 1.77200 * Cb
  168826. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168827. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168828. *
  168829. * To avoid floating-point arithmetic, we represent the fractional constants
  168830. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168831. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168832. * Notice that Y, being an integral input, does not contribute any fraction
  168833. * so it need not participate in the rounding.
  168834. *
  168835. * For even more speed, we avoid doing any multiplications in the inner loop
  168836. * by precalculating the constants times Cb and Cr for all possible values.
  168837. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168838. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168839. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168840. * colorspace anyway.
  168841. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168842. * values for the G calculation are left scaled up, since we must add them
  168843. * together before rounding.
  168844. */
  168845. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168846. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168847. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168848. /*
  168849. * Initialize tables for YCC->RGB colorspace conversion.
  168850. */
  168851. LOCAL(void)
  168852. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168853. {
  168854. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168855. int i;
  168856. INT32 x;
  168857. SHIFT_TEMPS
  168858. cconvert->Cr_r_tab = (int *)
  168859. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168860. (MAXJSAMPLE+1) * SIZEOF(int));
  168861. cconvert->Cb_b_tab = (int *)
  168862. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168863. (MAXJSAMPLE+1) * SIZEOF(int));
  168864. cconvert->Cr_g_tab = (INT32 *)
  168865. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168866. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168867. cconvert->Cb_g_tab = (INT32 *)
  168868. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168869. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168870. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168871. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168872. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168873. /* Cr=>R value is nearest int to 1.40200 * x */
  168874. cconvert->Cr_r_tab[i] = (int)
  168875. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168876. /* Cb=>B value is nearest int to 1.77200 * x */
  168877. cconvert->Cb_b_tab[i] = (int)
  168878. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168879. /* Cr=>G value is scaled-up -0.71414 * x */
  168880. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168881. /* Cb=>G value is scaled-up -0.34414 * x */
  168882. /* We also add in ONE_HALF so that need not do it in inner loop */
  168883. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168884. }
  168885. }
  168886. /*
  168887. * Convert some rows of samples to the output colorspace.
  168888. *
  168889. * Note that we change from noninterleaved, one-plane-per-component format
  168890. * to interleaved-pixel format. The output buffer is therefore three times
  168891. * as wide as the input buffer.
  168892. * A starting row offset is provided only for the input buffer. The caller
  168893. * can easily adjust the passed output_buf value to accommodate any row
  168894. * offset required on that side.
  168895. */
  168896. METHODDEF(void)
  168897. ycc_rgb_convert (j_decompress_ptr cinfo,
  168898. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168899. JSAMPARRAY output_buf, int num_rows)
  168900. {
  168901. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168902. register int y, cb, cr;
  168903. register JSAMPROW outptr;
  168904. register JSAMPROW inptr0, inptr1, inptr2;
  168905. register JDIMENSION col;
  168906. JDIMENSION num_cols = cinfo->output_width;
  168907. /* copy these pointers into registers if possible */
  168908. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168909. register int * Crrtab = cconvert->Cr_r_tab;
  168910. register int * Cbbtab = cconvert->Cb_b_tab;
  168911. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168912. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168913. SHIFT_TEMPS
  168914. while (--num_rows >= 0) {
  168915. inptr0 = input_buf[0][input_row];
  168916. inptr1 = input_buf[1][input_row];
  168917. inptr2 = input_buf[2][input_row];
  168918. input_row++;
  168919. outptr = *output_buf++;
  168920. for (col = 0; col < num_cols; col++) {
  168921. y = GETJSAMPLE(inptr0[col]);
  168922. cb = GETJSAMPLE(inptr1[col]);
  168923. cr = GETJSAMPLE(inptr2[col]);
  168924. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168925. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168926. outptr[RGB_GREEN] = range_limit[y +
  168927. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168928. SCALEBITS))];
  168929. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168930. outptr += RGB_PIXELSIZE;
  168931. }
  168932. }
  168933. }
  168934. /**************** Cases other than YCbCr -> RGB **************/
  168935. /*
  168936. * Color conversion for no colorspace change: just copy the data,
  168937. * converting from separate-planes to interleaved representation.
  168938. */
  168939. METHODDEF(void)
  168940. null_convert2 (j_decompress_ptr cinfo,
  168941. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168942. JSAMPARRAY output_buf, int num_rows)
  168943. {
  168944. register JSAMPROW inptr, outptr;
  168945. register JDIMENSION count;
  168946. register int num_components = cinfo->num_components;
  168947. JDIMENSION num_cols = cinfo->output_width;
  168948. int ci;
  168949. while (--num_rows >= 0) {
  168950. for (ci = 0; ci < num_components; ci++) {
  168951. inptr = input_buf[ci][input_row];
  168952. outptr = output_buf[0] + ci;
  168953. for (count = num_cols; count > 0; count--) {
  168954. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168955. outptr += num_components;
  168956. }
  168957. }
  168958. input_row++;
  168959. output_buf++;
  168960. }
  168961. }
  168962. /*
  168963. * Color conversion for grayscale: just copy the data.
  168964. * This also works for YCbCr -> grayscale conversion, in which
  168965. * we just copy the Y (luminance) component and ignore chrominance.
  168966. */
  168967. METHODDEF(void)
  168968. grayscale_convert2 (j_decompress_ptr cinfo,
  168969. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168970. JSAMPARRAY output_buf, int num_rows)
  168971. {
  168972. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168973. num_rows, cinfo->output_width);
  168974. }
  168975. /*
  168976. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168977. * This is provided to support applications that don't want to cope
  168978. * with grayscale as a separate case.
  168979. */
  168980. METHODDEF(void)
  168981. gray_rgb_convert (j_decompress_ptr cinfo,
  168982. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168983. JSAMPARRAY output_buf, int num_rows)
  168984. {
  168985. register JSAMPROW inptr, outptr;
  168986. register JDIMENSION col;
  168987. JDIMENSION num_cols = cinfo->output_width;
  168988. while (--num_rows >= 0) {
  168989. inptr = input_buf[0][input_row++];
  168990. outptr = *output_buf++;
  168991. for (col = 0; col < num_cols; col++) {
  168992. /* We can dispense with GETJSAMPLE() here */
  168993. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168994. outptr += RGB_PIXELSIZE;
  168995. }
  168996. }
  168997. }
  168998. /*
  168999. * Adobe-style YCCK->CMYK conversion.
  169000. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169001. * conversion as above, while passing K (black) unchanged.
  169002. * We assume build_ycc_rgb_table has been called.
  169003. */
  169004. METHODDEF(void)
  169005. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169006. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169007. JSAMPARRAY output_buf, int num_rows)
  169008. {
  169009. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169010. register int y, cb, cr;
  169011. register JSAMPROW outptr;
  169012. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169013. register JDIMENSION col;
  169014. JDIMENSION num_cols = cinfo->output_width;
  169015. /* copy these pointers into registers if possible */
  169016. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169017. register int * Crrtab = cconvert->Cr_r_tab;
  169018. register int * Cbbtab = cconvert->Cb_b_tab;
  169019. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169020. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169021. SHIFT_TEMPS
  169022. while (--num_rows >= 0) {
  169023. inptr0 = input_buf[0][input_row];
  169024. inptr1 = input_buf[1][input_row];
  169025. inptr2 = input_buf[2][input_row];
  169026. inptr3 = input_buf[3][input_row];
  169027. input_row++;
  169028. outptr = *output_buf++;
  169029. for (col = 0; col < num_cols; col++) {
  169030. y = GETJSAMPLE(inptr0[col]);
  169031. cb = GETJSAMPLE(inptr1[col]);
  169032. cr = GETJSAMPLE(inptr2[col]);
  169033. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169034. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169035. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169036. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169037. SCALEBITS)))];
  169038. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169039. /* K passes through unchanged */
  169040. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169041. outptr += 4;
  169042. }
  169043. }
  169044. }
  169045. /*
  169046. * Empty method for start_pass.
  169047. */
  169048. METHODDEF(void)
  169049. start_pass_dcolor (j_decompress_ptr)
  169050. {
  169051. /* no work needed */
  169052. }
  169053. /*
  169054. * Module initialization routine for output colorspace conversion.
  169055. */
  169056. GLOBAL(void)
  169057. jinit_color_deconverter (j_decompress_ptr cinfo)
  169058. {
  169059. my_cconvert_ptr2 cconvert;
  169060. int ci;
  169061. cconvert = (my_cconvert_ptr2)
  169062. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169063. SIZEOF(my_color_deconverter2));
  169064. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169065. cconvert->pub.start_pass = start_pass_dcolor;
  169066. /* Make sure num_components agrees with jpeg_color_space */
  169067. switch (cinfo->jpeg_color_space) {
  169068. case JCS_GRAYSCALE:
  169069. if (cinfo->num_components != 1)
  169070. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169071. break;
  169072. case JCS_RGB:
  169073. case JCS_YCbCr:
  169074. if (cinfo->num_components != 3)
  169075. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169076. break;
  169077. case JCS_CMYK:
  169078. case JCS_YCCK:
  169079. if (cinfo->num_components != 4)
  169080. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169081. break;
  169082. default: /* JCS_UNKNOWN can be anything */
  169083. if (cinfo->num_components < 1)
  169084. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169085. break;
  169086. }
  169087. /* Set out_color_components and conversion method based on requested space.
  169088. * Also clear the component_needed flags for any unused components,
  169089. * so that earlier pipeline stages can avoid useless computation.
  169090. */
  169091. switch (cinfo->out_color_space) {
  169092. case JCS_GRAYSCALE:
  169093. cinfo->out_color_components = 1;
  169094. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169095. cinfo->jpeg_color_space == JCS_YCbCr) {
  169096. cconvert->pub.color_convert = grayscale_convert2;
  169097. /* For color->grayscale conversion, only the Y (0) component is needed */
  169098. for (ci = 1; ci < cinfo->num_components; ci++)
  169099. cinfo->comp_info[ci].component_needed = FALSE;
  169100. } else
  169101. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169102. break;
  169103. case JCS_RGB:
  169104. cinfo->out_color_components = RGB_PIXELSIZE;
  169105. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169106. cconvert->pub.color_convert = ycc_rgb_convert;
  169107. build_ycc_rgb_table(cinfo);
  169108. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169109. cconvert->pub.color_convert = gray_rgb_convert;
  169110. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169111. cconvert->pub.color_convert = null_convert2;
  169112. } else
  169113. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169114. break;
  169115. case JCS_CMYK:
  169116. cinfo->out_color_components = 4;
  169117. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169118. cconvert->pub.color_convert = ycck_cmyk_convert;
  169119. build_ycc_rgb_table(cinfo);
  169120. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169121. cconvert->pub.color_convert = null_convert2;
  169122. } else
  169123. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169124. break;
  169125. default:
  169126. /* Permit null conversion to same output space */
  169127. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169128. cinfo->out_color_components = cinfo->num_components;
  169129. cconvert->pub.color_convert = null_convert2;
  169130. } else /* unsupported non-null conversion */
  169131. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169132. break;
  169133. }
  169134. if (cinfo->quantize_colors)
  169135. cinfo->output_components = 1; /* single colormapped output component */
  169136. else
  169137. cinfo->output_components = cinfo->out_color_components;
  169138. }
  169139. /*** End of inlined file: jdcolor.c ***/
  169140. #undef FIX
  169141. /*** Start of inlined file: jddctmgr.c ***/
  169142. #define JPEG_INTERNALS
  169143. /*
  169144. * The decompressor input side (jdinput.c) saves away the appropriate
  169145. * quantization table for each component at the start of the first scan
  169146. * involving that component. (This is necessary in order to correctly
  169147. * decode files that reuse Q-table slots.)
  169148. * When we are ready to make an output pass, the saved Q-table is converted
  169149. * to a multiplier table that will actually be used by the IDCT routine.
  169150. * The multiplier table contents are IDCT-method-dependent. To support
  169151. * application changes in IDCT method between scans, we can remake the
  169152. * multiplier tables if necessary.
  169153. * In buffered-image mode, the first output pass may occur before any data
  169154. * has been seen for some components, and thus before their Q-tables have
  169155. * been saved away. To handle this case, multiplier tables are preset
  169156. * to zeroes; the result of the IDCT will be a neutral gray level.
  169157. */
  169158. /* Private subobject for this module */
  169159. typedef struct {
  169160. struct jpeg_inverse_dct pub; /* public fields */
  169161. /* This array contains the IDCT method code that each multiplier table
  169162. * is currently set up for, or -1 if it's not yet set up.
  169163. * The actual multiplier tables are pointed to by dct_table in the
  169164. * per-component comp_info structures.
  169165. */
  169166. int cur_method[MAX_COMPONENTS];
  169167. } my_idct_controller;
  169168. typedef my_idct_controller * my_idct_ptr;
  169169. /* Allocated multiplier tables: big enough for any supported variant */
  169170. typedef union {
  169171. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169172. #ifdef DCT_IFAST_SUPPORTED
  169173. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169174. #endif
  169175. #ifdef DCT_FLOAT_SUPPORTED
  169176. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169177. #endif
  169178. } multiplier_table;
  169179. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169180. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169181. */
  169182. #ifdef DCT_ISLOW_SUPPORTED
  169183. #define PROVIDE_ISLOW_TABLES
  169184. #else
  169185. #ifdef IDCT_SCALING_SUPPORTED
  169186. #define PROVIDE_ISLOW_TABLES
  169187. #endif
  169188. #endif
  169189. /*
  169190. * Prepare for an output pass.
  169191. * Here we select the proper IDCT routine for each component and build
  169192. * a matching multiplier table.
  169193. */
  169194. METHODDEF(void)
  169195. start_pass (j_decompress_ptr cinfo)
  169196. {
  169197. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169198. int ci, i;
  169199. jpeg_component_info *compptr;
  169200. int method = 0;
  169201. inverse_DCT_method_ptr method_ptr = NULL;
  169202. JQUANT_TBL * qtbl;
  169203. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169204. ci++, compptr++) {
  169205. /* Select the proper IDCT routine for this component's scaling */
  169206. switch (compptr->DCT_scaled_size) {
  169207. #ifdef IDCT_SCALING_SUPPORTED
  169208. case 1:
  169209. method_ptr = jpeg_idct_1x1;
  169210. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169211. break;
  169212. case 2:
  169213. method_ptr = jpeg_idct_2x2;
  169214. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169215. break;
  169216. case 4:
  169217. method_ptr = jpeg_idct_4x4;
  169218. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169219. break;
  169220. #endif
  169221. case DCTSIZE:
  169222. switch (cinfo->dct_method) {
  169223. #ifdef DCT_ISLOW_SUPPORTED
  169224. case JDCT_ISLOW:
  169225. method_ptr = jpeg_idct_islow;
  169226. method = JDCT_ISLOW;
  169227. break;
  169228. #endif
  169229. #ifdef DCT_IFAST_SUPPORTED
  169230. case JDCT_IFAST:
  169231. method_ptr = jpeg_idct_ifast;
  169232. method = JDCT_IFAST;
  169233. break;
  169234. #endif
  169235. #ifdef DCT_FLOAT_SUPPORTED
  169236. case JDCT_FLOAT:
  169237. method_ptr = jpeg_idct_float;
  169238. method = JDCT_FLOAT;
  169239. break;
  169240. #endif
  169241. default:
  169242. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169243. break;
  169244. }
  169245. break;
  169246. default:
  169247. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169248. break;
  169249. }
  169250. idct->pub.inverse_DCT[ci] = method_ptr;
  169251. /* Create multiplier table from quant table.
  169252. * However, we can skip this if the component is uninteresting
  169253. * or if we already built the table. Also, if no quant table
  169254. * has yet been saved for the component, we leave the
  169255. * multiplier table all-zero; we'll be reading zeroes from the
  169256. * coefficient controller's buffer anyway.
  169257. */
  169258. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169259. continue;
  169260. qtbl = compptr->quant_table;
  169261. if (qtbl == NULL) /* happens if no data yet for component */
  169262. continue;
  169263. idct->cur_method[ci] = method;
  169264. switch (method) {
  169265. #ifdef PROVIDE_ISLOW_TABLES
  169266. case JDCT_ISLOW:
  169267. {
  169268. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169269. * coefficients, but are stored as ints to ensure access efficiency.
  169270. */
  169271. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169272. for (i = 0; i < DCTSIZE2; i++) {
  169273. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169274. }
  169275. }
  169276. break;
  169277. #endif
  169278. #ifdef DCT_IFAST_SUPPORTED
  169279. case JDCT_IFAST:
  169280. {
  169281. /* For AA&N IDCT method, multipliers are equal to quantization
  169282. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169283. * scalefactor[0] = 1
  169284. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169285. * For integer operation, the multiplier table is to be scaled by
  169286. * IFAST_SCALE_BITS.
  169287. */
  169288. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169289. #define CONST_BITS 14
  169290. static const INT16 aanscales[DCTSIZE2] = {
  169291. /* precomputed values scaled up by 14 bits */
  169292. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169293. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169294. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169295. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169296. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169297. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169298. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169299. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169300. };
  169301. SHIFT_TEMPS
  169302. for (i = 0; i < DCTSIZE2; i++) {
  169303. ifmtbl[i] = (IFAST_MULT_TYPE)
  169304. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169305. (INT32) aanscales[i]),
  169306. CONST_BITS-IFAST_SCALE_BITS);
  169307. }
  169308. }
  169309. break;
  169310. #endif
  169311. #ifdef DCT_FLOAT_SUPPORTED
  169312. case JDCT_FLOAT:
  169313. {
  169314. /* For float AA&N IDCT method, multipliers are equal to quantization
  169315. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169316. * scalefactor[0] = 1
  169317. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169318. */
  169319. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169320. int row, col;
  169321. static const double aanscalefactor[DCTSIZE] = {
  169322. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169323. 1.0, 0.785694958, 0.541196100, 0.275899379
  169324. };
  169325. i = 0;
  169326. for (row = 0; row < DCTSIZE; row++) {
  169327. for (col = 0; col < DCTSIZE; col++) {
  169328. fmtbl[i] = (FLOAT_MULT_TYPE)
  169329. ((double) qtbl->quantval[i] *
  169330. aanscalefactor[row] * aanscalefactor[col]);
  169331. i++;
  169332. }
  169333. }
  169334. }
  169335. break;
  169336. #endif
  169337. default:
  169338. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169339. break;
  169340. }
  169341. }
  169342. }
  169343. /*
  169344. * Initialize IDCT manager.
  169345. */
  169346. GLOBAL(void)
  169347. jinit_inverse_dct (j_decompress_ptr cinfo)
  169348. {
  169349. my_idct_ptr idct;
  169350. int ci;
  169351. jpeg_component_info *compptr;
  169352. idct = (my_idct_ptr)
  169353. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169354. SIZEOF(my_idct_controller));
  169355. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169356. idct->pub.start_pass = start_pass;
  169357. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169358. ci++, compptr++) {
  169359. /* Allocate and pre-zero a multiplier table for each component */
  169360. compptr->dct_table =
  169361. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169362. SIZEOF(multiplier_table));
  169363. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169364. /* Mark multiplier table not yet set up for any method */
  169365. idct->cur_method[ci] = -1;
  169366. }
  169367. }
  169368. /*** End of inlined file: jddctmgr.c ***/
  169369. #undef CONST_BITS
  169370. #undef ASSIGN_STATE
  169371. /*** Start of inlined file: jdhuff.c ***/
  169372. #define JPEG_INTERNALS
  169373. /*** Start of inlined file: jdhuff.h ***/
  169374. /* Short forms of external names for systems with brain-damaged linkers. */
  169375. #ifndef __jdhuff_h__
  169376. #define __jdhuff_h__
  169377. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169378. #define jpeg_make_d_derived_tbl jMkDDerived
  169379. #define jpeg_fill_bit_buffer jFilBitBuf
  169380. #define jpeg_huff_decode jHufDecode
  169381. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169382. /* Derived data constructed for each Huffman table */
  169383. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169384. typedef struct {
  169385. /* Basic tables: (element [0] of each array is unused) */
  169386. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169387. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169388. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169389. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169390. * the smallest code of length k; so given a code of length k, the
  169391. * corresponding symbol is huffval[code + valoffset[k]]
  169392. */
  169393. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169394. JHUFF_TBL *pub;
  169395. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169396. * the input data stream. If the next Huffman code is no more
  169397. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169398. * the corresponding symbol directly from these tables.
  169399. */
  169400. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169401. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169402. } d_derived_tbl;
  169403. /* Expand a Huffman table definition into the derived format */
  169404. EXTERN(void) jpeg_make_d_derived_tbl
  169405. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169406. d_derived_tbl ** pdtbl));
  169407. /*
  169408. * Fetching the next N bits from the input stream is a time-critical operation
  169409. * for the Huffman decoders. We implement it with a combination of inline
  169410. * macros and out-of-line subroutines. Note that N (the number of bits
  169411. * demanded at one time) never exceeds 15 for JPEG use.
  169412. *
  169413. * We read source bytes into get_buffer and dole out bits as needed.
  169414. * If get_buffer already contains enough bits, they are fetched in-line
  169415. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169416. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169417. * as full as possible (not just to the number of bits needed; this
  169418. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169419. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169420. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169421. * at least the requested number of bits --- dummy zeroes are inserted if
  169422. * necessary.
  169423. */
  169424. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169425. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169426. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169427. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169428. * appropriately should be a win. Unfortunately we can't define the size
  169429. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169430. * because not all machines measure sizeof in 8-bit bytes.
  169431. */
  169432. typedef struct { /* Bitreading state saved across MCUs */
  169433. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169434. int bits_left; /* # of unused bits in it */
  169435. } bitread_perm_state;
  169436. typedef struct { /* Bitreading working state within an MCU */
  169437. /* Current data source location */
  169438. /* We need a copy, rather than munging the original, in case of suspension */
  169439. const JOCTET * next_input_byte; /* => next byte to read from source */
  169440. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169441. /* Bit input buffer --- note these values are kept in register variables,
  169442. * not in this struct, inside the inner loops.
  169443. */
  169444. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169445. int bits_left; /* # of unused bits in it */
  169446. /* Pointer needed by jpeg_fill_bit_buffer. */
  169447. j_decompress_ptr cinfo; /* back link to decompress master record */
  169448. } bitread_working_state;
  169449. /* Macros to declare and load/save bitread local variables. */
  169450. #define BITREAD_STATE_VARS \
  169451. register bit_buf_type get_buffer; \
  169452. register int bits_left; \
  169453. bitread_working_state br_state
  169454. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169455. br_state.cinfo = cinfop; \
  169456. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169457. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169458. get_buffer = permstate.get_buffer; \
  169459. bits_left = permstate.bits_left;
  169460. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169461. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169462. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169463. permstate.get_buffer = get_buffer; \
  169464. permstate.bits_left = bits_left
  169465. /*
  169466. * These macros provide the in-line portion of bit fetching.
  169467. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169468. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169469. * The variables get_buffer and bits_left are assumed to be locals,
  169470. * but the state struct might not be (jpeg_huff_decode needs this).
  169471. * CHECK_BIT_BUFFER(state,n,action);
  169472. * Ensure there are N bits in get_buffer; if suspend, take action.
  169473. * val = GET_BITS(n);
  169474. * Fetch next N bits.
  169475. * val = PEEK_BITS(n);
  169476. * Fetch next N bits without removing them from the buffer.
  169477. * DROP_BITS(n);
  169478. * Discard next N bits.
  169479. * The value N should be a simple variable, not an expression, because it
  169480. * is evaluated multiple times.
  169481. */
  169482. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169483. { if (bits_left < (nbits)) { \
  169484. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169485. { action; } \
  169486. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169487. #define GET_BITS(nbits) \
  169488. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169489. #define PEEK_BITS(nbits) \
  169490. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169491. #define DROP_BITS(nbits) \
  169492. (bits_left -= (nbits))
  169493. /* Load up the bit buffer to a depth of at least nbits */
  169494. EXTERN(boolean) jpeg_fill_bit_buffer
  169495. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169496. register int bits_left, int nbits));
  169497. /*
  169498. * Code for extracting next Huffman-coded symbol from input bit stream.
  169499. * Again, this is time-critical and we make the main paths be macros.
  169500. *
  169501. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169502. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169503. * or fewer bits long. The few overlength codes are handled with a loop,
  169504. * which need not be inline code.
  169505. *
  169506. * Notes about the HUFF_DECODE macro:
  169507. * 1. Near the end of the data segment, we may fail to get enough bits
  169508. * for a lookahead. In that case, we do it the hard way.
  169509. * 2. If the lookahead table contains no entry, the next code must be
  169510. * more than HUFF_LOOKAHEAD bits long.
  169511. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169512. */
  169513. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169514. { register int nb, look; \
  169515. if (bits_left < HUFF_LOOKAHEAD) { \
  169516. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169517. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169518. if (bits_left < HUFF_LOOKAHEAD) { \
  169519. nb = 1; goto slowlabel; \
  169520. } \
  169521. } \
  169522. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169523. if ((nb = htbl->look_nbits[look]) != 0) { \
  169524. DROP_BITS(nb); \
  169525. result = htbl->look_sym[look]; \
  169526. } else { \
  169527. nb = HUFF_LOOKAHEAD+1; \
  169528. slowlabel: \
  169529. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169530. { failaction; } \
  169531. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169532. } \
  169533. }
  169534. /* Out-of-line case for Huffman code fetching */
  169535. EXTERN(int) jpeg_huff_decode
  169536. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169537. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169538. #endif
  169539. /*** End of inlined file: jdhuff.h ***/
  169540. /* Declarations shared with jdphuff.c */
  169541. /*
  169542. * Expanded entropy decoder object for Huffman decoding.
  169543. *
  169544. * The savable_state subrecord contains fields that change within an MCU,
  169545. * but must not be updated permanently until we complete the MCU.
  169546. */
  169547. typedef struct {
  169548. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169549. } savable_state2;
  169550. /* This macro is to work around compilers with missing or broken
  169551. * structure assignment. You'll need to fix this code if you have
  169552. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169553. */
  169554. #ifndef NO_STRUCT_ASSIGN
  169555. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169556. #else
  169557. #if MAX_COMPS_IN_SCAN == 4
  169558. #define ASSIGN_STATE(dest,src) \
  169559. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169560. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169561. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169562. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169563. #endif
  169564. #endif
  169565. typedef struct {
  169566. struct jpeg_entropy_decoder pub; /* public fields */
  169567. /* These fields are loaded into local variables at start of each MCU.
  169568. * In case of suspension, we exit WITHOUT updating them.
  169569. */
  169570. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169571. savable_state2 saved; /* Other state at start of MCU */
  169572. /* These fields are NOT loaded into local working state. */
  169573. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169574. /* Pointers to derived tables (these workspaces have image lifespan) */
  169575. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169576. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169577. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169578. /* Pointers to derived tables to be used for each block within an MCU */
  169579. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169580. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169581. /* Whether we care about the DC and AC coefficient values for each block */
  169582. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169583. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169584. } huff_entropy_decoder2;
  169585. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169586. /*
  169587. * Initialize for a Huffman-compressed scan.
  169588. */
  169589. METHODDEF(void)
  169590. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169591. {
  169592. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169593. int ci, blkn, dctbl, actbl;
  169594. jpeg_component_info * compptr;
  169595. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169596. * This ought to be an error condition, but we make it a warning because
  169597. * there are some baseline files out there with all zeroes in these bytes.
  169598. */
  169599. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169600. cinfo->Ah != 0 || cinfo->Al != 0)
  169601. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169602. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169603. compptr = cinfo->cur_comp_info[ci];
  169604. dctbl = compptr->dc_tbl_no;
  169605. actbl = compptr->ac_tbl_no;
  169606. /* Compute derived values for Huffman tables */
  169607. /* We may do this more than once for a table, but it's not expensive */
  169608. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169609. & entropy->dc_derived_tbls[dctbl]);
  169610. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169611. & entropy->ac_derived_tbls[actbl]);
  169612. /* Initialize DC predictions to 0 */
  169613. entropy->saved.last_dc_val[ci] = 0;
  169614. }
  169615. /* Precalculate decoding info for each block in an MCU of this scan */
  169616. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169617. ci = cinfo->MCU_membership[blkn];
  169618. compptr = cinfo->cur_comp_info[ci];
  169619. /* Precalculate which table to use for each block */
  169620. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169621. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169622. /* Decide whether we really care about the coefficient values */
  169623. if (compptr->component_needed) {
  169624. entropy->dc_needed[blkn] = TRUE;
  169625. /* we don't need the ACs if producing a 1/8th-size image */
  169626. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169627. } else {
  169628. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169629. }
  169630. }
  169631. /* Initialize bitread state variables */
  169632. entropy->bitstate.bits_left = 0;
  169633. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169634. entropy->pub.insufficient_data = FALSE;
  169635. /* Initialize restart counter */
  169636. entropy->restarts_to_go = cinfo->restart_interval;
  169637. }
  169638. /*
  169639. * Compute the derived values for a Huffman table.
  169640. * This routine also performs some validation checks on the table.
  169641. *
  169642. * Note this is also used by jdphuff.c.
  169643. */
  169644. GLOBAL(void)
  169645. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169646. d_derived_tbl ** pdtbl)
  169647. {
  169648. JHUFF_TBL *htbl;
  169649. d_derived_tbl *dtbl;
  169650. int p, i, l, si, numsymbols;
  169651. int lookbits, ctr;
  169652. char huffsize[257];
  169653. unsigned int huffcode[257];
  169654. unsigned int code;
  169655. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169656. * paralleling the order of the symbols themselves in htbl->huffval[].
  169657. */
  169658. /* Find the input Huffman table */
  169659. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169660. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169661. htbl =
  169662. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169663. if (htbl == NULL)
  169664. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169665. /* Allocate a workspace if we haven't already done so. */
  169666. if (*pdtbl == NULL)
  169667. *pdtbl = (d_derived_tbl *)
  169668. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169669. SIZEOF(d_derived_tbl));
  169670. dtbl = *pdtbl;
  169671. dtbl->pub = htbl; /* fill in back link */
  169672. /* Figure C.1: make table of Huffman code length for each symbol */
  169673. p = 0;
  169674. for (l = 1; l <= 16; l++) {
  169675. i = (int) htbl->bits[l];
  169676. if (i < 0 || p + i > 256) /* protect against table overrun */
  169677. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169678. while (i--)
  169679. huffsize[p++] = (char) l;
  169680. }
  169681. huffsize[p] = 0;
  169682. numsymbols = p;
  169683. /* Figure C.2: generate the codes themselves */
  169684. /* We also validate that the counts represent a legal Huffman code tree. */
  169685. code = 0;
  169686. si = huffsize[0];
  169687. p = 0;
  169688. while (huffsize[p]) {
  169689. while (((int) huffsize[p]) == si) {
  169690. huffcode[p++] = code;
  169691. code++;
  169692. }
  169693. /* code is now 1 more than the last code used for codelength si; but
  169694. * it must still fit in si bits, since no code is allowed to be all ones.
  169695. */
  169696. if (((INT32) code) >= (((INT32) 1) << si))
  169697. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169698. code <<= 1;
  169699. si++;
  169700. }
  169701. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169702. p = 0;
  169703. for (l = 1; l <= 16; l++) {
  169704. if (htbl->bits[l]) {
  169705. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169706. * minus the minimum code of length l
  169707. */
  169708. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169709. p += htbl->bits[l];
  169710. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169711. } else {
  169712. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169713. }
  169714. }
  169715. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169716. /* Compute lookahead tables to speed up decoding.
  169717. * First we set all the table entries to 0, indicating "too long";
  169718. * then we iterate through the Huffman codes that are short enough and
  169719. * fill in all the entries that correspond to bit sequences starting
  169720. * with that code.
  169721. */
  169722. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169723. p = 0;
  169724. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169725. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169726. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169727. /* Generate left-justified code followed by all possible bit sequences */
  169728. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169729. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169730. dtbl->look_nbits[lookbits] = l;
  169731. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169732. lookbits++;
  169733. }
  169734. }
  169735. }
  169736. /* Validate symbols as being reasonable.
  169737. * For AC tables, we make no check, but accept all byte values 0..255.
  169738. * For DC tables, we require the symbols to be in range 0..15.
  169739. * (Tighter bounds could be applied depending on the data depth and mode,
  169740. * but this is sufficient to ensure safe decoding.)
  169741. */
  169742. if (isDC) {
  169743. for (i = 0; i < numsymbols; i++) {
  169744. int sym = htbl->huffval[i];
  169745. if (sym < 0 || sym > 15)
  169746. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169747. }
  169748. }
  169749. }
  169750. /*
  169751. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169752. * See jdhuff.h for info about usage.
  169753. * Note: current values of get_buffer and bits_left are passed as parameters,
  169754. * but are returned in the corresponding fields of the state struct.
  169755. *
  169756. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169757. * of get_buffer to be used. (On machines with wider words, an even larger
  169758. * buffer could be used.) However, on some machines 32-bit shifts are
  169759. * quite slow and take time proportional to the number of places shifted.
  169760. * (This is true with most PC compilers, for instance.) In this case it may
  169761. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169762. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169763. */
  169764. #ifdef SLOW_SHIFT_32
  169765. #define MIN_GET_BITS 15 /* minimum allowable value */
  169766. #else
  169767. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169768. #endif
  169769. GLOBAL(boolean)
  169770. jpeg_fill_bit_buffer (bitread_working_state * state,
  169771. register bit_buf_type get_buffer, register int bits_left,
  169772. int nbits)
  169773. /* Load up the bit buffer to a depth of at least nbits */
  169774. {
  169775. /* Copy heavily used state fields into locals (hopefully registers) */
  169776. register const JOCTET * next_input_byte = state->next_input_byte;
  169777. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169778. j_decompress_ptr cinfo = state->cinfo;
  169779. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169780. /* (It is assumed that no request will be for more than that many bits.) */
  169781. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169782. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169783. while (bits_left < MIN_GET_BITS) {
  169784. register int c;
  169785. /* Attempt to read a byte */
  169786. if (bytes_in_buffer == 0) {
  169787. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169788. return FALSE;
  169789. next_input_byte = cinfo->src->next_input_byte;
  169790. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169791. }
  169792. bytes_in_buffer--;
  169793. c = GETJOCTET(*next_input_byte++);
  169794. /* If it's 0xFF, check and discard stuffed zero byte */
  169795. if (c == 0xFF) {
  169796. /* Loop here to discard any padding FF's on terminating marker,
  169797. * so that we can save a valid unread_marker value. NOTE: we will
  169798. * accept multiple FF's followed by a 0 as meaning a single FF data
  169799. * byte. This data pattern is not valid according to the standard.
  169800. */
  169801. do {
  169802. if (bytes_in_buffer == 0) {
  169803. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169804. return FALSE;
  169805. next_input_byte = cinfo->src->next_input_byte;
  169806. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169807. }
  169808. bytes_in_buffer--;
  169809. c = GETJOCTET(*next_input_byte++);
  169810. } while (c == 0xFF);
  169811. if (c == 0) {
  169812. /* Found FF/00, which represents an FF data byte */
  169813. c = 0xFF;
  169814. } else {
  169815. /* Oops, it's actually a marker indicating end of compressed data.
  169816. * Save the marker code for later use.
  169817. * Fine point: it might appear that we should save the marker into
  169818. * bitread working state, not straight into permanent state. But
  169819. * once we have hit a marker, we cannot need to suspend within the
  169820. * current MCU, because we will read no more bytes from the data
  169821. * source. So it is OK to update permanent state right away.
  169822. */
  169823. cinfo->unread_marker = c;
  169824. /* See if we need to insert some fake zero bits. */
  169825. goto no_more_bytes;
  169826. }
  169827. }
  169828. /* OK, load c into get_buffer */
  169829. get_buffer = (get_buffer << 8) | c;
  169830. bits_left += 8;
  169831. } /* end while */
  169832. } else {
  169833. no_more_bytes:
  169834. /* We get here if we've read the marker that terminates the compressed
  169835. * data segment. There should be enough bits in the buffer register
  169836. * to satisfy the request; if so, no problem.
  169837. */
  169838. if (nbits > bits_left) {
  169839. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169840. * the data stream, so that we can produce some kind of image.
  169841. * We use a nonvolatile flag to ensure that only one warning message
  169842. * appears per data segment.
  169843. */
  169844. if (! cinfo->entropy->insufficient_data) {
  169845. WARNMS(cinfo, JWRN_HIT_MARKER);
  169846. cinfo->entropy->insufficient_data = TRUE;
  169847. }
  169848. /* Fill the buffer with zero bits */
  169849. get_buffer <<= MIN_GET_BITS - bits_left;
  169850. bits_left = MIN_GET_BITS;
  169851. }
  169852. }
  169853. /* Unload the local registers */
  169854. state->next_input_byte = next_input_byte;
  169855. state->bytes_in_buffer = bytes_in_buffer;
  169856. state->get_buffer = get_buffer;
  169857. state->bits_left = bits_left;
  169858. return TRUE;
  169859. }
  169860. /*
  169861. * Out-of-line code for Huffman code decoding.
  169862. * See jdhuff.h for info about usage.
  169863. */
  169864. GLOBAL(int)
  169865. jpeg_huff_decode (bitread_working_state * state,
  169866. register bit_buf_type get_buffer, register int bits_left,
  169867. d_derived_tbl * htbl, int min_bits)
  169868. {
  169869. register int l = min_bits;
  169870. register INT32 code;
  169871. /* HUFF_DECODE has determined that the code is at least min_bits */
  169872. /* bits long, so fetch that many bits in one swoop. */
  169873. CHECK_BIT_BUFFER(*state, l, return -1);
  169874. code = GET_BITS(l);
  169875. /* Collect the rest of the Huffman code one bit at a time. */
  169876. /* This is per Figure F.16 in the JPEG spec. */
  169877. while (code > htbl->maxcode[l]) {
  169878. code <<= 1;
  169879. CHECK_BIT_BUFFER(*state, 1, return -1);
  169880. code |= GET_BITS(1);
  169881. l++;
  169882. }
  169883. /* Unload the local registers */
  169884. state->get_buffer = get_buffer;
  169885. state->bits_left = bits_left;
  169886. /* With garbage input we may reach the sentinel value l = 17. */
  169887. if (l > 16) {
  169888. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169889. return 0; /* fake a zero as the safest result */
  169890. }
  169891. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169892. }
  169893. /*
  169894. * Check for a restart marker & resynchronize decoder.
  169895. * Returns FALSE if must suspend.
  169896. */
  169897. LOCAL(boolean)
  169898. process_restart (j_decompress_ptr cinfo)
  169899. {
  169900. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169901. int ci;
  169902. /* Throw away any unused bits remaining in bit buffer; */
  169903. /* include any full bytes in next_marker's count of discarded bytes */
  169904. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169905. entropy->bitstate.bits_left = 0;
  169906. /* Advance past the RSTn marker */
  169907. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169908. return FALSE;
  169909. /* Re-initialize DC predictions to 0 */
  169910. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169911. entropy->saved.last_dc_val[ci] = 0;
  169912. /* Reset restart counter */
  169913. entropy->restarts_to_go = cinfo->restart_interval;
  169914. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169915. * against a marker. In that case we will end up treating the next data
  169916. * segment as empty, and we can avoid producing bogus output pixels by
  169917. * leaving the flag set.
  169918. */
  169919. if (cinfo->unread_marker == 0)
  169920. entropy->pub.insufficient_data = FALSE;
  169921. return TRUE;
  169922. }
  169923. /*
  169924. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169925. * The coefficients are reordered from zigzag order into natural array order,
  169926. * but are not dequantized.
  169927. *
  169928. * The i'th block of the MCU is stored into the block pointed to by
  169929. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169930. * (Wholesale zeroing is usually a little faster than retail...)
  169931. *
  169932. * Returns FALSE if data source requested suspension. In that case no
  169933. * changes have been made to permanent state. (Exception: some output
  169934. * coefficients may already have been assigned. This is harmless for
  169935. * this module, since we'll just re-assign them on the next call.)
  169936. */
  169937. METHODDEF(boolean)
  169938. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169939. {
  169940. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169941. int blkn;
  169942. BITREAD_STATE_VARS;
  169943. savable_state2 state;
  169944. /* Process restart marker if needed; may have to suspend */
  169945. if (cinfo->restart_interval) {
  169946. if (entropy->restarts_to_go == 0)
  169947. if (! process_restart(cinfo))
  169948. return FALSE;
  169949. }
  169950. /* If we've run out of data, just leave the MCU set to zeroes.
  169951. * This way, we return uniform gray for the remainder of the segment.
  169952. */
  169953. if (! entropy->pub.insufficient_data) {
  169954. /* Load up working state */
  169955. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169956. ASSIGN_STATE(state, entropy->saved);
  169957. /* Outer loop handles each block in the MCU */
  169958. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169959. JBLOCKROW block = MCU_data[blkn];
  169960. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169961. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169962. register int s, k, r;
  169963. /* Decode a single block's worth of coefficients */
  169964. /* Section F.2.2.1: decode the DC coefficient difference */
  169965. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169966. if (s) {
  169967. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169968. r = GET_BITS(s);
  169969. s = HUFF_EXTEND(r, s);
  169970. }
  169971. if (entropy->dc_needed[blkn]) {
  169972. /* Convert DC difference to actual value, update last_dc_val */
  169973. int ci = cinfo->MCU_membership[blkn];
  169974. s += state.last_dc_val[ci];
  169975. state.last_dc_val[ci] = s;
  169976. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169977. (*block)[0] = (JCOEF) s;
  169978. }
  169979. if (entropy->ac_needed[blkn]) {
  169980. /* Section F.2.2.2: decode the AC coefficients */
  169981. /* Since zeroes are skipped, output area must be cleared beforehand */
  169982. for (k = 1; k < DCTSIZE2; k++) {
  169983. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169984. r = s >> 4;
  169985. s &= 15;
  169986. if (s) {
  169987. k += r;
  169988. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169989. r = GET_BITS(s);
  169990. s = HUFF_EXTEND(r, s);
  169991. /* Output coefficient in natural (dezigzagged) order.
  169992. * Note: the extra entries in jpeg_natural_order[] will save us
  169993. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169994. */
  169995. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169996. } else {
  169997. if (r != 15)
  169998. break;
  169999. k += 15;
  170000. }
  170001. }
  170002. } else {
  170003. /* Section F.2.2.2: decode the AC coefficients */
  170004. /* In this path we just discard the values */
  170005. for (k = 1; k < DCTSIZE2; k++) {
  170006. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170007. r = s >> 4;
  170008. s &= 15;
  170009. if (s) {
  170010. k += r;
  170011. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170012. DROP_BITS(s);
  170013. } else {
  170014. if (r != 15)
  170015. break;
  170016. k += 15;
  170017. }
  170018. }
  170019. }
  170020. }
  170021. /* Completed MCU, so update state */
  170022. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170023. ASSIGN_STATE(entropy->saved, state);
  170024. }
  170025. /* Account for restart interval (no-op if not using restarts) */
  170026. entropy->restarts_to_go--;
  170027. return TRUE;
  170028. }
  170029. /*
  170030. * Module initialization routine for Huffman entropy decoding.
  170031. */
  170032. GLOBAL(void)
  170033. jinit_huff_decoder (j_decompress_ptr cinfo)
  170034. {
  170035. huff_entropy_ptr2 entropy;
  170036. int i;
  170037. entropy = (huff_entropy_ptr2)
  170038. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170039. SIZEOF(huff_entropy_decoder2));
  170040. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170041. entropy->pub.start_pass = start_pass_huff_decoder;
  170042. entropy->pub.decode_mcu = decode_mcu;
  170043. /* Mark tables unallocated */
  170044. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170045. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170046. }
  170047. }
  170048. /*** End of inlined file: jdhuff.c ***/
  170049. /*** Start of inlined file: jdinput.c ***/
  170050. #define JPEG_INTERNALS
  170051. /* Private state */
  170052. typedef struct {
  170053. struct jpeg_input_controller pub; /* public fields */
  170054. boolean inheaders; /* TRUE until first SOS is reached */
  170055. } my_input_controller;
  170056. typedef my_input_controller * my_inputctl_ptr;
  170057. /* Forward declarations */
  170058. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170059. /*
  170060. * Routines to calculate various quantities related to the size of the image.
  170061. */
  170062. LOCAL(void)
  170063. initial_setup2 (j_decompress_ptr cinfo)
  170064. /* Called once, when first SOS marker is reached */
  170065. {
  170066. int ci;
  170067. jpeg_component_info *compptr;
  170068. /* Make sure image isn't bigger than I can handle */
  170069. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170070. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170071. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170072. /* For now, precision must match compiled-in value... */
  170073. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170074. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170075. /* Check that number of components won't exceed internal array sizes */
  170076. if (cinfo->num_components > MAX_COMPONENTS)
  170077. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170078. MAX_COMPONENTS);
  170079. /* Compute maximum sampling factors; check factor validity */
  170080. cinfo->max_h_samp_factor = 1;
  170081. cinfo->max_v_samp_factor = 1;
  170082. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170083. ci++, compptr++) {
  170084. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170085. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170086. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170087. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170088. compptr->h_samp_factor);
  170089. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170090. compptr->v_samp_factor);
  170091. }
  170092. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170093. * In the full decompressor, this will be overridden by jdmaster.c;
  170094. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170095. */
  170096. cinfo->min_DCT_scaled_size = DCTSIZE;
  170097. /* Compute dimensions of components */
  170098. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170099. ci++, compptr++) {
  170100. compptr->DCT_scaled_size = DCTSIZE;
  170101. /* Size in DCT blocks */
  170102. compptr->width_in_blocks = (JDIMENSION)
  170103. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170104. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170105. compptr->height_in_blocks = (JDIMENSION)
  170106. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170107. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170108. /* downsampled_width and downsampled_height will also be overridden by
  170109. * jdmaster.c if we are doing full decompression. The transcoder library
  170110. * doesn't use these values, but the calling application might.
  170111. */
  170112. /* Size in samples */
  170113. compptr->downsampled_width = (JDIMENSION)
  170114. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170115. (long) cinfo->max_h_samp_factor);
  170116. compptr->downsampled_height = (JDIMENSION)
  170117. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170118. (long) cinfo->max_v_samp_factor);
  170119. /* Mark component needed, until color conversion says otherwise */
  170120. compptr->component_needed = TRUE;
  170121. /* Mark no quantization table yet saved for component */
  170122. compptr->quant_table = NULL;
  170123. }
  170124. /* Compute number of fully interleaved MCU rows. */
  170125. cinfo->total_iMCU_rows = (JDIMENSION)
  170126. jdiv_round_up((long) cinfo->image_height,
  170127. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170128. /* Decide whether file contains multiple scans */
  170129. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170130. cinfo->inputctl->has_multiple_scans = TRUE;
  170131. else
  170132. cinfo->inputctl->has_multiple_scans = FALSE;
  170133. }
  170134. LOCAL(void)
  170135. per_scan_setup2 (j_decompress_ptr cinfo)
  170136. /* Do computations that are needed before processing a JPEG scan */
  170137. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170138. {
  170139. int ci, mcublks, tmp;
  170140. jpeg_component_info *compptr;
  170141. if (cinfo->comps_in_scan == 1) {
  170142. /* Noninterleaved (single-component) scan */
  170143. compptr = cinfo->cur_comp_info[0];
  170144. /* Overall image size in MCUs */
  170145. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170146. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170147. /* For noninterleaved scan, always one block per MCU */
  170148. compptr->MCU_width = 1;
  170149. compptr->MCU_height = 1;
  170150. compptr->MCU_blocks = 1;
  170151. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170152. compptr->last_col_width = 1;
  170153. /* For noninterleaved scans, it is convenient to define last_row_height
  170154. * as the number of block rows present in the last iMCU row.
  170155. */
  170156. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170157. if (tmp == 0) tmp = compptr->v_samp_factor;
  170158. compptr->last_row_height = tmp;
  170159. /* Prepare array describing MCU composition */
  170160. cinfo->blocks_in_MCU = 1;
  170161. cinfo->MCU_membership[0] = 0;
  170162. } else {
  170163. /* Interleaved (multi-component) scan */
  170164. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170165. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170166. MAX_COMPS_IN_SCAN);
  170167. /* Overall image size in MCUs */
  170168. cinfo->MCUs_per_row = (JDIMENSION)
  170169. jdiv_round_up((long) cinfo->image_width,
  170170. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170171. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170172. jdiv_round_up((long) cinfo->image_height,
  170173. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170174. cinfo->blocks_in_MCU = 0;
  170175. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170176. compptr = cinfo->cur_comp_info[ci];
  170177. /* Sampling factors give # of blocks of component in each MCU */
  170178. compptr->MCU_width = compptr->h_samp_factor;
  170179. compptr->MCU_height = compptr->v_samp_factor;
  170180. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170181. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170182. /* Figure number of non-dummy blocks in last MCU column & row */
  170183. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170184. if (tmp == 0) tmp = compptr->MCU_width;
  170185. compptr->last_col_width = tmp;
  170186. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170187. if (tmp == 0) tmp = compptr->MCU_height;
  170188. compptr->last_row_height = tmp;
  170189. /* Prepare array describing MCU composition */
  170190. mcublks = compptr->MCU_blocks;
  170191. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170192. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170193. while (mcublks-- > 0) {
  170194. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170195. }
  170196. }
  170197. }
  170198. }
  170199. /*
  170200. * Save away a copy of the Q-table referenced by each component present
  170201. * in the current scan, unless already saved during a prior scan.
  170202. *
  170203. * In a multiple-scan JPEG file, the encoder could assign different components
  170204. * the same Q-table slot number, but change table definitions between scans
  170205. * so that each component uses a different Q-table. (The IJG encoder is not
  170206. * currently capable of doing this, but other encoders might.) Since we want
  170207. * to be able to dequantize all the components at the end of the file, this
  170208. * means that we have to save away the table actually used for each component.
  170209. * We do this by copying the table at the start of the first scan containing
  170210. * the component.
  170211. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170212. * slot between scans of a component using that slot. If the encoder does so
  170213. * anyway, this decoder will simply use the Q-table values that were current
  170214. * at the start of the first scan for the component.
  170215. *
  170216. * The decompressor output side looks only at the saved quant tables,
  170217. * not at the current Q-table slots.
  170218. */
  170219. LOCAL(void)
  170220. latch_quant_tables (j_decompress_ptr cinfo)
  170221. {
  170222. int ci, qtblno;
  170223. jpeg_component_info *compptr;
  170224. JQUANT_TBL * qtbl;
  170225. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170226. compptr = cinfo->cur_comp_info[ci];
  170227. /* No work if we already saved Q-table for this component */
  170228. if (compptr->quant_table != NULL)
  170229. continue;
  170230. /* Make sure specified quantization table is present */
  170231. qtblno = compptr->quant_tbl_no;
  170232. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170233. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170234. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170235. /* OK, save away the quantization table */
  170236. qtbl = (JQUANT_TBL *)
  170237. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170238. SIZEOF(JQUANT_TBL));
  170239. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170240. compptr->quant_table = qtbl;
  170241. }
  170242. }
  170243. /*
  170244. * Initialize the input modules to read a scan of compressed data.
  170245. * The first call to this is done by jdmaster.c after initializing
  170246. * the entire decompressor (during jpeg_start_decompress).
  170247. * Subsequent calls come from consume_markers, below.
  170248. */
  170249. METHODDEF(void)
  170250. start_input_pass2 (j_decompress_ptr cinfo)
  170251. {
  170252. per_scan_setup2(cinfo);
  170253. latch_quant_tables(cinfo);
  170254. (*cinfo->entropy->start_pass) (cinfo);
  170255. (*cinfo->coef->start_input_pass) (cinfo);
  170256. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170257. }
  170258. /*
  170259. * Finish up after inputting a compressed-data scan.
  170260. * This is called by the coefficient controller after it's read all
  170261. * the expected data of the scan.
  170262. */
  170263. METHODDEF(void)
  170264. finish_input_pass (j_decompress_ptr cinfo)
  170265. {
  170266. cinfo->inputctl->consume_input = consume_markers;
  170267. }
  170268. /*
  170269. * Read JPEG markers before, between, or after compressed-data scans.
  170270. * Change state as necessary when a new scan is reached.
  170271. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170272. *
  170273. * The consume_input method pointer points either here or to the
  170274. * coefficient controller's consume_data routine, depending on whether
  170275. * we are reading a compressed data segment or inter-segment markers.
  170276. */
  170277. METHODDEF(int)
  170278. consume_markers (j_decompress_ptr cinfo)
  170279. {
  170280. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170281. int val;
  170282. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170283. return JPEG_REACHED_EOI;
  170284. val = (*cinfo->marker->read_markers) (cinfo);
  170285. switch (val) {
  170286. case JPEG_REACHED_SOS: /* Found SOS */
  170287. if (inputctl->inheaders) { /* 1st SOS */
  170288. initial_setup2(cinfo);
  170289. inputctl->inheaders = FALSE;
  170290. /* Note: start_input_pass must be called by jdmaster.c
  170291. * before any more input can be consumed. jdapimin.c is
  170292. * responsible for enforcing this sequencing.
  170293. */
  170294. } else { /* 2nd or later SOS marker */
  170295. if (! inputctl->pub.has_multiple_scans)
  170296. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170297. start_input_pass2(cinfo);
  170298. }
  170299. break;
  170300. case JPEG_REACHED_EOI: /* Found EOI */
  170301. inputctl->pub.eoi_reached = TRUE;
  170302. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170303. if (cinfo->marker->saw_SOF)
  170304. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170305. } else {
  170306. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170307. * if user set output_scan_number larger than number of scans.
  170308. */
  170309. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170310. cinfo->output_scan_number = cinfo->input_scan_number;
  170311. }
  170312. break;
  170313. case JPEG_SUSPENDED:
  170314. break;
  170315. }
  170316. return val;
  170317. }
  170318. /*
  170319. * Reset state to begin a fresh datastream.
  170320. */
  170321. METHODDEF(void)
  170322. reset_input_controller (j_decompress_ptr cinfo)
  170323. {
  170324. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170325. inputctl->pub.consume_input = consume_markers;
  170326. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170327. inputctl->pub.eoi_reached = FALSE;
  170328. inputctl->inheaders = TRUE;
  170329. /* Reset other modules */
  170330. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170331. (*cinfo->marker->reset_marker_reader) (cinfo);
  170332. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170333. cinfo->coef_bits = NULL;
  170334. }
  170335. /*
  170336. * Initialize the input controller module.
  170337. * This is called only once, when the decompression object is created.
  170338. */
  170339. GLOBAL(void)
  170340. jinit_input_controller (j_decompress_ptr cinfo)
  170341. {
  170342. my_inputctl_ptr inputctl;
  170343. /* Create subobject in permanent pool */
  170344. inputctl = (my_inputctl_ptr)
  170345. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170346. SIZEOF(my_input_controller));
  170347. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170348. /* Initialize method pointers */
  170349. inputctl->pub.consume_input = consume_markers;
  170350. inputctl->pub.reset_input_controller = reset_input_controller;
  170351. inputctl->pub.start_input_pass = start_input_pass2;
  170352. inputctl->pub.finish_input_pass = finish_input_pass;
  170353. /* Initialize state: can't use reset_input_controller since we don't
  170354. * want to try to reset other modules yet.
  170355. */
  170356. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170357. inputctl->pub.eoi_reached = FALSE;
  170358. inputctl->inheaders = TRUE;
  170359. }
  170360. /*** End of inlined file: jdinput.c ***/
  170361. /*** Start of inlined file: jdmainct.c ***/
  170362. #define JPEG_INTERNALS
  170363. /*
  170364. * In the current system design, the main buffer need never be a full-image
  170365. * buffer; any full-height buffers will be found inside the coefficient or
  170366. * postprocessing controllers. Nonetheless, the main controller is not
  170367. * trivial. Its responsibility is to provide context rows for upsampling/
  170368. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170369. *
  170370. * Postprocessor input data is counted in "row groups". A row group
  170371. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170372. * sample rows of each component. (We require DCT_scaled_size values to be
  170373. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170374. * values will likely be powers of two, so we actually have the stronger
  170375. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170376. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170377. * row group (times any additional scale factor that the upsampler is
  170378. * applying).
  170379. *
  170380. * The coefficient controller will deliver data to us one iMCU row at a time;
  170381. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170382. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170383. * to one row of MCUs when the image is fully interleaved.) Note that the
  170384. * number of sample rows varies across components, but the number of row
  170385. * groups does not. Some garbage sample rows may be included in the last iMCU
  170386. * row at the bottom of the image.
  170387. *
  170388. * Depending on the vertical scaling algorithm used, the upsampler may need
  170389. * access to the sample row(s) above and below its current input row group.
  170390. * The upsampler is required to set need_context_rows TRUE at global selection
  170391. * time if so. When need_context_rows is FALSE, this controller can simply
  170392. * obtain one iMCU row at a time from the coefficient controller and dole it
  170393. * out as row groups to the postprocessor.
  170394. *
  170395. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170396. * passed to postprocessing contains at least one row group's worth of samples
  170397. * above and below the row group(s) being processed. Note that the context
  170398. * rows "above" the first passed row group appear at negative row offsets in
  170399. * the passed buffer. At the top and bottom of the image, the required
  170400. * context rows are manufactured by duplicating the first or last real sample
  170401. * row; this avoids having special cases in the upsampling inner loops.
  170402. *
  170403. * The amount of context is fixed at one row group just because that's a
  170404. * convenient number for this controller to work with. The existing
  170405. * upsamplers really only need one sample row of context. An upsampler
  170406. * supporting arbitrary output rescaling might wish for more than one row
  170407. * group of context when shrinking the image; tough, we don't handle that.
  170408. * (This is justified by the assumption that downsizing will be handled mostly
  170409. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170410. * the upsample step needn't be much less than one.)
  170411. *
  170412. * To provide the desired context, we have to retain the last two row groups
  170413. * of one iMCU row while reading in the next iMCU row. (The last row group
  170414. * can't be processed until we have another row group for its below-context,
  170415. * and so we have to save the next-to-last group too for its above-context.)
  170416. * We could do this most simply by copying data around in our buffer, but
  170417. * that'd be very slow. We can avoid copying any data by creating a rather
  170418. * strange pointer structure. Here's how it works. We allocate a workspace
  170419. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170420. * of row groups per iMCU row). We create two sets of redundant pointers to
  170421. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170422. * pointer lists look like this:
  170423. * M+1 M-1
  170424. * master pointer --> 0 master pointer --> 0
  170425. * 1 1
  170426. * ... ...
  170427. * M-3 M-3
  170428. * M-2 M
  170429. * M-1 M+1
  170430. * M M-2
  170431. * M+1 M-1
  170432. * 0 0
  170433. * We read alternate iMCU rows using each master pointer; thus the last two
  170434. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170435. * The pointer lists are set up so that the required context rows appear to
  170436. * be adjacent to the proper places when we pass the pointer lists to the
  170437. * upsampler.
  170438. *
  170439. * The above pictures describe the normal state of the pointer lists.
  170440. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170441. * the first or last sample row as necessary (this is cheaper than copying
  170442. * sample rows around).
  170443. *
  170444. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170445. * situation each iMCU row provides only one row group so the buffering logic
  170446. * must be different (eg, we must read two iMCU rows before we can emit the
  170447. * first row group). For now, we simply do not support providing context
  170448. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170449. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170450. * want it quick and dirty, so a context-free upsampler is sufficient.
  170451. */
  170452. /* Private buffer controller object */
  170453. typedef struct {
  170454. struct jpeg_d_main_controller pub; /* public fields */
  170455. /* Pointer to allocated workspace (M or M+2 row groups). */
  170456. JSAMPARRAY buffer[MAX_COMPONENTS];
  170457. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170458. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170459. /* Remaining fields are only used in the context case. */
  170460. /* These are the master pointers to the funny-order pointer lists. */
  170461. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170462. int whichptr; /* indicates which pointer set is now in use */
  170463. int context_state; /* process_data state machine status */
  170464. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170465. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170466. } my_main_controller4;
  170467. typedef my_main_controller4 * my_main_ptr4;
  170468. /* context_state values: */
  170469. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170470. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170471. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170472. /* Forward declarations */
  170473. METHODDEF(void) process_data_simple_main2
  170474. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170475. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170476. METHODDEF(void) process_data_context_main
  170477. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170478. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170479. #ifdef QUANT_2PASS_SUPPORTED
  170480. METHODDEF(void) process_data_crank_post
  170481. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170482. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170483. #endif
  170484. LOCAL(void)
  170485. alloc_funny_pointers (j_decompress_ptr cinfo)
  170486. /* Allocate space for the funny pointer lists.
  170487. * This is done only once, not once per pass.
  170488. */
  170489. {
  170490. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170491. int ci, rgroup;
  170492. int M = cinfo->min_DCT_scaled_size;
  170493. jpeg_component_info *compptr;
  170494. JSAMPARRAY xbuf;
  170495. /* Get top-level space for component array pointers.
  170496. * We alloc both arrays with one call to save a few cycles.
  170497. */
  170498. main_->xbuffer[0] = (JSAMPIMAGE)
  170499. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170500. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170501. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170502. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170503. ci++, compptr++) {
  170504. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170505. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170506. /* Get space for pointer lists --- M+4 row groups in each list.
  170507. * We alloc both pointer lists with one call to save a few cycles.
  170508. */
  170509. xbuf = (JSAMPARRAY)
  170510. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170511. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170512. xbuf += rgroup; /* want one row group at negative offsets */
  170513. main_->xbuffer[0][ci] = xbuf;
  170514. xbuf += rgroup * (M + 4);
  170515. main_->xbuffer[1][ci] = xbuf;
  170516. }
  170517. }
  170518. LOCAL(void)
  170519. make_funny_pointers (j_decompress_ptr cinfo)
  170520. /* Create the funny pointer lists discussed in the comments above.
  170521. * The actual workspace is already allocated (in main->buffer),
  170522. * and the space for the pointer lists is allocated too.
  170523. * This routine just fills in the curiously ordered lists.
  170524. * This will be repeated at the beginning of each pass.
  170525. */
  170526. {
  170527. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170528. int ci, i, rgroup;
  170529. int M = cinfo->min_DCT_scaled_size;
  170530. jpeg_component_info *compptr;
  170531. JSAMPARRAY buf, xbuf0, xbuf1;
  170532. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170533. ci++, compptr++) {
  170534. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170535. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170536. xbuf0 = main_->xbuffer[0][ci];
  170537. xbuf1 = main_->xbuffer[1][ci];
  170538. /* First copy the workspace pointers as-is */
  170539. buf = main_->buffer[ci];
  170540. for (i = 0; i < rgroup * (M + 2); i++) {
  170541. xbuf0[i] = xbuf1[i] = buf[i];
  170542. }
  170543. /* In the second list, put the last four row groups in swapped order */
  170544. for (i = 0; i < rgroup * 2; i++) {
  170545. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170546. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170547. }
  170548. /* The wraparound pointers at top and bottom will be filled later
  170549. * (see set_wraparound_pointers, below). Initially we want the "above"
  170550. * pointers to duplicate the first actual data line. This only needs
  170551. * to happen in xbuffer[0].
  170552. */
  170553. for (i = 0; i < rgroup; i++) {
  170554. xbuf0[i - rgroup] = xbuf0[0];
  170555. }
  170556. }
  170557. }
  170558. LOCAL(void)
  170559. set_wraparound_pointers (j_decompress_ptr cinfo)
  170560. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170561. * This changes the pointer list state from top-of-image to the normal state.
  170562. */
  170563. {
  170564. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170565. int ci, i, rgroup;
  170566. int M = cinfo->min_DCT_scaled_size;
  170567. jpeg_component_info *compptr;
  170568. JSAMPARRAY xbuf0, xbuf1;
  170569. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170570. ci++, compptr++) {
  170571. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170572. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170573. xbuf0 = main_->xbuffer[0][ci];
  170574. xbuf1 = main_->xbuffer[1][ci];
  170575. for (i = 0; i < rgroup; i++) {
  170576. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170577. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170578. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170579. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170580. }
  170581. }
  170582. }
  170583. LOCAL(void)
  170584. set_bottom_pointers (j_decompress_ptr cinfo)
  170585. /* Change the pointer lists to duplicate the last sample row at the bottom
  170586. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170587. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170588. */
  170589. {
  170590. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170591. int ci, i, rgroup, iMCUheight, rows_left;
  170592. jpeg_component_info *compptr;
  170593. JSAMPARRAY xbuf;
  170594. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170595. ci++, compptr++) {
  170596. /* Count sample rows in one iMCU row and in one row group */
  170597. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170598. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170599. /* Count nondummy sample rows remaining for this component */
  170600. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170601. if (rows_left == 0) rows_left = iMCUheight;
  170602. /* Count nondummy row groups. Should get same answer for each component,
  170603. * so we need only do it once.
  170604. */
  170605. if (ci == 0) {
  170606. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170607. }
  170608. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170609. * last partial rowgroup and ensures at least one full rowgroup of context.
  170610. */
  170611. xbuf = main_->xbuffer[main_->whichptr][ci];
  170612. for (i = 0; i < rgroup * 2; i++) {
  170613. xbuf[rows_left + i] = xbuf[rows_left-1];
  170614. }
  170615. }
  170616. }
  170617. /*
  170618. * Initialize for a processing pass.
  170619. */
  170620. METHODDEF(void)
  170621. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170622. {
  170623. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170624. switch (pass_mode) {
  170625. case JBUF_PASS_THRU:
  170626. if (cinfo->upsample->need_context_rows) {
  170627. main_->pub.process_data = process_data_context_main;
  170628. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170629. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170630. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170631. main_->iMCU_row_ctr = 0;
  170632. } else {
  170633. /* Simple case with no context needed */
  170634. main_->pub.process_data = process_data_simple_main2;
  170635. }
  170636. main_->buffer_full = FALSE; /* Mark buffer empty */
  170637. main_->rowgroup_ctr = 0;
  170638. break;
  170639. #ifdef QUANT_2PASS_SUPPORTED
  170640. case JBUF_CRANK_DEST:
  170641. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170642. main_->pub.process_data = process_data_crank_post;
  170643. break;
  170644. #endif
  170645. default:
  170646. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170647. break;
  170648. }
  170649. }
  170650. /*
  170651. * Process some data.
  170652. * This handles the simple case where no context is required.
  170653. */
  170654. METHODDEF(void)
  170655. process_data_simple_main2 (j_decompress_ptr cinfo,
  170656. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170657. JDIMENSION out_rows_avail)
  170658. {
  170659. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170660. JDIMENSION rowgroups_avail;
  170661. /* Read input data if we haven't filled the main buffer yet */
  170662. if (! main_->buffer_full) {
  170663. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170664. return; /* suspension forced, can do nothing more */
  170665. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170666. }
  170667. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170668. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170669. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170670. * to the postprocessor. The postprocessor has to check for bottom
  170671. * of image anyway (at row resolution), so no point in us doing it too.
  170672. */
  170673. /* Feed the postprocessor */
  170674. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170675. &main_->rowgroup_ctr, rowgroups_avail,
  170676. output_buf, out_row_ctr, out_rows_avail);
  170677. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170678. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170679. main_->buffer_full = FALSE;
  170680. main_->rowgroup_ctr = 0;
  170681. }
  170682. }
  170683. /*
  170684. * Process some data.
  170685. * This handles the case where context rows must be provided.
  170686. */
  170687. METHODDEF(void)
  170688. process_data_context_main (j_decompress_ptr cinfo,
  170689. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170690. JDIMENSION out_rows_avail)
  170691. {
  170692. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170693. /* Read input data if we haven't filled the main buffer yet */
  170694. if (! main_->buffer_full) {
  170695. if (! (*cinfo->coef->decompress_data) (cinfo,
  170696. main_->xbuffer[main_->whichptr]))
  170697. return; /* suspension forced, can do nothing more */
  170698. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170699. main_->iMCU_row_ctr++; /* count rows received */
  170700. }
  170701. /* Postprocessor typically will not swallow all the input data it is handed
  170702. * in one call (due to filling the output buffer first). Must be prepared
  170703. * to exit and restart. This switch lets us keep track of how far we got.
  170704. * Note that each case falls through to the next on successful completion.
  170705. */
  170706. switch (main_->context_state) {
  170707. case CTX_POSTPONED_ROW:
  170708. /* Call postprocessor using previously set pointers for postponed row */
  170709. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170710. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170711. output_buf, out_row_ctr, out_rows_avail);
  170712. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170713. return; /* Need to suspend */
  170714. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170715. if (*out_row_ctr >= out_rows_avail)
  170716. return; /* Postprocessor exactly filled output buf */
  170717. /*FALLTHROUGH*/
  170718. case CTX_PREPARE_FOR_IMCU:
  170719. /* Prepare to process first M-1 row groups of this iMCU row */
  170720. main_->rowgroup_ctr = 0;
  170721. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170722. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170723. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170724. */
  170725. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170726. set_bottom_pointers(cinfo);
  170727. main_->context_state = CTX_PROCESS_IMCU;
  170728. /*FALLTHROUGH*/
  170729. case CTX_PROCESS_IMCU:
  170730. /* Call postprocessor using previously set pointers */
  170731. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170732. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170733. output_buf, out_row_ctr, out_rows_avail);
  170734. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170735. return; /* Need to suspend */
  170736. /* After the first iMCU, change wraparound pointers to normal state */
  170737. if (main_->iMCU_row_ctr == 1)
  170738. set_wraparound_pointers(cinfo);
  170739. /* Prepare to load new iMCU row using other xbuffer list */
  170740. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170741. main_->buffer_full = FALSE;
  170742. /* Still need to process last row group of this iMCU row, */
  170743. /* which is saved at index M+1 of the other xbuffer */
  170744. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170745. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170746. main_->context_state = CTX_POSTPONED_ROW;
  170747. }
  170748. }
  170749. /*
  170750. * Process some data.
  170751. * Final pass of two-pass quantization: just call the postprocessor.
  170752. * Source data will be the postprocessor controller's internal buffer.
  170753. */
  170754. #ifdef QUANT_2PASS_SUPPORTED
  170755. METHODDEF(void)
  170756. process_data_crank_post (j_decompress_ptr cinfo,
  170757. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170758. JDIMENSION out_rows_avail)
  170759. {
  170760. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170761. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170762. output_buf, out_row_ctr, out_rows_avail);
  170763. }
  170764. #endif /* QUANT_2PASS_SUPPORTED */
  170765. /*
  170766. * Initialize main buffer controller.
  170767. */
  170768. GLOBAL(void)
  170769. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170770. {
  170771. my_main_ptr4 main_;
  170772. int ci, rgroup, ngroups;
  170773. jpeg_component_info *compptr;
  170774. main_ = (my_main_ptr4)
  170775. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170776. SIZEOF(my_main_controller4));
  170777. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170778. main_->pub.start_pass = start_pass_main2;
  170779. if (need_full_buffer) /* shouldn't happen */
  170780. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170781. /* Allocate the workspace.
  170782. * ngroups is the number of row groups we need.
  170783. */
  170784. if (cinfo->upsample->need_context_rows) {
  170785. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170786. ERREXIT(cinfo, JERR_NOTIMPL);
  170787. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170788. ngroups = cinfo->min_DCT_scaled_size + 2;
  170789. } else {
  170790. ngroups = cinfo->min_DCT_scaled_size;
  170791. }
  170792. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170793. ci++, compptr++) {
  170794. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170795. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170796. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170797. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170798. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170799. (JDIMENSION) (rgroup * ngroups));
  170800. }
  170801. }
  170802. /*** End of inlined file: jdmainct.c ***/
  170803. /*** Start of inlined file: jdmarker.c ***/
  170804. #define JPEG_INTERNALS
  170805. /* Private state */
  170806. typedef struct {
  170807. struct jpeg_marker_reader pub; /* public fields */
  170808. /* Application-overridable marker processing methods */
  170809. jpeg_marker_parser_method process_COM;
  170810. jpeg_marker_parser_method process_APPn[16];
  170811. /* Limit on marker data length to save for each marker type */
  170812. unsigned int length_limit_COM;
  170813. unsigned int length_limit_APPn[16];
  170814. /* Status of COM/APPn marker saving */
  170815. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170816. unsigned int bytes_read; /* data bytes read so far in marker */
  170817. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170818. } my_marker_reader;
  170819. typedef my_marker_reader * my_marker_ptr2;
  170820. /*
  170821. * Macros for fetching data from the data source module.
  170822. *
  170823. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170824. * the current restart point; we update them only when we have reached a
  170825. * suitable place to restart if a suspension occurs.
  170826. */
  170827. /* Declare and initialize local copies of input pointer/count */
  170828. #define INPUT_VARS(cinfo) \
  170829. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170830. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170831. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170832. /* Unload the local copies --- do this only at a restart boundary */
  170833. #define INPUT_SYNC(cinfo) \
  170834. ( datasrc->next_input_byte = next_input_byte, \
  170835. datasrc->bytes_in_buffer = bytes_in_buffer )
  170836. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170837. #define INPUT_RELOAD(cinfo) \
  170838. ( next_input_byte = datasrc->next_input_byte, \
  170839. bytes_in_buffer = datasrc->bytes_in_buffer )
  170840. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170841. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170842. * but we must reload the local copies after a successful fill.
  170843. */
  170844. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170845. if (bytes_in_buffer == 0) { \
  170846. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170847. { action; } \
  170848. INPUT_RELOAD(cinfo); \
  170849. }
  170850. /* Read a byte into variable V.
  170851. * If must suspend, take the specified action (typically "return FALSE").
  170852. */
  170853. #define INPUT_BYTE(cinfo,V,action) \
  170854. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170855. bytes_in_buffer--; \
  170856. V = GETJOCTET(*next_input_byte++); )
  170857. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170858. * V should be declared unsigned int or perhaps INT32.
  170859. */
  170860. #define INPUT_2BYTES(cinfo,V,action) \
  170861. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170862. bytes_in_buffer--; \
  170863. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170864. MAKE_BYTE_AVAIL(cinfo,action); \
  170865. bytes_in_buffer--; \
  170866. V += GETJOCTET(*next_input_byte++); )
  170867. /*
  170868. * Routines to process JPEG markers.
  170869. *
  170870. * Entry condition: JPEG marker itself has been read and its code saved
  170871. * in cinfo->unread_marker; input restart point is just after the marker.
  170872. *
  170873. * Exit: if return TRUE, have read and processed any parameters, and have
  170874. * updated the restart point to point after the parameters.
  170875. * If return FALSE, was forced to suspend before reaching end of
  170876. * marker parameters; restart point has not been moved. Same routine
  170877. * will be called again after application supplies more input data.
  170878. *
  170879. * This approach to suspension assumes that all of a marker's parameters
  170880. * can fit into a single input bufferload. This should hold for "normal"
  170881. * markers. Some COM/APPn markers might have large parameter segments
  170882. * that might not fit. If we are simply dropping such a marker, we use
  170883. * skip_input_data to get past it, and thereby put the problem on the
  170884. * source manager's shoulders. If we are saving the marker's contents
  170885. * into memory, we use a slightly different convention: when forced to
  170886. * suspend, the marker processor updates the restart point to the end of
  170887. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170888. * On resumption, cinfo->unread_marker still contains the marker code,
  170889. * but the data source will point to the next chunk of marker data.
  170890. * The marker processor must retain internal state to deal with this.
  170891. *
  170892. * Note that we don't bother to avoid duplicate trace messages if a
  170893. * suspension occurs within marker parameters. Other side effects
  170894. * require more care.
  170895. */
  170896. LOCAL(boolean)
  170897. get_soi (j_decompress_ptr cinfo)
  170898. /* Process an SOI marker */
  170899. {
  170900. int i;
  170901. TRACEMS(cinfo, 1, JTRC_SOI);
  170902. if (cinfo->marker->saw_SOI)
  170903. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170904. /* Reset all parameters that are defined to be reset by SOI */
  170905. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170906. cinfo->arith_dc_L[i] = 0;
  170907. cinfo->arith_dc_U[i] = 1;
  170908. cinfo->arith_ac_K[i] = 5;
  170909. }
  170910. cinfo->restart_interval = 0;
  170911. /* Set initial assumptions for colorspace etc */
  170912. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170913. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170914. cinfo->saw_JFIF_marker = FALSE;
  170915. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170916. cinfo->JFIF_minor_version = 1;
  170917. cinfo->density_unit = 0;
  170918. cinfo->X_density = 1;
  170919. cinfo->Y_density = 1;
  170920. cinfo->saw_Adobe_marker = FALSE;
  170921. cinfo->Adobe_transform = 0;
  170922. cinfo->marker->saw_SOI = TRUE;
  170923. return TRUE;
  170924. }
  170925. LOCAL(boolean)
  170926. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170927. /* Process a SOFn marker */
  170928. {
  170929. INT32 length;
  170930. int c, ci;
  170931. jpeg_component_info * compptr;
  170932. INPUT_VARS(cinfo);
  170933. cinfo->progressive_mode = is_prog;
  170934. cinfo->arith_code = is_arith;
  170935. INPUT_2BYTES(cinfo, length, return FALSE);
  170936. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170937. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170938. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170939. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170940. length -= 8;
  170941. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170942. (int) cinfo->image_width, (int) cinfo->image_height,
  170943. cinfo->num_components);
  170944. if (cinfo->marker->saw_SOF)
  170945. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170946. /* We don't support files in which the image height is initially specified */
  170947. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170948. /* might as well have a general sanity check. */
  170949. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170950. || cinfo->num_components <= 0)
  170951. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170952. if (length != (cinfo->num_components * 3))
  170953. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170954. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170955. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170956. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170957. cinfo->num_components * SIZEOF(jpeg_component_info));
  170958. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170959. ci++, compptr++) {
  170960. compptr->component_index = ci;
  170961. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170962. INPUT_BYTE(cinfo, c, return FALSE);
  170963. compptr->h_samp_factor = (c >> 4) & 15;
  170964. compptr->v_samp_factor = (c ) & 15;
  170965. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170966. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170967. compptr->component_id, compptr->h_samp_factor,
  170968. compptr->v_samp_factor, compptr->quant_tbl_no);
  170969. }
  170970. cinfo->marker->saw_SOF = TRUE;
  170971. INPUT_SYNC(cinfo);
  170972. return TRUE;
  170973. }
  170974. LOCAL(boolean)
  170975. get_sos (j_decompress_ptr cinfo)
  170976. /* Process a SOS marker */
  170977. {
  170978. INT32 length;
  170979. int i, ci, n, c, cc;
  170980. jpeg_component_info * compptr;
  170981. INPUT_VARS(cinfo);
  170982. if (! cinfo->marker->saw_SOF)
  170983. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170984. INPUT_2BYTES(cinfo, length, return FALSE);
  170985. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170986. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170987. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170988. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170989. cinfo->comps_in_scan = n;
  170990. /* Collect the component-spec parameters */
  170991. for (i = 0; i < n; i++) {
  170992. INPUT_BYTE(cinfo, cc, return FALSE);
  170993. INPUT_BYTE(cinfo, c, return FALSE);
  170994. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170995. ci++, compptr++) {
  170996. if (cc == compptr->component_id)
  170997. goto id_found;
  170998. }
  170999. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171000. id_found:
  171001. cinfo->cur_comp_info[i] = compptr;
  171002. compptr->dc_tbl_no = (c >> 4) & 15;
  171003. compptr->ac_tbl_no = (c ) & 15;
  171004. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171005. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171006. }
  171007. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171008. INPUT_BYTE(cinfo, c, return FALSE);
  171009. cinfo->Ss = c;
  171010. INPUT_BYTE(cinfo, c, return FALSE);
  171011. cinfo->Se = c;
  171012. INPUT_BYTE(cinfo, c, return FALSE);
  171013. cinfo->Ah = (c >> 4) & 15;
  171014. cinfo->Al = (c ) & 15;
  171015. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171016. cinfo->Ah, cinfo->Al);
  171017. /* Prepare to scan data & restart markers */
  171018. cinfo->marker->next_restart_num = 0;
  171019. /* Count another SOS marker */
  171020. cinfo->input_scan_number++;
  171021. INPUT_SYNC(cinfo);
  171022. return TRUE;
  171023. }
  171024. #ifdef D_ARITH_CODING_SUPPORTED
  171025. LOCAL(boolean)
  171026. get_dac (j_decompress_ptr cinfo)
  171027. /* Process a DAC marker */
  171028. {
  171029. INT32 length;
  171030. int index, val;
  171031. INPUT_VARS(cinfo);
  171032. INPUT_2BYTES(cinfo, length, return FALSE);
  171033. length -= 2;
  171034. while (length > 0) {
  171035. INPUT_BYTE(cinfo, index, return FALSE);
  171036. INPUT_BYTE(cinfo, val, return FALSE);
  171037. length -= 2;
  171038. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171039. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171040. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171041. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171042. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171043. } else { /* define DC table */
  171044. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171045. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171046. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171047. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171048. }
  171049. }
  171050. if (length != 0)
  171051. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171052. INPUT_SYNC(cinfo);
  171053. return TRUE;
  171054. }
  171055. #else /* ! D_ARITH_CODING_SUPPORTED */
  171056. #define get_dac(cinfo) skip_variable(cinfo)
  171057. #endif /* D_ARITH_CODING_SUPPORTED */
  171058. LOCAL(boolean)
  171059. get_dht (j_decompress_ptr cinfo)
  171060. /* Process a DHT marker */
  171061. {
  171062. INT32 length;
  171063. UINT8 bits[17];
  171064. UINT8 huffval[256];
  171065. int i, index, count;
  171066. JHUFF_TBL **htblptr;
  171067. INPUT_VARS(cinfo);
  171068. INPUT_2BYTES(cinfo, length, return FALSE);
  171069. length -= 2;
  171070. while (length > 16) {
  171071. INPUT_BYTE(cinfo, index, return FALSE);
  171072. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171073. bits[0] = 0;
  171074. count = 0;
  171075. for (i = 1; i <= 16; i++) {
  171076. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171077. count += bits[i];
  171078. }
  171079. length -= 1 + 16;
  171080. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171081. bits[1], bits[2], bits[3], bits[4],
  171082. bits[5], bits[6], bits[7], bits[8]);
  171083. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171084. bits[9], bits[10], bits[11], bits[12],
  171085. bits[13], bits[14], bits[15], bits[16]);
  171086. /* Here we just do minimal validation of the counts to avoid walking
  171087. * off the end of our table space. jdhuff.c will check more carefully.
  171088. */
  171089. if (count > 256 || ((INT32) count) > length)
  171090. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171091. for (i = 0; i < count; i++)
  171092. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171093. length -= count;
  171094. if (index & 0x10) { /* AC table definition */
  171095. index -= 0x10;
  171096. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171097. } else { /* DC table definition */
  171098. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171099. }
  171100. if (index < 0 || index >= NUM_HUFF_TBLS)
  171101. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171102. if (*htblptr == NULL)
  171103. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171104. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171105. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171106. }
  171107. if (length != 0)
  171108. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171109. INPUT_SYNC(cinfo);
  171110. return TRUE;
  171111. }
  171112. LOCAL(boolean)
  171113. get_dqt (j_decompress_ptr cinfo)
  171114. /* Process a DQT marker */
  171115. {
  171116. INT32 length;
  171117. int n, i, prec;
  171118. unsigned int tmp;
  171119. JQUANT_TBL *quant_ptr;
  171120. INPUT_VARS(cinfo);
  171121. INPUT_2BYTES(cinfo, length, return FALSE);
  171122. length -= 2;
  171123. while (length > 0) {
  171124. INPUT_BYTE(cinfo, n, return FALSE);
  171125. prec = n >> 4;
  171126. n &= 0x0F;
  171127. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171128. if (n >= NUM_QUANT_TBLS)
  171129. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171130. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171131. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171132. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171133. for (i = 0; i < DCTSIZE2; i++) {
  171134. if (prec)
  171135. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171136. else
  171137. INPUT_BYTE(cinfo, tmp, return FALSE);
  171138. /* We convert the zigzag-order table to natural array order. */
  171139. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171140. }
  171141. if (cinfo->err->trace_level >= 2) {
  171142. for (i = 0; i < DCTSIZE2; i += 8) {
  171143. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171144. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171145. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171146. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171147. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171148. }
  171149. }
  171150. length -= DCTSIZE2+1;
  171151. if (prec) length -= DCTSIZE2;
  171152. }
  171153. if (length != 0)
  171154. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171155. INPUT_SYNC(cinfo);
  171156. return TRUE;
  171157. }
  171158. LOCAL(boolean)
  171159. get_dri (j_decompress_ptr cinfo)
  171160. /* Process a DRI marker */
  171161. {
  171162. INT32 length;
  171163. unsigned int tmp;
  171164. INPUT_VARS(cinfo);
  171165. INPUT_2BYTES(cinfo, length, return FALSE);
  171166. if (length != 4)
  171167. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171168. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171169. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171170. cinfo->restart_interval = tmp;
  171171. INPUT_SYNC(cinfo);
  171172. return TRUE;
  171173. }
  171174. /*
  171175. * Routines for processing APPn and COM markers.
  171176. * These are either saved in memory or discarded, per application request.
  171177. * APP0 and APP14 are specially checked to see if they are
  171178. * JFIF and Adobe markers, respectively.
  171179. */
  171180. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171181. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171182. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171183. LOCAL(void)
  171184. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171185. unsigned int datalen, INT32 remaining)
  171186. /* Examine first few bytes from an APP0.
  171187. * Take appropriate action if it is a JFIF marker.
  171188. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171189. */
  171190. {
  171191. INT32 totallen = (INT32) datalen + remaining;
  171192. if (datalen >= APP0_DATA_LEN &&
  171193. GETJOCTET(data[0]) == 0x4A &&
  171194. GETJOCTET(data[1]) == 0x46 &&
  171195. GETJOCTET(data[2]) == 0x49 &&
  171196. GETJOCTET(data[3]) == 0x46 &&
  171197. GETJOCTET(data[4]) == 0) {
  171198. /* Found JFIF APP0 marker: save info */
  171199. cinfo->saw_JFIF_marker = TRUE;
  171200. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171201. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171202. cinfo->density_unit = GETJOCTET(data[7]);
  171203. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171204. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171205. /* Check version.
  171206. * Major version must be 1, anything else signals an incompatible change.
  171207. * (We used to treat this as an error, but now it's a nonfatal warning,
  171208. * because some bozo at Hijaak couldn't read the spec.)
  171209. * Minor version should be 0..2, but process anyway if newer.
  171210. */
  171211. if (cinfo->JFIF_major_version != 1)
  171212. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171213. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171214. /* Generate trace messages */
  171215. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171216. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171217. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171218. /* Validate thumbnail dimensions and issue appropriate messages */
  171219. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171220. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171221. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171222. totallen -= APP0_DATA_LEN;
  171223. if (totallen !=
  171224. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171225. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171226. } else if (datalen >= 6 &&
  171227. GETJOCTET(data[0]) == 0x4A &&
  171228. GETJOCTET(data[1]) == 0x46 &&
  171229. GETJOCTET(data[2]) == 0x58 &&
  171230. GETJOCTET(data[3]) == 0x58 &&
  171231. GETJOCTET(data[4]) == 0) {
  171232. /* Found JFIF "JFXX" extension APP0 marker */
  171233. /* The library doesn't actually do anything with these,
  171234. * but we try to produce a helpful trace message.
  171235. */
  171236. switch (GETJOCTET(data[5])) {
  171237. case 0x10:
  171238. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171239. break;
  171240. case 0x11:
  171241. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171242. break;
  171243. case 0x13:
  171244. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171245. break;
  171246. default:
  171247. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171248. GETJOCTET(data[5]), (int) totallen);
  171249. break;
  171250. }
  171251. } else {
  171252. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171253. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171254. }
  171255. }
  171256. LOCAL(void)
  171257. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171258. unsigned int datalen, INT32 remaining)
  171259. /* Examine first few bytes from an APP14.
  171260. * Take appropriate action if it is an Adobe marker.
  171261. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171262. */
  171263. {
  171264. unsigned int version, flags0, flags1, transform;
  171265. if (datalen >= APP14_DATA_LEN &&
  171266. GETJOCTET(data[0]) == 0x41 &&
  171267. GETJOCTET(data[1]) == 0x64 &&
  171268. GETJOCTET(data[2]) == 0x6F &&
  171269. GETJOCTET(data[3]) == 0x62 &&
  171270. GETJOCTET(data[4]) == 0x65) {
  171271. /* Found Adobe APP14 marker */
  171272. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171273. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171274. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171275. transform = GETJOCTET(data[11]);
  171276. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171277. cinfo->saw_Adobe_marker = TRUE;
  171278. cinfo->Adobe_transform = (UINT8) transform;
  171279. } else {
  171280. /* Start of APP14 does not match "Adobe", or too short */
  171281. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171282. }
  171283. }
  171284. METHODDEF(boolean)
  171285. get_interesting_appn (j_decompress_ptr cinfo)
  171286. /* Process an APP0 or APP14 marker without saving it */
  171287. {
  171288. INT32 length;
  171289. JOCTET b[APPN_DATA_LEN];
  171290. unsigned int i, numtoread;
  171291. INPUT_VARS(cinfo);
  171292. INPUT_2BYTES(cinfo, length, return FALSE);
  171293. length -= 2;
  171294. /* get the interesting part of the marker data */
  171295. if (length >= APPN_DATA_LEN)
  171296. numtoread = APPN_DATA_LEN;
  171297. else if (length > 0)
  171298. numtoread = (unsigned int) length;
  171299. else
  171300. numtoread = 0;
  171301. for (i = 0; i < numtoread; i++)
  171302. INPUT_BYTE(cinfo, b[i], return FALSE);
  171303. length -= numtoread;
  171304. /* process it */
  171305. switch (cinfo->unread_marker) {
  171306. case M_APP0:
  171307. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171308. break;
  171309. case M_APP14:
  171310. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171311. break;
  171312. default:
  171313. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171314. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171315. break;
  171316. }
  171317. /* skip any remaining data -- could be lots */
  171318. INPUT_SYNC(cinfo);
  171319. if (length > 0)
  171320. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171321. return TRUE;
  171322. }
  171323. #ifdef SAVE_MARKERS_SUPPORTED
  171324. METHODDEF(boolean)
  171325. save_marker (j_decompress_ptr cinfo)
  171326. /* Save an APPn or COM marker into the marker list */
  171327. {
  171328. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171329. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171330. unsigned int bytes_read, data_length;
  171331. JOCTET FAR * data;
  171332. INT32 length = 0;
  171333. INPUT_VARS(cinfo);
  171334. if (cur_marker == NULL) {
  171335. /* begin reading a marker */
  171336. INPUT_2BYTES(cinfo, length, return FALSE);
  171337. length -= 2;
  171338. if (length >= 0) { /* watch out for bogus length word */
  171339. /* figure out how much we want to save */
  171340. unsigned int limit;
  171341. if (cinfo->unread_marker == (int) M_COM)
  171342. limit = marker->length_limit_COM;
  171343. else
  171344. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171345. if ((unsigned int) length < limit)
  171346. limit = (unsigned int) length;
  171347. /* allocate and initialize the marker item */
  171348. cur_marker = (jpeg_saved_marker_ptr)
  171349. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171350. SIZEOF(struct jpeg_marker_struct) + limit);
  171351. cur_marker->next = NULL;
  171352. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171353. cur_marker->original_length = (unsigned int) length;
  171354. cur_marker->data_length = limit;
  171355. /* data area is just beyond the jpeg_marker_struct */
  171356. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171357. marker->cur_marker = cur_marker;
  171358. marker->bytes_read = 0;
  171359. bytes_read = 0;
  171360. data_length = limit;
  171361. } else {
  171362. /* deal with bogus length word */
  171363. bytes_read = data_length = 0;
  171364. data = NULL;
  171365. }
  171366. } else {
  171367. /* resume reading a marker */
  171368. bytes_read = marker->bytes_read;
  171369. data_length = cur_marker->data_length;
  171370. data = cur_marker->data + bytes_read;
  171371. }
  171372. while (bytes_read < data_length) {
  171373. INPUT_SYNC(cinfo); /* move the restart point to here */
  171374. marker->bytes_read = bytes_read;
  171375. /* If there's not at least one byte in buffer, suspend */
  171376. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171377. /* Copy bytes with reasonable rapidity */
  171378. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171379. *data++ = *next_input_byte++;
  171380. bytes_in_buffer--;
  171381. bytes_read++;
  171382. }
  171383. }
  171384. /* Done reading what we want to read */
  171385. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171386. /* Add new marker to end of list */
  171387. if (cinfo->marker_list == NULL) {
  171388. cinfo->marker_list = cur_marker;
  171389. } else {
  171390. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171391. while (prev->next != NULL)
  171392. prev = prev->next;
  171393. prev->next = cur_marker;
  171394. }
  171395. /* Reset pointer & calc remaining data length */
  171396. data = cur_marker->data;
  171397. length = cur_marker->original_length - data_length;
  171398. }
  171399. /* Reset to initial state for next marker */
  171400. marker->cur_marker = NULL;
  171401. /* Process the marker if interesting; else just make a generic trace msg */
  171402. switch (cinfo->unread_marker) {
  171403. case M_APP0:
  171404. examine_app0(cinfo, data, data_length, length);
  171405. break;
  171406. case M_APP14:
  171407. examine_app14(cinfo, data, data_length, length);
  171408. break;
  171409. default:
  171410. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171411. (int) (data_length + length));
  171412. break;
  171413. }
  171414. /* skip any remaining data -- could be lots */
  171415. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171416. if (length > 0)
  171417. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171418. return TRUE;
  171419. }
  171420. #endif /* SAVE_MARKERS_SUPPORTED */
  171421. METHODDEF(boolean)
  171422. skip_variable (j_decompress_ptr cinfo)
  171423. /* Skip over an unknown or uninteresting variable-length marker */
  171424. {
  171425. INT32 length;
  171426. INPUT_VARS(cinfo);
  171427. INPUT_2BYTES(cinfo, length, return FALSE);
  171428. length -= 2;
  171429. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171430. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171431. if (length > 0)
  171432. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171433. return TRUE;
  171434. }
  171435. /*
  171436. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171437. * Returns FALSE if had to suspend before reaching a marker;
  171438. * in that case cinfo->unread_marker is unchanged.
  171439. *
  171440. * Note that the result might not be a valid marker code,
  171441. * but it will never be 0 or FF.
  171442. */
  171443. LOCAL(boolean)
  171444. next_marker (j_decompress_ptr cinfo)
  171445. {
  171446. int c;
  171447. INPUT_VARS(cinfo);
  171448. for (;;) {
  171449. INPUT_BYTE(cinfo, c, return FALSE);
  171450. /* Skip any non-FF bytes.
  171451. * This may look a bit inefficient, but it will not occur in a valid file.
  171452. * We sync after each discarded byte so that a suspending data source
  171453. * can discard the byte from its buffer.
  171454. */
  171455. while (c != 0xFF) {
  171456. cinfo->marker->discarded_bytes++;
  171457. INPUT_SYNC(cinfo);
  171458. INPUT_BYTE(cinfo, c, return FALSE);
  171459. }
  171460. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171461. * pad bytes, so don't count them in discarded_bytes. We assume there
  171462. * will not be so many consecutive FF bytes as to overflow a suspending
  171463. * data source's input buffer.
  171464. */
  171465. do {
  171466. INPUT_BYTE(cinfo, c, return FALSE);
  171467. } while (c == 0xFF);
  171468. if (c != 0)
  171469. break; /* found a valid marker, exit loop */
  171470. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171471. * Discard it and loop back to try again.
  171472. */
  171473. cinfo->marker->discarded_bytes += 2;
  171474. INPUT_SYNC(cinfo);
  171475. }
  171476. if (cinfo->marker->discarded_bytes != 0) {
  171477. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171478. cinfo->marker->discarded_bytes = 0;
  171479. }
  171480. cinfo->unread_marker = c;
  171481. INPUT_SYNC(cinfo);
  171482. return TRUE;
  171483. }
  171484. LOCAL(boolean)
  171485. first_marker (j_decompress_ptr cinfo)
  171486. /* Like next_marker, but used to obtain the initial SOI marker. */
  171487. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171488. * we might well scan an entire input file before realizing it ain't JPEG.
  171489. * If an application wants to process non-JFIF files, it must seek to the
  171490. * SOI before calling the JPEG library.
  171491. */
  171492. {
  171493. int c, c2;
  171494. INPUT_VARS(cinfo);
  171495. INPUT_BYTE(cinfo, c, return FALSE);
  171496. INPUT_BYTE(cinfo, c2, return FALSE);
  171497. if (c != 0xFF || c2 != (int) M_SOI)
  171498. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171499. cinfo->unread_marker = c2;
  171500. INPUT_SYNC(cinfo);
  171501. return TRUE;
  171502. }
  171503. /*
  171504. * Read markers until SOS or EOI.
  171505. *
  171506. * Returns same codes as are defined for jpeg_consume_input:
  171507. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171508. */
  171509. METHODDEF(int)
  171510. read_markers (j_decompress_ptr cinfo)
  171511. {
  171512. /* Outer loop repeats once for each marker. */
  171513. for (;;) {
  171514. /* Collect the marker proper, unless we already did. */
  171515. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171516. if (cinfo->unread_marker == 0) {
  171517. if (! cinfo->marker->saw_SOI) {
  171518. if (! first_marker(cinfo))
  171519. return JPEG_SUSPENDED;
  171520. } else {
  171521. if (! next_marker(cinfo))
  171522. return JPEG_SUSPENDED;
  171523. }
  171524. }
  171525. /* At this point cinfo->unread_marker contains the marker code and the
  171526. * input point is just past the marker proper, but before any parameters.
  171527. * A suspension will cause us to return with this state still true.
  171528. */
  171529. switch (cinfo->unread_marker) {
  171530. case M_SOI:
  171531. if (! get_soi(cinfo))
  171532. return JPEG_SUSPENDED;
  171533. break;
  171534. case M_SOF0: /* Baseline */
  171535. case M_SOF1: /* Extended sequential, Huffman */
  171536. if (! get_sof(cinfo, FALSE, FALSE))
  171537. return JPEG_SUSPENDED;
  171538. break;
  171539. case M_SOF2: /* Progressive, Huffman */
  171540. if (! get_sof(cinfo, TRUE, FALSE))
  171541. return JPEG_SUSPENDED;
  171542. break;
  171543. case M_SOF9: /* Extended sequential, arithmetic */
  171544. if (! get_sof(cinfo, FALSE, TRUE))
  171545. return JPEG_SUSPENDED;
  171546. break;
  171547. case M_SOF10: /* Progressive, arithmetic */
  171548. if (! get_sof(cinfo, TRUE, TRUE))
  171549. return JPEG_SUSPENDED;
  171550. break;
  171551. /* Currently unsupported SOFn types */
  171552. case M_SOF3: /* Lossless, Huffman */
  171553. case M_SOF5: /* Differential sequential, Huffman */
  171554. case M_SOF6: /* Differential progressive, Huffman */
  171555. case M_SOF7: /* Differential lossless, Huffman */
  171556. case M_JPG: /* Reserved for JPEG extensions */
  171557. case M_SOF11: /* Lossless, arithmetic */
  171558. case M_SOF13: /* Differential sequential, arithmetic */
  171559. case M_SOF14: /* Differential progressive, arithmetic */
  171560. case M_SOF15: /* Differential lossless, arithmetic */
  171561. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171562. break;
  171563. case M_SOS:
  171564. if (! get_sos(cinfo))
  171565. return JPEG_SUSPENDED;
  171566. cinfo->unread_marker = 0; /* processed the marker */
  171567. return JPEG_REACHED_SOS;
  171568. case M_EOI:
  171569. TRACEMS(cinfo, 1, JTRC_EOI);
  171570. cinfo->unread_marker = 0; /* processed the marker */
  171571. return JPEG_REACHED_EOI;
  171572. case M_DAC:
  171573. if (! get_dac(cinfo))
  171574. return JPEG_SUSPENDED;
  171575. break;
  171576. case M_DHT:
  171577. if (! get_dht(cinfo))
  171578. return JPEG_SUSPENDED;
  171579. break;
  171580. case M_DQT:
  171581. if (! get_dqt(cinfo))
  171582. return JPEG_SUSPENDED;
  171583. break;
  171584. case M_DRI:
  171585. if (! get_dri(cinfo))
  171586. return JPEG_SUSPENDED;
  171587. break;
  171588. case M_APP0:
  171589. case M_APP1:
  171590. case M_APP2:
  171591. case M_APP3:
  171592. case M_APP4:
  171593. case M_APP5:
  171594. case M_APP6:
  171595. case M_APP7:
  171596. case M_APP8:
  171597. case M_APP9:
  171598. case M_APP10:
  171599. case M_APP11:
  171600. case M_APP12:
  171601. case M_APP13:
  171602. case M_APP14:
  171603. case M_APP15:
  171604. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171605. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171606. return JPEG_SUSPENDED;
  171607. break;
  171608. case M_COM:
  171609. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171610. return JPEG_SUSPENDED;
  171611. break;
  171612. case M_RST0: /* these are all parameterless */
  171613. case M_RST1:
  171614. case M_RST2:
  171615. case M_RST3:
  171616. case M_RST4:
  171617. case M_RST5:
  171618. case M_RST6:
  171619. case M_RST7:
  171620. case M_TEM:
  171621. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171622. break;
  171623. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171624. if (! skip_variable(cinfo))
  171625. return JPEG_SUSPENDED;
  171626. break;
  171627. default: /* must be DHP, EXP, JPGn, or RESn */
  171628. /* For now, we treat the reserved markers as fatal errors since they are
  171629. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171630. * Once the JPEG 3 version-number marker is well defined, this code
  171631. * ought to change!
  171632. */
  171633. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171634. break;
  171635. }
  171636. /* Successfully processed marker, so reset state variable */
  171637. cinfo->unread_marker = 0;
  171638. } /* end loop */
  171639. }
  171640. /*
  171641. * Read a restart marker, which is expected to appear next in the datastream;
  171642. * if the marker is not there, take appropriate recovery action.
  171643. * Returns FALSE if suspension is required.
  171644. *
  171645. * This is called by the entropy decoder after it has read an appropriate
  171646. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171647. * has already read a marker from the data source. Under normal conditions
  171648. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171649. * it holds a marker which the decoder will be unable to read past.
  171650. */
  171651. METHODDEF(boolean)
  171652. read_restart_marker (j_decompress_ptr cinfo)
  171653. {
  171654. /* Obtain a marker unless we already did. */
  171655. /* Note that next_marker will complain if it skips any data. */
  171656. if (cinfo->unread_marker == 0) {
  171657. if (! next_marker(cinfo))
  171658. return FALSE;
  171659. }
  171660. if (cinfo->unread_marker ==
  171661. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171662. /* Normal case --- swallow the marker and let entropy decoder continue */
  171663. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171664. cinfo->unread_marker = 0;
  171665. } else {
  171666. /* Uh-oh, the restart markers have been messed up. */
  171667. /* Let the data source manager determine how to resync. */
  171668. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171669. cinfo->marker->next_restart_num))
  171670. return FALSE;
  171671. }
  171672. /* Update next-restart state */
  171673. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171674. return TRUE;
  171675. }
  171676. /*
  171677. * This is the default resync_to_restart method for data source managers
  171678. * to use if they don't have any better approach. Some data source managers
  171679. * may be able to back up, or may have additional knowledge about the data
  171680. * which permits a more intelligent recovery strategy; such managers would
  171681. * presumably supply their own resync method.
  171682. *
  171683. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171684. * the restart marker it was expecting. (This code is *not* used unless
  171685. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171686. * the marker code actually found (might be anything, except 0 or FF).
  171687. * The desired restart marker number (0..7) is passed as a parameter.
  171688. * This routine is supposed to apply whatever error recovery strategy seems
  171689. * appropriate in order to position the input stream to the next data segment.
  171690. * Note that cinfo->unread_marker is treated as a marker appearing before
  171691. * the current data-source input point; usually it should be reset to zero
  171692. * before returning.
  171693. * Returns FALSE if suspension is required.
  171694. *
  171695. * This implementation is substantially constrained by wanting to treat the
  171696. * input as a data stream; this means we can't back up. Therefore, we have
  171697. * only the following actions to work with:
  171698. * 1. Simply discard the marker and let the entropy decoder resume at next
  171699. * byte of file.
  171700. * 2. Read forward until we find another marker, discarding intervening
  171701. * data. (In theory we could look ahead within the current bufferload,
  171702. * without having to discard data if we don't find the desired marker.
  171703. * This idea is not implemented here, in part because it makes behavior
  171704. * dependent on buffer size and chance buffer-boundary positions.)
  171705. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171706. * This will cause the entropy decoder to process an empty data segment,
  171707. * inserting dummy zeroes, and then we will reprocess the marker.
  171708. *
  171709. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171710. * appropriate if the found marker is a future restart marker (indicating
  171711. * that we have missed the desired restart marker, probably because it got
  171712. * corrupted).
  171713. * We apply #2 or #3 if the found marker is a restart marker no more than
  171714. * two counts behind or ahead of the expected one. We also apply #2 if the
  171715. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171716. * If the found marker is a restart marker more than 2 counts away, we do #1
  171717. * (too much risk that the marker is erroneous; with luck we will be able to
  171718. * resync at some future point).
  171719. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171720. * overrunning the end of a scan. An implementation limited to single-scan
  171721. * files might find it better to apply #2 for markers other than EOI, since
  171722. * any other marker would have to be bogus data in that case.
  171723. */
  171724. GLOBAL(boolean)
  171725. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171726. {
  171727. int marker = cinfo->unread_marker;
  171728. int action = 1;
  171729. /* Always put up a warning. */
  171730. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171731. /* Outer loop handles repeated decision after scanning forward. */
  171732. for (;;) {
  171733. if (marker < (int) M_SOF0)
  171734. action = 2; /* invalid marker */
  171735. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171736. action = 3; /* valid non-restart marker */
  171737. else {
  171738. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171739. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171740. action = 3; /* one of the next two expected restarts */
  171741. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171742. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171743. action = 2; /* a prior restart, so advance */
  171744. else
  171745. action = 1; /* desired restart or too far away */
  171746. }
  171747. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171748. switch (action) {
  171749. case 1:
  171750. /* Discard marker and let entropy decoder resume processing. */
  171751. cinfo->unread_marker = 0;
  171752. return TRUE;
  171753. case 2:
  171754. /* Scan to the next marker, and repeat the decision loop. */
  171755. if (! next_marker(cinfo))
  171756. return FALSE;
  171757. marker = cinfo->unread_marker;
  171758. break;
  171759. case 3:
  171760. /* Return without advancing past this marker. */
  171761. /* Entropy decoder will be forced to process an empty segment. */
  171762. return TRUE;
  171763. }
  171764. } /* end loop */
  171765. }
  171766. /*
  171767. * Reset marker processing state to begin a fresh datastream.
  171768. */
  171769. METHODDEF(void)
  171770. reset_marker_reader (j_decompress_ptr cinfo)
  171771. {
  171772. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171773. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171774. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171775. cinfo->unread_marker = 0; /* no pending marker */
  171776. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171777. marker->pub.saw_SOF = FALSE;
  171778. marker->pub.discarded_bytes = 0;
  171779. marker->cur_marker = NULL;
  171780. }
  171781. /*
  171782. * Initialize the marker reader module.
  171783. * This is called only once, when the decompression object is created.
  171784. */
  171785. GLOBAL(void)
  171786. jinit_marker_reader (j_decompress_ptr cinfo)
  171787. {
  171788. my_marker_ptr2 marker;
  171789. int i;
  171790. /* Create subobject in permanent pool */
  171791. marker = (my_marker_ptr2)
  171792. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171793. SIZEOF(my_marker_reader));
  171794. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171795. /* Initialize public method pointers */
  171796. marker->pub.reset_marker_reader = reset_marker_reader;
  171797. marker->pub.read_markers = read_markers;
  171798. marker->pub.read_restart_marker = read_restart_marker;
  171799. /* Initialize COM/APPn processing.
  171800. * By default, we examine and then discard APP0 and APP14,
  171801. * but simply discard COM and all other APPn.
  171802. */
  171803. marker->process_COM = skip_variable;
  171804. marker->length_limit_COM = 0;
  171805. for (i = 0; i < 16; i++) {
  171806. marker->process_APPn[i] = skip_variable;
  171807. marker->length_limit_APPn[i] = 0;
  171808. }
  171809. marker->process_APPn[0] = get_interesting_appn;
  171810. marker->process_APPn[14] = get_interesting_appn;
  171811. /* Reset marker processing state */
  171812. reset_marker_reader(cinfo);
  171813. }
  171814. /*
  171815. * Control saving of COM and APPn markers into marker_list.
  171816. */
  171817. #ifdef SAVE_MARKERS_SUPPORTED
  171818. GLOBAL(void)
  171819. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171820. unsigned int length_limit)
  171821. {
  171822. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171823. long maxlength;
  171824. jpeg_marker_parser_method processor;
  171825. /* Length limit mustn't be larger than what we can allocate
  171826. * (should only be a concern in a 16-bit environment).
  171827. */
  171828. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171829. if (((long) length_limit) > maxlength)
  171830. length_limit = (unsigned int) maxlength;
  171831. /* Choose processor routine to use.
  171832. * APP0/APP14 have special requirements.
  171833. */
  171834. if (length_limit) {
  171835. processor = save_marker;
  171836. /* If saving APP0/APP14, save at least enough for our internal use. */
  171837. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171838. length_limit = APP0_DATA_LEN;
  171839. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171840. length_limit = APP14_DATA_LEN;
  171841. } else {
  171842. processor = skip_variable;
  171843. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171844. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171845. processor = get_interesting_appn;
  171846. }
  171847. if (marker_code == (int) M_COM) {
  171848. marker->process_COM = processor;
  171849. marker->length_limit_COM = length_limit;
  171850. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171851. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171852. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171853. } else
  171854. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171855. }
  171856. #endif /* SAVE_MARKERS_SUPPORTED */
  171857. /*
  171858. * Install a special processing method for COM or APPn markers.
  171859. */
  171860. GLOBAL(void)
  171861. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171862. jpeg_marker_parser_method routine)
  171863. {
  171864. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171865. if (marker_code == (int) M_COM)
  171866. marker->process_COM = routine;
  171867. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171868. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171869. else
  171870. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171871. }
  171872. /*** End of inlined file: jdmarker.c ***/
  171873. /*** Start of inlined file: jdmaster.c ***/
  171874. #define JPEG_INTERNALS
  171875. /* Private state */
  171876. typedef struct {
  171877. struct jpeg_decomp_master pub; /* public fields */
  171878. int pass_number; /* # of passes completed */
  171879. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171880. /* Saved references to initialized quantizer modules,
  171881. * in case we need to switch modes.
  171882. */
  171883. struct jpeg_color_quantizer * quantizer_1pass;
  171884. struct jpeg_color_quantizer * quantizer_2pass;
  171885. } my_decomp_master;
  171886. typedef my_decomp_master * my_master_ptr6;
  171887. /*
  171888. * Determine whether merged upsample/color conversion should be used.
  171889. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171890. */
  171891. LOCAL(boolean)
  171892. use_merged_upsample (j_decompress_ptr cinfo)
  171893. {
  171894. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171895. /* Merging is the equivalent of plain box-filter upsampling */
  171896. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171897. return FALSE;
  171898. /* jdmerge.c only supports YCC=>RGB color conversion */
  171899. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171900. cinfo->out_color_space != JCS_RGB ||
  171901. cinfo->out_color_components != RGB_PIXELSIZE)
  171902. return FALSE;
  171903. /* and it only handles 2h1v or 2h2v sampling ratios */
  171904. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171905. cinfo->comp_info[1].h_samp_factor != 1 ||
  171906. cinfo->comp_info[2].h_samp_factor != 1 ||
  171907. cinfo->comp_info[0].v_samp_factor > 2 ||
  171908. cinfo->comp_info[1].v_samp_factor != 1 ||
  171909. cinfo->comp_info[2].v_samp_factor != 1)
  171910. return FALSE;
  171911. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171912. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171913. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171914. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171915. return FALSE;
  171916. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171917. return TRUE; /* by golly, it'll work... */
  171918. #else
  171919. return FALSE;
  171920. #endif
  171921. }
  171922. /*
  171923. * Compute output image dimensions and related values.
  171924. * NOTE: this is exported for possible use by application.
  171925. * Hence it mustn't do anything that can't be done twice.
  171926. * Also note that it may be called before the master module is initialized!
  171927. */
  171928. GLOBAL(void)
  171929. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171930. /* Do computations that are needed before master selection phase */
  171931. {
  171932. #ifdef IDCT_SCALING_SUPPORTED
  171933. int ci;
  171934. jpeg_component_info *compptr;
  171935. #endif
  171936. /* Prevent application from calling me at wrong times */
  171937. if (cinfo->global_state != DSTATE_READY)
  171938. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171939. #ifdef IDCT_SCALING_SUPPORTED
  171940. /* Compute actual output image dimensions and DCT scaling choices. */
  171941. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171942. /* Provide 1/8 scaling */
  171943. cinfo->output_width = (JDIMENSION)
  171944. jdiv_round_up((long) cinfo->image_width, 8L);
  171945. cinfo->output_height = (JDIMENSION)
  171946. jdiv_round_up((long) cinfo->image_height, 8L);
  171947. cinfo->min_DCT_scaled_size = 1;
  171948. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171949. /* Provide 1/4 scaling */
  171950. cinfo->output_width = (JDIMENSION)
  171951. jdiv_round_up((long) cinfo->image_width, 4L);
  171952. cinfo->output_height = (JDIMENSION)
  171953. jdiv_round_up((long) cinfo->image_height, 4L);
  171954. cinfo->min_DCT_scaled_size = 2;
  171955. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171956. /* Provide 1/2 scaling */
  171957. cinfo->output_width = (JDIMENSION)
  171958. jdiv_round_up((long) cinfo->image_width, 2L);
  171959. cinfo->output_height = (JDIMENSION)
  171960. jdiv_round_up((long) cinfo->image_height, 2L);
  171961. cinfo->min_DCT_scaled_size = 4;
  171962. } else {
  171963. /* Provide 1/1 scaling */
  171964. cinfo->output_width = cinfo->image_width;
  171965. cinfo->output_height = cinfo->image_height;
  171966. cinfo->min_DCT_scaled_size = DCTSIZE;
  171967. }
  171968. /* In selecting the actual DCT scaling for each component, we try to
  171969. * scale up the chroma components via IDCT scaling rather than upsampling.
  171970. * This saves time if the upsampler gets to use 1:1 scaling.
  171971. * Note this code assumes that the supported DCT scalings are powers of 2.
  171972. */
  171973. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171974. ci++, compptr++) {
  171975. int ssize = cinfo->min_DCT_scaled_size;
  171976. while (ssize < DCTSIZE &&
  171977. (compptr->h_samp_factor * ssize * 2 <=
  171978. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171979. (compptr->v_samp_factor * ssize * 2 <=
  171980. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171981. ssize = ssize * 2;
  171982. }
  171983. compptr->DCT_scaled_size = ssize;
  171984. }
  171985. /* Recompute downsampled dimensions of components;
  171986. * application needs to know these if using raw downsampled data.
  171987. */
  171988. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171989. ci++, compptr++) {
  171990. /* Size in samples, after IDCT scaling */
  171991. compptr->downsampled_width = (JDIMENSION)
  171992. jdiv_round_up((long) cinfo->image_width *
  171993. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171994. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171995. compptr->downsampled_height = (JDIMENSION)
  171996. jdiv_round_up((long) cinfo->image_height *
  171997. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171998. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171999. }
  172000. #else /* !IDCT_SCALING_SUPPORTED */
  172001. /* Hardwire it to "no scaling" */
  172002. cinfo->output_width = cinfo->image_width;
  172003. cinfo->output_height = cinfo->image_height;
  172004. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172005. * and has computed unscaled downsampled_width and downsampled_height.
  172006. */
  172007. #endif /* IDCT_SCALING_SUPPORTED */
  172008. /* Report number of components in selected colorspace. */
  172009. /* Probably this should be in the color conversion module... */
  172010. switch (cinfo->out_color_space) {
  172011. case JCS_GRAYSCALE:
  172012. cinfo->out_color_components = 1;
  172013. break;
  172014. case JCS_RGB:
  172015. #if RGB_PIXELSIZE != 3
  172016. cinfo->out_color_components = RGB_PIXELSIZE;
  172017. break;
  172018. #endif /* else share code with YCbCr */
  172019. case JCS_YCbCr:
  172020. cinfo->out_color_components = 3;
  172021. break;
  172022. case JCS_CMYK:
  172023. case JCS_YCCK:
  172024. cinfo->out_color_components = 4;
  172025. break;
  172026. default: /* else must be same colorspace as in file */
  172027. cinfo->out_color_components = cinfo->num_components;
  172028. break;
  172029. }
  172030. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172031. cinfo->out_color_components);
  172032. /* See if upsampler will want to emit more than one row at a time */
  172033. if (use_merged_upsample(cinfo))
  172034. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172035. else
  172036. cinfo->rec_outbuf_height = 1;
  172037. }
  172038. /*
  172039. * Several decompression processes need to range-limit values to the range
  172040. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172041. * due to noise introduced by quantization, roundoff error, etc. These
  172042. * processes are inner loops and need to be as fast as possible. On most
  172043. * machines, particularly CPUs with pipelines or instruction prefetch,
  172044. * a (subscript-check-less) C table lookup
  172045. * x = sample_range_limit[x];
  172046. * is faster than explicit tests
  172047. * if (x < 0) x = 0;
  172048. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172049. * These processes all use a common table prepared by the routine below.
  172050. *
  172051. * For most steps we can mathematically guarantee that the initial value
  172052. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172053. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172054. * limiting step (just after the IDCT), a wildly out-of-range value is
  172055. * possible if the input data is corrupt. To avoid any chance of indexing
  172056. * off the end of memory and getting a bad-pointer trap, we perform the
  172057. * post-IDCT limiting thus:
  172058. * x = range_limit[x & MASK];
  172059. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172060. * samples. Under normal circumstances this is more than enough range and
  172061. * a correct output will be generated; with bogus input data the mask will
  172062. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172063. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172064. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172065. * So the post-IDCT limiting table ends up looking like this:
  172066. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172067. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172068. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172069. * 0,1,...,CENTERJSAMPLE-1
  172070. * Negative inputs select values from the upper half of the table after
  172071. * masking.
  172072. *
  172073. * We can save some space by overlapping the start of the post-IDCT table
  172074. * with the simpler range limiting table. The post-IDCT table begins at
  172075. * sample_range_limit + CENTERJSAMPLE.
  172076. *
  172077. * Note that the table is allocated in near data space on PCs; it's small
  172078. * enough and used often enough to justify this.
  172079. */
  172080. LOCAL(void)
  172081. prepare_range_limit_table (j_decompress_ptr cinfo)
  172082. /* Allocate and fill in the sample_range_limit table */
  172083. {
  172084. JSAMPLE * table;
  172085. int i;
  172086. table = (JSAMPLE *)
  172087. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172088. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172089. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172090. cinfo->sample_range_limit = table;
  172091. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172092. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172093. /* Main part of "simple" table: limit[x] = x */
  172094. for (i = 0; i <= MAXJSAMPLE; i++)
  172095. table[i] = (JSAMPLE) i;
  172096. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172097. /* End of simple table, rest of first half of post-IDCT table */
  172098. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172099. table[i] = MAXJSAMPLE;
  172100. /* Second half of post-IDCT table */
  172101. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172102. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172103. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172104. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172105. }
  172106. /*
  172107. * Master selection of decompression modules.
  172108. * This is done once at jpeg_start_decompress time. We determine
  172109. * which modules will be used and give them appropriate initialization calls.
  172110. * We also initialize the decompressor input side to begin consuming data.
  172111. *
  172112. * Since jpeg_read_header has finished, we know what is in the SOF
  172113. * and (first) SOS markers. We also have all the application parameter
  172114. * settings.
  172115. */
  172116. LOCAL(void)
  172117. master_selection (j_decompress_ptr cinfo)
  172118. {
  172119. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172120. boolean use_c_buffer;
  172121. long samplesperrow;
  172122. JDIMENSION jd_samplesperrow;
  172123. /* Initialize dimensions and other stuff */
  172124. jpeg_calc_output_dimensions(cinfo);
  172125. prepare_range_limit_table(cinfo);
  172126. /* Width of an output scanline must be representable as JDIMENSION. */
  172127. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172128. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172129. if ((long) jd_samplesperrow != samplesperrow)
  172130. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172131. /* Initialize my private state */
  172132. master->pass_number = 0;
  172133. master->using_merged_upsample = use_merged_upsample(cinfo);
  172134. /* Color quantizer selection */
  172135. master->quantizer_1pass = NULL;
  172136. master->quantizer_2pass = NULL;
  172137. /* No mode changes if not using buffered-image mode. */
  172138. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172139. cinfo->enable_1pass_quant = FALSE;
  172140. cinfo->enable_external_quant = FALSE;
  172141. cinfo->enable_2pass_quant = FALSE;
  172142. }
  172143. if (cinfo->quantize_colors) {
  172144. if (cinfo->raw_data_out)
  172145. ERREXIT(cinfo, JERR_NOTIMPL);
  172146. /* 2-pass quantizer only works in 3-component color space. */
  172147. if (cinfo->out_color_components != 3) {
  172148. cinfo->enable_1pass_quant = TRUE;
  172149. cinfo->enable_external_quant = FALSE;
  172150. cinfo->enable_2pass_quant = FALSE;
  172151. cinfo->colormap = NULL;
  172152. } else if (cinfo->colormap != NULL) {
  172153. cinfo->enable_external_quant = TRUE;
  172154. } else if (cinfo->two_pass_quantize) {
  172155. cinfo->enable_2pass_quant = TRUE;
  172156. } else {
  172157. cinfo->enable_1pass_quant = TRUE;
  172158. }
  172159. if (cinfo->enable_1pass_quant) {
  172160. #ifdef QUANT_1PASS_SUPPORTED
  172161. jinit_1pass_quantizer(cinfo);
  172162. master->quantizer_1pass = cinfo->cquantize;
  172163. #else
  172164. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172165. #endif
  172166. }
  172167. /* We use the 2-pass code to map to external colormaps. */
  172168. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172169. #ifdef QUANT_2PASS_SUPPORTED
  172170. jinit_2pass_quantizer(cinfo);
  172171. master->quantizer_2pass = cinfo->cquantize;
  172172. #else
  172173. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172174. #endif
  172175. }
  172176. /* If both quantizers are initialized, the 2-pass one is left active;
  172177. * this is necessary for starting with quantization to an external map.
  172178. */
  172179. }
  172180. /* Post-processing: in particular, color conversion first */
  172181. if (! cinfo->raw_data_out) {
  172182. if (master->using_merged_upsample) {
  172183. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172184. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172185. #else
  172186. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172187. #endif
  172188. } else {
  172189. jinit_color_deconverter(cinfo);
  172190. jinit_upsampler(cinfo);
  172191. }
  172192. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172193. }
  172194. /* Inverse DCT */
  172195. jinit_inverse_dct(cinfo);
  172196. /* Entropy decoding: either Huffman or arithmetic coding. */
  172197. if (cinfo->arith_code) {
  172198. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172199. } else {
  172200. if (cinfo->progressive_mode) {
  172201. #ifdef D_PROGRESSIVE_SUPPORTED
  172202. jinit_phuff_decoder(cinfo);
  172203. #else
  172204. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172205. #endif
  172206. } else
  172207. jinit_huff_decoder(cinfo);
  172208. }
  172209. /* Initialize principal buffer controllers. */
  172210. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172211. jinit_d_coef_controller(cinfo, use_c_buffer);
  172212. if (! cinfo->raw_data_out)
  172213. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172214. /* We can now tell the memory manager to allocate virtual arrays. */
  172215. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172216. /* Initialize input side of decompressor to consume first scan. */
  172217. (*cinfo->inputctl->start_input_pass) (cinfo);
  172218. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172219. /* If jpeg_start_decompress will read the whole file, initialize
  172220. * progress monitoring appropriately. The input step is counted
  172221. * as one pass.
  172222. */
  172223. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172224. cinfo->inputctl->has_multiple_scans) {
  172225. int nscans;
  172226. /* Estimate number of scans to set pass_limit. */
  172227. if (cinfo->progressive_mode) {
  172228. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172229. nscans = 2 + 3 * cinfo->num_components;
  172230. } else {
  172231. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172232. nscans = cinfo->num_components;
  172233. }
  172234. cinfo->progress->pass_counter = 0L;
  172235. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172236. cinfo->progress->completed_passes = 0;
  172237. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172238. /* Count the input pass as done */
  172239. master->pass_number++;
  172240. }
  172241. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172242. }
  172243. /*
  172244. * Per-pass setup.
  172245. * This is called at the beginning of each output pass. We determine which
  172246. * modules will be active during this pass and give them appropriate
  172247. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172248. * is a "real" output pass or a dummy pass for color quantization.
  172249. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172250. */
  172251. METHODDEF(void)
  172252. prepare_for_output_pass (j_decompress_ptr cinfo)
  172253. {
  172254. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172255. if (master->pub.is_dummy_pass) {
  172256. #ifdef QUANT_2PASS_SUPPORTED
  172257. /* Final pass of 2-pass quantization */
  172258. master->pub.is_dummy_pass = FALSE;
  172259. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172260. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172261. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172262. #else
  172263. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172264. #endif /* QUANT_2PASS_SUPPORTED */
  172265. } else {
  172266. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172267. /* Select new quantization method */
  172268. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172269. cinfo->cquantize = master->quantizer_2pass;
  172270. master->pub.is_dummy_pass = TRUE;
  172271. } else if (cinfo->enable_1pass_quant) {
  172272. cinfo->cquantize = master->quantizer_1pass;
  172273. } else {
  172274. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172275. }
  172276. }
  172277. (*cinfo->idct->start_pass) (cinfo);
  172278. (*cinfo->coef->start_output_pass) (cinfo);
  172279. if (! cinfo->raw_data_out) {
  172280. if (! master->using_merged_upsample)
  172281. (*cinfo->cconvert->start_pass) (cinfo);
  172282. (*cinfo->upsample->start_pass) (cinfo);
  172283. if (cinfo->quantize_colors)
  172284. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172285. (*cinfo->post->start_pass) (cinfo,
  172286. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172287. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172288. }
  172289. }
  172290. /* Set up progress monitor's pass info if present */
  172291. if (cinfo->progress != NULL) {
  172292. cinfo->progress->completed_passes = master->pass_number;
  172293. cinfo->progress->total_passes = master->pass_number +
  172294. (master->pub.is_dummy_pass ? 2 : 1);
  172295. /* In buffered-image mode, we assume one more output pass if EOI not
  172296. * yet reached, but no more passes if EOI has been reached.
  172297. */
  172298. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172299. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172300. }
  172301. }
  172302. }
  172303. /*
  172304. * Finish up at end of an output pass.
  172305. */
  172306. METHODDEF(void)
  172307. finish_output_pass (j_decompress_ptr cinfo)
  172308. {
  172309. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172310. if (cinfo->quantize_colors)
  172311. (*cinfo->cquantize->finish_pass) (cinfo);
  172312. master->pass_number++;
  172313. }
  172314. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172315. /*
  172316. * Switch to a new external colormap between output passes.
  172317. */
  172318. GLOBAL(void)
  172319. jpeg_new_colormap (j_decompress_ptr cinfo)
  172320. {
  172321. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172322. /* Prevent application from calling me at wrong times */
  172323. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172324. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172325. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172326. cinfo->colormap != NULL) {
  172327. /* Select 2-pass quantizer for external colormap use */
  172328. cinfo->cquantize = master->quantizer_2pass;
  172329. /* Notify quantizer of colormap change */
  172330. (*cinfo->cquantize->new_color_map) (cinfo);
  172331. master->pub.is_dummy_pass = FALSE; /* just in case */
  172332. } else
  172333. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172334. }
  172335. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172336. /*
  172337. * Initialize master decompression control and select active modules.
  172338. * This is performed at the start of jpeg_start_decompress.
  172339. */
  172340. GLOBAL(void)
  172341. jinit_master_decompress (j_decompress_ptr cinfo)
  172342. {
  172343. my_master_ptr6 master;
  172344. master = (my_master_ptr6)
  172345. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172346. SIZEOF(my_decomp_master));
  172347. cinfo->master = (struct jpeg_decomp_master *) master;
  172348. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172349. master->pub.finish_output_pass = finish_output_pass;
  172350. master->pub.is_dummy_pass = FALSE;
  172351. master_selection(cinfo);
  172352. }
  172353. /*** End of inlined file: jdmaster.c ***/
  172354. #undef FIX
  172355. /*** Start of inlined file: jdmerge.c ***/
  172356. #define JPEG_INTERNALS
  172357. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172358. /* Private subobject */
  172359. typedef struct {
  172360. struct jpeg_upsampler pub; /* public fields */
  172361. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172362. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172363. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172364. JSAMPARRAY output_buf));
  172365. /* Private state for YCC->RGB conversion */
  172366. int * Cr_r_tab; /* => table for Cr to R conversion */
  172367. int * Cb_b_tab; /* => table for Cb to B conversion */
  172368. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172369. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172370. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172371. * We need a "spare" row buffer to hold the second output row if the
  172372. * application provides just a one-row buffer; we also use the spare
  172373. * to discard the dummy last row if the image height is odd.
  172374. */
  172375. JSAMPROW spare_row;
  172376. boolean spare_full; /* T if spare buffer is occupied */
  172377. JDIMENSION out_row_width; /* samples per output row */
  172378. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172379. } my_upsampler;
  172380. typedef my_upsampler * my_upsample_ptr;
  172381. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172382. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172383. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172384. /*
  172385. * Initialize tables for YCC->RGB colorspace conversion.
  172386. * This is taken directly from jdcolor.c; see that file for more info.
  172387. */
  172388. LOCAL(void)
  172389. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172390. {
  172391. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172392. int i;
  172393. INT32 x;
  172394. SHIFT_TEMPS
  172395. upsample->Cr_r_tab = (int *)
  172396. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172397. (MAXJSAMPLE+1) * SIZEOF(int));
  172398. upsample->Cb_b_tab = (int *)
  172399. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172400. (MAXJSAMPLE+1) * SIZEOF(int));
  172401. upsample->Cr_g_tab = (INT32 *)
  172402. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172403. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172404. upsample->Cb_g_tab = (INT32 *)
  172405. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172406. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172407. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172408. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172409. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172410. /* Cr=>R value is nearest int to 1.40200 * x */
  172411. upsample->Cr_r_tab[i] = (int)
  172412. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172413. /* Cb=>B value is nearest int to 1.77200 * x */
  172414. upsample->Cb_b_tab[i] = (int)
  172415. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172416. /* Cr=>G value is scaled-up -0.71414 * x */
  172417. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172418. /* Cb=>G value is scaled-up -0.34414 * x */
  172419. /* We also add in ONE_HALF so that need not do it in inner loop */
  172420. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172421. }
  172422. }
  172423. /*
  172424. * Initialize for an upsampling pass.
  172425. */
  172426. METHODDEF(void)
  172427. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172428. {
  172429. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172430. /* Mark the spare buffer empty */
  172431. upsample->spare_full = FALSE;
  172432. /* Initialize total-height counter for detecting bottom of image */
  172433. upsample->rows_to_go = cinfo->output_height;
  172434. }
  172435. /*
  172436. * Control routine to do upsampling (and color conversion).
  172437. *
  172438. * The control routine just handles the row buffering considerations.
  172439. */
  172440. METHODDEF(void)
  172441. merged_2v_upsample (j_decompress_ptr cinfo,
  172442. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172443. JDIMENSION,
  172444. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172445. JDIMENSION out_rows_avail)
  172446. /* 2:1 vertical sampling case: may need a spare row. */
  172447. {
  172448. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172449. JSAMPROW work_ptrs[2];
  172450. JDIMENSION num_rows; /* number of rows returned to caller */
  172451. if (upsample->spare_full) {
  172452. /* If we have a spare row saved from a previous cycle, just return it. */
  172453. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172454. 1, upsample->out_row_width);
  172455. num_rows = 1;
  172456. upsample->spare_full = FALSE;
  172457. } else {
  172458. /* Figure number of rows to return to caller. */
  172459. num_rows = 2;
  172460. /* Not more than the distance to the end of the image. */
  172461. if (num_rows > upsample->rows_to_go)
  172462. num_rows = upsample->rows_to_go;
  172463. /* And not more than what the client can accept: */
  172464. out_rows_avail -= *out_row_ctr;
  172465. if (num_rows > out_rows_avail)
  172466. num_rows = out_rows_avail;
  172467. /* Create output pointer array for upsampler. */
  172468. work_ptrs[0] = output_buf[*out_row_ctr];
  172469. if (num_rows > 1) {
  172470. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172471. } else {
  172472. work_ptrs[1] = upsample->spare_row;
  172473. upsample->spare_full = TRUE;
  172474. }
  172475. /* Now do the upsampling. */
  172476. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172477. }
  172478. /* Adjust counts */
  172479. *out_row_ctr += num_rows;
  172480. upsample->rows_to_go -= num_rows;
  172481. /* When the buffer is emptied, declare this input row group consumed */
  172482. if (! upsample->spare_full)
  172483. (*in_row_group_ctr)++;
  172484. }
  172485. METHODDEF(void)
  172486. merged_1v_upsample (j_decompress_ptr cinfo,
  172487. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172488. JDIMENSION,
  172489. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172490. JDIMENSION)
  172491. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172492. {
  172493. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172494. /* Just do the upsampling. */
  172495. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172496. output_buf + *out_row_ctr);
  172497. /* Adjust counts */
  172498. (*out_row_ctr)++;
  172499. (*in_row_group_ctr)++;
  172500. }
  172501. /*
  172502. * These are the routines invoked by the control routines to do
  172503. * the actual upsampling/conversion. One row group is processed per call.
  172504. *
  172505. * Note: since we may be writing directly into application-supplied buffers,
  172506. * we have to be honest about the output width; we can't assume the buffer
  172507. * has been rounded up to an even width.
  172508. */
  172509. /*
  172510. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172511. */
  172512. METHODDEF(void)
  172513. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172514. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172515. JSAMPARRAY output_buf)
  172516. {
  172517. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172518. register int y, cred, cgreen, cblue;
  172519. int cb, cr;
  172520. register JSAMPROW outptr;
  172521. JSAMPROW inptr0, inptr1, inptr2;
  172522. JDIMENSION col;
  172523. /* copy these pointers into registers if possible */
  172524. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172525. int * Crrtab = upsample->Cr_r_tab;
  172526. int * Cbbtab = upsample->Cb_b_tab;
  172527. INT32 * Crgtab = upsample->Cr_g_tab;
  172528. INT32 * Cbgtab = upsample->Cb_g_tab;
  172529. SHIFT_TEMPS
  172530. inptr0 = input_buf[0][in_row_group_ctr];
  172531. inptr1 = input_buf[1][in_row_group_ctr];
  172532. inptr2 = input_buf[2][in_row_group_ctr];
  172533. outptr = output_buf[0];
  172534. /* Loop for each pair of output pixels */
  172535. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172536. /* Do the chroma part of the calculation */
  172537. cb = GETJSAMPLE(*inptr1++);
  172538. cr = GETJSAMPLE(*inptr2++);
  172539. cred = Crrtab[cr];
  172540. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172541. cblue = Cbbtab[cb];
  172542. /* Fetch 2 Y values and emit 2 pixels */
  172543. y = GETJSAMPLE(*inptr0++);
  172544. outptr[RGB_RED] = range_limit[y + cred];
  172545. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172546. outptr[RGB_BLUE] = range_limit[y + cblue];
  172547. outptr += RGB_PIXELSIZE;
  172548. y = GETJSAMPLE(*inptr0++);
  172549. outptr[RGB_RED] = range_limit[y + cred];
  172550. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172551. outptr[RGB_BLUE] = range_limit[y + cblue];
  172552. outptr += RGB_PIXELSIZE;
  172553. }
  172554. /* If image width is odd, do the last output column separately */
  172555. if (cinfo->output_width & 1) {
  172556. cb = GETJSAMPLE(*inptr1);
  172557. cr = GETJSAMPLE(*inptr2);
  172558. cred = Crrtab[cr];
  172559. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172560. cblue = Cbbtab[cb];
  172561. y = GETJSAMPLE(*inptr0);
  172562. outptr[RGB_RED] = range_limit[y + cred];
  172563. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172564. outptr[RGB_BLUE] = range_limit[y + cblue];
  172565. }
  172566. }
  172567. /*
  172568. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172569. */
  172570. METHODDEF(void)
  172571. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172572. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172573. JSAMPARRAY output_buf)
  172574. {
  172575. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172576. register int y, cred, cgreen, cblue;
  172577. int cb, cr;
  172578. register JSAMPROW outptr0, outptr1;
  172579. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172580. JDIMENSION col;
  172581. /* copy these pointers into registers if possible */
  172582. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172583. int * Crrtab = upsample->Cr_r_tab;
  172584. int * Cbbtab = upsample->Cb_b_tab;
  172585. INT32 * Crgtab = upsample->Cr_g_tab;
  172586. INT32 * Cbgtab = upsample->Cb_g_tab;
  172587. SHIFT_TEMPS
  172588. inptr00 = input_buf[0][in_row_group_ctr*2];
  172589. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172590. inptr1 = input_buf[1][in_row_group_ctr];
  172591. inptr2 = input_buf[2][in_row_group_ctr];
  172592. outptr0 = output_buf[0];
  172593. outptr1 = output_buf[1];
  172594. /* Loop for each group of output pixels */
  172595. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172596. /* Do the chroma part of the calculation */
  172597. cb = GETJSAMPLE(*inptr1++);
  172598. cr = GETJSAMPLE(*inptr2++);
  172599. cred = Crrtab[cr];
  172600. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172601. cblue = Cbbtab[cb];
  172602. /* Fetch 4 Y values and emit 4 pixels */
  172603. y = GETJSAMPLE(*inptr00++);
  172604. outptr0[RGB_RED] = range_limit[y + cred];
  172605. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172606. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172607. outptr0 += RGB_PIXELSIZE;
  172608. y = GETJSAMPLE(*inptr00++);
  172609. outptr0[RGB_RED] = range_limit[y + cred];
  172610. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172611. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172612. outptr0 += RGB_PIXELSIZE;
  172613. y = GETJSAMPLE(*inptr01++);
  172614. outptr1[RGB_RED] = range_limit[y + cred];
  172615. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172616. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172617. outptr1 += RGB_PIXELSIZE;
  172618. y = GETJSAMPLE(*inptr01++);
  172619. outptr1[RGB_RED] = range_limit[y + cred];
  172620. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172621. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172622. outptr1 += RGB_PIXELSIZE;
  172623. }
  172624. /* If image width is odd, do the last output column separately */
  172625. if (cinfo->output_width & 1) {
  172626. cb = GETJSAMPLE(*inptr1);
  172627. cr = GETJSAMPLE(*inptr2);
  172628. cred = Crrtab[cr];
  172629. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172630. cblue = Cbbtab[cb];
  172631. y = GETJSAMPLE(*inptr00);
  172632. outptr0[RGB_RED] = range_limit[y + cred];
  172633. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172634. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172635. y = GETJSAMPLE(*inptr01);
  172636. outptr1[RGB_RED] = range_limit[y + cred];
  172637. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172638. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172639. }
  172640. }
  172641. /*
  172642. * Module initialization routine for merged upsampling/color conversion.
  172643. *
  172644. * NB: this is called under the conditions determined by use_merged_upsample()
  172645. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172646. * of this module; no safety checks are made here.
  172647. */
  172648. GLOBAL(void)
  172649. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172650. {
  172651. my_upsample_ptr upsample;
  172652. upsample = (my_upsample_ptr)
  172653. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172654. SIZEOF(my_upsampler));
  172655. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172656. upsample->pub.start_pass = start_pass_merged_upsample;
  172657. upsample->pub.need_context_rows = FALSE;
  172658. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172659. if (cinfo->max_v_samp_factor == 2) {
  172660. upsample->pub.upsample = merged_2v_upsample;
  172661. upsample->upmethod = h2v2_merged_upsample;
  172662. /* Allocate a spare row buffer */
  172663. upsample->spare_row = (JSAMPROW)
  172664. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172665. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172666. } else {
  172667. upsample->pub.upsample = merged_1v_upsample;
  172668. upsample->upmethod = h2v1_merged_upsample;
  172669. /* No spare row needed */
  172670. upsample->spare_row = NULL;
  172671. }
  172672. build_ycc_rgb_table2(cinfo);
  172673. }
  172674. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172675. /*** End of inlined file: jdmerge.c ***/
  172676. #undef ASSIGN_STATE
  172677. /*** Start of inlined file: jdphuff.c ***/
  172678. #define JPEG_INTERNALS
  172679. #ifdef D_PROGRESSIVE_SUPPORTED
  172680. /*
  172681. * Expanded entropy decoder object for progressive Huffman decoding.
  172682. *
  172683. * The savable_state subrecord contains fields that change within an MCU,
  172684. * but must not be updated permanently until we complete the MCU.
  172685. */
  172686. typedef struct {
  172687. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172688. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172689. } savable_state3;
  172690. /* This macro is to work around compilers with missing or broken
  172691. * structure assignment. You'll need to fix this code if you have
  172692. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172693. */
  172694. #ifndef NO_STRUCT_ASSIGN
  172695. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172696. #else
  172697. #if MAX_COMPS_IN_SCAN == 4
  172698. #define ASSIGN_STATE(dest,src) \
  172699. ((dest).EOBRUN = (src).EOBRUN, \
  172700. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172701. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172702. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172703. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172704. #endif
  172705. #endif
  172706. typedef struct {
  172707. struct jpeg_entropy_decoder pub; /* public fields */
  172708. /* These fields are loaded into local variables at start of each MCU.
  172709. * In case of suspension, we exit WITHOUT updating them.
  172710. */
  172711. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172712. savable_state3 saved; /* Other state at start of MCU */
  172713. /* These fields are NOT loaded into local working state. */
  172714. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172715. /* Pointers to derived tables (these workspaces have image lifespan) */
  172716. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172717. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172718. } phuff_entropy_decoder;
  172719. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172720. /* Forward declarations */
  172721. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172722. JBLOCKROW *MCU_data));
  172723. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172724. JBLOCKROW *MCU_data));
  172725. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172726. JBLOCKROW *MCU_data));
  172727. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172728. JBLOCKROW *MCU_data));
  172729. /*
  172730. * Initialize for a Huffman-compressed scan.
  172731. */
  172732. METHODDEF(void)
  172733. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172734. {
  172735. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172736. boolean is_DC_band, bad;
  172737. int ci, coefi, tbl;
  172738. int *coef_bit_ptr;
  172739. jpeg_component_info * compptr;
  172740. is_DC_band = (cinfo->Ss == 0);
  172741. /* Validate scan parameters */
  172742. bad = FALSE;
  172743. if (is_DC_band) {
  172744. if (cinfo->Se != 0)
  172745. bad = TRUE;
  172746. } else {
  172747. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172748. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172749. bad = TRUE;
  172750. /* AC scans may have only one component */
  172751. if (cinfo->comps_in_scan != 1)
  172752. bad = TRUE;
  172753. }
  172754. if (cinfo->Ah != 0) {
  172755. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172756. if (cinfo->Al != cinfo->Ah-1)
  172757. bad = TRUE;
  172758. }
  172759. if (cinfo->Al > 13) /* need not check for < 0 */
  172760. bad = TRUE;
  172761. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172762. * but the spec doesn't say so, and we try to be liberal about what we
  172763. * accept. Note: large Al values could result in out-of-range DC
  172764. * coefficients during early scans, leading to bizarre displays due to
  172765. * overflows in the IDCT math. But we won't crash.
  172766. */
  172767. if (bad)
  172768. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172769. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172770. /* Update progression status, and verify that scan order is legal.
  172771. * Note that inter-scan inconsistencies are treated as warnings
  172772. * not fatal errors ... not clear if this is right way to behave.
  172773. */
  172774. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172775. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172776. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172777. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172778. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172779. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172780. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172781. if (cinfo->Ah != expected)
  172782. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172783. coef_bit_ptr[coefi] = cinfo->Al;
  172784. }
  172785. }
  172786. /* Select MCU decoding routine */
  172787. if (cinfo->Ah == 0) {
  172788. if (is_DC_band)
  172789. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172790. else
  172791. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172792. } else {
  172793. if (is_DC_band)
  172794. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172795. else
  172796. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172797. }
  172798. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172799. compptr = cinfo->cur_comp_info[ci];
  172800. /* Make sure requested tables are present, and compute derived tables.
  172801. * We may build same derived table more than once, but it's not expensive.
  172802. */
  172803. if (is_DC_band) {
  172804. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172805. tbl = compptr->dc_tbl_no;
  172806. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172807. & entropy->derived_tbls[tbl]);
  172808. }
  172809. } else {
  172810. tbl = compptr->ac_tbl_no;
  172811. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172812. & entropy->derived_tbls[tbl]);
  172813. /* remember the single active table */
  172814. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172815. }
  172816. /* Initialize DC predictions to 0 */
  172817. entropy->saved.last_dc_val[ci] = 0;
  172818. }
  172819. /* Initialize bitread state variables */
  172820. entropy->bitstate.bits_left = 0;
  172821. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172822. entropy->pub.insufficient_data = FALSE;
  172823. /* Initialize private state variables */
  172824. entropy->saved.EOBRUN = 0;
  172825. /* Initialize restart counter */
  172826. entropy->restarts_to_go = cinfo->restart_interval;
  172827. }
  172828. /*
  172829. * Check for a restart marker & resynchronize decoder.
  172830. * Returns FALSE if must suspend.
  172831. */
  172832. LOCAL(boolean)
  172833. process_restartp (j_decompress_ptr cinfo)
  172834. {
  172835. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172836. int ci;
  172837. /* Throw away any unused bits remaining in bit buffer; */
  172838. /* include any full bytes in next_marker's count of discarded bytes */
  172839. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172840. entropy->bitstate.bits_left = 0;
  172841. /* Advance past the RSTn marker */
  172842. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172843. return FALSE;
  172844. /* Re-initialize DC predictions to 0 */
  172845. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172846. entropy->saved.last_dc_val[ci] = 0;
  172847. /* Re-init EOB run count, too */
  172848. entropy->saved.EOBRUN = 0;
  172849. /* Reset restart counter */
  172850. entropy->restarts_to_go = cinfo->restart_interval;
  172851. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172852. * against a marker. In that case we will end up treating the next data
  172853. * segment as empty, and we can avoid producing bogus output pixels by
  172854. * leaving the flag set.
  172855. */
  172856. if (cinfo->unread_marker == 0)
  172857. entropy->pub.insufficient_data = FALSE;
  172858. return TRUE;
  172859. }
  172860. /*
  172861. * Huffman MCU decoding.
  172862. * Each of these routines decodes and returns one MCU's worth of
  172863. * Huffman-compressed coefficients.
  172864. * The coefficients are reordered from zigzag order into natural array order,
  172865. * but are not dequantized.
  172866. *
  172867. * The i'th block of the MCU is stored into the block pointed to by
  172868. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172869. *
  172870. * We return FALSE if data source requested suspension. In that case no
  172871. * changes have been made to permanent state. (Exception: some output
  172872. * coefficients may already have been assigned. This is harmless for
  172873. * spectral selection, since we'll just re-assign them on the next call.
  172874. * Successive approximation AC refinement has to be more careful, however.)
  172875. */
  172876. /*
  172877. * MCU decoding for DC initial scan (either spectral selection,
  172878. * or first pass of successive approximation).
  172879. */
  172880. METHODDEF(boolean)
  172881. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172882. {
  172883. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172884. int Al = cinfo->Al;
  172885. register int s, r;
  172886. int blkn, ci;
  172887. JBLOCKROW block;
  172888. BITREAD_STATE_VARS;
  172889. savable_state3 state;
  172890. d_derived_tbl * tbl;
  172891. jpeg_component_info * compptr;
  172892. /* Process restart marker if needed; may have to suspend */
  172893. if (cinfo->restart_interval) {
  172894. if (entropy->restarts_to_go == 0)
  172895. if (! process_restartp(cinfo))
  172896. return FALSE;
  172897. }
  172898. /* If we've run out of data, just leave the MCU set to zeroes.
  172899. * This way, we return uniform gray for the remainder of the segment.
  172900. */
  172901. if (! entropy->pub.insufficient_data) {
  172902. /* Load up working state */
  172903. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172904. ASSIGN_STATE(state, entropy->saved);
  172905. /* Outer loop handles each block in the MCU */
  172906. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172907. block = MCU_data[blkn];
  172908. ci = cinfo->MCU_membership[blkn];
  172909. compptr = cinfo->cur_comp_info[ci];
  172910. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172911. /* Decode a single block's worth of coefficients */
  172912. /* Section F.2.2.1: decode the DC coefficient difference */
  172913. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172914. if (s) {
  172915. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172916. r = GET_BITS(s);
  172917. s = HUFF_EXTEND(r, s);
  172918. }
  172919. /* Convert DC difference to actual value, update last_dc_val */
  172920. s += state.last_dc_val[ci];
  172921. state.last_dc_val[ci] = s;
  172922. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172923. (*block)[0] = (JCOEF) (s << Al);
  172924. }
  172925. /* Completed MCU, so update state */
  172926. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172927. ASSIGN_STATE(entropy->saved, state);
  172928. }
  172929. /* Account for restart interval (no-op if not using restarts) */
  172930. entropy->restarts_to_go--;
  172931. return TRUE;
  172932. }
  172933. /*
  172934. * MCU decoding for AC initial scan (either spectral selection,
  172935. * or first pass of successive approximation).
  172936. */
  172937. METHODDEF(boolean)
  172938. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172939. {
  172940. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172941. int Se = cinfo->Se;
  172942. int Al = cinfo->Al;
  172943. register int s, k, r;
  172944. unsigned int EOBRUN;
  172945. JBLOCKROW block;
  172946. BITREAD_STATE_VARS;
  172947. d_derived_tbl * tbl;
  172948. /* Process restart marker if needed; may have to suspend */
  172949. if (cinfo->restart_interval) {
  172950. if (entropy->restarts_to_go == 0)
  172951. if (! process_restartp(cinfo))
  172952. return FALSE;
  172953. }
  172954. /* If we've run out of data, just leave the MCU set to zeroes.
  172955. * This way, we return uniform gray for the remainder of the segment.
  172956. */
  172957. if (! entropy->pub.insufficient_data) {
  172958. /* Load up working state.
  172959. * We can avoid loading/saving bitread state if in an EOB run.
  172960. */
  172961. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172962. /* There is always only one block per MCU */
  172963. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172964. EOBRUN--; /* ...process it now (we do nothing) */
  172965. else {
  172966. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172967. block = MCU_data[0];
  172968. tbl = entropy->ac_derived_tbl;
  172969. for (k = cinfo->Ss; k <= Se; k++) {
  172970. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172971. r = s >> 4;
  172972. s &= 15;
  172973. if (s) {
  172974. k += r;
  172975. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172976. r = GET_BITS(s);
  172977. s = HUFF_EXTEND(r, s);
  172978. /* Scale and output coefficient in natural (dezigzagged) order */
  172979. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172980. } else {
  172981. if (r == 15) { /* ZRL */
  172982. k += 15; /* skip 15 zeroes in band */
  172983. } else { /* EOBr, run length is 2^r + appended bits */
  172984. EOBRUN = 1 << r;
  172985. if (r) { /* EOBr, r > 0 */
  172986. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172987. r = GET_BITS(r);
  172988. EOBRUN += r;
  172989. }
  172990. EOBRUN--; /* this band is processed at this moment */
  172991. break; /* force end-of-band */
  172992. }
  172993. }
  172994. }
  172995. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172996. }
  172997. /* Completed MCU, so update state */
  172998. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172999. }
  173000. /* Account for restart interval (no-op if not using restarts) */
  173001. entropy->restarts_to_go--;
  173002. return TRUE;
  173003. }
  173004. /*
  173005. * MCU decoding for DC successive approximation refinement scan.
  173006. * Note: we assume such scans can be multi-component, although the spec
  173007. * is not very clear on the point.
  173008. */
  173009. METHODDEF(boolean)
  173010. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173011. {
  173012. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173013. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173014. int blkn;
  173015. JBLOCKROW block;
  173016. BITREAD_STATE_VARS;
  173017. /* Process restart marker if needed; may have to suspend */
  173018. if (cinfo->restart_interval) {
  173019. if (entropy->restarts_to_go == 0)
  173020. if (! process_restartp(cinfo))
  173021. return FALSE;
  173022. }
  173023. /* Not worth the cycles to check insufficient_data here,
  173024. * since we will not change the data anyway if we read zeroes.
  173025. */
  173026. /* Load up working state */
  173027. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173028. /* Outer loop handles each block in the MCU */
  173029. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173030. block = MCU_data[blkn];
  173031. /* Encoded data is simply the next bit of the two's-complement DC value */
  173032. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173033. if (GET_BITS(1))
  173034. (*block)[0] |= p1;
  173035. /* Note: since we use |=, repeating the assignment later is safe */
  173036. }
  173037. /* Completed MCU, so update state */
  173038. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173039. /* Account for restart interval (no-op if not using restarts) */
  173040. entropy->restarts_to_go--;
  173041. return TRUE;
  173042. }
  173043. /*
  173044. * MCU decoding for AC successive approximation refinement scan.
  173045. */
  173046. METHODDEF(boolean)
  173047. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173048. {
  173049. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173050. int Se = cinfo->Se;
  173051. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173052. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173053. register int s, k, r;
  173054. unsigned int EOBRUN;
  173055. JBLOCKROW block;
  173056. JCOEFPTR thiscoef;
  173057. BITREAD_STATE_VARS;
  173058. d_derived_tbl * tbl;
  173059. int num_newnz;
  173060. int newnz_pos[DCTSIZE2];
  173061. /* Process restart marker if needed; may have to suspend */
  173062. if (cinfo->restart_interval) {
  173063. if (entropy->restarts_to_go == 0)
  173064. if (! process_restartp(cinfo))
  173065. return FALSE;
  173066. }
  173067. /* If we've run out of data, don't modify the MCU.
  173068. */
  173069. if (! entropy->pub.insufficient_data) {
  173070. /* Load up working state */
  173071. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173072. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173073. /* There is always only one block per MCU */
  173074. block = MCU_data[0];
  173075. tbl = entropy->ac_derived_tbl;
  173076. /* If we are forced to suspend, we must undo the assignments to any newly
  173077. * nonzero coefficients in the block, because otherwise we'd get confused
  173078. * next time about which coefficients were already nonzero.
  173079. * But we need not undo addition of bits to already-nonzero coefficients;
  173080. * instead, we can test the current bit to see if we already did it.
  173081. */
  173082. num_newnz = 0;
  173083. /* initialize coefficient loop counter to start of band */
  173084. k = cinfo->Ss;
  173085. if (EOBRUN == 0) {
  173086. for (; k <= Se; k++) {
  173087. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173088. r = s >> 4;
  173089. s &= 15;
  173090. if (s) {
  173091. if (s != 1) /* size of new coef should always be 1 */
  173092. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173093. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173094. if (GET_BITS(1))
  173095. s = p1; /* newly nonzero coef is positive */
  173096. else
  173097. s = m1; /* newly nonzero coef is negative */
  173098. } else {
  173099. if (r != 15) {
  173100. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173101. if (r) {
  173102. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173103. r = GET_BITS(r);
  173104. EOBRUN += r;
  173105. }
  173106. break; /* rest of block is handled by EOB logic */
  173107. }
  173108. /* note s = 0 for processing ZRL */
  173109. }
  173110. /* Advance over already-nonzero coefs and r still-zero coefs,
  173111. * appending correction bits to the nonzeroes. A correction bit is 1
  173112. * if the absolute value of the coefficient must be increased.
  173113. */
  173114. do {
  173115. thiscoef = *block + jpeg_natural_order[k];
  173116. if (*thiscoef != 0) {
  173117. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173118. if (GET_BITS(1)) {
  173119. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173120. if (*thiscoef >= 0)
  173121. *thiscoef += p1;
  173122. else
  173123. *thiscoef += m1;
  173124. }
  173125. }
  173126. } else {
  173127. if (--r < 0)
  173128. break; /* reached target zero coefficient */
  173129. }
  173130. k++;
  173131. } while (k <= Se);
  173132. if (s) {
  173133. int pos = jpeg_natural_order[k];
  173134. /* Output newly nonzero coefficient */
  173135. (*block)[pos] = (JCOEF) s;
  173136. /* Remember its position in case we have to suspend */
  173137. newnz_pos[num_newnz++] = pos;
  173138. }
  173139. }
  173140. }
  173141. if (EOBRUN > 0) {
  173142. /* Scan any remaining coefficient positions after the end-of-band
  173143. * (the last newly nonzero coefficient, if any). Append a correction
  173144. * bit to each already-nonzero coefficient. A correction bit is 1
  173145. * if the absolute value of the coefficient must be increased.
  173146. */
  173147. for (; k <= Se; k++) {
  173148. thiscoef = *block + jpeg_natural_order[k];
  173149. if (*thiscoef != 0) {
  173150. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173151. if (GET_BITS(1)) {
  173152. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173153. if (*thiscoef >= 0)
  173154. *thiscoef += p1;
  173155. else
  173156. *thiscoef += m1;
  173157. }
  173158. }
  173159. }
  173160. }
  173161. /* Count one block completed in EOB run */
  173162. EOBRUN--;
  173163. }
  173164. /* Completed MCU, so update state */
  173165. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173166. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173167. }
  173168. /* Account for restart interval (no-op if not using restarts) */
  173169. entropy->restarts_to_go--;
  173170. return TRUE;
  173171. undoit:
  173172. /* Re-zero any output coefficients that we made newly nonzero */
  173173. while (num_newnz > 0)
  173174. (*block)[newnz_pos[--num_newnz]] = 0;
  173175. return FALSE;
  173176. }
  173177. /*
  173178. * Module initialization routine for progressive Huffman entropy decoding.
  173179. */
  173180. GLOBAL(void)
  173181. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173182. {
  173183. phuff_entropy_ptr2 entropy;
  173184. int *coef_bit_ptr;
  173185. int ci, i;
  173186. entropy = (phuff_entropy_ptr2)
  173187. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173188. SIZEOF(phuff_entropy_decoder));
  173189. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173190. entropy->pub.start_pass = start_pass_phuff_decoder;
  173191. /* Mark derived tables unallocated */
  173192. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173193. entropy->derived_tbls[i] = NULL;
  173194. }
  173195. /* Create progression status table */
  173196. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173197. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173198. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173199. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173200. for (ci = 0; ci < cinfo->num_components; ci++)
  173201. for (i = 0; i < DCTSIZE2; i++)
  173202. *coef_bit_ptr++ = -1;
  173203. }
  173204. #endif /* D_PROGRESSIVE_SUPPORTED */
  173205. /*** End of inlined file: jdphuff.c ***/
  173206. /*** Start of inlined file: jdpostct.c ***/
  173207. #define JPEG_INTERNALS
  173208. /* Private buffer controller object */
  173209. typedef struct {
  173210. struct jpeg_d_post_controller pub; /* public fields */
  173211. /* Color quantization source buffer: this holds output data from
  173212. * the upsample/color conversion step to be passed to the quantizer.
  173213. * For two-pass color quantization, we need a full-image buffer;
  173214. * for one-pass operation, a strip buffer is sufficient.
  173215. */
  173216. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173217. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173218. JDIMENSION strip_height; /* buffer size in rows */
  173219. /* for two-pass mode only: */
  173220. JDIMENSION starting_row; /* row # of first row in current strip */
  173221. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173222. } my_post_controller;
  173223. typedef my_post_controller * my_post_ptr;
  173224. /* Forward declarations */
  173225. METHODDEF(void) post_process_1pass
  173226. JPP((j_decompress_ptr cinfo,
  173227. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173228. JDIMENSION in_row_groups_avail,
  173229. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173230. JDIMENSION out_rows_avail));
  173231. #ifdef QUANT_2PASS_SUPPORTED
  173232. METHODDEF(void) post_process_prepass
  173233. JPP((j_decompress_ptr cinfo,
  173234. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173235. JDIMENSION in_row_groups_avail,
  173236. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173237. JDIMENSION out_rows_avail));
  173238. METHODDEF(void) post_process_2pass
  173239. JPP((j_decompress_ptr cinfo,
  173240. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173241. JDIMENSION in_row_groups_avail,
  173242. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173243. JDIMENSION out_rows_avail));
  173244. #endif
  173245. /*
  173246. * Initialize for a processing pass.
  173247. */
  173248. METHODDEF(void)
  173249. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173250. {
  173251. my_post_ptr post = (my_post_ptr) cinfo->post;
  173252. switch (pass_mode) {
  173253. case JBUF_PASS_THRU:
  173254. if (cinfo->quantize_colors) {
  173255. /* Single-pass processing with color quantization. */
  173256. post->pub.post_process_data = post_process_1pass;
  173257. /* We could be doing buffered-image output before starting a 2-pass
  173258. * color quantization; in that case, jinit_d_post_controller did not
  173259. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173260. */
  173261. if (post->buffer == NULL) {
  173262. post->buffer = (*cinfo->mem->access_virt_sarray)
  173263. ((j_common_ptr) cinfo, post->whole_image,
  173264. (JDIMENSION) 0, post->strip_height, TRUE);
  173265. }
  173266. } else {
  173267. /* For single-pass processing without color quantization,
  173268. * I have no work to do; just call the upsampler directly.
  173269. */
  173270. post->pub.post_process_data = cinfo->upsample->upsample;
  173271. }
  173272. break;
  173273. #ifdef QUANT_2PASS_SUPPORTED
  173274. case JBUF_SAVE_AND_PASS:
  173275. /* First pass of 2-pass quantization */
  173276. if (post->whole_image == NULL)
  173277. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173278. post->pub.post_process_data = post_process_prepass;
  173279. break;
  173280. case JBUF_CRANK_DEST:
  173281. /* Second pass of 2-pass quantization */
  173282. if (post->whole_image == NULL)
  173283. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173284. post->pub.post_process_data = post_process_2pass;
  173285. break;
  173286. #endif /* QUANT_2PASS_SUPPORTED */
  173287. default:
  173288. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173289. break;
  173290. }
  173291. post->starting_row = post->next_row = 0;
  173292. }
  173293. /*
  173294. * Process some data in the one-pass (strip buffer) case.
  173295. * This is used for color precision reduction as well as one-pass quantization.
  173296. */
  173297. METHODDEF(void)
  173298. post_process_1pass (j_decompress_ptr cinfo,
  173299. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173300. JDIMENSION in_row_groups_avail,
  173301. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173302. JDIMENSION out_rows_avail)
  173303. {
  173304. my_post_ptr post = (my_post_ptr) cinfo->post;
  173305. JDIMENSION num_rows, max_rows;
  173306. /* Fill the buffer, but not more than what we can dump out in one go. */
  173307. /* Note we rely on the upsampler to detect bottom of image. */
  173308. max_rows = out_rows_avail - *out_row_ctr;
  173309. if (max_rows > post->strip_height)
  173310. max_rows = post->strip_height;
  173311. num_rows = 0;
  173312. (*cinfo->upsample->upsample) (cinfo,
  173313. input_buf, in_row_group_ctr, in_row_groups_avail,
  173314. post->buffer, &num_rows, max_rows);
  173315. /* Quantize and emit data. */
  173316. (*cinfo->cquantize->color_quantize) (cinfo,
  173317. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173318. *out_row_ctr += num_rows;
  173319. }
  173320. #ifdef QUANT_2PASS_SUPPORTED
  173321. /*
  173322. * Process some data in the first pass of 2-pass quantization.
  173323. */
  173324. METHODDEF(void)
  173325. post_process_prepass (j_decompress_ptr cinfo,
  173326. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173327. JDIMENSION in_row_groups_avail,
  173328. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173329. JDIMENSION)
  173330. {
  173331. my_post_ptr post = (my_post_ptr) cinfo->post;
  173332. JDIMENSION old_next_row, num_rows;
  173333. /* Reposition virtual buffer if at start of strip. */
  173334. if (post->next_row == 0) {
  173335. post->buffer = (*cinfo->mem->access_virt_sarray)
  173336. ((j_common_ptr) cinfo, post->whole_image,
  173337. post->starting_row, post->strip_height, TRUE);
  173338. }
  173339. /* Upsample some data (up to a strip height's worth). */
  173340. old_next_row = post->next_row;
  173341. (*cinfo->upsample->upsample) (cinfo,
  173342. input_buf, in_row_group_ctr, in_row_groups_avail,
  173343. post->buffer, &post->next_row, post->strip_height);
  173344. /* Allow quantizer to scan new data. No data is emitted, */
  173345. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173346. if (post->next_row > old_next_row) {
  173347. num_rows = post->next_row - old_next_row;
  173348. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173349. (JSAMPARRAY) NULL, (int) num_rows);
  173350. *out_row_ctr += num_rows;
  173351. }
  173352. /* Advance if we filled the strip. */
  173353. if (post->next_row >= post->strip_height) {
  173354. post->starting_row += post->strip_height;
  173355. post->next_row = 0;
  173356. }
  173357. }
  173358. /*
  173359. * Process some data in the second pass of 2-pass quantization.
  173360. */
  173361. METHODDEF(void)
  173362. post_process_2pass (j_decompress_ptr cinfo,
  173363. JSAMPIMAGE, JDIMENSION *,
  173364. JDIMENSION,
  173365. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173366. JDIMENSION out_rows_avail)
  173367. {
  173368. my_post_ptr post = (my_post_ptr) cinfo->post;
  173369. JDIMENSION num_rows, max_rows;
  173370. /* Reposition virtual buffer if at start of strip. */
  173371. if (post->next_row == 0) {
  173372. post->buffer = (*cinfo->mem->access_virt_sarray)
  173373. ((j_common_ptr) cinfo, post->whole_image,
  173374. post->starting_row, post->strip_height, FALSE);
  173375. }
  173376. /* Determine number of rows to emit. */
  173377. num_rows = post->strip_height - post->next_row; /* available in strip */
  173378. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173379. if (num_rows > max_rows)
  173380. num_rows = max_rows;
  173381. /* We have to check bottom of image here, can't depend on upsampler. */
  173382. max_rows = cinfo->output_height - post->starting_row;
  173383. if (num_rows > max_rows)
  173384. num_rows = max_rows;
  173385. /* Quantize and emit data. */
  173386. (*cinfo->cquantize->color_quantize) (cinfo,
  173387. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173388. (int) num_rows);
  173389. *out_row_ctr += num_rows;
  173390. /* Advance if we filled the strip. */
  173391. post->next_row += num_rows;
  173392. if (post->next_row >= post->strip_height) {
  173393. post->starting_row += post->strip_height;
  173394. post->next_row = 0;
  173395. }
  173396. }
  173397. #endif /* QUANT_2PASS_SUPPORTED */
  173398. /*
  173399. * Initialize postprocessing controller.
  173400. */
  173401. GLOBAL(void)
  173402. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173403. {
  173404. my_post_ptr post;
  173405. post = (my_post_ptr)
  173406. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173407. SIZEOF(my_post_controller));
  173408. cinfo->post = (struct jpeg_d_post_controller *) post;
  173409. post->pub.start_pass = start_pass_dpost;
  173410. post->whole_image = NULL; /* flag for no virtual arrays */
  173411. post->buffer = NULL; /* flag for no strip buffer */
  173412. /* Create the quantization buffer, if needed */
  173413. if (cinfo->quantize_colors) {
  173414. /* The buffer strip height is max_v_samp_factor, which is typically
  173415. * an efficient number of rows for upsampling to return.
  173416. * (In the presence of output rescaling, we might want to be smarter?)
  173417. */
  173418. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173419. if (need_full_buffer) {
  173420. /* Two-pass color quantization: need full-image storage. */
  173421. /* We round up the number of rows to a multiple of the strip height. */
  173422. #ifdef QUANT_2PASS_SUPPORTED
  173423. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173424. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173425. cinfo->output_width * cinfo->out_color_components,
  173426. (JDIMENSION) jround_up((long) cinfo->output_height,
  173427. (long) post->strip_height),
  173428. post->strip_height);
  173429. #else
  173430. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173431. #endif /* QUANT_2PASS_SUPPORTED */
  173432. } else {
  173433. /* One-pass color quantization: just make a strip buffer. */
  173434. post->buffer = (*cinfo->mem->alloc_sarray)
  173435. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173436. cinfo->output_width * cinfo->out_color_components,
  173437. post->strip_height);
  173438. }
  173439. }
  173440. }
  173441. /*** End of inlined file: jdpostct.c ***/
  173442. #undef FIX
  173443. /*** Start of inlined file: jdsample.c ***/
  173444. #define JPEG_INTERNALS
  173445. /* Pointer to routine to upsample a single component */
  173446. typedef JMETHOD(void, upsample1_ptr,
  173447. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173448. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173449. /* Private subobject */
  173450. typedef struct {
  173451. struct jpeg_upsampler pub; /* public fields */
  173452. /* Color conversion buffer. When using separate upsampling and color
  173453. * conversion steps, this buffer holds one upsampled row group until it
  173454. * has been color converted and output.
  173455. * Note: we do not allocate any storage for component(s) which are full-size,
  173456. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173457. * simply set to point to the input data array, thereby avoiding copying.
  173458. */
  173459. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173460. /* Per-component upsampling method pointers */
  173461. upsample1_ptr methods[MAX_COMPONENTS];
  173462. int next_row_out; /* counts rows emitted from color_buf */
  173463. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173464. /* Height of an input row group for each component. */
  173465. int rowgroup_height[MAX_COMPONENTS];
  173466. /* These arrays save pixel expansion factors so that int_expand need not
  173467. * recompute them each time. They are unused for other upsampling methods.
  173468. */
  173469. UINT8 h_expand[MAX_COMPONENTS];
  173470. UINT8 v_expand[MAX_COMPONENTS];
  173471. } my_upsampler2;
  173472. typedef my_upsampler2 * my_upsample_ptr2;
  173473. /*
  173474. * Initialize for an upsampling pass.
  173475. */
  173476. METHODDEF(void)
  173477. start_pass_upsample (j_decompress_ptr cinfo)
  173478. {
  173479. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173480. /* Mark the conversion buffer empty */
  173481. upsample->next_row_out = cinfo->max_v_samp_factor;
  173482. /* Initialize total-height counter for detecting bottom of image */
  173483. upsample->rows_to_go = cinfo->output_height;
  173484. }
  173485. /*
  173486. * Control routine to do upsampling (and color conversion).
  173487. *
  173488. * In this version we upsample each component independently.
  173489. * We upsample one row group into the conversion buffer, then apply
  173490. * color conversion a row at a time.
  173491. */
  173492. METHODDEF(void)
  173493. sep_upsample (j_decompress_ptr cinfo,
  173494. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173495. JDIMENSION,
  173496. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173497. JDIMENSION out_rows_avail)
  173498. {
  173499. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173500. int ci;
  173501. jpeg_component_info * compptr;
  173502. JDIMENSION num_rows;
  173503. /* Fill the conversion buffer, if it's empty */
  173504. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173505. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173506. ci++, compptr++) {
  173507. /* Invoke per-component upsample method. Notice we pass a POINTER
  173508. * to color_buf[ci], so that fullsize_upsample can change it.
  173509. */
  173510. (*upsample->methods[ci]) (cinfo, compptr,
  173511. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173512. upsample->color_buf + ci);
  173513. }
  173514. upsample->next_row_out = 0;
  173515. }
  173516. /* Color-convert and emit rows */
  173517. /* How many we have in the buffer: */
  173518. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173519. /* Not more than the distance to the end of the image. Need this test
  173520. * in case the image height is not a multiple of max_v_samp_factor:
  173521. */
  173522. if (num_rows > upsample->rows_to_go)
  173523. num_rows = upsample->rows_to_go;
  173524. /* And not more than what the client can accept: */
  173525. out_rows_avail -= *out_row_ctr;
  173526. if (num_rows > out_rows_avail)
  173527. num_rows = out_rows_avail;
  173528. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173529. (JDIMENSION) upsample->next_row_out,
  173530. output_buf + *out_row_ctr,
  173531. (int) num_rows);
  173532. /* Adjust counts */
  173533. *out_row_ctr += num_rows;
  173534. upsample->rows_to_go -= num_rows;
  173535. upsample->next_row_out += num_rows;
  173536. /* When the buffer is emptied, declare this input row group consumed */
  173537. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173538. (*in_row_group_ctr)++;
  173539. }
  173540. /*
  173541. * These are the routines invoked by sep_upsample to upsample pixel values
  173542. * of a single component. One row group is processed per call.
  173543. */
  173544. /*
  173545. * For full-size components, we just make color_buf[ci] point at the
  173546. * input buffer, and thus avoid copying any data. Note that this is
  173547. * safe only because sep_upsample doesn't declare the input row group
  173548. * "consumed" until we are done color converting and emitting it.
  173549. */
  173550. METHODDEF(void)
  173551. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173552. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173553. {
  173554. *output_data_ptr = input_data;
  173555. }
  173556. /*
  173557. * This is a no-op version used for "uninteresting" components.
  173558. * These components will not be referenced by color conversion.
  173559. */
  173560. METHODDEF(void)
  173561. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173562. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173563. {
  173564. *output_data_ptr = NULL; /* safety check */
  173565. }
  173566. /*
  173567. * This version handles any integral sampling ratios.
  173568. * This is not used for typical JPEG files, so it need not be fast.
  173569. * Nor, for that matter, is it particularly accurate: the algorithm is
  173570. * simple replication of the input pixel onto the corresponding output
  173571. * pixels. The hi-falutin sampling literature refers to this as a
  173572. * "box filter". A box filter tends to introduce visible artifacts,
  173573. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173574. * you would be well advised to improve this code.
  173575. */
  173576. METHODDEF(void)
  173577. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173578. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173579. {
  173580. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173581. JSAMPARRAY output_data = *output_data_ptr;
  173582. register JSAMPROW inptr, outptr;
  173583. register JSAMPLE invalue;
  173584. register int h;
  173585. JSAMPROW outend;
  173586. int h_expand, v_expand;
  173587. int inrow, outrow;
  173588. h_expand = upsample->h_expand[compptr->component_index];
  173589. v_expand = upsample->v_expand[compptr->component_index];
  173590. inrow = outrow = 0;
  173591. while (outrow < cinfo->max_v_samp_factor) {
  173592. /* Generate one output row with proper horizontal expansion */
  173593. inptr = input_data[inrow];
  173594. outptr = output_data[outrow];
  173595. outend = outptr + cinfo->output_width;
  173596. while (outptr < outend) {
  173597. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173598. for (h = h_expand; h > 0; h--) {
  173599. *outptr++ = invalue;
  173600. }
  173601. }
  173602. /* Generate any additional output rows by duplicating the first one */
  173603. if (v_expand > 1) {
  173604. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173605. v_expand-1, cinfo->output_width);
  173606. }
  173607. inrow++;
  173608. outrow += v_expand;
  173609. }
  173610. }
  173611. /*
  173612. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173613. * It's still a box filter.
  173614. */
  173615. METHODDEF(void)
  173616. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173617. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173618. {
  173619. JSAMPARRAY output_data = *output_data_ptr;
  173620. register JSAMPROW inptr, outptr;
  173621. register JSAMPLE invalue;
  173622. JSAMPROW outend;
  173623. int inrow;
  173624. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173625. inptr = input_data[inrow];
  173626. outptr = output_data[inrow];
  173627. outend = outptr + cinfo->output_width;
  173628. while (outptr < outend) {
  173629. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173630. *outptr++ = invalue;
  173631. *outptr++ = invalue;
  173632. }
  173633. }
  173634. }
  173635. /*
  173636. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173637. * It's still a box filter.
  173638. */
  173639. METHODDEF(void)
  173640. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173641. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173642. {
  173643. JSAMPARRAY output_data = *output_data_ptr;
  173644. register JSAMPROW inptr, outptr;
  173645. register JSAMPLE invalue;
  173646. JSAMPROW outend;
  173647. int inrow, outrow;
  173648. inrow = outrow = 0;
  173649. while (outrow < cinfo->max_v_samp_factor) {
  173650. inptr = input_data[inrow];
  173651. outptr = output_data[outrow];
  173652. outend = outptr + cinfo->output_width;
  173653. while (outptr < outend) {
  173654. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173655. *outptr++ = invalue;
  173656. *outptr++ = invalue;
  173657. }
  173658. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173659. 1, cinfo->output_width);
  173660. inrow++;
  173661. outrow += 2;
  173662. }
  173663. }
  173664. /*
  173665. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173666. *
  173667. * The upsampling algorithm is linear interpolation between pixel centers,
  173668. * also known as a "triangle filter". This is a good compromise between
  173669. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173670. * of the way between input pixel centers.
  173671. *
  173672. * A note about the "bias" calculations: when rounding fractional values to
  173673. * integer, we do not want to always round 0.5 up to the next integer.
  173674. * If we did that, we'd introduce a noticeable bias towards larger values.
  173675. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173676. * alternate pixel locations (a simple ordered dither pattern).
  173677. */
  173678. METHODDEF(void)
  173679. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173680. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173681. {
  173682. JSAMPARRAY output_data = *output_data_ptr;
  173683. register JSAMPROW inptr, outptr;
  173684. register int invalue;
  173685. register JDIMENSION colctr;
  173686. int inrow;
  173687. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173688. inptr = input_data[inrow];
  173689. outptr = output_data[inrow];
  173690. /* Special case for first column */
  173691. invalue = GETJSAMPLE(*inptr++);
  173692. *outptr++ = (JSAMPLE) invalue;
  173693. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173694. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173695. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173696. invalue = GETJSAMPLE(*inptr++) * 3;
  173697. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173698. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173699. }
  173700. /* Special case for last column */
  173701. invalue = GETJSAMPLE(*inptr);
  173702. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173703. *outptr++ = (JSAMPLE) invalue;
  173704. }
  173705. }
  173706. /*
  173707. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173708. * Again a triangle filter; see comments for h2v1 case, above.
  173709. *
  173710. * It is OK for us to reference the adjacent input rows because we demanded
  173711. * context from the main buffer controller (see initialization code).
  173712. */
  173713. METHODDEF(void)
  173714. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173715. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173716. {
  173717. JSAMPARRAY output_data = *output_data_ptr;
  173718. register JSAMPROW inptr0, inptr1, outptr;
  173719. #if BITS_IN_JSAMPLE == 8
  173720. register int thiscolsum, lastcolsum, nextcolsum;
  173721. #else
  173722. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173723. #endif
  173724. register JDIMENSION colctr;
  173725. int inrow, outrow, v;
  173726. inrow = outrow = 0;
  173727. while (outrow < cinfo->max_v_samp_factor) {
  173728. for (v = 0; v < 2; v++) {
  173729. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173730. inptr0 = input_data[inrow];
  173731. if (v == 0) /* next nearest is row above */
  173732. inptr1 = input_data[inrow-1];
  173733. else /* next nearest is row below */
  173734. inptr1 = input_data[inrow+1];
  173735. outptr = output_data[outrow++];
  173736. /* Special case for first column */
  173737. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173738. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173739. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173740. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173741. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173742. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173743. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173744. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173745. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173746. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173747. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173748. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173749. }
  173750. /* Special case for last column */
  173751. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173752. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173753. }
  173754. inrow++;
  173755. }
  173756. }
  173757. /*
  173758. * Module initialization routine for upsampling.
  173759. */
  173760. GLOBAL(void)
  173761. jinit_upsampler (j_decompress_ptr cinfo)
  173762. {
  173763. my_upsample_ptr2 upsample;
  173764. int ci;
  173765. jpeg_component_info * compptr;
  173766. boolean need_buffer, do_fancy;
  173767. int h_in_group, v_in_group, h_out_group, v_out_group;
  173768. upsample = (my_upsample_ptr2)
  173769. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173770. SIZEOF(my_upsampler2));
  173771. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173772. upsample->pub.start_pass = start_pass_upsample;
  173773. upsample->pub.upsample = sep_upsample;
  173774. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173775. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173776. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173777. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173778. * so don't ask for it.
  173779. */
  173780. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173781. /* Verify we can handle the sampling factors, select per-component methods,
  173782. * and create storage as needed.
  173783. */
  173784. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173785. ci++, compptr++) {
  173786. /* Compute size of an "input group" after IDCT scaling. This many samples
  173787. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173788. */
  173789. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173790. cinfo->min_DCT_scaled_size;
  173791. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173792. cinfo->min_DCT_scaled_size;
  173793. h_out_group = cinfo->max_h_samp_factor;
  173794. v_out_group = cinfo->max_v_samp_factor;
  173795. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173796. need_buffer = TRUE;
  173797. if (! compptr->component_needed) {
  173798. /* Don't bother to upsample an uninteresting component. */
  173799. upsample->methods[ci] = noop_upsample;
  173800. need_buffer = FALSE;
  173801. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173802. /* Fullsize components can be processed without any work. */
  173803. upsample->methods[ci] = fullsize_upsample;
  173804. need_buffer = FALSE;
  173805. } else if (h_in_group * 2 == h_out_group &&
  173806. v_in_group == v_out_group) {
  173807. /* Special cases for 2h1v upsampling */
  173808. if (do_fancy && compptr->downsampled_width > 2)
  173809. upsample->methods[ci] = h2v1_fancy_upsample;
  173810. else
  173811. upsample->methods[ci] = h2v1_upsample;
  173812. } else if (h_in_group * 2 == h_out_group &&
  173813. v_in_group * 2 == v_out_group) {
  173814. /* Special cases for 2h2v upsampling */
  173815. if (do_fancy && compptr->downsampled_width > 2) {
  173816. upsample->methods[ci] = h2v2_fancy_upsample;
  173817. upsample->pub.need_context_rows = TRUE;
  173818. } else
  173819. upsample->methods[ci] = h2v2_upsample;
  173820. } else if ((h_out_group % h_in_group) == 0 &&
  173821. (v_out_group % v_in_group) == 0) {
  173822. /* Generic integral-factors upsampling method */
  173823. upsample->methods[ci] = int_upsample;
  173824. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173825. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173826. } else
  173827. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173828. if (need_buffer) {
  173829. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173830. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173831. (JDIMENSION) jround_up((long) cinfo->output_width,
  173832. (long) cinfo->max_h_samp_factor),
  173833. (JDIMENSION) cinfo->max_v_samp_factor);
  173834. }
  173835. }
  173836. }
  173837. /*** End of inlined file: jdsample.c ***/
  173838. /*** Start of inlined file: jdtrans.c ***/
  173839. #define JPEG_INTERNALS
  173840. /* Forward declarations */
  173841. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173842. /*
  173843. * Read the coefficient arrays from a JPEG file.
  173844. * jpeg_read_header must be completed before calling this.
  173845. *
  173846. * The entire image is read into a set of virtual coefficient-block arrays,
  173847. * one per component. The return value is a pointer to the array of
  173848. * virtual-array descriptors. These can be manipulated directly via the
  173849. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173850. * To release the memory occupied by the virtual arrays, call
  173851. * jpeg_finish_decompress() when done with the data.
  173852. *
  173853. * An alternative usage is to simply obtain access to the coefficient arrays
  173854. * during a buffered-image-mode decompression operation. This is allowed
  173855. * after any jpeg_finish_output() call. The arrays can be accessed until
  173856. * jpeg_finish_decompress() is called. (Note that any call to the library
  173857. * may reposition the arrays, so don't rely on access_virt_barray() results
  173858. * to stay valid across library calls.)
  173859. *
  173860. * Returns NULL if suspended. This case need be checked only if
  173861. * a suspending data source is used.
  173862. */
  173863. GLOBAL(jvirt_barray_ptr *)
  173864. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173865. {
  173866. if (cinfo->global_state == DSTATE_READY) {
  173867. /* First call: initialize active modules */
  173868. transdecode_master_selection(cinfo);
  173869. cinfo->global_state = DSTATE_RDCOEFS;
  173870. }
  173871. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173872. /* Absorb whole file into the coef buffer */
  173873. for (;;) {
  173874. int retcode;
  173875. /* Call progress monitor hook if present */
  173876. if (cinfo->progress != NULL)
  173877. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173878. /* Absorb some more input */
  173879. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173880. if (retcode == JPEG_SUSPENDED)
  173881. return NULL;
  173882. if (retcode == JPEG_REACHED_EOI)
  173883. break;
  173884. /* Advance progress counter if appropriate */
  173885. if (cinfo->progress != NULL &&
  173886. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173887. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173888. /* startup underestimated number of scans; ratchet up one scan */
  173889. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173890. }
  173891. }
  173892. }
  173893. /* Set state so that jpeg_finish_decompress does the right thing */
  173894. cinfo->global_state = DSTATE_STOPPING;
  173895. }
  173896. /* At this point we should be in state DSTATE_STOPPING if being used
  173897. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173898. * to the coefficients during a full buffered-image-mode decompression.
  173899. */
  173900. if ((cinfo->global_state == DSTATE_STOPPING ||
  173901. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173902. return cinfo->coef->coef_arrays;
  173903. }
  173904. /* Oops, improper usage */
  173905. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173906. return NULL; /* keep compiler happy */
  173907. }
  173908. /*
  173909. * Master selection of decompression modules for transcoding.
  173910. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173911. */
  173912. LOCAL(void)
  173913. transdecode_master_selection (j_decompress_ptr cinfo)
  173914. {
  173915. /* This is effectively a buffered-image operation. */
  173916. cinfo->buffered_image = TRUE;
  173917. /* Entropy decoding: either Huffman or arithmetic coding. */
  173918. if (cinfo->arith_code) {
  173919. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173920. } else {
  173921. if (cinfo->progressive_mode) {
  173922. #ifdef D_PROGRESSIVE_SUPPORTED
  173923. jinit_phuff_decoder(cinfo);
  173924. #else
  173925. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173926. #endif
  173927. } else
  173928. jinit_huff_decoder(cinfo);
  173929. }
  173930. /* Always get a full-image coefficient buffer. */
  173931. jinit_d_coef_controller(cinfo, TRUE);
  173932. /* We can now tell the memory manager to allocate virtual arrays. */
  173933. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173934. /* Initialize input side of decompressor to consume first scan. */
  173935. (*cinfo->inputctl->start_input_pass) (cinfo);
  173936. /* Initialize progress monitoring. */
  173937. if (cinfo->progress != NULL) {
  173938. int nscans;
  173939. /* Estimate number of scans to set pass_limit. */
  173940. if (cinfo->progressive_mode) {
  173941. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173942. nscans = 2 + 3 * cinfo->num_components;
  173943. } else if (cinfo->inputctl->has_multiple_scans) {
  173944. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173945. nscans = cinfo->num_components;
  173946. } else {
  173947. nscans = 1;
  173948. }
  173949. cinfo->progress->pass_counter = 0L;
  173950. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173951. cinfo->progress->completed_passes = 0;
  173952. cinfo->progress->total_passes = 1;
  173953. }
  173954. }
  173955. /*** End of inlined file: jdtrans.c ***/
  173956. /*** Start of inlined file: jfdctflt.c ***/
  173957. #define JPEG_INTERNALS
  173958. #ifdef DCT_FLOAT_SUPPORTED
  173959. /*
  173960. * This module is specialized to the case DCTSIZE = 8.
  173961. */
  173962. #if DCTSIZE != 8
  173963. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173964. #endif
  173965. /*
  173966. * Perform the forward DCT on one block of samples.
  173967. */
  173968. GLOBAL(void)
  173969. jpeg_fdct_float (FAST_FLOAT * data)
  173970. {
  173971. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173972. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173973. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173974. FAST_FLOAT *dataptr;
  173975. int ctr;
  173976. /* Pass 1: process rows. */
  173977. dataptr = data;
  173978. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173979. tmp0 = dataptr[0] + dataptr[7];
  173980. tmp7 = dataptr[0] - dataptr[7];
  173981. tmp1 = dataptr[1] + dataptr[6];
  173982. tmp6 = dataptr[1] - dataptr[6];
  173983. tmp2 = dataptr[2] + dataptr[5];
  173984. tmp5 = dataptr[2] - dataptr[5];
  173985. tmp3 = dataptr[3] + dataptr[4];
  173986. tmp4 = dataptr[3] - dataptr[4];
  173987. /* Even part */
  173988. tmp10 = tmp0 + tmp3; /* phase 2 */
  173989. tmp13 = tmp0 - tmp3;
  173990. tmp11 = tmp1 + tmp2;
  173991. tmp12 = tmp1 - tmp2;
  173992. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173993. dataptr[4] = tmp10 - tmp11;
  173994. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173995. dataptr[2] = tmp13 + z1; /* phase 5 */
  173996. dataptr[6] = tmp13 - z1;
  173997. /* Odd part */
  173998. tmp10 = tmp4 + tmp5; /* phase 2 */
  173999. tmp11 = tmp5 + tmp6;
  174000. tmp12 = tmp6 + tmp7;
  174001. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174002. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174003. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174004. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174005. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174006. z11 = tmp7 + z3; /* phase 5 */
  174007. z13 = tmp7 - z3;
  174008. dataptr[5] = z13 + z2; /* phase 6 */
  174009. dataptr[3] = z13 - z2;
  174010. dataptr[1] = z11 + z4;
  174011. dataptr[7] = z11 - z4;
  174012. dataptr += DCTSIZE; /* advance pointer to next row */
  174013. }
  174014. /* Pass 2: process columns. */
  174015. dataptr = data;
  174016. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174017. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174018. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174019. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174020. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174021. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174022. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174023. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174024. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174025. /* Even part */
  174026. tmp10 = tmp0 + tmp3; /* phase 2 */
  174027. tmp13 = tmp0 - tmp3;
  174028. tmp11 = tmp1 + tmp2;
  174029. tmp12 = tmp1 - tmp2;
  174030. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174031. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174032. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174033. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174034. dataptr[DCTSIZE*6] = tmp13 - z1;
  174035. /* Odd part */
  174036. tmp10 = tmp4 + tmp5; /* phase 2 */
  174037. tmp11 = tmp5 + tmp6;
  174038. tmp12 = tmp6 + tmp7;
  174039. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174040. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174041. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174042. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174043. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174044. z11 = tmp7 + z3; /* phase 5 */
  174045. z13 = tmp7 - z3;
  174046. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174047. dataptr[DCTSIZE*3] = z13 - z2;
  174048. dataptr[DCTSIZE*1] = z11 + z4;
  174049. dataptr[DCTSIZE*7] = z11 - z4;
  174050. dataptr++; /* advance pointer to next column */
  174051. }
  174052. }
  174053. #endif /* DCT_FLOAT_SUPPORTED */
  174054. /*** End of inlined file: jfdctflt.c ***/
  174055. /*** Start of inlined file: jfdctint.c ***/
  174056. #define JPEG_INTERNALS
  174057. #ifdef DCT_ISLOW_SUPPORTED
  174058. /*
  174059. * This module is specialized to the case DCTSIZE = 8.
  174060. */
  174061. #if DCTSIZE != 8
  174062. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174063. #endif
  174064. /*
  174065. * The poop on this scaling stuff is as follows:
  174066. *
  174067. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174068. * larger than the true DCT outputs. The final outputs are therefore
  174069. * a factor of N larger than desired; since N=8 this can be cured by
  174070. * a simple right shift at the end of the algorithm. The advantage of
  174071. * this arrangement is that we save two multiplications per 1-D DCT,
  174072. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174073. * In the IJG code, this factor of 8 is removed by the quantization step
  174074. * (in jcdctmgr.c), NOT in this module.
  174075. *
  174076. * We have to do addition and subtraction of the integer inputs, which
  174077. * is no problem, and multiplication by fractional constants, which is
  174078. * a problem to do in integer arithmetic. We multiply all the constants
  174079. * by CONST_SCALE and convert them to integer constants (thus retaining
  174080. * CONST_BITS bits of precision in the constants). After doing a
  174081. * multiplication we have to divide the product by CONST_SCALE, with proper
  174082. * rounding, to produce the correct output. This division can be done
  174083. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174084. * as long as possible so that partial sums can be added together with
  174085. * full fractional precision.
  174086. *
  174087. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174088. * they are represented to better-than-integral precision. These outputs
  174089. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174090. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174091. * array is INT32 anyway.)
  174092. *
  174093. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174094. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174095. * shows that the values given below are the most effective.
  174096. */
  174097. #if BITS_IN_JSAMPLE == 8
  174098. #define CONST_BITS 13
  174099. #define PASS1_BITS 2
  174100. #else
  174101. #define CONST_BITS 13
  174102. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174103. #endif
  174104. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174105. * causing a lot of useless floating-point operations at run time.
  174106. * To get around this we use the following pre-calculated constants.
  174107. * If you change CONST_BITS you may want to add appropriate values.
  174108. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174109. */
  174110. #if CONST_BITS == 13
  174111. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174112. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174113. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174114. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174115. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174116. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174117. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174118. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174119. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174120. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174121. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174122. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174123. #else
  174124. #define FIX_0_298631336 FIX(0.298631336)
  174125. #define FIX_0_390180644 FIX(0.390180644)
  174126. #define FIX_0_541196100 FIX(0.541196100)
  174127. #define FIX_0_765366865 FIX(0.765366865)
  174128. #define FIX_0_899976223 FIX(0.899976223)
  174129. #define FIX_1_175875602 FIX(1.175875602)
  174130. #define FIX_1_501321110 FIX(1.501321110)
  174131. #define FIX_1_847759065 FIX(1.847759065)
  174132. #define FIX_1_961570560 FIX(1.961570560)
  174133. #define FIX_2_053119869 FIX(2.053119869)
  174134. #define FIX_2_562915447 FIX(2.562915447)
  174135. #define FIX_3_072711026 FIX(3.072711026)
  174136. #endif
  174137. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174138. * For 8-bit samples with the recommended scaling, all the variable
  174139. * and constant values involved are no more than 16 bits wide, so a
  174140. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174141. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174142. */
  174143. #if BITS_IN_JSAMPLE == 8
  174144. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174145. #else
  174146. #define MULTIPLY(var,const) ((var) * (const))
  174147. #endif
  174148. /*
  174149. * Perform the forward DCT on one block of samples.
  174150. */
  174151. GLOBAL(void)
  174152. jpeg_fdct_islow (DCTELEM * data)
  174153. {
  174154. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174155. INT32 tmp10, tmp11, tmp12, tmp13;
  174156. INT32 z1, z2, z3, z4, z5;
  174157. DCTELEM *dataptr;
  174158. int ctr;
  174159. SHIFT_TEMPS
  174160. /* Pass 1: process rows. */
  174161. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174162. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174163. dataptr = data;
  174164. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174165. tmp0 = dataptr[0] + dataptr[7];
  174166. tmp7 = dataptr[0] - dataptr[7];
  174167. tmp1 = dataptr[1] + dataptr[6];
  174168. tmp6 = dataptr[1] - dataptr[6];
  174169. tmp2 = dataptr[2] + dataptr[5];
  174170. tmp5 = dataptr[2] - dataptr[5];
  174171. tmp3 = dataptr[3] + dataptr[4];
  174172. tmp4 = dataptr[3] - dataptr[4];
  174173. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174174. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174175. */
  174176. tmp10 = tmp0 + tmp3;
  174177. tmp13 = tmp0 - tmp3;
  174178. tmp11 = tmp1 + tmp2;
  174179. tmp12 = tmp1 - tmp2;
  174180. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174181. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174182. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174183. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174184. CONST_BITS-PASS1_BITS);
  174185. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174186. CONST_BITS-PASS1_BITS);
  174187. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174188. * cK represents cos(K*pi/16).
  174189. * i0..i3 in the paper are tmp4..tmp7 here.
  174190. */
  174191. z1 = tmp4 + tmp7;
  174192. z2 = tmp5 + tmp6;
  174193. z3 = tmp4 + tmp6;
  174194. z4 = tmp5 + tmp7;
  174195. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174196. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174197. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174198. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174199. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174200. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174201. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174202. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174203. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174204. z3 += z5;
  174205. z4 += z5;
  174206. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174207. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174208. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174209. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174210. dataptr += DCTSIZE; /* advance pointer to next row */
  174211. }
  174212. /* Pass 2: process columns.
  174213. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174214. * by an overall factor of 8.
  174215. */
  174216. dataptr = data;
  174217. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174218. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174219. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174220. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174221. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174222. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174223. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174224. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174225. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174226. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174227. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174228. */
  174229. tmp10 = tmp0 + tmp3;
  174230. tmp13 = tmp0 - tmp3;
  174231. tmp11 = tmp1 + tmp2;
  174232. tmp12 = tmp1 - tmp2;
  174233. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174234. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174235. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174236. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174237. CONST_BITS+PASS1_BITS);
  174238. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174239. CONST_BITS+PASS1_BITS);
  174240. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174241. * cK represents cos(K*pi/16).
  174242. * i0..i3 in the paper are tmp4..tmp7 here.
  174243. */
  174244. z1 = tmp4 + tmp7;
  174245. z2 = tmp5 + tmp6;
  174246. z3 = tmp4 + tmp6;
  174247. z4 = tmp5 + tmp7;
  174248. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174249. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174250. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174251. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174252. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174253. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174254. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174255. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174256. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174257. z3 += z5;
  174258. z4 += z5;
  174259. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174260. CONST_BITS+PASS1_BITS);
  174261. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174262. CONST_BITS+PASS1_BITS);
  174263. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174264. CONST_BITS+PASS1_BITS);
  174265. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174266. CONST_BITS+PASS1_BITS);
  174267. dataptr++; /* advance pointer to next column */
  174268. }
  174269. }
  174270. #endif /* DCT_ISLOW_SUPPORTED */
  174271. /*** End of inlined file: jfdctint.c ***/
  174272. #undef CONST_BITS
  174273. #undef MULTIPLY
  174274. #undef FIX_0_541196100
  174275. /*** Start of inlined file: jfdctfst.c ***/
  174276. #define JPEG_INTERNALS
  174277. #ifdef DCT_IFAST_SUPPORTED
  174278. /*
  174279. * This module is specialized to the case DCTSIZE = 8.
  174280. */
  174281. #if DCTSIZE != 8
  174282. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174283. #endif
  174284. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174285. * see jfdctint.c for more details. However, we choose to descale
  174286. * (right shift) multiplication products as soon as they are formed,
  174287. * rather than carrying additional fractional bits into subsequent additions.
  174288. * This compromises accuracy slightly, but it lets us save a few shifts.
  174289. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174290. * everywhere except in the multiplications proper; this saves a good deal
  174291. * of work on 16-bit-int machines.
  174292. *
  174293. * Again to save a few shifts, the intermediate results between pass 1 and
  174294. * pass 2 are not upscaled, but are represented only to integral precision.
  174295. *
  174296. * A final compromise is to represent the multiplicative constants to only
  174297. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174298. * machines, and may also reduce the cost of multiplication (since there
  174299. * are fewer one-bits in the constants).
  174300. */
  174301. #define CONST_BITS 8
  174302. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174303. * causing a lot of useless floating-point operations at run time.
  174304. * To get around this we use the following pre-calculated constants.
  174305. * If you change CONST_BITS you may want to add appropriate values.
  174306. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174307. */
  174308. #if CONST_BITS == 8
  174309. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174310. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174311. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174312. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174313. #else
  174314. #define FIX_0_382683433 FIX(0.382683433)
  174315. #define FIX_0_541196100 FIX(0.541196100)
  174316. #define FIX_0_707106781 FIX(0.707106781)
  174317. #define FIX_1_306562965 FIX(1.306562965)
  174318. #endif
  174319. /* We can gain a little more speed, with a further compromise in accuracy,
  174320. * by omitting the addition in a descaling shift. This yields an incorrectly
  174321. * rounded result half the time...
  174322. */
  174323. #ifndef USE_ACCURATE_ROUNDING
  174324. #undef DESCALE
  174325. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174326. #endif
  174327. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174328. * descale to yield a DCTELEM result.
  174329. */
  174330. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174331. /*
  174332. * Perform the forward DCT on one block of samples.
  174333. */
  174334. GLOBAL(void)
  174335. jpeg_fdct_ifast (DCTELEM * data)
  174336. {
  174337. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174338. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174339. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174340. DCTELEM *dataptr;
  174341. int ctr;
  174342. SHIFT_TEMPS
  174343. /* Pass 1: process rows. */
  174344. dataptr = data;
  174345. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174346. tmp0 = dataptr[0] + dataptr[7];
  174347. tmp7 = dataptr[0] - dataptr[7];
  174348. tmp1 = dataptr[1] + dataptr[6];
  174349. tmp6 = dataptr[1] - dataptr[6];
  174350. tmp2 = dataptr[2] + dataptr[5];
  174351. tmp5 = dataptr[2] - dataptr[5];
  174352. tmp3 = dataptr[3] + dataptr[4];
  174353. tmp4 = dataptr[3] - dataptr[4];
  174354. /* Even part */
  174355. tmp10 = tmp0 + tmp3; /* phase 2 */
  174356. tmp13 = tmp0 - tmp3;
  174357. tmp11 = tmp1 + tmp2;
  174358. tmp12 = tmp1 - tmp2;
  174359. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174360. dataptr[4] = tmp10 - tmp11;
  174361. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174362. dataptr[2] = tmp13 + z1; /* phase 5 */
  174363. dataptr[6] = tmp13 - z1;
  174364. /* Odd part */
  174365. tmp10 = tmp4 + tmp5; /* phase 2 */
  174366. tmp11 = tmp5 + tmp6;
  174367. tmp12 = tmp6 + tmp7;
  174368. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174369. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174370. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174371. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174372. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174373. z11 = tmp7 + z3; /* phase 5 */
  174374. z13 = tmp7 - z3;
  174375. dataptr[5] = z13 + z2; /* phase 6 */
  174376. dataptr[3] = z13 - z2;
  174377. dataptr[1] = z11 + z4;
  174378. dataptr[7] = z11 - z4;
  174379. dataptr += DCTSIZE; /* advance pointer to next row */
  174380. }
  174381. /* Pass 2: process columns. */
  174382. dataptr = data;
  174383. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174384. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174385. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174386. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174387. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174388. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174389. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174390. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174391. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174392. /* Even part */
  174393. tmp10 = tmp0 + tmp3; /* phase 2 */
  174394. tmp13 = tmp0 - tmp3;
  174395. tmp11 = tmp1 + tmp2;
  174396. tmp12 = tmp1 - tmp2;
  174397. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174398. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174399. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174400. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174401. dataptr[DCTSIZE*6] = tmp13 - z1;
  174402. /* Odd part */
  174403. tmp10 = tmp4 + tmp5; /* phase 2 */
  174404. tmp11 = tmp5 + tmp6;
  174405. tmp12 = tmp6 + tmp7;
  174406. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174407. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174408. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174409. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174410. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174411. z11 = tmp7 + z3; /* phase 5 */
  174412. z13 = tmp7 - z3;
  174413. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174414. dataptr[DCTSIZE*3] = z13 - z2;
  174415. dataptr[DCTSIZE*1] = z11 + z4;
  174416. dataptr[DCTSIZE*7] = z11 - z4;
  174417. dataptr++; /* advance pointer to next column */
  174418. }
  174419. }
  174420. #endif /* DCT_IFAST_SUPPORTED */
  174421. /*** End of inlined file: jfdctfst.c ***/
  174422. #undef FIX_0_541196100
  174423. /*** Start of inlined file: jidctflt.c ***/
  174424. #define JPEG_INTERNALS
  174425. #ifdef DCT_FLOAT_SUPPORTED
  174426. /*
  174427. * This module is specialized to the case DCTSIZE = 8.
  174428. */
  174429. #if DCTSIZE != 8
  174430. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174431. #endif
  174432. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174433. * entry; produce a float result.
  174434. */
  174435. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174436. /*
  174437. * Perform dequantization and inverse DCT on one block of coefficients.
  174438. */
  174439. GLOBAL(void)
  174440. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174441. JCOEFPTR coef_block,
  174442. JSAMPARRAY output_buf, JDIMENSION output_col)
  174443. {
  174444. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174445. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174446. FAST_FLOAT z5, z10, z11, z12, z13;
  174447. JCOEFPTR inptr;
  174448. FLOAT_MULT_TYPE * quantptr;
  174449. FAST_FLOAT * wsptr;
  174450. JSAMPROW outptr;
  174451. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174452. int ctr;
  174453. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174454. SHIFT_TEMPS
  174455. /* Pass 1: process columns from input, store into work array. */
  174456. inptr = coef_block;
  174457. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174458. wsptr = workspace;
  174459. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174460. /* Due to quantization, we will usually find that many of the input
  174461. * coefficients are zero, especially the AC terms. We can exploit this
  174462. * by short-circuiting the IDCT calculation for any column in which all
  174463. * the AC terms are zero. In that case each output is equal to the
  174464. * DC coefficient (with scale factor as needed).
  174465. * With typical images and quantization tables, half or more of the
  174466. * column DCT calculations can be simplified this way.
  174467. */
  174468. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174469. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174470. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174471. inptr[DCTSIZE*7] == 0) {
  174472. /* AC terms all zero */
  174473. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174474. wsptr[DCTSIZE*0] = dcval;
  174475. wsptr[DCTSIZE*1] = dcval;
  174476. wsptr[DCTSIZE*2] = dcval;
  174477. wsptr[DCTSIZE*3] = dcval;
  174478. wsptr[DCTSIZE*4] = dcval;
  174479. wsptr[DCTSIZE*5] = dcval;
  174480. wsptr[DCTSIZE*6] = dcval;
  174481. wsptr[DCTSIZE*7] = dcval;
  174482. inptr++; /* advance pointers to next column */
  174483. quantptr++;
  174484. wsptr++;
  174485. continue;
  174486. }
  174487. /* Even part */
  174488. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174489. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174490. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174491. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174492. tmp10 = tmp0 + tmp2; /* phase 3 */
  174493. tmp11 = tmp0 - tmp2;
  174494. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174495. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174496. tmp0 = tmp10 + tmp13; /* phase 2 */
  174497. tmp3 = tmp10 - tmp13;
  174498. tmp1 = tmp11 + tmp12;
  174499. tmp2 = tmp11 - tmp12;
  174500. /* Odd part */
  174501. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174502. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174503. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174504. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174505. z13 = tmp6 + tmp5; /* phase 6 */
  174506. z10 = tmp6 - tmp5;
  174507. z11 = tmp4 + tmp7;
  174508. z12 = tmp4 - tmp7;
  174509. tmp7 = z11 + z13; /* phase 5 */
  174510. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174511. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174512. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174513. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174514. tmp6 = tmp12 - tmp7; /* phase 2 */
  174515. tmp5 = tmp11 - tmp6;
  174516. tmp4 = tmp10 + tmp5;
  174517. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174518. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174519. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174520. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174521. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174522. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174523. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174524. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174525. inptr++; /* advance pointers to next column */
  174526. quantptr++;
  174527. wsptr++;
  174528. }
  174529. /* Pass 2: process rows from work array, store into output array. */
  174530. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174531. wsptr = workspace;
  174532. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174533. outptr = output_buf[ctr] + output_col;
  174534. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174535. * However, the column calculation has created many nonzero AC terms, so
  174536. * the simplification applies less often (typically 5% to 10% of the time).
  174537. * And testing floats for zero is relatively expensive, so we don't bother.
  174538. */
  174539. /* Even part */
  174540. tmp10 = wsptr[0] + wsptr[4];
  174541. tmp11 = wsptr[0] - wsptr[4];
  174542. tmp13 = wsptr[2] + wsptr[6];
  174543. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174544. tmp0 = tmp10 + tmp13;
  174545. tmp3 = tmp10 - tmp13;
  174546. tmp1 = tmp11 + tmp12;
  174547. tmp2 = tmp11 - tmp12;
  174548. /* Odd part */
  174549. z13 = wsptr[5] + wsptr[3];
  174550. z10 = wsptr[5] - wsptr[3];
  174551. z11 = wsptr[1] + wsptr[7];
  174552. z12 = wsptr[1] - wsptr[7];
  174553. tmp7 = z11 + z13;
  174554. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174555. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174556. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174557. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174558. tmp6 = tmp12 - tmp7;
  174559. tmp5 = tmp11 - tmp6;
  174560. tmp4 = tmp10 + tmp5;
  174561. /* Final output stage: scale down by a factor of 8 and range-limit */
  174562. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174563. & RANGE_MASK];
  174564. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174565. & RANGE_MASK];
  174566. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174567. & RANGE_MASK];
  174568. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174569. & RANGE_MASK];
  174570. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174571. & RANGE_MASK];
  174572. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174573. & RANGE_MASK];
  174574. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174575. & RANGE_MASK];
  174576. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174577. & RANGE_MASK];
  174578. wsptr += DCTSIZE; /* advance pointer to next row */
  174579. }
  174580. }
  174581. #endif /* DCT_FLOAT_SUPPORTED */
  174582. /*** End of inlined file: jidctflt.c ***/
  174583. #undef CONST_BITS
  174584. #undef FIX_1_847759065
  174585. #undef MULTIPLY
  174586. #undef DEQUANTIZE
  174587. #undef DESCALE
  174588. /*** Start of inlined file: jidctfst.c ***/
  174589. #define JPEG_INTERNALS
  174590. #ifdef DCT_IFAST_SUPPORTED
  174591. /*
  174592. * This module is specialized to the case DCTSIZE = 8.
  174593. */
  174594. #if DCTSIZE != 8
  174595. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174596. #endif
  174597. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174598. * see jidctint.c for more details. However, we choose to descale
  174599. * (right shift) multiplication products as soon as they are formed,
  174600. * rather than carrying additional fractional bits into subsequent additions.
  174601. * This compromises accuracy slightly, but it lets us save a few shifts.
  174602. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174603. * everywhere except in the multiplications proper; this saves a good deal
  174604. * of work on 16-bit-int machines.
  174605. *
  174606. * The dequantized coefficients are not integers because the AA&N scaling
  174607. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174608. * so that the first and second IDCT rounds have the same input scaling.
  174609. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174610. * avoid a descaling shift; this compromises accuracy rather drastically
  174611. * for small quantization table entries, but it saves a lot of shifts.
  174612. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174613. * so we use a much larger scaling factor to preserve accuracy.
  174614. *
  174615. * A final compromise is to represent the multiplicative constants to only
  174616. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174617. * machines, and may also reduce the cost of multiplication (since there
  174618. * are fewer one-bits in the constants).
  174619. */
  174620. #if BITS_IN_JSAMPLE == 8
  174621. #define CONST_BITS 8
  174622. #define PASS1_BITS 2
  174623. #else
  174624. #define CONST_BITS 8
  174625. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174626. #endif
  174627. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174628. * causing a lot of useless floating-point operations at run time.
  174629. * To get around this we use the following pre-calculated constants.
  174630. * If you change CONST_BITS you may want to add appropriate values.
  174631. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174632. */
  174633. #if CONST_BITS == 8
  174634. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174635. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174636. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174637. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174638. #else
  174639. #define FIX_1_082392200 FIX(1.082392200)
  174640. #define FIX_1_414213562 FIX(1.414213562)
  174641. #define FIX_1_847759065 FIX(1.847759065)
  174642. #define FIX_2_613125930 FIX(2.613125930)
  174643. #endif
  174644. /* We can gain a little more speed, with a further compromise in accuracy,
  174645. * by omitting the addition in a descaling shift. This yields an incorrectly
  174646. * rounded result half the time...
  174647. */
  174648. #ifndef USE_ACCURATE_ROUNDING
  174649. #undef DESCALE
  174650. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174651. #endif
  174652. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174653. * descale to yield a DCTELEM result.
  174654. */
  174655. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174656. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174657. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174658. * multiplication will do. For 12-bit data, the multiplier table is
  174659. * declared INT32, so a 32-bit multiply will be used.
  174660. */
  174661. #if BITS_IN_JSAMPLE == 8
  174662. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174663. #else
  174664. #define DEQUANTIZE(coef,quantval) \
  174665. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174666. #endif
  174667. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174668. * We assume that int right shift is unsigned if INT32 right shift is.
  174669. */
  174670. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174671. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174672. #if BITS_IN_JSAMPLE == 8
  174673. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174674. #else
  174675. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174676. #endif
  174677. #define IRIGHT_SHIFT(x,shft) \
  174678. ((ishift_temp = (x)) < 0 ? \
  174679. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174680. (ishift_temp >> (shft)))
  174681. #else
  174682. #define ISHIFT_TEMPS
  174683. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174684. #endif
  174685. #ifdef USE_ACCURATE_ROUNDING
  174686. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174687. #else
  174688. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174689. #endif
  174690. /*
  174691. * Perform dequantization and inverse DCT on one block of coefficients.
  174692. */
  174693. GLOBAL(void)
  174694. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174695. JCOEFPTR coef_block,
  174696. JSAMPARRAY output_buf, JDIMENSION output_col)
  174697. {
  174698. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174699. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174700. DCTELEM z5, z10, z11, z12, z13;
  174701. JCOEFPTR inptr;
  174702. IFAST_MULT_TYPE * quantptr;
  174703. int * wsptr;
  174704. JSAMPROW outptr;
  174705. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174706. int ctr;
  174707. int workspace[DCTSIZE2]; /* buffers data between passes */
  174708. SHIFT_TEMPS /* for DESCALE */
  174709. ISHIFT_TEMPS /* for IDESCALE */
  174710. /* Pass 1: process columns from input, store into work array. */
  174711. inptr = coef_block;
  174712. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174713. wsptr = workspace;
  174714. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174715. /* Due to quantization, we will usually find that many of the input
  174716. * coefficients are zero, especially the AC terms. We can exploit this
  174717. * by short-circuiting the IDCT calculation for any column in which all
  174718. * the AC terms are zero. In that case each output is equal to the
  174719. * DC coefficient (with scale factor as needed).
  174720. * With typical images and quantization tables, half or more of the
  174721. * column DCT calculations can be simplified this way.
  174722. */
  174723. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174724. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174725. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174726. inptr[DCTSIZE*7] == 0) {
  174727. /* AC terms all zero */
  174728. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174729. wsptr[DCTSIZE*0] = dcval;
  174730. wsptr[DCTSIZE*1] = dcval;
  174731. wsptr[DCTSIZE*2] = dcval;
  174732. wsptr[DCTSIZE*3] = dcval;
  174733. wsptr[DCTSIZE*4] = dcval;
  174734. wsptr[DCTSIZE*5] = dcval;
  174735. wsptr[DCTSIZE*6] = dcval;
  174736. wsptr[DCTSIZE*7] = dcval;
  174737. inptr++; /* advance pointers to next column */
  174738. quantptr++;
  174739. wsptr++;
  174740. continue;
  174741. }
  174742. /* Even part */
  174743. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174744. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174745. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174746. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174747. tmp10 = tmp0 + tmp2; /* phase 3 */
  174748. tmp11 = tmp0 - tmp2;
  174749. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174750. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174751. tmp0 = tmp10 + tmp13; /* phase 2 */
  174752. tmp3 = tmp10 - tmp13;
  174753. tmp1 = tmp11 + tmp12;
  174754. tmp2 = tmp11 - tmp12;
  174755. /* Odd part */
  174756. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174757. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174758. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174759. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174760. z13 = tmp6 + tmp5; /* phase 6 */
  174761. z10 = tmp6 - tmp5;
  174762. z11 = tmp4 + tmp7;
  174763. z12 = tmp4 - tmp7;
  174764. tmp7 = z11 + z13; /* phase 5 */
  174765. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174766. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174767. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174768. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174769. tmp6 = tmp12 - tmp7; /* phase 2 */
  174770. tmp5 = tmp11 - tmp6;
  174771. tmp4 = tmp10 + tmp5;
  174772. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174773. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174774. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174775. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174776. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174777. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174778. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174779. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174780. inptr++; /* advance pointers to next column */
  174781. quantptr++;
  174782. wsptr++;
  174783. }
  174784. /* Pass 2: process rows from work array, store into output array. */
  174785. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174786. /* and also undo the PASS1_BITS scaling. */
  174787. wsptr = workspace;
  174788. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174789. outptr = output_buf[ctr] + output_col;
  174790. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174791. * However, the column calculation has created many nonzero AC terms, so
  174792. * the simplification applies less often (typically 5% to 10% of the time).
  174793. * On machines with very fast multiplication, it's possible that the
  174794. * test takes more time than it's worth. In that case this section
  174795. * may be commented out.
  174796. */
  174797. #ifndef NO_ZERO_ROW_TEST
  174798. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174799. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174800. /* AC terms all zero */
  174801. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174802. & RANGE_MASK];
  174803. outptr[0] = dcval;
  174804. outptr[1] = dcval;
  174805. outptr[2] = dcval;
  174806. outptr[3] = dcval;
  174807. outptr[4] = dcval;
  174808. outptr[5] = dcval;
  174809. outptr[6] = dcval;
  174810. outptr[7] = dcval;
  174811. wsptr += DCTSIZE; /* advance pointer to next row */
  174812. continue;
  174813. }
  174814. #endif
  174815. /* Even part */
  174816. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174817. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174818. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174819. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174820. - tmp13;
  174821. tmp0 = tmp10 + tmp13;
  174822. tmp3 = tmp10 - tmp13;
  174823. tmp1 = tmp11 + tmp12;
  174824. tmp2 = tmp11 - tmp12;
  174825. /* Odd part */
  174826. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174827. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174828. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174829. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174830. tmp7 = z11 + z13; /* phase 5 */
  174831. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174832. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174833. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174834. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174835. tmp6 = tmp12 - tmp7; /* phase 2 */
  174836. tmp5 = tmp11 - tmp6;
  174837. tmp4 = tmp10 + tmp5;
  174838. /* Final output stage: scale down by a factor of 8 and range-limit */
  174839. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174840. & RANGE_MASK];
  174841. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174842. & RANGE_MASK];
  174843. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174844. & RANGE_MASK];
  174845. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174846. & RANGE_MASK];
  174847. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174848. & RANGE_MASK];
  174849. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174850. & RANGE_MASK];
  174851. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174852. & RANGE_MASK];
  174853. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174854. & RANGE_MASK];
  174855. wsptr += DCTSIZE; /* advance pointer to next row */
  174856. }
  174857. }
  174858. #endif /* DCT_IFAST_SUPPORTED */
  174859. /*** End of inlined file: jidctfst.c ***/
  174860. #undef CONST_BITS
  174861. #undef FIX_1_847759065
  174862. #undef MULTIPLY
  174863. #undef DEQUANTIZE
  174864. /*** Start of inlined file: jidctint.c ***/
  174865. #define JPEG_INTERNALS
  174866. #ifdef DCT_ISLOW_SUPPORTED
  174867. /*
  174868. * This module is specialized to the case DCTSIZE = 8.
  174869. */
  174870. #if DCTSIZE != 8
  174871. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174872. #endif
  174873. /*
  174874. * The poop on this scaling stuff is as follows:
  174875. *
  174876. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174877. * larger than the true IDCT outputs. The final outputs are therefore
  174878. * a factor of N larger than desired; since N=8 this can be cured by
  174879. * a simple right shift at the end of the algorithm. The advantage of
  174880. * this arrangement is that we save two multiplications per 1-D IDCT,
  174881. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174882. *
  174883. * We have to do addition and subtraction of the integer inputs, which
  174884. * is no problem, and multiplication by fractional constants, which is
  174885. * a problem to do in integer arithmetic. We multiply all the constants
  174886. * by CONST_SCALE and convert them to integer constants (thus retaining
  174887. * CONST_BITS bits of precision in the constants). After doing a
  174888. * multiplication we have to divide the product by CONST_SCALE, with proper
  174889. * rounding, to produce the correct output. This division can be done
  174890. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174891. * as long as possible so that partial sums can be added together with
  174892. * full fractional precision.
  174893. *
  174894. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174895. * they are represented to better-than-integral precision. These outputs
  174896. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174897. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174898. * intermediate INT32 array would be needed.)
  174899. *
  174900. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174901. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174902. * shows that the values given below are the most effective.
  174903. */
  174904. #if BITS_IN_JSAMPLE == 8
  174905. #define CONST_BITS 13
  174906. #define PASS1_BITS 2
  174907. #else
  174908. #define CONST_BITS 13
  174909. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174910. #endif
  174911. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174912. * causing a lot of useless floating-point operations at run time.
  174913. * To get around this we use the following pre-calculated constants.
  174914. * If you change CONST_BITS you may want to add appropriate values.
  174915. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174916. */
  174917. #if CONST_BITS == 13
  174918. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174919. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174920. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174921. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174922. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174923. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174924. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174925. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174926. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174927. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174928. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174929. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174930. #else
  174931. #define FIX_0_298631336 FIX(0.298631336)
  174932. #define FIX_0_390180644 FIX(0.390180644)
  174933. #define FIX_0_541196100 FIX(0.541196100)
  174934. #define FIX_0_765366865 FIX(0.765366865)
  174935. #define FIX_0_899976223 FIX(0.899976223)
  174936. #define FIX_1_175875602 FIX(1.175875602)
  174937. #define FIX_1_501321110 FIX(1.501321110)
  174938. #define FIX_1_847759065 FIX(1.847759065)
  174939. #define FIX_1_961570560 FIX(1.961570560)
  174940. #define FIX_2_053119869 FIX(2.053119869)
  174941. #define FIX_2_562915447 FIX(2.562915447)
  174942. #define FIX_3_072711026 FIX(3.072711026)
  174943. #endif
  174944. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174945. * For 8-bit samples with the recommended scaling, all the variable
  174946. * and constant values involved are no more than 16 bits wide, so a
  174947. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174948. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174949. */
  174950. #if BITS_IN_JSAMPLE == 8
  174951. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174952. #else
  174953. #define MULTIPLY(var,const) ((var) * (const))
  174954. #endif
  174955. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174956. * entry; produce an int result. In this module, both inputs and result
  174957. * are 16 bits or less, so either int or short multiply will work.
  174958. */
  174959. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174960. /*
  174961. * Perform dequantization and inverse DCT on one block of coefficients.
  174962. */
  174963. GLOBAL(void)
  174964. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174965. JCOEFPTR coef_block,
  174966. JSAMPARRAY output_buf, JDIMENSION output_col)
  174967. {
  174968. INT32 tmp0, tmp1, tmp2, tmp3;
  174969. INT32 tmp10, tmp11, tmp12, tmp13;
  174970. INT32 z1, z2, z3, z4, z5;
  174971. JCOEFPTR inptr;
  174972. ISLOW_MULT_TYPE * quantptr;
  174973. int * wsptr;
  174974. JSAMPROW outptr;
  174975. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174976. int ctr;
  174977. int workspace[DCTSIZE2]; /* buffers data between passes */
  174978. SHIFT_TEMPS
  174979. /* Pass 1: process columns from input, store into work array. */
  174980. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174981. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174982. inptr = coef_block;
  174983. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174984. wsptr = workspace;
  174985. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174986. /* Due to quantization, we will usually find that many of the input
  174987. * coefficients are zero, especially the AC terms. We can exploit this
  174988. * by short-circuiting the IDCT calculation for any column in which all
  174989. * the AC terms are zero. In that case each output is equal to the
  174990. * DC coefficient (with scale factor as needed).
  174991. * With typical images and quantization tables, half or more of the
  174992. * column DCT calculations can be simplified this way.
  174993. */
  174994. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174995. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174996. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174997. inptr[DCTSIZE*7] == 0) {
  174998. /* AC terms all zero */
  174999. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175000. wsptr[DCTSIZE*0] = dcval;
  175001. wsptr[DCTSIZE*1] = dcval;
  175002. wsptr[DCTSIZE*2] = dcval;
  175003. wsptr[DCTSIZE*3] = dcval;
  175004. wsptr[DCTSIZE*4] = dcval;
  175005. wsptr[DCTSIZE*5] = dcval;
  175006. wsptr[DCTSIZE*6] = dcval;
  175007. wsptr[DCTSIZE*7] = dcval;
  175008. inptr++; /* advance pointers to next column */
  175009. quantptr++;
  175010. wsptr++;
  175011. continue;
  175012. }
  175013. /* Even part: reverse the even part of the forward DCT. */
  175014. /* The rotator is sqrt(2)*c(-6). */
  175015. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175016. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175017. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175018. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175019. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175020. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175021. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175022. tmp0 = (z2 + z3) << CONST_BITS;
  175023. tmp1 = (z2 - z3) << CONST_BITS;
  175024. tmp10 = tmp0 + tmp3;
  175025. tmp13 = tmp0 - tmp3;
  175026. tmp11 = tmp1 + tmp2;
  175027. tmp12 = tmp1 - tmp2;
  175028. /* Odd part per figure 8; the matrix is unitary and hence its
  175029. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175030. */
  175031. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175032. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175033. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175034. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175035. z1 = tmp0 + tmp3;
  175036. z2 = tmp1 + tmp2;
  175037. z3 = tmp0 + tmp2;
  175038. z4 = tmp1 + tmp3;
  175039. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175040. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175041. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175042. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175043. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175044. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175045. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175046. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175047. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175048. z3 += z5;
  175049. z4 += z5;
  175050. tmp0 += z1 + z3;
  175051. tmp1 += z2 + z4;
  175052. tmp2 += z2 + z3;
  175053. tmp3 += z1 + z4;
  175054. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175055. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175056. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175057. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175058. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175059. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175060. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175061. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175062. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175063. inptr++; /* advance pointers to next column */
  175064. quantptr++;
  175065. wsptr++;
  175066. }
  175067. /* Pass 2: process rows from work array, store into output array. */
  175068. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175069. /* and also undo the PASS1_BITS scaling. */
  175070. wsptr = workspace;
  175071. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175072. outptr = output_buf[ctr] + output_col;
  175073. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175074. * However, the column calculation has created many nonzero AC terms, so
  175075. * the simplification applies less often (typically 5% to 10% of the time).
  175076. * On machines with very fast multiplication, it's possible that the
  175077. * test takes more time than it's worth. In that case this section
  175078. * may be commented out.
  175079. */
  175080. #ifndef NO_ZERO_ROW_TEST
  175081. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175082. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175083. /* AC terms all zero */
  175084. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175085. & RANGE_MASK];
  175086. outptr[0] = dcval;
  175087. outptr[1] = dcval;
  175088. outptr[2] = dcval;
  175089. outptr[3] = dcval;
  175090. outptr[4] = dcval;
  175091. outptr[5] = dcval;
  175092. outptr[6] = dcval;
  175093. outptr[7] = dcval;
  175094. wsptr += DCTSIZE; /* advance pointer to next row */
  175095. continue;
  175096. }
  175097. #endif
  175098. /* Even part: reverse the even part of the forward DCT. */
  175099. /* The rotator is sqrt(2)*c(-6). */
  175100. z2 = (INT32) wsptr[2];
  175101. z3 = (INT32) wsptr[6];
  175102. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175103. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175104. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175105. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175106. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175107. tmp10 = tmp0 + tmp3;
  175108. tmp13 = tmp0 - tmp3;
  175109. tmp11 = tmp1 + tmp2;
  175110. tmp12 = tmp1 - tmp2;
  175111. /* Odd part per figure 8; the matrix is unitary and hence its
  175112. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175113. */
  175114. tmp0 = (INT32) wsptr[7];
  175115. tmp1 = (INT32) wsptr[5];
  175116. tmp2 = (INT32) wsptr[3];
  175117. tmp3 = (INT32) wsptr[1];
  175118. z1 = tmp0 + tmp3;
  175119. z2 = tmp1 + tmp2;
  175120. z3 = tmp0 + tmp2;
  175121. z4 = tmp1 + tmp3;
  175122. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175123. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175124. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175125. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175126. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175127. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175128. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175129. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175130. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175131. z3 += z5;
  175132. z4 += z5;
  175133. tmp0 += z1 + z3;
  175134. tmp1 += z2 + z4;
  175135. tmp2 += z2 + z3;
  175136. tmp3 += z1 + z4;
  175137. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175138. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175139. CONST_BITS+PASS1_BITS+3)
  175140. & RANGE_MASK];
  175141. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175142. CONST_BITS+PASS1_BITS+3)
  175143. & RANGE_MASK];
  175144. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175145. CONST_BITS+PASS1_BITS+3)
  175146. & RANGE_MASK];
  175147. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175148. CONST_BITS+PASS1_BITS+3)
  175149. & RANGE_MASK];
  175150. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175151. CONST_BITS+PASS1_BITS+3)
  175152. & RANGE_MASK];
  175153. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175154. CONST_BITS+PASS1_BITS+3)
  175155. & RANGE_MASK];
  175156. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175157. CONST_BITS+PASS1_BITS+3)
  175158. & RANGE_MASK];
  175159. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175160. CONST_BITS+PASS1_BITS+3)
  175161. & RANGE_MASK];
  175162. wsptr += DCTSIZE; /* advance pointer to next row */
  175163. }
  175164. }
  175165. #endif /* DCT_ISLOW_SUPPORTED */
  175166. /*** End of inlined file: jidctint.c ***/
  175167. /*** Start of inlined file: jidctred.c ***/
  175168. #define JPEG_INTERNALS
  175169. #ifdef IDCT_SCALING_SUPPORTED
  175170. /*
  175171. * This module is specialized to the case DCTSIZE = 8.
  175172. */
  175173. #if DCTSIZE != 8
  175174. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175175. #endif
  175176. /* Scaling is the same as in jidctint.c. */
  175177. #if BITS_IN_JSAMPLE == 8
  175178. #define CONST_BITS 13
  175179. #define PASS1_BITS 2
  175180. #else
  175181. #define CONST_BITS 13
  175182. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175183. #endif
  175184. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175185. * causing a lot of useless floating-point operations at run time.
  175186. * To get around this we use the following pre-calculated constants.
  175187. * If you change CONST_BITS you may want to add appropriate values.
  175188. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175189. */
  175190. #if CONST_BITS == 13
  175191. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175192. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175193. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175194. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175195. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175196. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175197. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175198. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175199. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175200. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175201. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175202. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175203. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175204. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175205. #else
  175206. #define FIX_0_211164243 FIX(0.211164243)
  175207. #define FIX_0_509795579 FIX(0.509795579)
  175208. #define FIX_0_601344887 FIX(0.601344887)
  175209. #define FIX_0_720959822 FIX(0.720959822)
  175210. #define FIX_0_765366865 FIX(0.765366865)
  175211. #define FIX_0_850430095 FIX(0.850430095)
  175212. #define FIX_0_899976223 FIX(0.899976223)
  175213. #define FIX_1_061594337 FIX(1.061594337)
  175214. #define FIX_1_272758580 FIX(1.272758580)
  175215. #define FIX_1_451774981 FIX(1.451774981)
  175216. #define FIX_1_847759065 FIX(1.847759065)
  175217. #define FIX_2_172734803 FIX(2.172734803)
  175218. #define FIX_2_562915447 FIX(2.562915447)
  175219. #define FIX_3_624509785 FIX(3.624509785)
  175220. #endif
  175221. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175222. * For 8-bit samples with the recommended scaling, all the variable
  175223. * and constant values involved are no more than 16 bits wide, so a
  175224. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175225. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175226. */
  175227. #if BITS_IN_JSAMPLE == 8
  175228. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175229. #else
  175230. #define MULTIPLY(var,const) ((var) * (const))
  175231. #endif
  175232. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175233. * entry; produce an int result. In this module, both inputs and result
  175234. * are 16 bits or less, so either int or short multiply will work.
  175235. */
  175236. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175237. /*
  175238. * Perform dequantization and inverse DCT on one block of coefficients,
  175239. * producing a reduced-size 4x4 output block.
  175240. */
  175241. GLOBAL(void)
  175242. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175243. JCOEFPTR coef_block,
  175244. JSAMPARRAY output_buf, JDIMENSION output_col)
  175245. {
  175246. INT32 tmp0, tmp2, tmp10, tmp12;
  175247. INT32 z1, z2, z3, z4;
  175248. JCOEFPTR inptr;
  175249. ISLOW_MULT_TYPE * quantptr;
  175250. int * wsptr;
  175251. JSAMPROW outptr;
  175252. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175253. int ctr;
  175254. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175255. SHIFT_TEMPS
  175256. /* Pass 1: process columns from input, store into work array. */
  175257. inptr = coef_block;
  175258. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175259. wsptr = workspace;
  175260. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175261. /* Don't bother to process column 4, because second pass won't use it */
  175262. if (ctr == DCTSIZE-4)
  175263. continue;
  175264. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175265. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175266. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175267. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175268. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175269. wsptr[DCTSIZE*0] = dcval;
  175270. wsptr[DCTSIZE*1] = dcval;
  175271. wsptr[DCTSIZE*2] = dcval;
  175272. wsptr[DCTSIZE*3] = dcval;
  175273. continue;
  175274. }
  175275. /* Even part */
  175276. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175277. tmp0 <<= (CONST_BITS+1);
  175278. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175279. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175280. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175281. tmp10 = tmp0 + tmp2;
  175282. tmp12 = tmp0 - tmp2;
  175283. /* Odd part */
  175284. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175285. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175286. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175287. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175288. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175289. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175290. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175291. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175292. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175293. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175294. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175295. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175296. /* Final output stage */
  175297. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175298. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175299. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175300. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175301. }
  175302. /* Pass 2: process 4 rows from work array, store into output array. */
  175303. wsptr = workspace;
  175304. for (ctr = 0; ctr < 4; ctr++) {
  175305. outptr = output_buf[ctr] + output_col;
  175306. /* It's not clear whether a zero row test is worthwhile here ... */
  175307. #ifndef NO_ZERO_ROW_TEST
  175308. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175309. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175310. /* AC terms all zero */
  175311. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175312. & RANGE_MASK];
  175313. outptr[0] = dcval;
  175314. outptr[1] = dcval;
  175315. outptr[2] = dcval;
  175316. outptr[3] = dcval;
  175317. wsptr += DCTSIZE; /* advance pointer to next row */
  175318. continue;
  175319. }
  175320. #endif
  175321. /* Even part */
  175322. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175323. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175324. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175325. tmp10 = tmp0 + tmp2;
  175326. tmp12 = tmp0 - tmp2;
  175327. /* Odd part */
  175328. z1 = (INT32) wsptr[7];
  175329. z2 = (INT32) wsptr[5];
  175330. z3 = (INT32) wsptr[3];
  175331. z4 = (INT32) wsptr[1];
  175332. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175333. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175334. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175335. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175336. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175337. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175338. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175339. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175340. /* Final output stage */
  175341. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175342. CONST_BITS+PASS1_BITS+3+1)
  175343. & RANGE_MASK];
  175344. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175345. CONST_BITS+PASS1_BITS+3+1)
  175346. & RANGE_MASK];
  175347. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175348. CONST_BITS+PASS1_BITS+3+1)
  175349. & RANGE_MASK];
  175350. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175351. CONST_BITS+PASS1_BITS+3+1)
  175352. & RANGE_MASK];
  175353. wsptr += DCTSIZE; /* advance pointer to next row */
  175354. }
  175355. }
  175356. /*
  175357. * Perform dequantization and inverse DCT on one block of coefficients,
  175358. * producing a reduced-size 2x2 output block.
  175359. */
  175360. GLOBAL(void)
  175361. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175362. JCOEFPTR coef_block,
  175363. JSAMPARRAY output_buf, JDIMENSION output_col)
  175364. {
  175365. INT32 tmp0, tmp10, z1;
  175366. JCOEFPTR inptr;
  175367. ISLOW_MULT_TYPE * quantptr;
  175368. int * wsptr;
  175369. JSAMPROW outptr;
  175370. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175371. int ctr;
  175372. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175373. SHIFT_TEMPS
  175374. /* Pass 1: process columns from input, store into work array. */
  175375. inptr = coef_block;
  175376. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175377. wsptr = workspace;
  175378. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175379. /* Don't bother to process columns 2,4,6 */
  175380. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175381. continue;
  175382. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175383. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175384. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175385. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175386. wsptr[DCTSIZE*0] = dcval;
  175387. wsptr[DCTSIZE*1] = dcval;
  175388. continue;
  175389. }
  175390. /* Even part */
  175391. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175392. tmp10 = z1 << (CONST_BITS+2);
  175393. /* Odd part */
  175394. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175395. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175396. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175397. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175398. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175399. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175400. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175401. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175402. /* Final output stage */
  175403. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175404. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175405. }
  175406. /* Pass 2: process 2 rows from work array, store into output array. */
  175407. wsptr = workspace;
  175408. for (ctr = 0; ctr < 2; ctr++) {
  175409. outptr = output_buf[ctr] + output_col;
  175410. /* It's not clear whether a zero row test is worthwhile here ... */
  175411. #ifndef NO_ZERO_ROW_TEST
  175412. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175413. /* AC terms all zero */
  175414. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175415. & RANGE_MASK];
  175416. outptr[0] = dcval;
  175417. outptr[1] = dcval;
  175418. wsptr += DCTSIZE; /* advance pointer to next row */
  175419. continue;
  175420. }
  175421. #endif
  175422. /* Even part */
  175423. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175424. /* Odd part */
  175425. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175426. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175427. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175428. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175429. /* Final output stage */
  175430. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175431. CONST_BITS+PASS1_BITS+3+2)
  175432. & RANGE_MASK];
  175433. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175434. CONST_BITS+PASS1_BITS+3+2)
  175435. & RANGE_MASK];
  175436. wsptr += DCTSIZE; /* advance pointer to next row */
  175437. }
  175438. }
  175439. /*
  175440. * Perform dequantization and inverse DCT on one block of coefficients,
  175441. * producing a reduced-size 1x1 output block.
  175442. */
  175443. GLOBAL(void)
  175444. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175445. JCOEFPTR coef_block,
  175446. JSAMPARRAY output_buf, JDIMENSION output_col)
  175447. {
  175448. int dcval;
  175449. ISLOW_MULT_TYPE * quantptr;
  175450. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175451. SHIFT_TEMPS
  175452. /* We hardly need an inverse DCT routine for this: just take the
  175453. * average pixel value, which is one-eighth of the DC coefficient.
  175454. */
  175455. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175456. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175457. dcval = (int) DESCALE((INT32) dcval, 3);
  175458. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175459. }
  175460. #endif /* IDCT_SCALING_SUPPORTED */
  175461. /*** End of inlined file: jidctred.c ***/
  175462. /*** Start of inlined file: jmemmgr.c ***/
  175463. #define JPEG_INTERNALS
  175464. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175465. /*** Start of inlined file: jmemsys.h ***/
  175466. #ifndef __jmemsys_h__
  175467. #define __jmemsys_h__
  175468. /* Short forms of external names for systems with brain-damaged linkers. */
  175469. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175470. #define jpeg_get_small jGetSmall
  175471. #define jpeg_free_small jFreeSmall
  175472. #define jpeg_get_large jGetLarge
  175473. #define jpeg_free_large jFreeLarge
  175474. #define jpeg_mem_available jMemAvail
  175475. #define jpeg_open_backing_store jOpenBackStore
  175476. #define jpeg_mem_init jMemInit
  175477. #define jpeg_mem_term jMemTerm
  175478. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175479. /*
  175480. * These two functions are used to allocate and release small chunks of
  175481. * memory. (Typically the total amount requested through jpeg_get_small is
  175482. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175483. * Behavior should be the same as for the standard library functions malloc
  175484. * and free; in particular, jpeg_get_small must return NULL on failure.
  175485. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175486. * size of the object being freed, just in case it's needed.
  175487. * On an 80x86 machine using small-data memory model, these manage near heap.
  175488. */
  175489. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175490. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175491. size_t sizeofobject));
  175492. /*
  175493. * These two functions are used to allocate and release large chunks of
  175494. * memory (up to the total free space designated by jpeg_mem_available).
  175495. * The interface is the same as above, except that on an 80x86 machine,
  175496. * far pointers are used. On most other machines these are identical to
  175497. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175498. * in case a different allocation strategy is desirable for large chunks.
  175499. */
  175500. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175501. size_t sizeofobject));
  175502. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175503. size_t sizeofobject));
  175504. /*
  175505. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175506. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175507. * matter, but that case should never come into play). This macro is needed
  175508. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175509. * On those machines, we expect that jconfig.h will provide a proper value.
  175510. * On machines with 32-bit flat address spaces, any large constant may be used.
  175511. *
  175512. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175513. * size_t and will be a multiple of sizeof(align_type).
  175514. */
  175515. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175516. #define MAX_ALLOC_CHUNK 1000000000L
  175517. #endif
  175518. /*
  175519. * This routine computes the total space still available for allocation by
  175520. * jpeg_get_large. If more space than this is needed, backing store will be
  175521. * used. NOTE: any memory already allocated must not be counted.
  175522. *
  175523. * There is a minimum space requirement, corresponding to the minimum
  175524. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175525. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175526. * all working storage in memory, is also passed in case it is useful.
  175527. * Finally, the total space already allocated is passed. If no better
  175528. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175529. * is often a suitable calculation.
  175530. *
  175531. * It is OK for jpeg_mem_available to underestimate the space available
  175532. * (that'll just lead to more backing-store access than is really necessary).
  175533. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175534. * a slop factor from the true available space. 5% should be enough.
  175535. *
  175536. * On machines with lots of virtual memory, any large constant may be returned.
  175537. * Conversely, zero may be returned to always use the minimum amount of memory.
  175538. */
  175539. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175540. long min_bytes_needed,
  175541. long max_bytes_needed,
  175542. long already_allocated));
  175543. /*
  175544. * This structure holds whatever state is needed to access a single
  175545. * backing-store object. The read/write/close method pointers are called
  175546. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175547. * are private to the system-dependent backing store routines.
  175548. */
  175549. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175550. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175551. typedef unsigned short XMSH; /* type of extended-memory handles */
  175552. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175553. typedef union {
  175554. short file_handle; /* DOS file handle if it's a temp file */
  175555. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175556. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175557. } handle_union;
  175558. #endif /* USE_MSDOS_MEMMGR */
  175559. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175560. #include <Files.h>
  175561. #endif /* USE_MAC_MEMMGR */
  175562. //typedef struct backing_store_struct * backing_store_ptr;
  175563. typedef struct backing_store_struct {
  175564. /* Methods for reading/writing/closing this backing-store object */
  175565. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175566. struct backing_store_struct *info,
  175567. void FAR * buffer_address,
  175568. long file_offset, long byte_count));
  175569. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175570. struct backing_store_struct *info,
  175571. void FAR * buffer_address,
  175572. long file_offset, long byte_count));
  175573. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175574. struct backing_store_struct *info));
  175575. /* Private fields for system-dependent backing-store management */
  175576. #ifdef USE_MSDOS_MEMMGR
  175577. /* For the MS-DOS manager (jmemdos.c), we need: */
  175578. handle_union handle; /* reference to backing-store storage object */
  175579. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175580. #else
  175581. #ifdef USE_MAC_MEMMGR
  175582. /* For the Mac manager (jmemmac.c), we need: */
  175583. short temp_file; /* file reference number to temp file */
  175584. FSSpec tempSpec; /* the FSSpec for the temp file */
  175585. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175586. #else
  175587. /* For a typical implementation with temp files, we need: */
  175588. FILE * temp_file; /* stdio reference to temp file */
  175589. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175590. #endif
  175591. #endif
  175592. } backing_store_info;
  175593. /*
  175594. * Initial opening of a backing-store object. This must fill in the
  175595. * read/write/close pointers in the object. The read/write routines
  175596. * may take an error exit if the specified maximum file size is exceeded.
  175597. * (If jpeg_mem_available always returns a large value, this routine can
  175598. * just take an error exit.)
  175599. */
  175600. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175601. struct backing_store_struct *info,
  175602. long total_bytes_needed));
  175603. /*
  175604. * These routines take care of any system-dependent initialization and
  175605. * cleanup required. jpeg_mem_init will be called before anything is
  175606. * allocated (and, therefore, nothing in cinfo is of use except the error
  175607. * manager pointer). It should return a suitable default value for
  175608. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175609. * application. (Note that max_memory_to_use is only important if
  175610. * jpeg_mem_available chooses to consult it ... no one else will.)
  175611. * jpeg_mem_term may assume that all requested memory has been freed and that
  175612. * all opened backing-store objects have been closed.
  175613. */
  175614. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175615. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175616. #endif
  175617. /*** End of inlined file: jmemsys.h ***/
  175618. /* import the system-dependent declarations */
  175619. #ifndef NO_GETENV
  175620. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175621. extern char * getenv JPP((const char * name));
  175622. #endif
  175623. #endif
  175624. /*
  175625. * Some important notes:
  175626. * The allocation routines provided here must never return NULL.
  175627. * They should exit to error_exit if unsuccessful.
  175628. *
  175629. * It's not a good idea to try to merge the sarray and barray routines,
  175630. * even though they are textually almost the same, because samples are
  175631. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175632. * in machines where byte pointers have a different representation from
  175633. * word pointers, the resulting machine code could not be the same.
  175634. */
  175635. /*
  175636. * Many machines require storage alignment: longs must start on 4-byte
  175637. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175638. * always returns pointers that are multiples of the worst-case alignment
  175639. * requirement, and we had better do so too.
  175640. * There isn't any really portable way to determine the worst-case alignment
  175641. * requirement. This module assumes that the alignment requirement is
  175642. * multiples of sizeof(ALIGN_TYPE).
  175643. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175644. * workstations (where doubles really do need 8-byte alignment) and will work
  175645. * fine on nearly everything. If your machine has lesser alignment needs,
  175646. * you can save a few bytes by making ALIGN_TYPE smaller.
  175647. * The only place I know of where this will NOT work is certain Macintosh
  175648. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175649. * Doing 10-byte alignment is counterproductive because longwords won't be
  175650. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175651. * such a compiler.
  175652. */
  175653. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175654. #define ALIGN_TYPE double
  175655. #endif
  175656. /*
  175657. * We allocate objects from "pools", where each pool is gotten with a single
  175658. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175659. * overhead within a pool, except for alignment padding. Each pool has a
  175660. * header with a link to the next pool of the same class.
  175661. * Small and large pool headers are identical except that the latter's
  175662. * link pointer must be FAR on 80x86 machines.
  175663. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175664. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175665. * of the alignment requirement of ALIGN_TYPE.
  175666. */
  175667. typedef union small_pool_struct * small_pool_ptr;
  175668. typedef union small_pool_struct {
  175669. struct {
  175670. small_pool_ptr next; /* next in list of pools */
  175671. size_t bytes_used; /* how many bytes already used within pool */
  175672. size_t bytes_left; /* bytes still available in this pool */
  175673. } hdr;
  175674. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175675. } small_pool_hdr;
  175676. typedef union large_pool_struct FAR * large_pool_ptr;
  175677. typedef union large_pool_struct {
  175678. struct {
  175679. large_pool_ptr next; /* next in list of pools */
  175680. size_t bytes_used; /* how many bytes already used within pool */
  175681. size_t bytes_left; /* bytes still available in this pool */
  175682. } hdr;
  175683. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175684. } large_pool_hdr;
  175685. /*
  175686. * Here is the full definition of a memory manager object.
  175687. */
  175688. typedef struct {
  175689. struct jpeg_memory_mgr pub; /* public fields */
  175690. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175691. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175692. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175693. /* Since we only have one lifetime class of virtual arrays, only one
  175694. * linked list is necessary (for each datatype). Note that the virtual
  175695. * array control blocks being linked together are actually stored somewhere
  175696. * in the small-pool list.
  175697. */
  175698. jvirt_sarray_ptr virt_sarray_list;
  175699. jvirt_barray_ptr virt_barray_list;
  175700. /* This counts total space obtained from jpeg_get_small/large */
  175701. long total_space_allocated;
  175702. /* alloc_sarray and alloc_barray set this value for use by virtual
  175703. * array routines.
  175704. */
  175705. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175706. } my_memory_mgr;
  175707. typedef my_memory_mgr * my_mem_ptr;
  175708. /*
  175709. * The control blocks for virtual arrays.
  175710. * Note that these blocks are allocated in the "small" pool area.
  175711. * System-dependent info for the associated backing store (if any) is hidden
  175712. * inside the backing_store_info struct.
  175713. */
  175714. struct jvirt_sarray_control {
  175715. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175716. JDIMENSION rows_in_array; /* total virtual array height */
  175717. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175718. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175719. JDIMENSION rows_in_mem; /* height of memory buffer */
  175720. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175721. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175722. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175723. boolean pre_zero; /* pre-zero mode requested? */
  175724. boolean dirty; /* do current buffer contents need written? */
  175725. boolean b_s_open; /* is backing-store data valid? */
  175726. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175727. backing_store_info b_s_info; /* System-dependent control info */
  175728. };
  175729. struct jvirt_barray_control {
  175730. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175731. JDIMENSION rows_in_array; /* total virtual array height */
  175732. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175733. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175734. JDIMENSION rows_in_mem; /* height of memory buffer */
  175735. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175736. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175737. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175738. boolean pre_zero; /* pre-zero mode requested? */
  175739. boolean dirty; /* do current buffer contents need written? */
  175740. boolean b_s_open; /* is backing-store data valid? */
  175741. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175742. backing_store_info b_s_info; /* System-dependent control info */
  175743. };
  175744. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175745. LOCAL(void)
  175746. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175747. {
  175748. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175749. small_pool_ptr shdr_ptr;
  175750. large_pool_ptr lhdr_ptr;
  175751. /* Since this is only a debugging stub, we can cheat a little by using
  175752. * fprintf directly rather than going through the trace message code.
  175753. * This is helpful because message parm array can't handle longs.
  175754. */
  175755. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175756. pool_id, mem->total_space_allocated);
  175757. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175758. lhdr_ptr = lhdr_ptr->hdr.next) {
  175759. fprintf(stderr, " Large chunk used %ld\n",
  175760. (long) lhdr_ptr->hdr.bytes_used);
  175761. }
  175762. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175763. shdr_ptr = shdr_ptr->hdr.next) {
  175764. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175765. (long) shdr_ptr->hdr.bytes_used,
  175766. (long) shdr_ptr->hdr.bytes_left);
  175767. }
  175768. }
  175769. #endif /* MEM_STATS */
  175770. LOCAL(void)
  175771. out_of_memory (j_common_ptr cinfo, int which)
  175772. /* Report an out-of-memory error and stop execution */
  175773. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175774. {
  175775. #ifdef MEM_STATS
  175776. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175777. #endif
  175778. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175779. }
  175780. /*
  175781. * Allocation of "small" objects.
  175782. *
  175783. * For these, we use pooled storage. When a new pool must be created,
  175784. * we try to get enough space for the current request plus a "slop" factor,
  175785. * where the slop will be the amount of leftover space in the new pool.
  175786. * The speed vs. space tradeoff is largely determined by the slop values.
  175787. * A different slop value is provided for each pool class (lifetime),
  175788. * and we also distinguish the first pool of a class from later ones.
  175789. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175790. * machines, but may be too small if longs are 64 bits or more.
  175791. */
  175792. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175793. {
  175794. 1600, /* first PERMANENT pool */
  175795. 16000 /* first IMAGE pool */
  175796. };
  175797. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175798. {
  175799. 0, /* additional PERMANENT pools */
  175800. 5000 /* additional IMAGE pools */
  175801. };
  175802. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175803. METHODDEF(void *)
  175804. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175805. /* Allocate a "small" object */
  175806. {
  175807. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175808. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175809. char * data_ptr;
  175810. size_t odd_bytes, min_request, slop;
  175811. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175812. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175813. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175814. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175815. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175816. if (odd_bytes > 0)
  175817. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175818. /* See if space is available in any existing pool */
  175819. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175820. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175821. prev_hdr_ptr = NULL;
  175822. hdr_ptr = mem->small_list[pool_id];
  175823. while (hdr_ptr != NULL) {
  175824. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175825. break; /* found pool with enough space */
  175826. prev_hdr_ptr = hdr_ptr;
  175827. hdr_ptr = hdr_ptr->hdr.next;
  175828. }
  175829. /* Time to make a new pool? */
  175830. if (hdr_ptr == NULL) {
  175831. /* min_request is what we need now, slop is what will be leftover */
  175832. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175833. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175834. slop = first_pool_slop[pool_id];
  175835. else
  175836. slop = extra_pool_slop[pool_id];
  175837. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175838. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175839. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175840. /* Try to get space, if fail reduce slop and try again */
  175841. for (;;) {
  175842. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175843. if (hdr_ptr != NULL)
  175844. break;
  175845. slop /= 2;
  175846. if (slop < MIN_SLOP) /* give up when it gets real small */
  175847. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175848. }
  175849. mem->total_space_allocated += min_request + slop;
  175850. /* Success, initialize the new pool header and add to end of list */
  175851. hdr_ptr->hdr.next = NULL;
  175852. hdr_ptr->hdr.bytes_used = 0;
  175853. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175854. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175855. mem->small_list[pool_id] = hdr_ptr;
  175856. else
  175857. prev_hdr_ptr->hdr.next = hdr_ptr;
  175858. }
  175859. /* OK, allocate the object from the current pool */
  175860. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175861. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175862. hdr_ptr->hdr.bytes_used += sizeofobject;
  175863. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175864. return (void *) data_ptr;
  175865. }
  175866. /*
  175867. * Allocation of "large" objects.
  175868. *
  175869. * The external semantics of these are the same as "small" objects,
  175870. * except that FAR pointers are used on 80x86. However the pool
  175871. * management heuristics are quite different. We assume that each
  175872. * request is large enough that it may as well be passed directly to
  175873. * jpeg_get_large; the pool management just links everything together
  175874. * so that we can free it all on demand.
  175875. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175876. * structures. The routines that create these structures (see below)
  175877. * deliberately bunch rows together to ensure a large request size.
  175878. */
  175879. METHODDEF(void FAR *)
  175880. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175881. /* Allocate a "large" object */
  175882. {
  175883. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175884. large_pool_ptr hdr_ptr;
  175885. size_t odd_bytes;
  175886. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175887. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175888. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175889. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175890. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175891. if (odd_bytes > 0)
  175892. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175893. /* Always make a new pool */
  175894. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175895. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175896. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175897. SIZEOF(large_pool_hdr));
  175898. if (hdr_ptr == NULL)
  175899. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175900. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175901. /* Success, initialize the new pool header and add to list */
  175902. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175903. /* We maintain space counts in each pool header for statistical purposes,
  175904. * even though they are not needed for allocation.
  175905. */
  175906. hdr_ptr->hdr.bytes_used = sizeofobject;
  175907. hdr_ptr->hdr.bytes_left = 0;
  175908. mem->large_list[pool_id] = hdr_ptr;
  175909. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175910. }
  175911. /*
  175912. * Creation of 2-D sample arrays.
  175913. * The pointers are in near heap, the samples themselves in FAR heap.
  175914. *
  175915. * To minimize allocation overhead and to allow I/O of large contiguous
  175916. * blocks, we allocate the sample rows in groups of as many rows as possible
  175917. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175918. * NB: the virtual array control routines, later in this file, know about
  175919. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175920. * object so that it can be saved away if this sarray is the workspace for
  175921. * a virtual array.
  175922. */
  175923. METHODDEF(JSAMPARRAY)
  175924. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175925. JDIMENSION samplesperrow, JDIMENSION numrows)
  175926. /* Allocate a 2-D sample array */
  175927. {
  175928. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175929. JSAMPARRAY result;
  175930. JSAMPROW workspace;
  175931. JDIMENSION rowsperchunk, currow, i;
  175932. long ltemp;
  175933. /* Calculate max # of rows allowed in one allocation chunk */
  175934. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175935. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175936. if (ltemp <= 0)
  175937. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175938. if (ltemp < (long) numrows)
  175939. rowsperchunk = (JDIMENSION) ltemp;
  175940. else
  175941. rowsperchunk = numrows;
  175942. mem->last_rowsperchunk = rowsperchunk;
  175943. /* Get space for row pointers (small object) */
  175944. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175945. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175946. /* Get the rows themselves (large objects) */
  175947. currow = 0;
  175948. while (currow < numrows) {
  175949. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175950. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175951. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175952. * SIZEOF(JSAMPLE)));
  175953. for (i = rowsperchunk; i > 0; i--) {
  175954. result[currow++] = workspace;
  175955. workspace += samplesperrow;
  175956. }
  175957. }
  175958. return result;
  175959. }
  175960. /*
  175961. * Creation of 2-D coefficient-block arrays.
  175962. * This is essentially the same as the code for sample arrays, above.
  175963. */
  175964. METHODDEF(JBLOCKARRAY)
  175965. alloc_barray (j_common_ptr cinfo, int pool_id,
  175966. JDIMENSION blocksperrow, JDIMENSION numrows)
  175967. /* Allocate a 2-D coefficient-block array */
  175968. {
  175969. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175970. JBLOCKARRAY result;
  175971. JBLOCKROW workspace;
  175972. JDIMENSION rowsperchunk, currow, i;
  175973. long ltemp;
  175974. /* Calculate max # of rows allowed in one allocation chunk */
  175975. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175976. ((long) blocksperrow * SIZEOF(JBLOCK));
  175977. if (ltemp <= 0)
  175978. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175979. if (ltemp < (long) numrows)
  175980. rowsperchunk = (JDIMENSION) ltemp;
  175981. else
  175982. rowsperchunk = numrows;
  175983. mem->last_rowsperchunk = rowsperchunk;
  175984. /* Get space for row pointers (small object) */
  175985. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175986. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175987. /* Get the rows themselves (large objects) */
  175988. currow = 0;
  175989. while (currow < numrows) {
  175990. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175991. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175992. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175993. * SIZEOF(JBLOCK)));
  175994. for (i = rowsperchunk; i > 0; i--) {
  175995. result[currow++] = workspace;
  175996. workspace += blocksperrow;
  175997. }
  175998. }
  175999. return result;
  176000. }
  176001. /*
  176002. * About virtual array management:
  176003. *
  176004. * The above "normal" array routines are only used to allocate strip buffers
  176005. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176006. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176007. * time, but the memory manager must save the whole array for repeated
  176008. * accesses. The intended implementation is that there is a strip buffer in
  176009. * memory (as high as is possible given the desired memory limit), plus a
  176010. * backing file that holds the rest of the array.
  176011. *
  176012. * The request_virt_array routines are told the total size of the image and
  176013. * the maximum number of rows that will be accessed at once. The in-memory
  176014. * buffer must be at least as large as the maxaccess value.
  176015. *
  176016. * The request routines create control blocks but not the in-memory buffers.
  176017. * That is postponed until realize_virt_arrays is called. At that time the
  176018. * total amount of space needed is known (approximately, anyway), so free
  176019. * memory can be divided up fairly.
  176020. *
  176021. * The access_virt_array routines are responsible for making a specific strip
  176022. * area accessible (after reading or writing the backing file, if necessary).
  176023. * Note that the access routines are told whether the caller intends to modify
  176024. * the accessed strip; during a read-only pass this saves having to rewrite
  176025. * data to disk. The access routines are also responsible for pre-zeroing
  176026. * any newly accessed rows, if pre-zeroing was requested.
  176027. *
  176028. * In current usage, the access requests are usually for nonoverlapping
  176029. * strips; that is, successive access start_row numbers differ by exactly
  176030. * num_rows = maxaccess. This means we can get good performance with simple
  176031. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176032. * of the access height; then there will never be accesses across bufferload
  176033. * boundaries. The code will still work with overlapping access requests,
  176034. * but it doesn't handle bufferload overlaps very efficiently.
  176035. */
  176036. METHODDEF(jvirt_sarray_ptr)
  176037. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176038. JDIMENSION samplesperrow, JDIMENSION numrows,
  176039. JDIMENSION maxaccess)
  176040. /* Request a virtual 2-D sample array */
  176041. {
  176042. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176043. jvirt_sarray_ptr result;
  176044. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176045. if (pool_id != JPOOL_IMAGE)
  176046. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176047. /* get control block */
  176048. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176049. SIZEOF(struct jvirt_sarray_control));
  176050. result->mem_buffer = NULL; /* marks array not yet realized */
  176051. result->rows_in_array = numrows;
  176052. result->samplesperrow = samplesperrow;
  176053. result->maxaccess = maxaccess;
  176054. result->pre_zero = pre_zero;
  176055. result->b_s_open = FALSE; /* no associated backing-store object */
  176056. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176057. mem->virt_sarray_list = result;
  176058. return result;
  176059. }
  176060. METHODDEF(jvirt_barray_ptr)
  176061. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176062. JDIMENSION blocksperrow, JDIMENSION numrows,
  176063. JDIMENSION maxaccess)
  176064. /* Request a virtual 2-D coefficient-block array */
  176065. {
  176066. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176067. jvirt_barray_ptr result;
  176068. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176069. if (pool_id != JPOOL_IMAGE)
  176070. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176071. /* get control block */
  176072. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176073. SIZEOF(struct jvirt_barray_control));
  176074. result->mem_buffer = NULL; /* marks array not yet realized */
  176075. result->rows_in_array = numrows;
  176076. result->blocksperrow = blocksperrow;
  176077. result->maxaccess = maxaccess;
  176078. result->pre_zero = pre_zero;
  176079. result->b_s_open = FALSE; /* no associated backing-store object */
  176080. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176081. mem->virt_barray_list = result;
  176082. return result;
  176083. }
  176084. METHODDEF(void)
  176085. realize_virt_arrays (j_common_ptr cinfo)
  176086. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176087. {
  176088. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176089. long space_per_minheight, maximum_space, avail_mem;
  176090. long minheights, max_minheights;
  176091. jvirt_sarray_ptr sptr;
  176092. jvirt_barray_ptr bptr;
  176093. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176094. * and the maximum space needed (full image height in each buffer).
  176095. * These may be of use to the system-dependent jpeg_mem_available routine.
  176096. */
  176097. space_per_minheight = 0;
  176098. maximum_space = 0;
  176099. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176100. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176101. space_per_minheight += (long) sptr->maxaccess *
  176102. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176103. maximum_space += (long) sptr->rows_in_array *
  176104. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176105. }
  176106. }
  176107. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176108. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176109. space_per_minheight += (long) bptr->maxaccess *
  176110. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176111. maximum_space += (long) bptr->rows_in_array *
  176112. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176113. }
  176114. }
  176115. if (space_per_minheight <= 0)
  176116. return; /* no unrealized arrays, no work */
  176117. /* Determine amount of memory to actually use; this is system-dependent. */
  176118. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176119. mem->total_space_allocated);
  176120. /* If the maximum space needed is available, make all the buffers full
  176121. * height; otherwise parcel it out with the same number of minheights
  176122. * in each buffer.
  176123. */
  176124. if (avail_mem >= maximum_space)
  176125. max_minheights = 1000000000L;
  176126. else {
  176127. max_minheights = avail_mem / space_per_minheight;
  176128. /* If there doesn't seem to be enough space, try to get the minimum
  176129. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176130. */
  176131. if (max_minheights <= 0)
  176132. max_minheights = 1;
  176133. }
  176134. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176135. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176136. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176137. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176138. if (minheights <= max_minheights) {
  176139. /* This buffer fits in memory */
  176140. sptr->rows_in_mem = sptr->rows_in_array;
  176141. } else {
  176142. /* It doesn't fit in memory, create backing store. */
  176143. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176144. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176145. (long) sptr->rows_in_array *
  176146. (long) sptr->samplesperrow *
  176147. (long) SIZEOF(JSAMPLE));
  176148. sptr->b_s_open = TRUE;
  176149. }
  176150. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176151. sptr->samplesperrow, sptr->rows_in_mem);
  176152. sptr->rowsperchunk = mem->last_rowsperchunk;
  176153. sptr->cur_start_row = 0;
  176154. sptr->first_undef_row = 0;
  176155. sptr->dirty = FALSE;
  176156. }
  176157. }
  176158. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176159. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176160. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176161. if (minheights <= max_minheights) {
  176162. /* This buffer fits in memory */
  176163. bptr->rows_in_mem = bptr->rows_in_array;
  176164. } else {
  176165. /* It doesn't fit in memory, create backing store. */
  176166. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176167. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176168. (long) bptr->rows_in_array *
  176169. (long) bptr->blocksperrow *
  176170. (long) SIZEOF(JBLOCK));
  176171. bptr->b_s_open = TRUE;
  176172. }
  176173. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176174. bptr->blocksperrow, bptr->rows_in_mem);
  176175. bptr->rowsperchunk = mem->last_rowsperchunk;
  176176. bptr->cur_start_row = 0;
  176177. bptr->first_undef_row = 0;
  176178. bptr->dirty = FALSE;
  176179. }
  176180. }
  176181. }
  176182. LOCAL(void)
  176183. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176184. /* Do backing store read or write of a virtual sample array */
  176185. {
  176186. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176187. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176188. file_offset = ptr->cur_start_row * bytesperrow;
  176189. /* Loop to read or write each allocation chunk in mem_buffer */
  176190. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176191. /* One chunk, but check for short chunk at end of buffer */
  176192. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176193. /* Transfer no more than is currently defined */
  176194. thisrow = (long) ptr->cur_start_row + i;
  176195. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176196. /* Transfer no more than fits in file */
  176197. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176198. if (rows <= 0) /* this chunk might be past end of file! */
  176199. break;
  176200. byte_count = rows * bytesperrow;
  176201. if (writing)
  176202. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176203. (void FAR *) ptr->mem_buffer[i],
  176204. file_offset, byte_count);
  176205. else
  176206. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176207. (void FAR *) ptr->mem_buffer[i],
  176208. file_offset, byte_count);
  176209. file_offset += byte_count;
  176210. }
  176211. }
  176212. LOCAL(void)
  176213. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176214. /* Do backing store read or write of a virtual coefficient-block array */
  176215. {
  176216. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176217. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176218. file_offset = ptr->cur_start_row * bytesperrow;
  176219. /* Loop to read or write each allocation chunk in mem_buffer */
  176220. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176221. /* One chunk, but check for short chunk at end of buffer */
  176222. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176223. /* Transfer no more than is currently defined */
  176224. thisrow = (long) ptr->cur_start_row + i;
  176225. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176226. /* Transfer no more than fits in file */
  176227. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176228. if (rows <= 0) /* this chunk might be past end of file! */
  176229. break;
  176230. byte_count = rows * bytesperrow;
  176231. if (writing)
  176232. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176233. (void FAR *) ptr->mem_buffer[i],
  176234. file_offset, byte_count);
  176235. else
  176236. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176237. (void FAR *) ptr->mem_buffer[i],
  176238. file_offset, byte_count);
  176239. file_offset += byte_count;
  176240. }
  176241. }
  176242. METHODDEF(JSAMPARRAY)
  176243. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176244. JDIMENSION start_row, JDIMENSION num_rows,
  176245. boolean writable)
  176246. /* Access the part of a virtual sample array starting at start_row */
  176247. /* and extending for num_rows rows. writable is true if */
  176248. /* caller intends to modify the accessed area. */
  176249. {
  176250. JDIMENSION end_row = start_row + num_rows;
  176251. JDIMENSION undef_row;
  176252. /* debugging check */
  176253. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176254. ptr->mem_buffer == NULL)
  176255. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176256. /* Make the desired part of the virtual array accessible */
  176257. if (start_row < ptr->cur_start_row ||
  176258. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176259. if (! ptr->b_s_open)
  176260. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176261. /* Flush old buffer contents if necessary */
  176262. if (ptr->dirty) {
  176263. do_sarray_io(cinfo, ptr, TRUE);
  176264. ptr->dirty = FALSE;
  176265. }
  176266. /* Decide what part of virtual array to access.
  176267. * Algorithm: if target address > current window, assume forward scan,
  176268. * load starting at target address. If target address < current window,
  176269. * assume backward scan, load so that target area is top of window.
  176270. * Note that when switching from forward write to forward read, will have
  176271. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176272. */
  176273. if (start_row > ptr->cur_start_row) {
  176274. ptr->cur_start_row = start_row;
  176275. } else {
  176276. /* use long arithmetic here to avoid overflow & unsigned problems */
  176277. long ltemp;
  176278. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176279. if (ltemp < 0)
  176280. ltemp = 0; /* don't fall off front end of file */
  176281. ptr->cur_start_row = (JDIMENSION) ltemp;
  176282. }
  176283. /* Read in the selected part of the array.
  176284. * During the initial write pass, we will do no actual read
  176285. * because the selected part is all undefined.
  176286. */
  176287. do_sarray_io(cinfo, ptr, FALSE);
  176288. }
  176289. /* Ensure the accessed part of the array is defined; prezero if needed.
  176290. * To improve locality of access, we only prezero the part of the array
  176291. * that the caller is about to access, not the entire in-memory array.
  176292. */
  176293. if (ptr->first_undef_row < end_row) {
  176294. if (ptr->first_undef_row < start_row) {
  176295. if (writable) /* writer skipped over a section of array */
  176296. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176297. undef_row = start_row; /* but reader is allowed to read ahead */
  176298. } else {
  176299. undef_row = ptr->first_undef_row;
  176300. }
  176301. if (writable)
  176302. ptr->first_undef_row = end_row;
  176303. if (ptr->pre_zero) {
  176304. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176305. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176306. end_row -= ptr->cur_start_row;
  176307. while (undef_row < end_row) {
  176308. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176309. undef_row++;
  176310. }
  176311. } else {
  176312. if (! writable) /* reader looking at undefined data */
  176313. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176314. }
  176315. }
  176316. /* Flag the buffer dirty if caller will write in it */
  176317. if (writable)
  176318. ptr->dirty = TRUE;
  176319. /* Return address of proper part of the buffer */
  176320. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176321. }
  176322. METHODDEF(JBLOCKARRAY)
  176323. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176324. JDIMENSION start_row, JDIMENSION num_rows,
  176325. boolean writable)
  176326. /* Access the part of a virtual block array starting at start_row */
  176327. /* and extending for num_rows rows. writable is true if */
  176328. /* caller intends to modify the accessed area. */
  176329. {
  176330. JDIMENSION end_row = start_row + num_rows;
  176331. JDIMENSION undef_row;
  176332. /* debugging check */
  176333. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176334. ptr->mem_buffer == NULL)
  176335. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176336. /* Make the desired part of the virtual array accessible */
  176337. if (start_row < ptr->cur_start_row ||
  176338. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176339. if (! ptr->b_s_open)
  176340. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176341. /* Flush old buffer contents if necessary */
  176342. if (ptr->dirty) {
  176343. do_barray_io(cinfo, ptr, TRUE);
  176344. ptr->dirty = FALSE;
  176345. }
  176346. /* Decide what part of virtual array to access.
  176347. * Algorithm: if target address > current window, assume forward scan,
  176348. * load starting at target address. If target address < current window,
  176349. * assume backward scan, load so that target area is top of window.
  176350. * Note that when switching from forward write to forward read, will have
  176351. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176352. */
  176353. if (start_row > ptr->cur_start_row) {
  176354. ptr->cur_start_row = start_row;
  176355. } else {
  176356. /* use long arithmetic here to avoid overflow & unsigned problems */
  176357. long ltemp;
  176358. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176359. if (ltemp < 0)
  176360. ltemp = 0; /* don't fall off front end of file */
  176361. ptr->cur_start_row = (JDIMENSION) ltemp;
  176362. }
  176363. /* Read in the selected part of the array.
  176364. * During the initial write pass, we will do no actual read
  176365. * because the selected part is all undefined.
  176366. */
  176367. do_barray_io(cinfo, ptr, FALSE);
  176368. }
  176369. /* Ensure the accessed part of the array is defined; prezero if needed.
  176370. * To improve locality of access, we only prezero the part of the array
  176371. * that the caller is about to access, not the entire in-memory array.
  176372. */
  176373. if (ptr->first_undef_row < end_row) {
  176374. if (ptr->first_undef_row < start_row) {
  176375. if (writable) /* writer skipped over a section of array */
  176376. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176377. undef_row = start_row; /* but reader is allowed to read ahead */
  176378. } else {
  176379. undef_row = ptr->first_undef_row;
  176380. }
  176381. if (writable)
  176382. ptr->first_undef_row = end_row;
  176383. if (ptr->pre_zero) {
  176384. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176385. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176386. end_row -= ptr->cur_start_row;
  176387. while (undef_row < end_row) {
  176388. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176389. undef_row++;
  176390. }
  176391. } else {
  176392. if (! writable) /* reader looking at undefined data */
  176393. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176394. }
  176395. }
  176396. /* Flag the buffer dirty if caller will write in it */
  176397. if (writable)
  176398. ptr->dirty = TRUE;
  176399. /* Return address of proper part of the buffer */
  176400. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176401. }
  176402. /*
  176403. * Release all objects belonging to a specified pool.
  176404. */
  176405. METHODDEF(void)
  176406. free_pool (j_common_ptr cinfo, int pool_id)
  176407. {
  176408. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176409. small_pool_ptr shdr_ptr;
  176410. large_pool_ptr lhdr_ptr;
  176411. size_t space_freed;
  176412. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176413. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176414. #ifdef MEM_STATS
  176415. if (cinfo->err->trace_level > 1)
  176416. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176417. #endif
  176418. /* If freeing IMAGE pool, close any virtual arrays first */
  176419. if (pool_id == JPOOL_IMAGE) {
  176420. jvirt_sarray_ptr sptr;
  176421. jvirt_barray_ptr bptr;
  176422. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176423. if (sptr->b_s_open) { /* there may be no backing store */
  176424. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176425. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176426. }
  176427. }
  176428. mem->virt_sarray_list = NULL;
  176429. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176430. if (bptr->b_s_open) { /* there may be no backing store */
  176431. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176432. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176433. }
  176434. }
  176435. mem->virt_barray_list = NULL;
  176436. }
  176437. /* Release large objects */
  176438. lhdr_ptr = mem->large_list[pool_id];
  176439. mem->large_list[pool_id] = NULL;
  176440. while (lhdr_ptr != NULL) {
  176441. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176442. space_freed = lhdr_ptr->hdr.bytes_used +
  176443. lhdr_ptr->hdr.bytes_left +
  176444. SIZEOF(large_pool_hdr);
  176445. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176446. mem->total_space_allocated -= space_freed;
  176447. lhdr_ptr = next_lhdr_ptr;
  176448. }
  176449. /* Release small objects */
  176450. shdr_ptr = mem->small_list[pool_id];
  176451. mem->small_list[pool_id] = NULL;
  176452. while (shdr_ptr != NULL) {
  176453. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176454. space_freed = shdr_ptr->hdr.bytes_used +
  176455. shdr_ptr->hdr.bytes_left +
  176456. SIZEOF(small_pool_hdr);
  176457. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176458. mem->total_space_allocated -= space_freed;
  176459. shdr_ptr = next_shdr_ptr;
  176460. }
  176461. }
  176462. /*
  176463. * Close up shop entirely.
  176464. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176465. */
  176466. METHODDEF(void)
  176467. self_destruct (j_common_ptr cinfo)
  176468. {
  176469. int pool;
  176470. /* Close all backing store, release all memory.
  176471. * Releasing pools in reverse order might help avoid fragmentation
  176472. * with some (brain-damaged) malloc libraries.
  176473. */
  176474. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176475. free_pool(cinfo, pool);
  176476. }
  176477. /* Release the memory manager control block too. */
  176478. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176479. cinfo->mem = NULL; /* ensures I will be called only once */
  176480. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176481. }
  176482. /*
  176483. * Memory manager initialization.
  176484. * When this is called, only the error manager pointer is valid in cinfo!
  176485. */
  176486. GLOBAL(void)
  176487. jinit_memory_mgr (j_common_ptr cinfo)
  176488. {
  176489. my_mem_ptr mem;
  176490. long max_to_use;
  176491. int pool;
  176492. size_t test_mac;
  176493. cinfo->mem = NULL; /* for safety if init fails */
  176494. /* Check for configuration errors.
  176495. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176496. * doesn't reflect any real hardware alignment requirement.
  176497. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176498. * in common if and only if X is a power of 2, ie has only one one-bit.
  176499. * Some compilers may give an "unreachable code" warning here; ignore it.
  176500. */
  176501. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176502. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176503. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176504. * a multiple of SIZEOF(ALIGN_TYPE).
  176505. * Again, an "unreachable code" warning may be ignored here.
  176506. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176507. */
  176508. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176509. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176510. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176511. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176512. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176513. /* Attempt to allocate memory manager's control block */
  176514. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176515. if (mem == NULL) {
  176516. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176517. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176518. }
  176519. /* OK, fill in the method pointers */
  176520. mem->pub.alloc_small = alloc_small;
  176521. mem->pub.alloc_large = alloc_large;
  176522. mem->pub.alloc_sarray = alloc_sarray;
  176523. mem->pub.alloc_barray = alloc_barray;
  176524. mem->pub.request_virt_sarray = request_virt_sarray;
  176525. mem->pub.request_virt_barray = request_virt_barray;
  176526. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176527. mem->pub.access_virt_sarray = access_virt_sarray;
  176528. mem->pub.access_virt_barray = access_virt_barray;
  176529. mem->pub.free_pool = free_pool;
  176530. mem->pub.self_destruct = self_destruct;
  176531. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176532. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176533. /* Initialize working state */
  176534. mem->pub.max_memory_to_use = max_to_use;
  176535. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176536. mem->small_list[pool] = NULL;
  176537. mem->large_list[pool] = NULL;
  176538. }
  176539. mem->virt_sarray_list = NULL;
  176540. mem->virt_barray_list = NULL;
  176541. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176542. /* Declare ourselves open for business */
  176543. cinfo->mem = & mem->pub;
  176544. /* Check for an environment variable JPEGMEM; if found, override the
  176545. * default max_memory setting from jpeg_mem_init. Note that the
  176546. * surrounding application may again override this value.
  176547. * If your system doesn't support getenv(), define NO_GETENV to disable
  176548. * this feature.
  176549. */
  176550. #ifndef NO_GETENV
  176551. { char * memenv;
  176552. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176553. char ch = 'x';
  176554. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176555. if (ch == 'm' || ch == 'M')
  176556. max_to_use *= 1000L;
  176557. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176558. }
  176559. }
  176560. }
  176561. #endif
  176562. }
  176563. /*** End of inlined file: jmemmgr.c ***/
  176564. /*** Start of inlined file: jmemnobs.c ***/
  176565. #define JPEG_INTERNALS
  176566. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176567. extern void * malloc JPP((size_t size));
  176568. extern void free JPP((void *ptr));
  176569. #endif
  176570. /*
  176571. * Memory allocation and freeing are controlled by the regular library
  176572. * routines malloc() and free().
  176573. */
  176574. GLOBAL(void *)
  176575. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176576. {
  176577. return (void *) malloc(sizeofobject);
  176578. }
  176579. GLOBAL(void)
  176580. jpeg_free_small (j_common_ptr , void * object, size_t)
  176581. {
  176582. free(object);
  176583. }
  176584. /*
  176585. * "Large" objects are treated the same as "small" ones.
  176586. * NB: although we include FAR keywords in the routine declarations,
  176587. * this file won't actually work in 80x86 small/medium model; at least,
  176588. * you probably won't be able to process useful-size images in only 64KB.
  176589. */
  176590. GLOBAL(void FAR *)
  176591. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176592. {
  176593. return (void FAR *) malloc(sizeofobject);
  176594. }
  176595. GLOBAL(void)
  176596. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176597. {
  176598. free(object);
  176599. }
  176600. /*
  176601. * This routine computes the total memory space available for allocation.
  176602. * Here we always say, "we got all you want bud!"
  176603. */
  176604. GLOBAL(long)
  176605. jpeg_mem_available (j_common_ptr, long,
  176606. long max_bytes_needed, long)
  176607. {
  176608. return max_bytes_needed;
  176609. }
  176610. /*
  176611. * Backing store (temporary file) management.
  176612. * Since jpeg_mem_available always promised the moon,
  176613. * this should never be called and we can just error out.
  176614. */
  176615. GLOBAL(void)
  176616. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176617. long )
  176618. {
  176619. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176620. }
  176621. /*
  176622. * These routines take care of any system-dependent initialization and
  176623. * cleanup required. Here, there isn't any.
  176624. */
  176625. GLOBAL(long)
  176626. jpeg_mem_init (j_common_ptr)
  176627. {
  176628. return 0; /* just set max_memory_to_use to 0 */
  176629. }
  176630. GLOBAL(void)
  176631. jpeg_mem_term (j_common_ptr)
  176632. {
  176633. /* no work */
  176634. }
  176635. /*** End of inlined file: jmemnobs.c ***/
  176636. /*** Start of inlined file: jquant1.c ***/
  176637. #define JPEG_INTERNALS
  176638. #ifdef QUANT_1PASS_SUPPORTED
  176639. /*
  176640. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176641. * high quality, colormapped output capability. A 2-pass quantizer usually
  176642. * gives better visual quality; however, for quantized grayscale output this
  176643. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176644. * quantizer, though you can turn it off if you really want to.
  176645. *
  176646. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176647. * image. We use a map consisting of all combinations of Ncolors[i] color
  176648. * values for the i'th component. The Ncolors[] values are chosen so that
  176649. * their product, the total number of colors, is no more than that requested.
  176650. * (In most cases, the product will be somewhat less.)
  176651. *
  176652. * Since the colormap is orthogonal, the representative value for each color
  176653. * component can be determined without considering the other components;
  176654. * then these indexes can be combined into a colormap index by a standard
  176655. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176656. * can be precalculated and stored in the lookup table colorindex[].
  176657. * colorindex[i][j] maps pixel value j in component i to the nearest
  176658. * representative value (grid plane) for that component; this index is
  176659. * multiplied by the array stride for component i, so that the
  176660. * index of the colormap entry closest to a given pixel value is just
  176661. * sum( colorindex[component-number][pixel-component-value] )
  176662. * Aside from being fast, this scheme allows for variable spacing between
  176663. * representative values with no additional lookup cost.
  176664. *
  176665. * If gamma correction has been applied in color conversion, it might be wise
  176666. * to adjust the color grid spacing so that the representative colors are
  176667. * equidistant in linear space. At this writing, gamma correction is not
  176668. * implemented by jdcolor, so nothing is done here.
  176669. */
  176670. /* Declarations for ordered dithering.
  176671. *
  176672. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176673. * dithering is described in many references, for instance Dale Schumacher's
  176674. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176675. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176676. * "dither" value to the input pixel and then round the result to the nearest
  176677. * output value. The dither value is equivalent to (0.5 - threshold) times
  176678. * the distance between output values. For ordered dithering, we assume that
  176679. * the output colors are equally spaced; if not, results will probably be
  176680. * worse, since the dither may be too much or too little at a given point.
  176681. *
  176682. * The normal calculation would be to form pixel value + dither, range-limit
  176683. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176684. * We can skip the separate range-limiting step by extending the colorindex
  176685. * table in both directions.
  176686. */
  176687. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176688. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176689. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176690. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176691. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176692. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176693. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176694. /* Bayer's order-4 dither array. Generated by the code given in
  176695. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176696. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176697. */
  176698. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176699. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176700. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176701. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176702. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176703. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176704. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176705. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176706. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176707. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176708. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176709. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176710. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176711. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176712. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176713. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176714. };
  176715. /* Declarations for Floyd-Steinberg dithering.
  176716. *
  176717. * Errors are accumulated into the array fserrors[], at a resolution of
  176718. * 1/16th of a pixel count. The error at a given pixel is propagated
  176719. * to its not-yet-processed neighbors using the standard F-S fractions,
  176720. * ... (here) 7/16
  176721. * 3/16 5/16 1/16
  176722. * We work left-to-right on even rows, right-to-left on odd rows.
  176723. *
  176724. * We can get away with a single array (holding one row's worth of errors)
  176725. * by using it to store the current row's errors at pixel columns not yet
  176726. * processed, but the next row's errors at columns already processed. We
  176727. * need only a few extra variables to hold the errors immediately around the
  176728. * current column. (If we are lucky, those variables are in registers, but
  176729. * even if not, they're probably cheaper to access than array elements are.)
  176730. *
  176731. * The fserrors[] array is indexed [component#][position].
  176732. * We provide (#columns + 2) entries per component; the extra entry at each
  176733. * end saves us from special-casing the first and last pixels.
  176734. *
  176735. * Note: on a wide image, we might not have enough room in a PC's near data
  176736. * segment to hold the error array; so it is allocated with alloc_large.
  176737. */
  176738. #if BITS_IN_JSAMPLE == 8
  176739. typedef INT16 FSERROR; /* 16 bits should be enough */
  176740. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176741. #else
  176742. typedef INT32 FSERROR; /* may need more than 16 bits */
  176743. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176744. #endif
  176745. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176746. /* Private subobject */
  176747. #define MAX_Q_COMPS 4 /* max components I can handle */
  176748. typedef struct {
  176749. struct jpeg_color_quantizer pub; /* public fields */
  176750. /* Initially allocated colormap is saved here */
  176751. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176752. int sv_actual; /* number of entries in use */
  176753. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176754. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176755. * premultiplied as described above. Since colormap indexes must fit into
  176756. * JSAMPLEs, the entries of this array will too.
  176757. */
  176758. boolean is_padded; /* is the colorindex padded for odither? */
  176759. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176760. /* Variables for ordered dithering */
  176761. int row_index; /* cur row's vertical index in dither matrix */
  176762. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176763. /* Variables for Floyd-Steinberg dithering */
  176764. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176765. boolean on_odd_row; /* flag to remember which row we are on */
  176766. } my_cquantizer;
  176767. typedef my_cquantizer * my_cquantize_ptr;
  176768. /*
  176769. * Policy-making subroutines for create_colormap and create_colorindex.
  176770. * These routines determine the colormap to be used. The rest of the module
  176771. * only assumes that the colormap is orthogonal.
  176772. *
  176773. * * select_ncolors decides how to divvy up the available colors
  176774. * among the components.
  176775. * * output_value defines the set of representative values for a component.
  176776. * * largest_input_value defines the mapping from input values to
  176777. * representative values for a component.
  176778. * Note that the latter two routines may impose different policies for
  176779. * different components, though this is not currently done.
  176780. */
  176781. LOCAL(int)
  176782. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176783. /* Determine allocation of desired colors to components, */
  176784. /* and fill in Ncolors[] array to indicate choice. */
  176785. /* Return value is total number of colors (product of Ncolors[] values). */
  176786. {
  176787. int nc = cinfo->out_color_components; /* number of color components */
  176788. int max_colors = cinfo->desired_number_of_colors;
  176789. int total_colors, iroot, i, j;
  176790. boolean changed;
  176791. long temp;
  176792. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176793. /* We can allocate at least the nc'th root of max_colors per component. */
  176794. /* Compute floor(nc'th root of max_colors). */
  176795. iroot = 1;
  176796. do {
  176797. iroot++;
  176798. temp = iroot; /* set temp = iroot ** nc */
  176799. for (i = 1; i < nc; i++)
  176800. temp *= iroot;
  176801. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176802. iroot--; /* now iroot = floor(root) */
  176803. /* Must have at least 2 color values per component */
  176804. if (iroot < 2)
  176805. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176806. /* Initialize to iroot color values for each component */
  176807. total_colors = 1;
  176808. for (i = 0; i < nc; i++) {
  176809. Ncolors[i] = iroot;
  176810. total_colors *= iroot;
  176811. }
  176812. /* We may be able to increment the count for one or more components without
  176813. * exceeding max_colors, though we know not all can be incremented.
  176814. * Sometimes, the first component can be incremented more than once!
  176815. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176816. * In RGB colorspace, try to increment G first, then R, then B.
  176817. */
  176818. do {
  176819. changed = FALSE;
  176820. for (i = 0; i < nc; i++) {
  176821. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176822. /* calculate new total_colors if Ncolors[j] is incremented */
  176823. temp = total_colors / Ncolors[j];
  176824. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176825. if (temp > (long) max_colors)
  176826. break; /* won't fit, done with this pass */
  176827. Ncolors[j]++; /* OK, apply the increment */
  176828. total_colors = (int) temp;
  176829. changed = TRUE;
  176830. }
  176831. } while (changed);
  176832. return total_colors;
  176833. }
  176834. LOCAL(int)
  176835. output_value (j_decompress_ptr, int, int j, int maxj)
  176836. /* Return j'th output value, where j will range from 0 to maxj */
  176837. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176838. {
  176839. /* We always provide values 0 and MAXJSAMPLE for each component;
  176840. * any additional values are equally spaced between these limits.
  176841. * (Forcing the upper and lower values to the limits ensures that
  176842. * dithering can't produce a color outside the selected gamut.)
  176843. */
  176844. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176845. }
  176846. LOCAL(int)
  176847. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176848. /* Return largest input value that should map to j'th output value */
  176849. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176850. {
  176851. /* Breakpoints are halfway between values returned by output_value */
  176852. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176853. }
  176854. /*
  176855. * Create the colormap.
  176856. */
  176857. LOCAL(void)
  176858. create_colormap (j_decompress_ptr cinfo)
  176859. {
  176860. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176861. JSAMPARRAY colormap; /* Created colormap */
  176862. int total_colors; /* Number of distinct output colors */
  176863. int i,j,k, nci, blksize, blkdist, ptr, val;
  176864. /* Select number of colors for each component */
  176865. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176866. /* Report selected color counts */
  176867. if (cinfo->out_color_components == 3)
  176868. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176869. total_colors, cquantize->Ncolors[0],
  176870. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176871. else
  176872. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176873. /* Allocate and fill in the colormap. */
  176874. /* The colors are ordered in the map in standard row-major order, */
  176875. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176876. colormap = (*cinfo->mem->alloc_sarray)
  176877. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176878. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176879. /* blksize is number of adjacent repeated entries for a component */
  176880. /* blkdist is distance between groups of identical entries for a component */
  176881. blkdist = total_colors;
  176882. for (i = 0; i < cinfo->out_color_components; i++) {
  176883. /* fill in colormap entries for i'th color component */
  176884. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176885. blksize = blkdist / nci;
  176886. for (j = 0; j < nci; j++) {
  176887. /* Compute j'th output value (out of nci) for component */
  176888. val = output_value(cinfo, i, j, nci-1);
  176889. /* Fill in all colormap entries that have this value of this component */
  176890. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176891. /* fill in blksize entries beginning at ptr */
  176892. for (k = 0; k < blksize; k++)
  176893. colormap[i][ptr+k] = (JSAMPLE) val;
  176894. }
  176895. }
  176896. blkdist = blksize; /* blksize of this color is blkdist of next */
  176897. }
  176898. /* Save the colormap in private storage,
  176899. * where it will survive color quantization mode changes.
  176900. */
  176901. cquantize->sv_colormap = colormap;
  176902. cquantize->sv_actual = total_colors;
  176903. }
  176904. /*
  176905. * Create the color index table.
  176906. */
  176907. LOCAL(void)
  176908. create_colorindex (j_decompress_ptr cinfo)
  176909. {
  176910. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176911. JSAMPROW indexptr;
  176912. int i,j,k, nci, blksize, val, pad;
  176913. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176914. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176915. * This is not necessary in the other dithering modes. However, we
  176916. * flag whether it was done in case user changes dithering mode.
  176917. */
  176918. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176919. pad = MAXJSAMPLE*2;
  176920. cquantize->is_padded = TRUE;
  176921. } else {
  176922. pad = 0;
  176923. cquantize->is_padded = FALSE;
  176924. }
  176925. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176926. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176927. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176928. (JDIMENSION) cinfo->out_color_components);
  176929. /* blksize is number of adjacent repeated entries for a component */
  176930. blksize = cquantize->sv_actual;
  176931. for (i = 0; i < cinfo->out_color_components; i++) {
  176932. /* fill in colorindex entries for i'th color component */
  176933. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176934. blksize = blksize / nci;
  176935. /* adjust colorindex pointers to provide padding at negative indexes. */
  176936. if (pad)
  176937. cquantize->colorindex[i] += MAXJSAMPLE;
  176938. /* in loop, val = index of current output value, */
  176939. /* and k = largest j that maps to current val */
  176940. indexptr = cquantize->colorindex[i];
  176941. val = 0;
  176942. k = largest_input_value(cinfo, i, 0, nci-1);
  176943. for (j = 0; j <= MAXJSAMPLE; j++) {
  176944. while (j > k) /* advance val if past boundary */
  176945. k = largest_input_value(cinfo, i, ++val, nci-1);
  176946. /* premultiply so that no multiplication needed in main processing */
  176947. indexptr[j] = (JSAMPLE) (val * blksize);
  176948. }
  176949. /* Pad at both ends if necessary */
  176950. if (pad)
  176951. for (j = 1; j <= MAXJSAMPLE; j++) {
  176952. indexptr[-j] = indexptr[0];
  176953. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176954. }
  176955. }
  176956. }
  176957. /*
  176958. * Create an ordered-dither array for a component having ncolors
  176959. * distinct output values.
  176960. */
  176961. LOCAL(ODITHER_MATRIX_PTR)
  176962. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176963. {
  176964. ODITHER_MATRIX_PTR odither;
  176965. int j,k;
  176966. INT32 num,den;
  176967. odither = (ODITHER_MATRIX_PTR)
  176968. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176969. SIZEOF(ODITHER_MATRIX));
  176970. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176971. * Hence the dither value for the matrix cell with fill order f
  176972. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176973. * On 16-bit-int machine, be careful to avoid overflow.
  176974. */
  176975. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176976. for (j = 0; j < ODITHER_SIZE; j++) {
  176977. for (k = 0; k < ODITHER_SIZE; k++) {
  176978. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176979. * MAXJSAMPLE;
  176980. /* Ensure round towards zero despite C's lack of consistency
  176981. * about rounding negative values in integer division...
  176982. */
  176983. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176984. }
  176985. }
  176986. return odither;
  176987. }
  176988. /*
  176989. * Create the ordered-dither tables.
  176990. * Components having the same number of representative colors may
  176991. * share a dither table.
  176992. */
  176993. LOCAL(void)
  176994. create_odither_tables (j_decompress_ptr cinfo)
  176995. {
  176996. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176997. ODITHER_MATRIX_PTR odither;
  176998. int i, j, nci;
  176999. for (i = 0; i < cinfo->out_color_components; i++) {
  177000. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177001. odither = NULL; /* search for matching prior component */
  177002. for (j = 0; j < i; j++) {
  177003. if (nci == cquantize->Ncolors[j]) {
  177004. odither = cquantize->odither[j];
  177005. break;
  177006. }
  177007. }
  177008. if (odither == NULL) /* need a new table? */
  177009. odither = make_odither_array(cinfo, nci);
  177010. cquantize->odither[i] = odither;
  177011. }
  177012. }
  177013. /*
  177014. * Map some rows of pixels to the output colormapped representation.
  177015. */
  177016. METHODDEF(void)
  177017. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177018. JSAMPARRAY output_buf, int num_rows)
  177019. /* General case, no dithering */
  177020. {
  177021. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177022. JSAMPARRAY colorindex = cquantize->colorindex;
  177023. register int pixcode, ci;
  177024. register JSAMPROW ptrin, ptrout;
  177025. int row;
  177026. JDIMENSION col;
  177027. JDIMENSION width = cinfo->output_width;
  177028. register int nc = cinfo->out_color_components;
  177029. for (row = 0; row < num_rows; row++) {
  177030. ptrin = input_buf[row];
  177031. ptrout = output_buf[row];
  177032. for (col = width; col > 0; col--) {
  177033. pixcode = 0;
  177034. for (ci = 0; ci < nc; ci++) {
  177035. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177036. }
  177037. *ptrout++ = (JSAMPLE) pixcode;
  177038. }
  177039. }
  177040. }
  177041. METHODDEF(void)
  177042. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177043. JSAMPARRAY output_buf, int num_rows)
  177044. /* Fast path for out_color_components==3, no dithering */
  177045. {
  177046. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177047. register int pixcode;
  177048. register JSAMPROW ptrin, ptrout;
  177049. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177050. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177051. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177052. int row;
  177053. JDIMENSION col;
  177054. JDIMENSION width = cinfo->output_width;
  177055. for (row = 0; row < num_rows; row++) {
  177056. ptrin = input_buf[row];
  177057. ptrout = output_buf[row];
  177058. for (col = width; col > 0; col--) {
  177059. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177060. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177061. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177062. *ptrout++ = (JSAMPLE) pixcode;
  177063. }
  177064. }
  177065. }
  177066. METHODDEF(void)
  177067. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177068. JSAMPARRAY output_buf, int num_rows)
  177069. /* General case, with ordered dithering */
  177070. {
  177071. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177072. register JSAMPROW input_ptr;
  177073. register JSAMPROW output_ptr;
  177074. JSAMPROW colorindex_ci;
  177075. int * dither; /* points to active row of dither matrix */
  177076. int row_index, col_index; /* current indexes into dither matrix */
  177077. int nc = cinfo->out_color_components;
  177078. int ci;
  177079. int row;
  177080. JDIMENSION col;
  177081. JDIMENSION width = cinfo->output_width;
  177082. for (row = 0; row < num_rows; row++) {
  177083. /* Initialize output values to 0 so can process components separately */
  177084. jzero_far((void FAR *) output_buf[row],
  177085. (size_t) (width * SIZEOF(JSAMPLE)));
  177086. row_index = cquantize->row_index;
  177087. for (ci = 0; ci < nc; ci++) {
  177088. input_ptr = input_buf[row] + ci;
  177089. output_ptr = output_buf[row];
  177090. colorindex_ci = cquantize->colorindex[ci];
  177091. dither = cquantize->odither[ci][row_index];
  177092. col_index = 0;
  177093. for (col = width; col > 0; col--) {
  177094. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177095. * select output value, accumulate into output code for this pixel.
  177096. * Range-limiting need not be done explicitly, as we have extended
  177097. * the colorindex table to produce the right answers for out-of-range
  177098. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177099. * required amount of padding.
  177100. */
  177101. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177102. input_ptr += nc;
  177103. output_ptr++;
  177104. col_index = (col_index + 1) & ODITHER_MASK;
  177105. }
  177106. }
  177107. /* Advance row index for next row */
  177108. row_index = (row_index + 1) & ODITHER_MASK;
  177109. cquantize->row_index = row_index;
  177110. }
  177111. }
  177112. METHODDEF(void)
  177113. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177114. JSAMPARRAY output_buf, int num_rows)
  177115. /* Fast path for out_color_components==3, with ordered dithering */
  177116. {
  177117. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177118. register int pixcode;
  177119. register JSAMPROW input_ptr;
  177120. register JSAMPROW output_ptr;
  177121. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177122. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177123. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177124. int * dither0; /* points to active row of dither matrix */
  177125. int * dither1;
  177126. int * dither2;
  177127. int row_index, col_index; /* current indexes into dither matrix */
  177128. int row;
  177129. JDIMENSION col;
  177130. JDIMENSION width = cinfo->output_width;
  177131. for (row = 0; row < num_rows; row++) {
  177132. row_index = cquantize->row_index;
  177133. input_ptr = input_buf[row];
  177134. output_ptr = output_buf[row];
  177135. dither0 = cquantize->odither[0][row_index];
  177136. dither1 = cquantize->odither[1][row_index];
  177137. dither2 = cquantize->odither[2][row_index];
  177138. col_index = 0;
  177139. for (col = width; col > 0; col--) {
  177140. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177141. dither0[col_index]]);
  177142. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177143. dither1[col_index]]);
  177144. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177145. dither2[col_index]]);
  177146. *output_ptr++ = (JSAMPLE) pixcode;
  177147. col_index = (col_index + 1) & ODITHER_MASK;
  177148. }
  177149. row_index = (row_index + 1) & ODITHER_MASK;
  177150. cquantize->row_index = row_index;
  177151. }
  177152. }
  177153. METHODDEF(void)
  177154. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177155. JSAMPARRAY output_buf, int num_rows)
  177156. /* General case, with Floyd-Steinberg dithering */
  177157. {
  177158. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177159. register LOCFSERROR cur; /* current error or pixel value */
  177160. LOCFSERROR belowerr; /* error for pixel below cur */
  177161. LOCFSERROR bpreverr; /* error for below/prev col */
  177162. LOCFSERROR bnexterr; /* error for below/next col */
  177163. LOCFSERROR delta;
  177164. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177165. register JSAMPROW input_ptr;
  177166. register JSAMPROW output_ptr;
  177167. JSAMPROW colorindex_ci;
  177168. JSAMPROW colormap_ci;
  177169. int pixcode;
  177170. int nc = cinfo->out_color_components;
  177171. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177172. int dirnc; /* dir * nc */
  177173. int ci;
  177174. int row;
  177175. JDIMENSION col;
  177176. JDIMENSION width = cinfo->output_width;
  177177. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177178. SHIFT_TEMPS
  177179. for (row = 0; row < num_rows; row++) {
  177180. /* Initialize output values to 0 so can process components separately */
  177181. jzero_far((void FAR *) output_buf[row],
  177182. (size_t) (width * SIZEOF(JSAMPLE)));
  177183. for (ci = 0; ci < nc; ci++) {
  177184. input_ptr = input_buf[row] + ci;
  177185. output_ptr = output_buf[row];
  177186. if (cquantize->on_odd_row) {
  177187. /* work right to left in this row */
  177188. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177189. output_ptr += width-1;
  177190. dir = -1;
  177191. dirnc = -nc;
  177192. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177193. } else {
  177194. /* work left to right in this row */
  177195. dir = 1;
  177196. dirnc = nc;
  177197. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177198. }
  177199. colorindex_ci = cquantize->colorindex[ci];
  177200. colormap_ci = cquantize->sv_colormap[ci];
  177201. /* Preset error values: no error propagated to first pixel from left */
  177202. cur = 0;
  177203. /* and no error propagated to row below yet */
  177204. belowerr = bpreverr = 0;
  177205. for (col = width; col > 0; col--) {
  177206. /* cur holds the error propagated from the previous pixel on the
  177207. * current line. Add the error propagated from the previous line
  177208. * to form the complete error correction term for this pixel, and
  177209. * round the error term (which is expressed * 16) to an integer.
  177210. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177211. * for either sign of the error value.
  177212. * Note: errorptr points to *previous* column's array entry.
  177213. */
  177214. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177215. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177216. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177217. * of the range_limit array.
  177218. */
  177219. cur += GETJSAMPLE(*input_ptr);
  177220. cur = GETJSAMPLE(range_limit[cur]);
  177221. /* Select output value, accumulate into output code for this pixel */
  177222. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177223. *output_ptr += (JSAMPLE) pixcode;
  177224. /* Compute actual representation error at this pixel */
  177225. /* Note: we can do this even though we don't have the final */
  177226. /* pixel code, because the colormap is orthogonal. */
  177227. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177228. /* Compute error fractions to be propagated to adjacent pixels.
  177229. * Add these into the running sums, and simultaneously shift the
  177230. * next-line error sums left by 1 column.
  177231. */
  177232. bnexterr = cur;
  177233. delta = cur * 2;
  177234. cur += delta; /* form error * 3 */
  177235. errorptr[0] = (FSERROR) (bpreverr + cur);
  177236. cur += delta; /* form error * 5 */
  177237. bpreverr = belowerr + cur;
  177238. belowerr = bnexterr;
  177239. cur += delta; /* form error * 7 */
  177240. /* At this point cur contains the 7/16 error value to be propagated
  177241. * to the next pixel on the current line, and all the errors for the
  177242. * next line have been shifted over. We are therefore ready to move on.
  177243. */
  177244. input_ptr += dirnc; /* advance input ptr to next column */
  177245. output_ptr += dir; /* advance output ptr to next column */
  177246. errorptr += dir; /* advance errorptr to current column */
  177247. }
  177248. /* Post-loop cleanup: we must unload the final error value into the
  177249. * final fserrors[] entry. Note we need not unload belowerr because
  177250. * it is for the dummy column before or after the actual array.
  177251. */
  177252. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177253. }
  177254. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177255. }
  177256. }
  177257. /*
  177258. * Allocate workspace for Floyd-Steinberg errors.
  177259. */
  177260. LOCAL(void)
  177261. alloc_fs_workspace (j_decompress_ptr cinfo)
  177262. {
  177263. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177264. size_t arraysize;
  177265. int i;
  177266. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177267. for (i = 0; i < cinfo->out_color_components; i++) {
  177268. cquantize->fserrors[i] = (FSERRPTR)
  177269. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177270. }
  177271. }
  177272. /*
  177273. * Initialize for one-pass color quantization.
  177274. */
  177275. METHODDEF(void)
  177276. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177277. {
  177278. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177279. size_t arraysize;
  177280. int i;
  177281. /* Install my colormap. */
  177282. cinfo->colormap = cquantize->sv_colormap;
  177283. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177284. /* Initialize for desired dithering mode. */
  177285. switch (cinfo->dither_mode) {
  177286. case JDITHER_NONE:
  177287. if (cinfo->out_color_components == 3)
  177288. cquantize->pub.color_quantize = color_quantize3;
  177289. else
  177290. cquantize->pub.color_quantize = color_quantize;
  177291. break;
  177292. case JDITHER_ORDERED:
  177293. if (cinfo->out_color_components == 3)
  177294. cquantize->pub.color_quantize = quantize3_ord_dither;
  177295. else
  177296. cquantize->pub.color_quantize = quantize_ord_dither;
  177297. cquantize->row_index = 0; /* initialize state for ordered dither */
  177298. /* If user changed to ordered dither from another mode,
  177299. * we must recreate the color index table with padding.
  177300. * This will cost extra space, but probably isn't very likely.
  177301. */
  177302. if (! cquantize->is_padded)
  177303. create_colorindex(cinfo);
  177304. /* Create ordered-dither tables if we didn't already. */
  177305. if (cquantize->odither[0] == NULL)
  177306. create_odither_tables(cinfo);
  177307. break;
  177308. case JDITHER_FS:
  177309. cquantize->pub.color_quantize = quantize_fs_dither;
  177310. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177311. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177312. if (cquantize->fserrors[0] == NULL)
  177313. alloc_fs_workspace(cinfo);
  177314. /* Initialize the propagated errors to zero. */
  177315. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177316. for (i = 0; i < cinfo->out_color_components; i++)
  177317. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177318. break;
  177319. default:
  177320. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177321. break;
  177322. }
  177323. }
  177324. /*
  177325. * Finish up at the end of the pass.
  177326. */
  177327. METHODDEF(void)
  177328. finish_pass_1_quant (j_decompress_ptr)
  177329. {
  177330. /* no work in 1-pass case */
  177331. }
  177332. /*
  177333. * Switch to a new external colormap between output passes.
  177334. * Shouldn't get to this module!
  177335. */
  177336. METHODDEF(void)
  177337. new_color_map_1_quant (j_decompress_ptr cinfo)
  177338. {
  177339. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177340. }
  177341. /*
  177342. * Module initialization routine for 1-pass color quantization.
  177343. */
  177344. GLOBAL(void)
  177345. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177346. {
  177347. my_cquantize_ptr cquantize;
  177348. cquantize = (my_cquantize_ptr)
  177349. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177350. SIZEOF(my_cquantizer));
  177351. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177352. cquantize->pub.start_pass = start_pass_1_quant;
  177353. cquantize->pub.finish_pass = finish_pass_1_quant;
  177354. cquantize->pub.new_color_map = new_color_map_1_quant;
  177355. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177356. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177357. /* Make sure my internal arrays won't overflow */
  177358. if (cinfo->out_color_components > MAX_Q_COMPS)
  177359. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177360. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177361. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177362. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177363. /* Create the colormap and color index table. */
  177364. create_colormap(cinfo);
  177365. create_colorindex(cinfo);
  177366. /* Allocate Floyd-Steinberg workspace now if requested.
  177367. * We do this now since it is FAR storage and may affect the memory
  177368. * manager's space calculations. If the user changes to FS dither
  177369. * mode in a later pass, we will allocate the space then, and will
  177370. * possibly overrun the max_memory_to_use setting.
  177371. */
  177372. if (cinfo->dither_mode == JDITHER_FS)
  177373. alloc_fs_workspace(cinfo);
  177374. }
  177375. #endif /* QUANT_1PASS_SUPPORTED */
  177376. /*** End of inlined file: jquant1.c ***/
  177377. /*** Start of inlined file: jquant2.c ***/
  177378. #define JPEG_INTERNALS
  177379. #ifdef QUANT_2PASS_SUPPORTED
  177380. /*
  177381. * This module implements the well-known Heckbert paradigm for color
  177382. * quantization. Most of the ideas used here can be traced back to
  177383. * Heckbert's seminal paper
  177384. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177385. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177386. *
  177387. * In the first pass over the image, we accumulate a histogram showing the
  177388. * usage count of each possible color. To keep the histogram to a reasonable
  177389. * size, we reduce the precision of the input; typical practice is to retain
  177390. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177391. * in the same histogram cell.
  177392. *
  177393. * Next, the color-selection step begins with a box representing the whole
  177394. * color space, and repeatedly splits the "largest" remaining box until we
  177395. * have as many boxes as desired colors. Then the mean color in each
  177396. * remaining box becomes one of the possible output colors.
  177397. *
  177398. * The second pass over the image maps each input pixel to the closest output
  177399. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177400. * This mapping is logically trivial, but making it go fast enough requires
  177401. * considerable care.
  177402. *
  177403. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177404. * the "largest" box and deciding where to cut it. The particular policies
  177405. * used here have proved out well in experimental comparisons, but better ones
  177406. * may yet be found.
  177407. *
  177408. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177409. * space, processing the raw upsampled data without a color conversion step.
  177410. * This allowed the color conversion math to be done only once per colormap
  177411. * entry, not once per pixel. However, that optimization precluded other
  177412. * useful optimizations (such as merging color conversion with upsampling)
  177413. * and it also interfered with desired capabilities such as quantizing to an
  177414. * externally-supplied colormap. We have therefore abandoned that approach.
  177415. * The present code works in the post-conversion color space, typically RGB.
  177416. *
  177417. * To improve the visual quality of the results, we actually work in scaled
  177418. * RGB space, giving G distances more weight than R, and R in turn more than
  177419. * B. To do everything in integer math, we must use integer scale factors.
  177420. * The 2/3/1 scale factors used here correspond loosely to the relative
  177421. * weights of the colors in the NTSC grayscale equation.
  177422. * If you want to use this code to quantize a non-RGB color space, you'll
  177423. * probably need to change these scale factors.
  177424. */
  177425. #define R_SCALE 2 /* scale R distances by this much */
  177426. #define G_SCALE 3 /* scale G distances by this much */
  177427. #define B_SCALE 1 /* and B by this much */
  177428. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177429. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177430. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177431. * you'll get compile errors until you extend this logic. In that case
  177432. * you'll probably want to tweak the histogram sizes too.
  177433. */
  177434. #if RGB_RED == 0
  177435. #define C0_SCALE R_SCALE
  177436. #endif
  177437. #if RGB_BLUE == 0
  177438. #define C0_SCALE B_SCALE
  177439. #endif
  177440. #if RGB_GREEN == 1
  177441. #define C1_SCALE G_SCALE
  177442. #endif
  177443. #if RGB_RED == 2
  177444. #define C2_SCALE R_SCALE
  177445. #endif
  177446. #if RGB_BLUE == 2
  177447. #define C2_SCALE B_SCALE
  177448. #endif
  177449. /*
  177450. * First we have the histogram data structure and routines for creating it.
  177451. *
  177452. * The number of bits of precision can be adjusted by changing these symbols.
  177453. * We recommend keeping 6 bits for G and 5 each for R and B.
  177454. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177455. * better results; if you are short of memory, 5 bits all around will save
  177456. * some space but degrade the results.
  177457. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177458. * (preferably unsigned long) for each cell. In practice this is overkill;
  177459. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177460. * and clamping those that do overflow to the maximum value will give close-
  177461. * enough results. This reduces the recommended histogram size from 256Kb
  177462. * to 128Kb, which is a useful savings on PC-class machines.
  177463. * (In the second pass the histogram space is re-used for pixel mapping data;
  177464. * in that capacity, each cell must be able to store zero to the number of
  177465. * desired colors. 16 bits/cell is plenty for that too.)
  177466. * Since the JPEG code is intended to run in small memory model on 80x86
  177467. * machines, we can't just allocate the histogram in one chunk. Instead
  177468. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177469. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177470. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177471. * on 80x86 machines, the pointer row is in near memory but the actual
  177472. * arrays are in far memory (same arrangement as we use for image arrays).
  177473. */
  177474. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177475. /* These will do the right thing for either R,G,B or B,G,R color order,
  177476. * but you may not like the results for other color orders.
  177477. */
  177478. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177479. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177480. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177481. /* Number of elements along histogram axes. */
  177482. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177483. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177484. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177485. /* These are the amounts to shift an input value to get a histogram index. */
  177486. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177487. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177488. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177489. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177490. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177491. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177492. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177493. typedef hist2d * hist3d; /* type for top-level pointer */
  177494. /* Declarations for Floyd-Steinberg dithering.
  177495. *
  177496. * Errors are accumulated into the array fserrors[], at a resolution of
  177497. * 1/16th of a pixel count. The error at a given pixel is propagated
  177498. * to its not-yet-processed neighbors using the standard F-S fractions,
  177499. * ... (here) 7/16
  177500. * 3/16 5/16 1/16
  177501. * We work left-to-right on even rows, right-to-left on odd rows.
  177502. *
  177503. * We can get away with a single array (holding one row's worth of errors)
  177504. * by using it to store the current row's errors at pixel columns not yet
  177505. * processed, but the next row's errors at columns already processed. We
  177506. * need only a few extra variables to hold the errors immediately around the
  177507. * current column. (If we are lucky, those variables are in registers, but
  177508. * even if not, they're probably cheaper to access than array elements are.)
  177509. *
  177510. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177511. * each end saves us from special-casing the first and last pixels.
  177512. * Each entry is three values long, one value for each color component.
  177513. *
  177514. * Note: on a wide image, we might not have enough room in a PC's near data
  177515. * segment to hold the error array; so it is allocated with alloc_large.
  177516. */
  177517. #if BITS_IN_JSAMPLE == 8
  177518. typedef INT16 FSERROR; /* 16 bits should be enough */
  177519. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177520. #else
  177521. typedef INT32 FSERROR; /* may need more than 16 bits */
  177522. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177523. #endif
  177524. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177525. /* Private subobject */
  177526. typedef struct {
  177527. struct jpeg_color_quantizer pub; /* public fields */
  177528. /* Space for the eventually created colormap is stashed here */
  177529. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177530. int desired; /* desired # of colors = size of colormap */
  177531. /* Variables for accumulating image statistics */
  177532. hist3d histogram; /* pointer to the histogram */
  177533. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177534. /* Variables for Floyd-Steinberg dithering */
  177535. FSERRPTR fserrors; /* accumulated errors */
  177536. boolean on_odd_row; /* flag to remember which row we are on */
  177537. int * error_limiter; /* table for clamping the applied error */
  177538. } my_cquantizer2;
  177539. typedef my_cquantizer2 * my_cquantize_ptr2;
  177540. /*
  177541. * Prescan some rows of pixels.
  177542. * In this module the prescan simply updates the histogram, which has been
  177543. * initialized to zeroes by start_pass.
  177544. * An output_buf parameter is required by the method signature, but no data
  177545. * is actually output (in fact the buffer controller is probably passing a
  177546. * NULL pointer).
  177547. */
  177548. METHODDEF(void)
  177549. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177550. JSAMPARRAY, int num_rows)
  177551. {
  177552. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177553. register JSAMPROW ptr;
  177554. register histptr histp;
  177555. register hist3d histogram = cquantize->histogram;
  177556. int row;
  177557. JDIMENSION col;
  177558. JDIMENSION width = cinfo->output_width;
  177559. for (row = 0; row < num_rows; row++) {
  177560. ptr = input_buf[row];
  177561. for (col = width; col > 0; col--) {
  177562. /* get pixel value and index into the histogram */
  177563. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177564. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177565. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177566. /* increment, check for overflow and undo increment if so. */
  177567. if (++(*histp) <= 0)
  177568. (*histp)--;
  177569. ptr += 3;
  177570. }
  177571. }
  177572. }
  177573. /*
  177574. * Next we have the really interesting routines: selection of a colormap
  177575. * given the completed histogram.
  177576. * These routines work with a list of "boxes", each representing a rectangular
  177577. * subset of the input color space (to histogram precision).
  177578. */
  177579. typedef struct {
  177580. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177581. int c0min, c0max;
  177582. int c1min, c1max;
  177583. int c2min, c2max;
  177584. /* The volume (actually 2-norm) of the box */
  177585. INT32 volume;
  177586. /* The number of nonzero histogram cells within this box */
  177587. long colorcount;
  177588. } box;
  177589. typedef box * boxptr;
  177590. LOCAL(boxptr)
  177591. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177592. /* Find the splittable box with the largest color population */
  177593. /* Returns NULL if no splittable boxes remain */
  177594. {
  177595. register boxptr boxp;
  177596. register int i;
  177597. register long maxc = 0;
  177598. boxptr which = NULL;
  177599. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177600. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177601. which = boxp;
  177602. maxc = boxp->colorcount;
  177603. }
  177604. }
  177605. return which;
  177606. }
  177607. LOCAL(boxptr)
  177608. find_biggest_volume (boxptr boxlist, int numboxes)
  177609. /* Find the splittable box with the largest (scaled) volume */
  177610. /* Returns NULL if no splittable boxes remain */
  177611. {
  177612. register boxptr boxp;
  177613. register int i;
  177614. register INT32 maxv = 0;
  177615. boxptr which = NULL;
  177616. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177617. if (boxp->volume > maxv) {
  177618. which = boxp;
  177619. maxv = boxp->volume;
  177620. }
  177621. }
  177622. return which;
  177623. }
  177624. LOCAL(void)
  177625. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177626. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177627. /* and recompute its volume and population */
  177628. {
  177629. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177630. hist3d histogram = cquantize->histogram;
  177631. histptr histp;
  177632. int c0,c1,c2;
  177633. int c0min,c0max,c1min,c1max,c2min,c2max;
  177634. INT32 dist0,dist1,dist2;
  177635. long ccount;
  177636. c0min = boxp->c0min; c0max = boxp->c0max;
  177637. c1min = boxp->c1min; c1max = boxp->c1max;
  177638. c2min = boxp->c2min; c2max = boxp->c2max;
  177639. if (c0max > c0min)
  177640. for (c0 = c0min; c0 <= c0max; c0++)
  177641. for (c1 = c1min; c1 <= c1max; c1++) {
  177642. histp = & histogram[c0][c1][c2min];
  177643. for (c2 = c2min; c2 <= c2max; c2++)
  177644. if (*histp++ != 0) {
  177645. boxp->c0min = c0min = c0;
  177646. goto have_c0min;
  177647. }
  177648. }
  177649. have_c0min:
  177650. if (c0max > c0min)
  177651. for (c0 = c0max; c0 >= c0min; c0--)
  177652. for (c1 = c1min; c1 <= c1max; c1++) {
  177653. histp = & histogram[c0][c1][c2min];
  177654. for (c2 = c2min; c2 <= c2max; c2++)
  177655. if (*histp++ != 0) {
  177656. boxp->c0max = c0max = c0;
  177657. goto have_c0max;
  177658. }
  177659. }
  177660. have_c0max:
  177661. if (c1max > c1min)
  177662. for (c1 = c1min; c1 <= c1max; c1++)
  177663. for (c0 = c0min; c0 <= c0max; c0++) {
  177664. histp = & histogram[c0][c1][c2min];
  177665. for (c2 = c2min; c2 <= c2max; c2++)
  177666. if (*histp++ != 0) {
  177667. boxp->c1min = c1min = c1;
  177668. goto have_c1min;
  177669. }
  177670. }
  177671. have_c1min:
  177672. if (c1max > c1min)
  177673. for (c1 = c1max; c1 >= c1min; c1--)
  177674. for (c0 = c0min; c0 <= c0max; c0++) {
  177675. histp = & histogram[c0][c1][c2min];
  177676. for (c2 = c2min; c2 <= c2max; c2++)
  177677. if (*histp++ != 0) {
  177678. boxp->c1max = c1max = c1;
  177679. goto have_c1max;
  177680. }
  177681. }
  177682. have_c1max:
  177683. if (c2max > c2min)
  177684. for (c2 = c2min; c2 <= c2max; c2++)
  177685. for (c0 = c0min; c0 <= c0max; c0++) {
  177686. histp = & histogram[c0][c1min][c2];
  177687. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177688. if (*histp != 0) {
  177689. boxp->c2min = c2min = c2;
  177690. goto have_c2min;
  177691. }
  177692. }
  177693. have_c2min:
  177694. if (c2max > c2min)
  177695. for (c2 = c2max; c2 >= c2min; c2--)
  177696. for (c0 = c0min; c0 <= c0max; c0++) {
  177697. histp = & histogram[c0][c1min][c2];
  177698. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177699. if (*histp != 0) {
  177700. boxp->c2max = c2max = c2;
  177701. goto have_c2max;
  177702. }
  177703. }
  177704. have_c2max:
  177705. /* Update box volume.
  177706. * We use 2-norm rather than real volume here; this biases the method
  177707. * against making long narrow boxes, and it has the side benefit that
  177708. * a box is splittable iff norm > 0.
  177709. * Since the differences are expressed in histogram-cell units,
  177710. * we have to shift back to JSAMPLE units to get consistent distances;
  177711. * after which, we scale according to the selected distance scale factors.
  177712. */
  177713. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177714. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177715. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177716. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177717. /* Now scan remaining volume of box and compute population */
  177718. ccount = 0;
  177719. for (c0 = c0min; c0 <= c0max; c0++)
  177720. for (c1 = c1min; c1 <= c1max; c1++) {
  177721. histp = & histogram[c0][c1][c2min];
  177722. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177723. if (*histp != 0) {
  177724. ccount++;
  177725. }
  177726. }
  177727. boxp->colorcount = ccount;
  177728. }
  177729. LOCAL(int)
  177730. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177731. int desired_colors)
  177732. /* Repeatedly select and split the largest box until we have enough boxes */
  177733. {
  177734. int n,lb;
  177735. int c0,c1,c2,cmax;
  177736. register boxptr b1,b2;
  177737. while (numboxes < desired_colors) {
  177738. /* Select box to split.
  177739. * Current algorithm: by population for first half, then by volume.
  177740. */
  177741. if (numboxes*2 <= desired_colors) {
  177742. b1 = find_biggest_color_pop(boxlist, numboxes);
  177743. } else {
  177744. b1 = find_biggest_volume(boxlist, numboxes);
  177745. }
  177746. if (b1 == NULL) /* no splittable boxes left! */
  177747. break;
  177748. b2 = &boxlist[numboxes]; /* where new box will go */
  177749. /* Copy the color bounds to the new box. */
  177750. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177751. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177752. /* Choose which axis to split the box on.
  177753. * Current algorithm: longest scaled axis.
  177754. * See notes in update_box about scaling distances.
  177755. */
  177756. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177757. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177758. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177759. /* We want to break any ties in favor of green, then red, blue last.
  177760. * This code does the right thing for R,G,B or B,G,R color orders only.
  177761. */
  177762. #if RGB_RED == 0
  177763. cmax = c1; n = 1;
  177764. if (c0 > cmax) { cmax = c0; n = 0; }
  177765. if (c2 > cmax) { n = 2; }
  177766. #else
  177767. cmax = c1; n = 1;
  177768. if (c2 > cmax) { cmax = c2; n = 2; }
  177769. if (c0 > cmax) { n = 0; }
  177770. #endif
  177771. /* Choose split point along selected axis, and update box bounds.
  177772. * Current algorithm: split at halfway point.
  177773. * (Since the box has been shrunk to minimum volume,
  177774. * any split will produce two nonempty subboxes.)
  177775. * Note that lb value is max for lower box, so must be < old max.
  177776. */
  177777. switch (n) {
  177778. case 0:
  177779. lb = (b1->c0max + b1->c0min) / 2;
  177780. b1->c0max = lb;
  177781. b2->c0min = lb+1;
  177782. break;
  177783. case 1:
  177784. lb = (b1->c1max + b1->c1min) / 2;
  177785. b1->c1max = lb;
  177786. b2->c1min = lb+1;
  177787. break;
  177788. case 2:
  177789. lb = (b1->c2max + b1->c2min) / 2;
  177790. b1->c2max = lb;
  177791. b2->c2min = lb+1;
  177792. break;
  177793. }
  177794. /* Update stats for boxes */
  177795. update_box(cinfo, b1);
  177796. update_box(cinfo, b2);
  177797. numboxes++;
  177798. }
  177799. return numboxes;
  177800. }
  177801. LOCAL(void)
  177802. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177803. /* Compute representative color for a box, put it in colormap[icolor] */
  177804. {
  177805. /* Current algorithm: mean weighted by pixels (not colors) */
  177806. /* Note it is important to get the rounding correct! */
  177807. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177808. hist3d histogram = cquantize->histogram;
  177809. histptr histp;
  177810. int c0,c1,c2;
  177811. int c0min,c0max,c1min,c1max,c2min,c2max;
  177812. long count;
  177813. long total = 0;
  177814. long c0total = 0;
  177815. long c1total = 0;
  177816. long c2total = 0;
  177817. c0min = boxp->c0min; c0max = boxp->c0max;
  177818. c1min = boxp->c1min; c1max = boxp->c1max;
  177819. c2min = boxp->c2min; c2max = boxp->c2max;
  177820. for (c0 = c0min; c0 <= c0max; c0++)
  177821. for (c1 = c1min; c1 <= c1max; c1++) {
  177822. histp = & histogram[c0][c1][c2min];
  177823. for (c2 = c2min; c2 <= c2max; c2++) {
  177824. if ((count = *histp++) != 0) {
  177825. total += count;
  177826. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177827. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177828. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177829. }
  177830. }
  177831. }
  177832. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177833. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177834. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177835. }
  177836. LOCAL(void)
  177837. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177838. /* Master routine for color selection */
  177839. {
  177840. boxptr boxlist;
  177841. int numboxes;
  177842. int i;
  177843. /* Allocate workspace for box list */
  177844. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177845. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177846. /* Initialize one box containing whole space */
  177847. numboxes = 1;
  177848. boxlist[0].c0min = 0;
  177849. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177850. boxlist[0].c1min = 0;
  177851. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177852. boxlist[0].c2min = 0;
  177853. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177854. /* Shrink it to actually-used volume and set its statistics */
  177855. update_box(cinfo, & boxlist[0]);
  177856. /* Perform median-cut to produce final box list */
  177857. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177858. /* Compute the representative color for each box, fill colormap */
  177859. for (i = 0; i < numboxes; i++)
  177860. compute_color(cinfo, & boxlist[i], i);
  177861. cinfo->actual_number_of_colors = numboxes;
  177862. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177863. }
  177864. /*
  177865. * These routines are concerned with the time-critical task of mapping input
  177866. * colors to the nearest color in the selected colormap.
  177867. *
  177868. * We re-use the histogram space as an "inverse color map", essentially a
  177869. * cache for the results of nearest-color searches. All colors within a
  177870. * histogram cell will be mapped to the same colormap entry, namely the one
  177871. * closest to the cell's center. This may not be quite the closest entry to
  177872. * the actual input color, but it's almost as good. A zero in the cache
  177873. * indicates we haven't found the nearest color for that cell yet; the array
  177874. * is cleared to zeroes before starting the mapping pass. When we find the
  177875. * nearest color for a cell, its colormap index plus one is recorded in the
  177876. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177877. * when they need to use an unfilled entry in the cache.
  177878. *
  177879. * Our method of efficiently finding nearest colors is based on the "locally
  177880. * sorted search" idea described by Heckbert and on the incremental distance
  177881. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177882. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177883. * the distances from a given colormap entry to each cell of the histogram can
  177884. * be computed quickly using an incremental method: the differences between
  177885. * distances to adjacent cells themselves differ by a constant. This allows a
  177886. * fairly fast implementation of the "brute force" approach of computing the
  177887. * distance from every colormap entry to every histogram cell. Unfortunately,
  177888. * it needs a work array to hold the best-distance-so-far for each histogram
  177889. * cell (because the inner loop has to be over cells, not colormap entries).
  177890. * The work array elements have to be INT32s, so the work array would need
  177891. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177892. *
  177893. * To get around these problems, we apply Thomas' method to compute the
  177894. * nearest colors for only the cells within a small subbox of the histogram.
  177895. * The work array need be only as big as the subbox, so the memory usage
  177896. * problem is solved. Furthermore, we need not fill subboxes that are never
  177897. * referenced in pass2; many images use only part of the color gamut, so a
  177898. * fair amount of work is saved. An additional advantage of this
  177899. * approach is that we can apply Heckbert's locality criterion to quickly
  177900. * eliminate colormap entries that are far away from the subbox; typically
  177901. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177902. * and we need not compute their distances to individual cells in the subbox.
  177903. * The speed of this approach is heavily influenced by the subbox size: too
  177904. * small means too much overhead, too big loses because Heckbert's criterion
  177905. * can't eliminate as many colormap entries. Empirically the best subbox
  177906. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177907. *
  177908. * Thomas' article also describes a refined method which is asymptotically
  177909. * faster than the brute-force method, but it is also far more complex and
  177910. * cannot efficiently be applied to small subboxes. It is therefore not
  177911. * useful for programs intended to be portable to DOS machines. On machines
  177912. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177913. * refined method might be faster than the present code --- but then again,
  177914. * it might not be any faster, and it's certainly more complicated.
  177915. */
  177916. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177917. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177918. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177919. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177920. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177921. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177922. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177923. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177924. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177925. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177926. /*
  177927. * The next three routines implement inverse colormap filling. They could
  177928. * all be folded into one big routine, but splitting them up this way saves
  177929. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177930. * and may allow some compilers to produce better code by registerizing more
  177931. * inner-loop variables.
  177932. */
  177933. LOCAL(int)
  177934. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177935. JSAMPLE colorlist[])
  177936. /* Locate the colormap entries close enough to an update box to be candidates
  177937. * for the nearest entry to some cell(s) in the update box. The update box
  177938. * is specified by the center coordinates of its first cell. The number of
  177939. * candidate colormap entries is returned, and their colormap indexes are
  177940. * placed in colorlist[].
  177941. * This routine uses Heckbert's "locally sorted search" criterion to select
  177942. * the colors that need further consideration.
  177943. */
  177944. {
  177945. int numcolors = cinfo->actual_number_of_colors;
  177946. int maxc0, maxc1, maxc2;
  177947. int centerc0, centerc1, centerc2;
  177948. int i, x, ncolors;
  177949. INT32 minmaxdist, min_dist, max_dist, tdist;
  177950. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177951. /* Compute true coordinates of update box's upper corner and center.
  177952. * Actually we compute the coordinates of the center of the upper-corner
  177953. * histogram cell, which are the upper bounds of the volume we care about.
  177954. * Note that since ">>" rounds down, the "center" values may be closer to
  177955. * min than to max; hence comparisons to them must be "<=", not "<".
  177956. */
  177957. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177958. centerc0 = (minc0 + maxc0) >> 1;
  177959. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177960. centerc1 = (minc1 + maxc1) >> 1;
  177961. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177962. centerc2 = (minc2 + maxc2) >> 1;
  177963. /* For each color in colormap, find:
  177964. * 1. its minimum squared-distance to any point in the update box
  177965. * (zero if color is within update box);
  177966. * 2. its maximum squared-distance to any point in the update box.
  177967. * Both of these can be found by considering only the corners of the box.
  177968. * We save the minimum distance for each color in mindist[];
  177969. * only the smallest maximum distance is of interest.
  177970. */
  177971. minmaxdist = 0x7FFFFFFFL;
  177972. for (i = 0; i < numcolors; i++) {
  177973. /* We compute the squared-c0-distance term, then add in the other two. */
  177974. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177975. if (x < minc0) {
  177976. tdist = (x - minc0) * C0_SCALE;
  177977. min_dist = tdist*tdist;
  177978. tdist = (x - maxc0) * C0_SCALE;
  177979. max_dist = tdist*tdist;
  177980. } else if (x > maxc0) {
  177981. tdist = (x - maxc0) * C0_SCALE;
  177982. min_dist = tdist*tdist;
  177983. tdist = (x - minc0) * C0_SCALE;
  177984. max_dist = tdist*tdist;
  177985. } else {
  177986. /* within cell range so no contribution to min_dist */
  177987. min_dist = 0;
  177988. if (x <= centerc0) {
  177989. tdist = (x - maxc0) * C0_SCALE;
  177990. max_dist = tdist*tdist;
  177991. } else {
  177992. tdist = (x - minc0) * C0_SCALE;
  177993. max_dist = tdist*tdist;
  177994. }
  177995. }
  177996. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177997. if (x < minc1) {
  177998. tdist = (x - minc1) * C1_SCALE;
  177999. min_dist += tdist*tdist;
  178000. tdist = (x - maxc1) * C1_SCALE;
  178001. max_dist += tdist*tdist;
  178002. } else if (x > maxc1) {
  178003. tdist = (x - maxc1) * C1_SCALE;
  178004. min_dist += tdist*tdist;
  178005. tdist = (x - minc1) * C1_SCALE;
  178006. max_dist += tdist*tdist;
  178007. } else {
  178008. /* within cell range so no contribution to min_dist */
  178009. if (x <= centerc1) {
  178010. tdist = (x - maxc1) * C1_SCALE;
  178011. max_dist += tdist*tdist;
  178012. } else {
  178013. tdist = (x - minc1) * C1_SCALE;
  178014. max_dist += tdist*tdist;
  178015. }
  178016. }
  178017. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178018. if (x < minc2) {
  178019. tdist = (x - minc2) * C2_SCALE;
  178020. min_dist += tdist*tdist;
  178021. tdist = (x - maxc2) * C2_SCALE;
  178022. max_dist += tdist*tdist;
  178023. } else if (x > maxc2) {
  178024. tdist = (x - maxc2) * C2_SCALE;
  178025. min_dist += tdist*tdist;
  178026. tdist = (x - minc2) * C2_SCALE;
  178027. max_dist += tdist*tdist;
  178028. } else {
  178029. /* within cell range so no contribution to min_dist */
  178030. if (x <= centerc2) {
  178031. tdist = (x - maxc2) * C2_SCALE;
  178032. max_dist += tdist*tdist;
  178033. } else {
  178034. tdist = (x - minc2) * C2_SCALE;
  178035. max_dist += tdist*tdist;
  178036. }
  178037. }
  178038. mindist[i] = min_dist; /* save away the results */
  178039. if (max_dist < minmaxdist)
  178040. minmaxdist = max_dist;
  178041. }
  178042. /* Now we know that no cell in the update box is more than minmaxdist
  178043. * away from some colormap entry. Therefore, only colors that are
  178044. * within minmaxdist of some part of the box need be considered.
  178045. */
  178046. ncolors = 0;
  178047. for (i = 0; i < numcolors; i++) {
  178048. if (mindist[i] <= minmaxdist)
  178049. colorlist[ncolors++] = (JSAMPLE) i;
  178050. }
  178051. return ncolors;
  178052. }
  178053. LOCAL(void)
  178054. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178055. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178056. /* Find the closest colormap entry for each cell in the update box,
  178057. * given the list of candidate colors prepared by find_nearby_colors.
  178058. * Return the indexes of the closest entries in the bestcolor[] array.
  178059. * This routine uses Thomas' incremental distance calculation method to
  178060. * find the distance from a colormap entry to successive cells in the box.
  178061. */
  178062. {
  178063. int ic0, ic1, ic2;
  178064. int i, icolor;
  178065. register INT32 * bptr; /* pointer into bestdist[] array */
  178066. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178067. INT32 dist0, dist1; /* initial distance values */
  178068. register INT32 dist2; /* current distance in inner loop */
  178069. INT32 xx0, xx1; /* distance increments */
  178070. register INT32 xx2;
  178071. INT32 inc0, inc1, inc2; /* initial values for increments */
  178072. /* This array holds the distance to the nearest-so-far color for each cell */
  178073. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178074. /* Initialize best-distance for each cell of the update box */
  178075. bptr = bestdist;
  178076. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178077. *bptr++ = 0x7FFFFFFFL;
  178078. /* For each color selected by find_nearby_colors,
  178079. * compute its distance to the center of each cell in the box.
  178080. * If that's less than best-so-far, update best distance and color number.
  178081. */
  178082. /* Nominal steps between cell centers ("x" in Thomas article) */
  178083. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178084. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178085. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178086. for (i = 0; i < numcolors; i++) {
  178087. icolor = GETJSAMPLE(colorlist[i]);
  178088. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178089. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178090. dist0 = inc0*inc0;
  178091. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178092. dist0 += inc1*inc1;
  178093. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178094. dist0 += inc2*inc2;
  178095. /* Form the initial difference increments */
  178096. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178097. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178098. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178099. /* Now loop over all cells in box, updating distance per Thomas method */
  178100. bptr = bestdist;
  178101. cptr = bestcolor;
  178102. xx0 = inc0;
  178103. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178104. dist1 = dist0;
  178105. xx1 = inc1;
  178106. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178107. dist2 = dist1;
  178108. xx2 = inc2;
  178109. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178110. if (dist2 < *bptr) {
  178111. *bptr = dist2;
  178112. *cptr = (JSAMPLE) icolor;
  178113. }
  178114. dist2 += xx2;
  178115. xx2 += 2 * STEP_C2 * STEP_C2;
  178116. bptr++;
  178117. cptr++;
  178118. }
  178119. dist1 += xx1;
  178120. xx1 += 2 * STEP_C1 * STEP_C1;
  178121. }
  178122. dist0 += xx0;
  178123. xx0 += 2 * STEP_C0 * STEP_C0;
  178124. }
  178125. }
  178126. }
  178127. LOCAL(void)
  178128. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178129. /* Fill the inverse-colormap entries in the update box that contains */
  178130. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178131. /* we can fill as many others as we wish.) */
  178132. {
  178133. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178134. hist3d histogram = cquantize->histogram;
  178135. int minc0, minc1, minc2; /* lower left corner of update box */
  178136. int ic0, ic1, ic2;
  178137. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178138. register histptr cachep; /* pointer into main cache array */
  178139. /* This array lists the candidate colormap indexes. */
  178140. JSAMPLE colorlist[MAXNUMCOLORS];
  178141. int numcolors; /* number of candidate colors */
  178142. /* This array holds the actually closest colormap index for each cell. */
  178143. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178144. /* Convert cell coordinates to update box ID */
  178145. c0 >>= BOX_C0_LOG;
  178146. c1 >>= BOX_C1_LOG;
  178147. c2 >>= BOX_C2_LOG;
  178148. /* Compute true coordinates of update box's origin corner.
  178149. * Actually we compute the coordinates of the center of the corner
  178150. * histogram cell, which are the lower bounds of the volume we care about.
  178151. */
  178152. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178153. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178154. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178155. /* Determine which colormap entries are close enough to be candidates
  178156. * for the nearest entry to some cell in the update box.
  178157. */
  178158. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178159. /* Determine the actually nearest colors. */
  178160. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178161. bestcolor);
  178162. /* Save the best color numbers (plus 1) in the main cache array */
  178163. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178164. c1 <<= BOX_C1_LOG;
  178165. c2 <<= BOX_C2_LOG;
  178166. cptr = bestcolor;
  178167. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178168. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178169. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178170. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178171. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178172. }
  178173. }
  178174. }
  178175. }
  178176. /*
  178177. * Map some rows of pixels to the output colormapped representation.
  178178. */
  178179. METHODDEF(void)
  178180. pass2_no_dither (j_decompress_ptr cinfo,
  178181. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178182. /* This version performs no dithering */
  178183. {
  178184. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178185. hist3d histogram = cquantize->histogram;
  178186. register JSAMPROW inptr, outptr;
  178187. register histptr cachep;
  178188. register int c0, c1, c2;
  178189. int row;
  178190. JDIMENSION col;
  178191. JDIMENSION width = cinfo->output_width;
  178192. for (row = 0; row < num_rows; row++) {
  178193. inptr = input_buf[row];
  178194. outptr = output_buf[row];
  178195. for (col = width; col > 0; col--) {
  178196. /* get pixel value and index into the cache */
  178197. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178198. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178199. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178200. cachep = & histogram[c0][c1][c2];
  178201. /* If we have not seen this color before, find nearest colormap entry */
  178202. /* and update the cache */
  178203. if (*cachep == 0)
  178204. fill_inverse_cmap(cinfo, c0,c1,c2);
  178205. /* Now emit the colormap index for this cell */
  178206. *outptr++ = (JSAMPLE) (*cachep - 1);
  178207. }
  178208. }
  178209. }
  178210. METHODDEF(void)
  178211. pass2_fs_dither (j_decompress_ptr cinfo,
  178212. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178213. /* This version performs Floyd-Steinberg dithering */
  178214. {
  178215. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178216. hist3d histogram = cquantize->histogram;
  178217. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178218. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178219. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178220. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178221. JSAMPROW inptr; /* => current input pixel */
  178222. JSAMPROW outptr; /* => current output pixel */
  178223. histptr cachep;
  178224. int dir; /* +1 or -1 depending on direction */
  178225. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178226. int row;
  178227. JDIMENSION col;
  178228. JDIMENSION width = cinfo->output_width;
  178229. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178230. int *error_limit = cquantize->error_limiter;
  178231. JSAMPROW colormap0 = cinfo->colormap[0];
  178232. JSAMPROW colormap1 = cinfo->colormap[1];
  178233. JSAMPROW colormap2 = cinfo->colormap[2];
  178234. SHIFT_TEMPS
  178235. for (row = 0; row < num_rows; row++) {
  178236. inptr = input_buf[row];
  178237. outptr = output_buf[row];
  178238. if (cquantize->on_odd_row) {
  178239. /* work right to left in this row */
  178240. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178241. outptr += width-1;
  178242. dir = -1;
  178243. dir3 = -3;
  178244. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178245. cquantize->on_odd_row = FALSE; /* flip for next time */
  178246. } else {
  178247. /* work left to right in this row */
  178248. dir = 1;
  178249. dir3 = 3;
  178250. errorptr = cquantize->fserrors; /* => entry before first real column */
  178251. cquantize->on_odd_row = TRUE; /* flip for next time */
  178252. }
  178253. /* Preset error values: no error propagated to first pixel from left */
  178254. cur0 = cur1 = cur2 = 0;
  178255. /* and no error propagated to row below yet */
  178256. belowerr0 = belowerr1 = belowerr2 = 0;
  178257. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178258. for (col = width; col > 0; col--) {
  178259. /* curN holds the error propagated from the previous pixel on the
  178260. * current line. Add the error propagated from the previous line
  178261. * to form the complete error correction term for this pixel, and
  178262. * round the error term (which is expressed * 16) to an integer.
  178263. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178264. * for either sign of the error value.
  178265. * Note: errorptr points to *previous* column's array entry.
  178266. */
  178267. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178268. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178269. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178270. /* Limit the error using transfer function set by init_error_limit.
  178271. * See comments with init_error_limit for rationale.
  178272. */
  178273. cur0 = error_limit[cur0];
  178274. cur1 = error_limit[cur1];
  178275. cur2 = error_limit[cur2];
  178276. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178277. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178278. * this sets the required size of the range_limit array.
  178279. */
  178280. cur0 += GETJSAMPLE(inptr[0]);
  178281. cur1 += GETJSAMPLE(inptr[1]);
  178282. cur2 += GETJSAMPLE(inptr[2]);
  178283. cur0 = GETJSAMPLE(range_limit[cur0]);
  178284. cur1 = GETJSAMPLE(range_limit[cur1]);
  178285. cur2 = GETJSAMPLE(range_limit[cur2]);
  178286. /* Index into the cache with adjusted pixel value */
  178287. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178288. /* If we have not seen this color before, find nearest colormap */
  178289. /* entry and update the cache */
  178290. if (*cachep == 0)
  178291. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178292. /* Now emit the colormap index for this cell */
  178293. { register int pixcode = *cachep - 1;
  178294. *outptr = (JSAMPLE) pixcode;
  178295. /* Compute representation error for this pixel */
  178296. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178297. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178298. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178299. }
  178300. /* Compute error fractions to be propagated to adjacent pixels.
  178301. * Add these into the running sums, and simultaneously shift the
  178302. * next-line error sums left by 1 column.
  178303. */
  178304. { register LOCFSERROR bnexterr, delta;
  178305. bnexterr = cur0; /* Process component 0 */
  178306. delta = cur0 * 2;
  178307. cur0 += delta; /* form error * 3 */
  178308. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178309. cur0 += delta; /* form error * 5 */
  178310. bpreverr0 = belowerr0 + cur0;
  178311. belowerr0 = bnexterr;
  178312. cur0 += delta; /* form error * 7 */
  178313. bnexterr = cur1; /* Process component 1 */
  178314. delta = cur1 * 2;
  178315. cur1 += delta; /* form error * 3 */
  178316. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178317. cur1 += delta; /* form error * 5 */
  178318. bpreverr1 = belowerr1 + cur1;
  178319. belowerr1 = bnexterr;
  178320. cur1 += delta; /* form error * 7 */
  178321. bnexterr = cur2; /* Process component 2 */
  178322. delta = cur2 * 2;
  178323. cur2 += delta; /* form error * 3 */
  178324. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178325. cur2 += delta; /* form error * 5 */
  178326. bpreverr2 = belowerr2 + cur2;
  178327. belowerr2 = bnexterr;
  178328. cur2 += delta; /* form error * 7 */
  178329. }
  178330. /* At this point curN contains the 7/16 error value to be propagated
  178331. * to the next pixel on the current line, and all the errors for the
  178332. * next line have been shifted over. We are therefore ready to move on.
  178333. */
  178334. inptr += dir3; /* Advance pixel pointers to next column */
  178335. outptr += dir;
  178336. errorptr += dir3; /* advance errorptr to current column */
  178337. }
  178338. /* Post-loop cleanup: we must unload the final error values into the
  178339. * final fserrors[] entry. Note we need not unload belowerrN because
  178340. * it is for the dummy column before or after the actual array.
  178341. */
  178342. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178343. errorptr[1] = (FSERROR) bpreverr1;
  178344. errorptr[2] = (FSERROR) bpreverr2;
  178345. }
  178346. }
  178347. /*
  178348. * Initialize the error-limiting transfer function (lookup table).
  178349. * The raw F-S error computation can potentially compute error values of up to
  178350. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178351. * much less, otherwise obviously wrong pixels will be created. (Typical
  178352. * effects include weird fringes at color-area boundaries, isolated bright
  178353. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178354. * is to ensure that the "corners" of the color cube are allocated as output
  178355. * colors; then repeated errors in the same direction cannot cause cascading
  178356. * error buildup. However, that only prevents the error from getting
  178357. * completely out of hand; Aaron Giles reports that error limiting improves
  178358. * the results even with corner colors allocated.
  178359. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178360. * well, but the smoother transfer function used below is even better. Thanks
  178361. * to Aaron Giles for this idea.
  178362. */
  178363. LOCAL(void)
  178364. init_error_limit (j_decompress_ptr cinfo)
  178365. /* Allocate and fill in the error_limiter table */
  178366. {
  178367. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178368. int * table;
  178369. int in, out;
  178370. table = (int *) (*cinfo->mem->alloc_small)
  178371. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178372. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178373. cquantize->error_limiter = table;
  178374. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178375. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178376. out = 0;
  178377. for (in = 0; in < STEPSIZE; in++, out++) {
  178378. table[in] = out; table[-in] = -out;
  178379. }
  178380. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178381. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178382. table[in] = out; table[-in] = -out;
  178383. }
  178384. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178385. for (; in <= MAXJSAMPLE; in++) {
  178386. table[in] = out; table[-in] = -out;
  178387. }
  178388. #undef STEPSIZE
  178389. }
  178390. /*
  178391. * Finish up at the end of each pass.
  178392. */
  178393. METHODDEF(void)
  178394. finish_pass1 (j_decompress_ptr cinfo)
  178395. {
  178396. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178397. /* Select the representative colors and fill in cinfo->colormap */
  178398. cinfo->colormap = cquantize->sv_colormap;
  178399. select_colors(cinfo, cquantize->desired);
  178400. /* Force next pass to zero the color index table */
  178401. cquantize->needs_zeroed = TRUE;
  178402. }
  178403. METHODDEF(void)
  178404. finish_pass2 (j_decompress_ptr)
  178405. {
  178406. /* no work */
  178407. }
  178408. /*
  178409. * Initialize for each processing pass.
  178410. */
  178411. METHODDEF(void)
  178412. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178413. {
  178414. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178415. hist3d histogram = cquantize->histogram;
  178416. int i;
  178417. /* Only F-S dithering or no dithering is supported. */
  178418. /* If user asks for ordered dither, give him F-S. */
  178419. if (cinfo->dither_mode != JDITHER_NONE)
  178420. cinfo->dither_mode = JDITHER_FS;
  178421. if (is_pre_scan) {
  178422. /* Set up method pointers */
  178423. cquantize->pub.color_quantize = prescan_quantize;
  178424. cquantize->pub.finish_pass = finish_pass1;
  178425. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178426. } else {
  178427. /* Set up method pointers */
  178428. if (cinfo->dither_mode == JDITHER_FS)
  178429. cquantize->pub.color_quantize = pass2_fs_dither;
  178430. else
  178431. cquantize->pub.color_quantize = pass2_no_dither;
  178432. cquantize->pub.finish_pass = finish_pass2;
  178433. /* Make sure color count is acceptable */
  178434. i = cinfo->actual_number_of_colors;
  178435. if (i < 1)
  178436. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178437. if (i > MAXNUMCOLORS)
  178438. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178439. if (cinfo->dither_mode == JDITHER_FS) {
  178440. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178441. (3 * SIZEOF(FSERROR)));
  178442. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178443. if (cquantize->fserrors == NULL)
  178444. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178445. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178446. /* Initialize the propagated errors to zero. */
  178447. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178448. /* Make the error-limit table if we didn't already. */
  178449. if (cquantize->error_limiter == NULL)
  178450. init_error_limit(cinfo);
  178451. cquantize->on_odd_row = FALSE;
  178452. }
  178453. }
  178454. /* Zero the histogram or inverse color map, if necessary */
  178455. if (cquantize->needs_zeroed) {
  178456. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178457. jzero_far((void FAR *) histogram[i],
  178458. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178459. }
  178460. cquantize->needs_zeroed = FALSE;
  178461. }
  178462. }
  178463. /*
  178464. * Switch to a new external colormap between output passes.
  178465. */
  178466. METHODDEF(void)
  178467. new_color_map_2_quant (j_decompress_ptr cinfo)
  178468. {
  178469. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178470. /* Reset the inverse color map */
  178471. cquantize->needs_zeroed = TRUE;
  178472. }
  178473. /*
  178474. * Module initialization routine for 2-pass color quantization.
  178475. */
  178476. GLOBAL(void)
  178477. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178478. {
  178479. my_cquantize_ptr2 cquantize;
  178480. int i;
  178481. cquantize = (my_cquantize_ptr2)
  178482. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178483. SIZEOF(my_cquantizer2));
  178484. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178485. cquantize->pub.start_pass = start_pass_2_quant;
  178486. cquantize->pub.new_color_map = new_color_map_2_quant;
  178487. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178488. cquantize->error_limiter = NULL;
  178489. /* Make sure jdmaster didn't give me a case I can't handle */
  178490. if (cinfo->out_color_components != 3)
  178491. ERREXIT(cinfo, JERR_NOTIMPL);
  178492. /* Allocate the histogram/inverse colormap storage */
  178493. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178494. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178495. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178496. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178497. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178498. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178499. }
  178500. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178501. /* Allocate storage for the completed colormap, if required.
  178502. * We do this now since it is FAR storage and may affect
  178503. * the memory manager's space calculations.
  178504. */
  178505. if (cinfo->enable_2pass_quant) {
  178506. /* Make sure color count is acceptable */
  178507. int desired = cinfo->desired_number_of_colors;
  178508. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178509. if (desired < 8)
  178510. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178511. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178512. if (desired > MAXNUMCOLORS)
  178513. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178514. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178515. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178516. cquantize->desired = desired;
  178517. } else
  178518. cquantize->sv_colormap = NULL;
  178519. /* Only F-S dithering or no dithering is supported. */
  178520. /* If user asks for ordered dither, give him F-S. */
  178521. if (cinfo->dither_mode != JDITHER_NONE)
  178522. cinfo->dither_mode = JDITHER_FS;
  178523. /* Allocate Floyd-Steinberg workspace if necessary.
  178524. * This isn't really needed until pass 2, but again it is FAR storage.
  178525. * Although we will cope with a later change in dither_mode,
  178526. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178527. */
  178528. if (cinfo->dither_mode == JDITHER_FS) {
  178529. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178530. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178531. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178532. /* Might as well create the error-limiting table too. */
  178533. init_error_limit(cinfo);
  178534. }
  178535. }
  178536. #endif /* QUANT_2PASS_SUPPORTED */
  178537. /*** End of inlined file: jquant2.c ***/
  178538. /*** Start of inlined file: jutils.c ***/
  178539. #define JPEG_INTERNALS
  178540. /*
  178541. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178542. * of a DCT block read in natural order (left to right, top to bottom).
  178543. */
  178544. #if 0 /* This table is not actually needed in v6a */
  178545. const int jpeg_zigzag_order[DCTSIZE2] = {
  178546. 0, 1, 5, 6, 14, 15, 27, 28,
  178547. 2, 4, 7, 13, 16, 26, 29, 42,
  178548. 3, 8, 12, 17, 25, 30, 41, 43,
  178549. 9, 11, 18, 24, 31, 40, 44, 53,
  178550. 10, 19, 23, 32, 39, 45, 52, 54,
  178551. 20, 22, 33, 38, 46, 51, 55, 60,
  178552. 21, 34, 37, 47, 50, 56, 59, 61,
  178553. 35, 36, 48, 49, 57, 58, 62, 63
  178554. };
  178555. #endif
  178556. /*
  178557. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178558. * of zigzag order.
  178559. *
  178560. * When reading corrupted data, the Huffman decoders could attempt
  178561. * to reference an entry beyond the end of this array (if the decoded
  178562. * zero run length reaches past the end of the block). To prevent
  178563. * wild stores without adding an inner-loop test, we put some extra
  178564. * "63"s after the real entries. This will cause the extra coefficient
  178565. * to be stored in location 63 of the block, not somewhere random.
  178566. * The worst case would be a run-length of 15, which means we need 16
  178567. * fake entries.
  178568. */
  178569. const int jpeg_natural_order[DCTSIZE2+16] = {
  178570. 0, 1, 8, 16, 9, 2, 3, 10,
  178571. 17, 24, 32, 25, 18, 11, 4, 5,
  178572. 12, 19, 26, 33, 40, 48, 41, 34,
  178573. 27, 20, 13, 6, 7, 14, 21, 28,
  178574. 35, 42, 49, 56, 57, 50, 43, 36,
  178575. 29, 22, 15, 23, 30, 37, 44, 51,
  178576. 58, 59, 52, 45, 38, 31, 39, 46,
  178577. 53, 60, 61, 54, 47, 55, 62, 63,
  178578. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178579. 63, 63, 63, 63, 63, 63, 63, 63
  178580. };
  178581. /*
  178582. * Arithmetic utilities
  178583. */
  178584. GLOBAL(long)
  178585. jdiv_round_up (long a, long b)
  178586. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178587. /* Assumes a >= 0, b > 0 */
  178588. {
  178589. return (a + b - 1L) / b;
  178590. }
  178591. GLOBAL(long)
  178592. jround_up (long a, long b)
  178593. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178594. /* Assumes a >= 0, b > 0 */
  178595. {
  178596. a += b - 1L;
  178597. return a - (a % b);
  178598. }
  178599. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178600. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178601. * are FAR and we're assuming a small-pointer memory model. However, some
  178602. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178603. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178604. * Otherwise, the routines below do it the hard way. (The performance cost
  178605. * is not all that great, because these routines aren't very heavily used.)
  178606. */
  178607. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178608. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178609. #define FMEMZERO(target,size) MEMZERO(target,size)
  178610. #else /* 80x86 case, define if we can */
  178611. #ifdef USE_FMEM
  178612. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178613. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178614. #endif
  178615. #endif
  178616. GLOBAL(void)
  178617. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178618. JSAMPARRAY output_array, int dest_row,
  178619. int num_rows, JDIMENSION num_cols)
  178620. /* Copy some rows of samples from one place to another.
  178621. * num_rows rows are copied from input_array[source_row++]
  178622. * to output_array[dest_row++]; these areas may overlap for duplication.
  178623. * The source and destination arrays must be at least as wide as num_cols.
  178624. */
  178625. {
  178626. register JSAMPROW inptr, outptr;
  178627. #ifdef FMEMCOPY
  178628. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178629. #else
  178630. register JDIMENSION count;
  178631. #endif
  178632. register int row;
  178633. input_array += source_row;
  178634. output_array += dest_row;
  178635. for (row = num_rows; row > 0; row--) {
  178636. inptr = *input_array++;
  178637. outptr = *output_array++;
  178638. #ifdef FMEMCOPY
  178639. FMEMCOPY(outptr, inptr, count);
  178640. #else
  178641. for (count = num_cols; count > 0; count--)
  178642. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178643. #endif
  178644. }
  178645. }
  178646. GLOBAL(void)
  178647. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178648. JDIMENSION num_blocks)
  178649. /* Copy a row of coefficient blocks from one place to another. */
  178650. {
  178651. #ifdef FMEMCOPY
  178652. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178653. #else
  178654. register JCOEFPTR inptr, outptr;
  178655. register long count;
  178656. inptr = (JCOEFPTR) input_row;
  178657. outptr = (JCOEFPTR) output_row;
  178658. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178659. *outptr++ = *inptr++;
  178660. }
  178661. #endif
  178662. }
  178663. GLOBAL(void)
  178664. jzero_far (void FAR * target, size_t bytestozero)
  178665. /* Zero out a chunk of FAR memory. */
  178666. /* This might be sample-array data, block-array data, or alloc_large data. */
  178667. {
  178668. #ifdef FMEMZERO
  178669. FMEMZERO(target, bytestozero);
  178670. #else
  178671. register char FAR * ptr = (char FAR *) target;
  178672. register size_t count;
  178673. for (count = bytestozero; count > 0; count--) {
  178674. *ptr++ = 0;
  178675. }
  178676. #endif
  178677. }
  178678. /*** End of inlined file: jutils.c ***/
  178679. /*** Start of inlined file: transupp.c ***/
  178680. /* Although this file really shouldn't have access to the library internals,
  178681. * it's helpful to let it call jround_up() and jcopy_block_row().
  178682. */
  178683. #define JPEG_INTERNALS
  178684. /*** Start of inlined file: transupp.h ***/
  178685. /* If you happen not to want the image transform support, disable it here */
  178686. #ifndef TRANSFORMS_SUPPORTED
  178687. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178688. #endif
  178689. /* Short forms of external names for systems with brain-damaged linkers. */
  178690. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178691. #define jtransform_request_workspace jTrRequest
  178692. #define jtransform_adjust_parameters jTrAdjust
  178693. #define jtransform_execute_transformation jTrExec
  178694. #define jcopy_markers_setup jCMrkSetup
  178695. #define jcopy_markers_execute jCMrkExec
  178696. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178697. /*
  178698. * Codes for supported types of image transformations.
  178699. */
  178700. typedef enum {
  178701. JXFORM_NONE, /* no transformation */
  178702. JXFORM_FLIP_H, /* horizontal flip */
  178703. JXFORM_FLIP_V, /* vertical flip */
  178704. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178705. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178706. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178707. JXFORM_ROT_180, /* 180-degree rotation */
  178708. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178709. } JXFORM_CODE;
  178710. /*
  178711. * Although rotating and flipping data expressed as DCT coefficients is not
  178712. * hard, there is an asymmetry in the JPEG format specification for images
  178713. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178714. * image edges are padded out to the next iMCU boundary with junk data; but
  178715. * no padding is possible at the top and left edges. If we were to flip
  178716. * the whole image including the pad data, then pad garbage would become
  178717. * visible at the top and/or left, and real pixels would disappear into the
  178718. * pad margins --- perhaps permanently, since encoders & decoders may not
  178719. * bother to preserve DCT blocks that appear to be completely outside the
  178720. * nominal image area. So, we have to exclude any partial iMCUs from the
  178721. * basic transformation.
  178722. *
  178723. * Transpose is the only transformation that can handle partial iMCUs at the
  178724. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178725. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178726. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178727. * The other transforms are defined as combinations of these basic transforms
  178728. * and process edge blocks in a way that preserves the equivalence.
  178729. *
  178730. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178731. * this is not strictly lossless, but it usually gives the best-looking
  178732. * result for odd-size images. Note that when this option is active,
  178733. * the expected mathematical equivalences between the transforms may not hold.
  178734. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178735. * followed by -rot 180 -trim trims both edges.)
  178736. *
  178737. * We also offer a "force to grayscale" option, which simply discards the
  178738. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178739. * the luminance channel is preserved exactly. It's not the same kind of
  178740. * thing as the rotate/flip transformations, but it's convenient to handle it
  178741. * as part of this package, mainly because the transformation routines have to
  178742. * be aware of the option to know how many components to work on.
  178743. */
  178744. typedef struct {
  178745. /* Options: set by caller */
  178746. JXFORM_CODE transform; /* image transform operator */
  178747. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178748. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178749. /* Internal workspace: caller should not touch these */
  178750. int num_components; /* # of components in workspace */
  178751. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178752. } jpeg_transform_info;
  178753. #if TRANSFORMS_SUPPORTED
  178754. /* Request any required workspace */
  178755. EXTERN(void) jtransform_request_workspace
  178756. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178757. /* Adjust output image parameters */
  178758. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178759. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178760. jvirt_barray_ptr *src_coef_arrays,
  178761. jpeg_transform_info *info));
  178762. /* Execute the actual transformation, if any */
  178763. EXTERN(void) jtransform_execute_transformation
  178764. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178765. jvirt_barray_ptr *src_coef_arrays,
  178766. jpeg_transform_info *info));
  178767. #endif /* TRANSFORMS_SUPPORTED */
  178768. /*
  178769. * Support for copying optional markers from source to destination file.
  178770. */
  178771. typedef enum {
  178772. JCOPYOPT_NONE, /* copy no optional markers */
  178773. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178774. JCOPYOPT_ALL /* copy all optional markers */
  178775. } JCOPY_OPTION;
  178776. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178777. /* Setup decompression object to save desired markers in memory */
  178778. EXTERN(void) jcopy_markers_setup
  178779. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178780. /* Copy markers saved in the given source object to the destination object */
  178781. EXTERN(void) jcopy_markers_execute
  178782. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178783. JCOPY_OPTION option));
  178784. /*** End of inlined file: transupp.h ***/
  178785. /* My own external interface */
  178786. #if TRANSFORMS_SUPPORTED
  178787. /*
  178788. * Lossless image transformation routines. These routines work on DCT
  178789. * coefficient arrays and thus do not require any lossy decompression
  178790. * or recompression of the image.
  178791. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178792. *
  178793. * Horizontal flipping is done in-place, using a single top-to-bottom
  178794. * pass through the virtual source array. It will thus be much the
  178795. * fastest option for images larger than main memory.
  178796. *
  178797. * The other routines require a set of destination virtual arrays, so they
  178798. * need twice as much memory as jpegtran normally does. The destination
  178799. * arrays are always written in normal scan order (top to bottom) because
  178800. * the virtual array manager expects this. The source arrays will be scanned
  178801. * in the corresponding order, which means multiple passes through the source
  178802. * arrays for most of the transforms. That could result in much thrashing
  178803. * if the image is larger than main memory.
  178804. *
  178805. * Some notes about the operating environment of the individual transform
  178806. * routines:
  178807. * 1. Both the source and destination virtual arrays are allocated from the
  178808. * source JPEG object, and therefore should be manipulated by calling the
  178809. * source's memory manager.
  178810. * 2. The destination's component count should be used. It may be smaller
  178811. * than the source's when forcing to grayscale.
  178812. * 3. Likewise the destination's sampling factors should be used. When
  178813. * forcing to grayscale the destination's sampling factors will be all 1,
  178814. * and we may as well take that as the effective iMCU size.
  178815. * 4. When "trim" is in effect, the destination's dimensions will be the
  178816. * trimmed values but the source's will be untrimmed.
  178817. * 5. All the routines assume that the source and destination buffers are
  178818. * padded out to a full iMCU boundary. This is true, although for the
  178819. * source buffer it is an undocumented property of jdcoefct.c.
  178820. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178821. * dimensions and ignore the source's.
  178822. */
  178823. LOCAL(void)
  178824. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178825. jvirt_barray_ptr *src_coef_arrays)
  178826. /* Horizontal flip; done in-place, so no separate dest array is required */
  178827. {
  178828. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178829. int ci, k, offset_y;
  178830. JBLOCKARRAY buffer;
  178831. JCOEFPTR ptr1, ptr2;
  178832. JCOEF temp1, temp2;
  178833. jpeg_component_info *compptr;
  178834. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178835. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178836. * mirroring by changing the signs of odd-numbered columns.
  178837. * Partial iMCUs at the right edge are left untouched.
  178838. */
  178839. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178840. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178841. compptr = dstinfo->comp_info + ci;
  178842. comp_width = MCU_cols * compptr->h_samp_factor;
  178843. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178844. blk_y += compptr->v_samp_factor) {
  178845. buffer = (*srcinfo->mem->access_virt_barray)
  178846. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178847. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178848. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178849. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178850. ptr1 = buffer[offset_y][blk_x];
  178851. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178852. /* this unrolled loop doesn't need to know which row it's on... */
  178853. for (k = 0; k < DCTSIZE2; k += 2) {
  178854. temp1 = *ptr1; /* swap even column */
  178855. temp2 = *ptr2;
  178856. *ptr1++ = temp2;
  178857. *ptr2++ = temp1;
  178858. temp1 = *ptr1; /* swap odd column with sign change */
  178859. temp2 = *ptr2;
  178860. *ptr1++ = -temp2;
  178861. *ptr2++ = -temp1;
  178862. }
  178863. }
  178864. }
  178865. }
  178866. }
  178867. }
  178868. LOCAL(void)
  178869. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178870. jvirt_barray_ptr *src_coef_arrays,
  178871. jvirt_barray_ptr *dst_coef_arrays)
  178872. /* Vertical flip */
  178873. {
  178874. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178875. int ci, i, j, offset_y;
  178876. JBLOCKARRAY src_buffer, dst_buffer;
  178877. JBLOCKROW src_row_ptr, dst_row_ptr;
  178878. JCOEFPTR src_ptr, dst_ptr;
  178879. jpeg_component_info *compptr;
  178880. /* We output into a separate array because we can't touch different
  178881. * rows of the source virtual array simultaneously. Otherwise, this
  178882. * is a pretty straightforward analog of horizontal flip.
  178883. * Within a DCT block, vertical mirroring is done by changing the signs
  178884. * of odd-numbered rows.
  178885. * Partial iMCUs at the bottom edge are copied verbatim.
  178886. */
  178887. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178888. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178889. compptr = dstinfo->comp_info + ci;
  178890. comp_height = MCU_rows * compptr->v_samp_factor;
  178891. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178892. dst_blk_y += compptr->v_samp_factor) {
  178893. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178894. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178895. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178896. if (dst_blk_y < comp_height) {
  178897. /* Row is within the mirrorable area. */
  178898. src_buffer = (*srcinfo->mem->access_virt_barray)
  178899. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178900. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178901. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178902. } else {
  178903. /* Bottom-edge blocks will be copied verbatim. */
  178904. src_buffer = (*srcinfo->mem->access_virt_barray)
  178905. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178906. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178907. }
  178908. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178909. if (dst_blk_y < comp_height) {
  178910. /* Row is within the mirrorable area. */
  178911. dst_row_ptr = dst_buffer[offset_y];
  178912. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178913. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178914. dst_blk_x++) {
  178915. dst_ptr = dst_row_ptr[dst_blk_x];
  178916. src_ptr = src_row_ptr[dst_blk_x];
  178917. for (i = 0; i < DCTSIZE; i += 2) {
  178918. /* copy even row */
  178919. for (j = 0; j < DCTSIZE; j++)
  178920. *dst_ptr++ = *src_ptr++;
  178921. /* copy odd row with sign change */
  178922. for (j = 0; j < DCTSIZE; j++)
  178923. *dst_ptr++ = - *src_ptr++;
  178924. }
  178925. }
  178926. } else {
  178927. /* Just copy row verbatim. */
  178928. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178929. compptr->width_in_blocks);
  178930. }
  178931. }
  178932. }
  178933. }
  178934. }
  178935. LOCAL(void)
  178936. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178937. jvirt_barray_ptr *src_coef_arrays,
  178938. jvirt_barray_ptr *dst_coef_arrays)
  178939. /* Transpose source into destination */
  178940. {
  178941. JDIMENSION dst_blk_x, dst_blk_y;
  178942. int ci, i, j, offset_x, offset_y;
  178943. JBLOCKARRAY src_buffer, dst_buffer;
  178944. JCOEFPTR src_ptr, dst_ptr;
  178945. jpeg_component_info *compptr;
  178946. /* Transposing pixels within a block just requires transposing the
  178947. * DCT coefficients.
  178948. * Partial iMCUs at the edges require no special treatment; we simply
  178949. * process all the available DCT blocks for every component.
  178950. */
  178951. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178952. compptr = dstinfo->comp_info + ci;
  178953. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178954. dst_blk_y += compptr->v_samp_factor) {
  178955. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178956. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178957. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178958. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178959. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178960. dst_blk_x += compptr->h_samp_factor) {
  178961. src_buffer = (*srcinfo->mem->access_virt_barray)
  178962. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178963. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178964. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178965. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178966. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178967. for (i = 0; i < DCTSIZE; i++)
  178968. for (j = 0; j < DCTSIZE; j++)
  178969. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178970. }
  178971. }
  178972. }
  178973. }
  178974. }
  178975. }
  178976. LOCAL(void)
  178977. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178978. jvirt_barray_ptr *src_coef_arrays,
  178979. jvirt_barray_ptr *dst_coef_arrays)
  178980. /* 90 degree rotation is equivalent to
  178981. * 1. Transposing the image;
  178982. * 2. Horizontal mirroring.
  178983. * These two steps are merged into a single processing routine.
  178984. */
  178985. {
  178986. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178987. int ci, i, j, offset_x, offset_y;
  178988. JBLOCKARRAY src_buffer, dst_buffer;
  178989. JCOEFPTR src_ptr, dst_ptr;
  178990. jpeg_component_info *compptr;
  178991. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178992. * at the (output) right edge properly. They just get transposed and
  178993. * not mirrored.
  178994. */
  178995. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178996. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178997. compptr = dstinfo->comp_info + ci;
  178998. comp_width = MCU_cols * compptr->h_samp_factor;
  178999. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179000. dst_blk_y += compptr->v_samp_factor) {
  179001. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179002. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179003. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179004. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179005. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179006. dst_blk_x += compptr->h_samp_factor) {
  179007. src_buffer = (*srcinfo->mem->access_virt_barray)
  179008. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179009. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179010. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179011. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179012. if (dst_blk_x < comp_width) {
  179013. /* Block is within the mirrorable area. */
  179014. dst_ptr = dst_buffer[offset_y]
  179015. [comp_width - dst_blk_x - offset_x - 1];
  179016. for (i = 0; i < DCTSIZE; i++) {
  179017. for (j = 0; j < DCTSIZE; j++)
  179018. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179019. i++;
  179020. for (j = 0; j < DCTSIZE; j++)
  179021. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179022. }
  179023. } else {
  179024. /* Edge blocks are transposed but not mirrored. */
  179025. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179026. for (i = 0; i < DCTSIZE; i++)
  179027. for (j = 0; j < DCTSIZE; j++)
  179028. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179029. }
  179030. }
  179031. }
  179032. }
  179033. }
  179034. }
  179035. }
  179036. LOCAL(void)
  179037. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179038. jvirt_barray_ptr *src_coef_arrays,
  179039. jvirt_barray_ptr *dst_coef_arrays)
  179040. /* 270 degree rotation is equivalent to
  179041. * 1. Horizontal mirroring;
  179042. * 2. Transposing the image.
  179043. * These two steps are merged into a single processing routine.
  179044. */
  179045. {
  179046. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179047. int ci, i, j, offset_x, offset_y;
  179048. JBLOCKARRAY src_buffer, dst_buffer;
  179049. JCOEFPTR src_ptr, dst_ptr;
  179050. jpeg_component_info *compptr;
  179051. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179052. * at the (output) bottom edge properly. They just get transposed and
  179053. * not mirrored.
  179054. */
  179055. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179056. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179057. compptr = dstinfo->comp_info + ci;
  179058. comp_height = MCU_rows * compptr->v_samp_factor;
  179059. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179060. dst_blk_y += compptr->v_samp_factor) {
  179061. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179062. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179063. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179064. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179065. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179066. dst_blk_x += compptr->h_samp_factor) {
  179067. src_buffer = (*srcinfo->mem->access_virt_barray)
  179068. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179069. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179070. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179071. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179072. if (dst_blk_y < comp_height) {
  179073. /* Block is within the mirrorable area. */
  179074. src_ptr = src_buffer[offset_x]
  179075. [comp_height - dst_blk_y - offset_y - 1];
  179076. for (i = 0; i < DCTSIZE; i++) {
  179077. for (j = 0; j < DCTSIZE; j++) {
  179078. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179079. j++;
  179080. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179081. }
  179082. }
  179083. } else {
  179084. /* Edge blocks are transposed but not mirrored. */
  179085. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179086. for (i = 0; i < DCTSIZE; i++)
  179087. for (j = 0; j < DCTSIZE; j++)
  179088. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179089. }
  179090. }
  179091. }
  179092. }
  179093. }
  179094. }
  179095. }
  179096. LOCAL(void)
  179097. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179098. jvirt_barray_ptr *src_coef_arrays,
  179099. jvirt_barray_ptr *dst_coef_arrays)
  179100. /* 180 degree rotation is equivalent to
  179101. * 1. Vertical mirroring;
  179102. * 2. Horizontal mirroring.
  179103. * These two steps are merged into a single processing routine.
  179104. */
  179105. {
  179106. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179107. int ci, i, j, offset_y;
  179108. JBLOCKARRAY src_buffer, dst_buffer;
  179109. JBLOCKROW src_row_ptr, dst_row_ptr;
  179110. JCOEFPTR src_ptr, dst_ptr;
  179111. jpeg_component_info *compptr;
  179112. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179113. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179114. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179115. compptr = dstinfo->comp_info + ci;
  179116. comp_width = MCU_cols * compptr->h_samp_factor;
  179117. comp_height = MCU_rows * compptr->v_samp_factor;
  179118. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179119. dst_blk_y += compptr->v_samp_factor) {
  179120. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179121. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179122. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179123. if (dst_blk_y < comp_height) {
  179124. /* Row is within the vertically mirrorable area. */
  179125. src_buffer = (*srcinfo->mem->access_virt_barray)
  179126. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179127. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179128. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179129. } else {
  179130. /* Bottom-edge rows are only mirrored horizontally. */
  179131. src_buffer = (*srcinfo->mem->access_virt_barray)
  179132. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179133. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179134. }
  179135. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179136. if (dst_blk_y < comp_height) {
  179137. /* Row is within the mirrorable area. */
  179138. dst_row_ptr = dst_buffer[offset_y];
  179139. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179140. /* Process the blocks that can be mirrored both ways. */
  179141. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179142. dst_ptr = dst_row_ptr[dst_blk_x];
  179143. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179144. for (i = 0; i < DCTSIZE; i += 2) {
  179145. /* For even row, negate every odd column. */
  179146. for (j = 0; j < DCTSIZE; j += 2) {
  179147. *dst_ptr++ = *src_ptr++;
  179148. *dst_ptr++ = - *src_ptr++;
  179149. }
  179150. /* For odd row, negate every even column. */
  179151. for (j = 0; j < DCTSIZE; j += 2) {
  179152. *dst_ptr++ = - *src_ptr++;
  179153. *dst_ptr++ = *src_ptr++;
  179154. }
  179155. }
  179156. }
  179157. /* Any remaining right-edge blocks are only mirrored vertically. */
  179158. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179159. dst_ptr = dst_row_ptr[dst_blk_x];
  179160. src_ptr = src_row_ptr[dst_blk_x];
  179161. for (i = 0; i < DCTSIZE; i += 2) {
  179162. for (j = 0; j < DCTSIZE; j++)
  179163. *dst_ptr++ = *src_ptr++;
  179164. for (j = 0; j < DCTSIZE; j++)
  179165. *dst_ptr++ = - *src_ptr++;
  179166. }
  179167. }
  179168. } else {
  179169. /* Remaining rows are just mirrored horizontally. */
  179170. dst_row_ptr = dst_buffer[offset_y];
  179171. src_row_ptr = src_buffer[offset_y];
  179172. /* Process the blocks that can be mirrored. */
  179173. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179174. dst_ptr = dst_row_ptr[dst_blk_x];
  179175. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179176. for (i = 0; i < DCTSIZE2; i += 2) {
  179177. *dst_ptr++ = *src_ptr++;
  179178. *dst_ptr++ = - *src_ptr++;
  179179. }
  179180. }
  179181. /* Any remaining right-edge blocks are only copied. */
  179182. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179183. dst_ptr = dst_row_ptr[dst_blk_x];
  179184. src_ptr = src_row_ptr[dst_blk_x];
  179185. for (i = 0; i < DCTSIZE2; i++)
  179186. *dst_ptr++ = *src_ptr++;
  179187. }
  179188. }
  179189. }
  179190. }
  179191. }
  179192. }
  179193. LOCAL(void)
  179194. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179195. jvirt_barray_ptr *src_coef_arrays,
  179196. jvirt_barray_ptr *dst_coef_arrays)
  179197. /* Transverse transpose is equivalent to
  179198. * 1. 180 degree rotation;
  179199. * 2. Transposition;
  179200. * or
  179201. * 1. Horizontal mirroring;
  179202. * 2. Transposition;
  179203. * 3. Horizontal mirroring.
  179204. * These steps are merged into a single processing routine.
  179205. */
  179206. {
  179207. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179208. int ci, i, j, offset_x, offset_y;
  179209. JBLOCKARRAY src_buffer, dst_buffer;
  179210. JCOEFPTR src_ptr, dst_ptr;
  179211. jpeg_component_info *compptr;
  179212. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179213. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179214. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179215. compptr = dstinfo->comp_info + ci;
  179216. comp_width = MCU_cols * compptr->h_samp_factor;
  179217. comp_height = MCU_rows * compptr->v_samp_factor;
  179218. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179219. dst_blk_y += compptr->v_samp_factor) {
  179220. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179221. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179222. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179223. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179224. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179225. dst_blk_x += compptr->h_samp_factor) {
  179226. src_buffer = (*srcinfo->mem->access_virt_barray)
  179227. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179228. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179229. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179230. if (dst_blk_y < comp_height) {
  179231. src_ptr = src_buffer[offset_x]
  179232. [comp_height - dst_blk_y - offset_y - 1];
  179233. if (dst_blk_x < comp_width) {
  179234. /* Block is within the mirrorable area. */
  179235. dst_ptr = dst_buffer[offset_y]
  179236. [comp_width - dst_blk_x - offset_x - 1];
  179237. for (i = 0; i < DCTSIZE; i++) {
  179238. for (j = 0; j < DCTSIZE; j++) {
  179239. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179240. j++;
  179241. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179242. }
  179243. i++;
  179244. for (j = 0; j < DCTSIZE; j++) {
  179245. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179246. j++;
  179247. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179248. }
  179249. }
  179250. } else {
  179251. /* Right-edge blocks are mirrored in y only */
  179252. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179253. for (i = 0; i < DCTSIZE; i++) {
  179254. for (j = 0; j < DCTSIZE; j++) {
  179255. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179256. j++;
  179257. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179258. }
  179259. }
  179260. }
  179261. } else {
  179262. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179263. if (dst_blk_x < comp_width) {
  179264. /* Bottom-edge blocks are mirrored in x only */
  179265. dst_ptr = dst_buffer[offset_y]
  179266. [comp_width - dst_blk_x - offset_x - 1];
  179267. for (i = 0; i < DCTSIZE; i++) {
  179268. for (j = 0; j < DCTSIZE; j++)
  179269. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179270. i++;
  179271. for (j = 0; j < DCTSIZE; j++)
  179272. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179273. }
  179274. } else {
  179275. /* At lower right corner, just transpose, no mirroring */
  179276. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179277. for (i = 0; i < DCTSIZE; i++)
  179278. for (j = 0; j < DCTSIZE; j++)
  179279. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179280. }
  179281. }
  179282. }
  179283. }
  179284. }
  179285. }
  179286. }
  179287. }
  179288. /* Request any required workspace.
  179289. *
  179290. * We allocate the workspace virtual arrays from the source decompression
  179291. * object, so that all the arrays (both the original data and the workspace)
  179292. * will be taken into account while making memory management decisions.
  179293. * Hence, this routine must be called after jpeg_read_header (which reads
  179294. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179295. * the source's virtual arrays).
  179296. */
  179297. GLOBAL(void)
  179298. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179299. jpeg_transform_info *info)
  179300. {
  179301. jvirt_barray_ptr *coef_arrays = NULL;
  179302. jpeg_component_info *compptr;
  179303. int ci;
  179304. if (info->force_grayscale &&
  179305. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179306. srcinfo->num_components == 3) {
  179307. /* We'll only process the first component */
  179308. info->num_components = 1;
  179309. } else {
  179310. /* Process all the components */
  179311. info->num_components = srcinfo->num_components;
  179312. }
  179313. switch (info->transform) {
  179314. case JXFORM_NONE:
  179315. case JXFORM_FLIP_H:
  179316. /* Don't need a workspace array */
  179317. break;
  179318. case JXFORM_FLIP_V:
  179319. case JXFORM_ROT_180:
  179320. /* Need workspace arrays having same dimensions as source image.
  179321. * Note that we allocate arrays padded out to the next iMCU boundary,
  179322. * so that transform routines need not worry about missing edge blocks.
  179323. */
  179324. coef_arrays = (jvirt_barray_ptr *)
  179325. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179326. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179327. for (ci = 0; ci < info->num_components; ci++) {
  179328. compptr = srcinfo->comp_info + ci;
  179329. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179330. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179331. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179332. (long) compptr->h_samp_factor),
  179333. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179334. (long) compptr->v_samp_factor),
  179335. (JDIMENSION) compptr->v_samp_factor);
  179336. }
  179337. break;
  179338. case JXFORM_TRANSPOSE:
  179339. case JXFORM_TRANSVERSE:
  179340. case JXFORM_ROT_90:
  179341. case JXFORM_ROT_270:
  179342. /* Need workspace arrays having transposed dimensions.
  179343. * Note that we allocate arrays padded out to the next iMCU boundary,
  179344. * so that transform routines need not worry about missing edge blocks.
  179345. */
  179346. coef_arrays = (jvirt_barray_ptr *)
  179347. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179348. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179349. for (ci = 0; ci < info->num_components; ci++) {
  179350. compptr = srcinfo->comp_info + ci;
  179351. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179352. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179353. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179354. (long) compptr->v_samp_factor),
  179355. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179356. (long) compptr->h_samp_factor),
  179357. (JDIMENSION) compptr->h_samp_factor);
  179358. }
  179359. break;
  179360. }
  179361. info->workspace_coef_arrays = coef_arrays;
  179362. }
  179363. /* Transpose destination image parameters */
  179364. LOCAL(void)
  179365. transpose_critical_parameters (j_compress_ptr dstinfo)
  179366. {
  179367. int tblno, i, j, ci, itemp;
  179368. jpeg_component_info *compptr;
  179369. JQUANT_TBL *qtblptr;
  179370. JDIMENSION dtemp;
  179371. UINT16 qtemp;
  179372. /* Transpose basic image dimensions */
  179373. dtemp = dstinfo->image_width;
  179374. dstinfo->image_width = dstinfo->image_height;
  179375. dstinfo->image_height = dtemp;
  179376. /* Transpose sampling factors */
  179377. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179378. compptr = dstinfo->comp_info + ci;
  179379. itemp = compptr->h_samp_factor;
  179380. compptr->h_samp_factor = compptr->v_samp_factor;
  179381. compptr->v_samp_factor = itemp;
  179382. }
  179383. /* Transpose quantization tables */
  179384. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179385. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179386. if (qtblptr != NULL) {
  179387. for (i = 0; i < DCTSIZE; i++) {
  179388. for (j = 0; j < i; j++) {
  179389. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179390. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179391. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179392. }
  179393. }
  179394. }
  179395. }
  179396. }
  179397. /* Trim off any partial iMCUs on the indicated destination edge */
  179398. LOCAL(void)
  179399. trim_right_edge (j_compress_ptr dstinfo)
  179400. {
  179401. int ci, max_h_samp_factor;
  179402. JDIMENSION MCU_cols;
  179403. /* We have to compute max_h_samp_factor ourselves,
  179404. * because it hasn't been set yet in the destination
  179405. * (and we don't want to use the source's value).
  179406. */
  179407. max_h_samp_factor = 1;
  179408. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179409. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179410. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179411. }
  179412. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179413. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179414. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179415. }
  179416. LOCAL(void)
  179417. trim_bottom_edge (j_compress_ptr dstinfo)
  179418. {
  179419. int ci, max_v_samp_factor;
  179420. JDIMENSION MCU_rows;
  179421. /* We have to compute max_v_samp_factor ourselves,
  179422. * because it hasn't been set yet in the destination
  179423. * (and we don't want to use the source's value).
  179424. */
  179425. max_v_samp_factor = 1;
  179426. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179427. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179428. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179429. }
  179430. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179431. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179432. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179433. }
  179434. /* Adjust output image parameters as needed.
  179435. *
  179436. * This must be called after jpeg_copy_critical_parameters()
  179437. * and before jpeg_write_coefficients().
  179438. *
  179439. * The return value is the set of virtual coefficient arrays to be written
  179440. * (either the ones allocated by jtransform_request_workspace, or the
  179441. * original source data arrays). The caller will need to pass this value
  179442. * to jpeg_write_coefficients().
  179443. */
  179444. GLOBAL(jvirt_barray_ptr *)
  179445. jtransform_adjust_parameters (j_decompress_ptr,
  179446. j_compress_ptr dstinfo,
  179447. jvirt_barray_ptr *src_coef_arrays,
  179448. jpeg_transform_info *info)
  179449. {
  179450. /* If force-to-grayscale is requested, adjust destination parameters */
  179451. if (info->force_grayscale) {
  179452. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179453. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179454. * will get set to 1, which typically won't match the source.
  179455. * In fact we do this even if the source is already grayscale; that
  179456. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179457. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179458. */
  179459. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179460. dstinfo->num_components == 3) ||
  179461. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179462. dstinfo->num_components == 1)) {
  179463. /* We have to preserve the source's quantization table number. */
  179464. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179465. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179466. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179467. } else {
  179468. /* Sorry, can't do it */
  179469. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179470. }
  179471. }
  179472. /* Correct the destination's image dimensions etc if necessary */
  179473. switch (info->transform) {
  179474. case JXFORM_NONE:
  179475. /* Nothing to do */
  179476. break;
  179477. case JXFORM_FLIP_H:
  179478. if (info->trim)
  179479. trim_right_edge(dstinfo);
  179480. break;
  179481. case JXFORM_FLIP_V:
  179482. if (info->trim)
  179483. trim_bottom_edge(dstinfo);
  179484. break;
  179485. case JXFORM_TRANSPOSE:
  179486. transpose_critical_parameters(dstinfo);
  179487. /* transpose does NOT have to trim anything */
  179488. break;
  179489. case JXFORM_TRANSVERSE:
  179490. transpose_critical_parameters(dstinfo);
  179491. if (info->trim) {
  179492. trim_right_edge(dstinfo);
  179493. trim_bottom_edge(dstinfo);
  179494. }
  179495. break;
  179496. case JXFORM_ROT_90:
  179497. transpose_critical_parameters(dstinfo);
  179498. if (info->trim)
  179499. trim_right_edge(dstinfo);
  179500. break;
  179501. case JXFORM_ROT_180:
  179502. if (info->trim) {
  179503. trim_right_edge(dstinfo);
  179504. trim_bottom_edge(dstinfo);
  179505. }
  179506. break;
  179507. case JXFORM_ROT_270:
  179508. transpose_critical_parameters(dstinfo);
  179509. if (info->trim)
  179510. trim_bottom_edge(dstinfo);
  179511. break;
  179512. }
  179513. /* Return the appropriate output data set */
  179514. if (info->workspace_coef_arrays != NULL)
  179515. return info->workspace_coef_arrays;
  179516. return src_coef_arrays;
  179517. }
  179518. /* Execute the actual transformation, if any.
  179519. *
  179520. * This must be called *after* jpeg_write_coefficients, because it depends
  179521. * on jpeg_write_coefficients to have computed subsidiary values such as
  179522. * the per-component width and height fields in the destination object.
  179523. *
  179524. * Note that some transformations will modify the source data arrays!
  179525. */
  179526. GLOBAL(void)
  179527. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179528. j_compress_ptr dstinfo,
  179529. jvirt_barray_ptr *src_coef_arrays,
  179530. jpeg_transform_info *info)
  179531. {
  179532. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179533. switch (info->transform) {
  179534. case JXFORM_NONE:
  179535. break;
  179536. case JXFORM_FLIP_H:
  179537. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179538. break;
  179539. case JXFORM_FLIP_V:
  179540. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179541. break;
  179542. case JXFORM_TRANSPOSE:
  179543. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179544. break;
  179545. case JXFORM_TRANSVERSE:
  179546. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179547. break;
  179548. case JXFORM_ROT_90:
  179549. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179550. break;
  179551. case JXFORM_ROT_180:
  179552. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179553. break;
  179554. case JXFORM_ROT_270:
  179555. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179556. break;
  179557. }
  179558. }
  179559. #endif /* TRANSFORMS_SUPPORTED */
  179560. /* Setup decompression object to save desired markers in memory.
  179561. * This must be called before jpeg_read_header() to have the desired effect.
  179562. */
  179563. GLOBAL(void)
  179564. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179565. {
  179566. #ifdef SAVE_MARKERS_SUPPORTED
  179567. int m;
  179568. /* Save comments except under NONE option */
  179569. if (option != JCOPYOPT_NONE) {
  179570. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179571. }
  179572. /* Save all types of APPn markers iff ALL option */
  179573. if (option == JCOPYOPT_ALL) {
  179574. for (m = 0; m < 16; m++)
  179575. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179576. }
  179577. #endif /* SAVE_MARKERS_SUPPORTED */
  179578. }
  179579. /* Copy markers saved in the given source object to the destination object.
  179580. * This should be called just after jpeg_start_compress() or
  179581. * jpeg_write_coefficients().
  179582. * Note that those routines will have written the SOI, and also the
  179583. * JFIF APP0 or Adobe APP14 markers if selected.
  179584. */
  179585. GLOBAL(void)
  179586. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179587. JCOPY_OPTION)
  179588. {
  179589. jpeg_saved_marker_ptr marker;
  179590. /* In the current implementation, we don't actually need to examine the
  179591. * option flag here; we just copy everything that got saved.
  179592. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179593. * if the encoder library already wrote one.
  179594. */
  179595. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179596. if (dstinfo->write_JFIF_header &&
  179597. marker->marker == JPEG_APP0 &&
  179598. marker->data_length >= 5 &&
  179599. GETJOCTET(marker->data[0]) == 0x4A &&
  179600. GETJOCTET(marker->data[1]) == 0x46 &&
  179601. GETJOCTET(marker->data[2]) == 0x49 &&
  179602. GETJOCTET(marker->data[3]) == 0x46 &&
  179603. GETJOCTET(marker->data[4]) == 0)
  179604. continue; /* reject duplicate JFIF */
  179605. if (dstinfo->write_Adobe_marker &&
  179606. marker->marker == JPEG_APP0+14 &&
  179607. marker->data_length >= 5 &&
  179608. GETJOCTET(marker->data[0]) == 0x41 &&
  179609. GETJOCTET(marker->data[1]) == 0x64 &&
  179610. GETJOCTET(marker->data[2]) == 0x6F &&
  179611. GETJOCTET(marker->data[3]) == 0x62 &&
  179612. GETJOCTET(marker->data[4]) == 0x65)
  179613. continue; /* reject duplicate Adobe */
  179614. #ifdef NEED_FAR_POINTERS
  179615. /* We could use jpeg_write_marker if the data weren't FAR... */
  179616. {
  179617. unsigned int i;
  179618. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179619. for (i = 0; i < marker->data_length; i++)
  179620. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179621. }
  179622. #else
  179623. jpeg_write_marker(dstinfo, marker->marker,
  179624. marker->data, marker->data_length);
  179625. #endif
  179626. }
  179627. }
  179628. /*** End of inlined file: transupp.c ***/
  179629. #else
  179630. #define JPEG_INTERNALS
  179631. #undef FAR
  179632. #include <jpeglib.h>
  179633. #endif
  179634. }
  179635. #undef max
  179636. #undef min
  179637. #if JUCE_MSVC
  179638. #pragma warning (pop)
  179639. #endif
  179640. BEGIN_JUCE_NAMESPACE
  179641. namespace JPEGHelpers
  179642. {
  179643. using namespace jpeglibNamespace;
  179644. #if ! JUCE_MSVC
  179645. using jpeglibNamespace::boolean;
  179646. #endif
  179647. struct JPEGDecodingFailure {};
  179648. void fatalErrorHandler (j_common_ptr)
  179649. {
  179650. throw JPEGDecodingFailure();
  179651. }
  179652. void silentErrorCallback1 (j_common_ptr) {}
  179653. void silentErrorCallback2 (j_common_ptr, int) {}
  179654. void silentErrorCallback3 (j_common_ptr, char*) {}
  179655. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179656. {
  179657. zerostruct (err);
  179658. err.error_exit = fatalErrorHandler;
  179659. err.emit_message = silentErrorCallback2;
  179660. err.output_message = silentErrorCallback1;
  179661. err.format_message = silentErrorCallback3;
  179662. err.reset_error_mgr = silentErrorCallback1;
  179663. }
  179664. void dummyCallback1 (j_decompress_ptr)
  179665. {
  179666. }
  179667. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179668. {
  179669. decompStruct->src->next_input_byte += num;
  179670. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179671. decompStruct->src->bytes_in_buffer -= num;
  179672. }
  179673. boolean jpegFill (j_decompress_ptr)
  179674. {
  179675. return 0;
  179676. }
  179677. const int jpegBufferSize = 512;
  179678. struct JuceJpegDest : public jpeg_destination_mgr
  179679. {
  179680. OutputStream* output;
  179681. char* buffer;
  179682. };
  179683. void jpegWriteInit (j_compress_ptr)
  179684. {
  179685. }
  179686. void jpegWriteTerminate (j_compress_ptr cinfo)
  179687. {
  179688. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179689. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179690. dest->output->write (dest->buffer, (int) numToWrite);
  179691. }
  179692. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179693. {
  179694. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179695. const int numToWrite = jpegBufferSize;
  179696. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179697. dest->free_in_buffer = jpegBufferSize;
  179698. return dest->output->write (dest->buffer, numToWrite);
  179699. }
  179700. }
  179701. JPEGImageFormat::JPEGImageFormat()
  179702. : quality (-1.0f)
  179703. {
  179704. }
  179705. JPEGImageFormat::~JPEGImageFormat() {}
  179706. void JPEGImageFormat::setQuality (const float newQuality)
  179707. {
  179708. quality = newQuality;
  179709. }
  179710. const String JPEGImageFormat::getFormatName()
  179711. {
  179712. return "JPEG";
  179713. }
  179714. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179715. {
  179716. const int bytesNeeded = 10;
  179717. uint8 header [bytesNeeded];
  179718. if (in.read (header, bytesNeeded) == bytesNeeded)
  179719. {
  179720. return header[0] == 0xff
  179721. && header[1] == 0xd8
  179722. && header[2] == 0xff
  179723. && (header[3] == 0xe0 || header[3] == 0xe1);
  179724. }
  179725. return false;
  179726. }
  179727. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179728. const Image juce_loadWithCoreImage (InputStream& input);
  179729. #endif
  179730. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179731. {
  179732. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179733. return juce_loadWithCoreImage (in);
  179734. #else
  179735. using namespace jpeglibNamespace;
  179736. using namespace JPEGHelpers;
  179737. MemoryOutputStream mb;
  179738. mb.writeFromInputStream (in, -1);
  179739. Image image;
  179740. if (mb.getDataSize() > 16)
  179741. {
  179742. struct jpeg_decompress_struct jpegDecompStruct;
  179743. struct jpeg_error_mgr jerr;
  179744. setupSilentErrorHandler (jerr);
  179745. jpegDecompStruct.err = &jerr;
  179746. jpeg_create_decompress (&jpegDecompStruct);
  179747. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179748. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179749. jpegDecompStruct.src->init_source = dummyCallback1;
  179750. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179751. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179752. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179753. jpegDecompStruct.src->term_source = dummyCallback1;
  179754. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179755. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179756. try
  179757. {
  179758. jpeg_read_header (&jpegDecompStruct, TRUE);
  179759. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179760. const int width = jpegDecompStruct.output_width;
  179761. const int height = jpegDecompStruct.output_height;
  179762. jpegDecompStruct.out_color_space = JCS_RGB;
  179763. JSAMPARRAY buffer
  179764. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179765. JPOOL_IMAGE,
  179766. width * 3, 1);
  179767. if (jpeg_start_decompress (&jpegDecompStruct))
  179768. {
  179769. image = Image (Image::RGB, width, height, false);
  179770. image.getProperties()->set ("originalImageHadAlpha", false);
  179771. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179772. const Image::BitmapData destData (image, true);
  179773. for (int y = 0; y < height; ++y)
  179774. {
  179775. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179776. const uint8* src = *buffer;
  179777. uint8* dest = destData.getLinePointer (y);
  179778. if (hasAlphaChan)
  179779. {
  179780. for (int i = width; --i >= 0;)
  179781. {
  179782. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179783. ((PixelARGB*) dest)->premultiply();
  179784. dest += destData.pixelStride;
  179785. src += 3;
  179786. }
  179787. }
  179788. else
  179789. {
  179790. for (int i = width; --i >= 0;)
  179791. {
  179792. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179793. dest += destData.pixelStride;
  179794. src += 3;
  179795. }
  179796. }
  179797. }
  179798. jpeg_finish_decompress (&jpegDecompStruct);
  179799. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179800. }
  179801. jpeg_destroy_decompress (&jpegDecompStruct);
  179802. }
  179803. catch (...)
  179804. {}
  179805. }
  179806. return image;
  179807. #endif
  179808. }
  179809. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179810. {
  179811. using namespace jpeglibNamespace;
  179812. using namespace JPEGHelpers;
  179813. if (image.hasAlphaChannel())
  179814. {
  179815. // this method could fill the background in white and still save the image..
  179816. jassertfalse;
  179817. return true;
  179818. }
  179819. struct jpeg_compress_struct jpegCompStruct;
  179820. struct jpeg_error_mgr jerr;
  179821. setupSilentErrorHandler (jerr);
  179822. jpegCompStruct.err = &jerr;
  179823. jpeg_create_compress (&jpegCompStruct);
  179824. JuceJpegDest dest;
  179825. jpegCompStruct.dest = &dest;
  179826. dest.output = &out;
  179827. HeapBlock <char> tempBuffer (jpegBufferSize);
  179828. dest.buffer = tempBuffer;
  179829. dest.next_output_byte = (JOCTET*) dest.buffer;
  179830. dest.free_in_buffer = jpegBufferSize;
  179831. dest.init_destination = jpegWriteInit;
  179832. dest.empty_output_buffer = jpegWriteFlush;
  179833. dest.term_destination = jpegWriteTerminate;
  179834. jpegCompStruct.image_width = image.getWidth();
  179835. jpegCompStruct.image_height = image.getHeight();
  179836. jpegCompStruct.input_components = 3;
  179837. jpegCompStruct.in_color_space = JCS_RGB;
  179838. jpegCompStruct.write_JFIF_header = 1;
  179839. jpegCompStruct.X_density = 72;
  179840. jpegCompStruct.Y_density = 72;
  179841. jpeg_set_defaults (&jpegCompStruct);
  179842. jpegCompStruct.dct_method = JDCT_FLOAT;
  179843. jpegCompStruct.optimize_coding = 1;
  179844. //jpegCompStruct.smoothing_factor = 10;
  179845. if (quality < 0.0f)
  179846. quality = 0.85f;
  179847. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179848. jpeg_start_compress (&jpegCompStruct, TRUE);
  179849. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179850. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179851. JPOOL_IMAGE, strideBytes, 1);
  179852. const Image::BitmapData srcData (image, false);
  179853. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179854. {
  179855. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179856. uint8* dst = *buffer;
  179857. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179858. {
  179859. *dst++ = ((const PixelRGB*) src)->getRed();
  179860. *dst++ = ((const PixelRGB*) src)->getGreen();
  179861. *dst++ = ((const PixelRGB*) src)->getBlue();
  179862. src += srcData.pixelStride;
  179863. }
  179864. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179865. }
  179866. jpeg_finish_compress (&jpegCompStruct);
  179867. jpeg_destroy_compress (&jpegCompStruct);
  179868. out.flush();
  179869. return true;
  179870. }
  179871. END_JUCE_NAMESPACE
  179872. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179873. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179874. #if JUCE_MSVC
  179875. #pragma warning (push)
  179876. #pragma warning (disable: 4390 4611)
  179877. #ifdef __INTEL_COMPILER
  179878. #pragma warning (disable: 2544 2545)
  179879. #endif
  179880. #endif
  179881. namespace zlibNamespace
  179882. {
  179883. #if JUCE_INCLUDE_ZLIB_CODE
  179884. #undef OS_CODE
  179885. #undef fdopen
  179886. #undef OS_CODE
  179887. #else
  179888. #include <zlib.h>
  179889. #endif
  179890. }
  179891. namespace pnglibNamespace
  179892. {
  179893. using namespace zlibNamespace;
  179894. #if JUCE_INCLUDE_PNGLIB_CODE
  179895. #if _MSC_VER != 1310
  179896. using ::calloc; // (causes conflict in VS.NET 2003)
  179897. using ::malloc;
  179898. using ::free;
  179899. #endif
  179900. using ::abs;
  179901. #define PNG_INTERNAL
  179902. #define NO_DUMMY_DECL
  179903. #define PNG_SETJMP_NOT_SUPPORTED
  179904. /*** Start of inlined file: png.h ***/
  179905. /* png.h - header file for PNG reference library
  179906. *
  179907. * libpng version 1.2.21 - October 4, 2007
  179908. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179909. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179910. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179911. *
  179912. * Authors and maintainers:
  179913. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179914. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179915. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179916. * See also "Contributing Authors", below.
  179917. *
  179918. * Note about libpng version numbers:
  179919. *
  179920. * Due to various miscommunications, unforeseen code incompatibilities
  179921. * and occasional factors outside the authors' control, version numbering
  179922. * on the library has not always been consistent and straightforward.
  179923. * The following table summarizes matters since version 0.89c, which was
  179924. * the first widely used release:
  179925. *
  179926. * source png.h png.h shared-lib
  179927. * version string int version
  179928. * ------- ------ ----- ----------
  179929. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179930. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179931. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179932. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179933. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179934. * 0.97c 0.97 97 2.0.97
  179935. * 0.98 0.98 98 2.0.98
  179936. * 0.99 0.99 98 2.0.99
  179937. * 0.99a-m 0.99 99 2.0.99
  179938. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179939. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179940. * 1.0.1 png.h string is 10001 2.1.0
  179941. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179942. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179943. * 1.0.2a-b 10003 version, except as noted.
  179944. * 1.0.3 10003
  179945. * 1.0.3a-d 10004
  179946. * 1.0.4 10004
  179947. * 1.0.4a-f 10005
  179948. * 1.0.5 (+ 2 patches) 10005
  179949. * 1.0.5a-d 10006
  179950. * 1.0.5e-r 10100 (not source compatible)
  179951. * 1.0.5s-v 10006 (not binary compatible)
  179952. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179953. * 1.0.6d-f 10007 (still binary incompatible)
  179954. * 1.0.6g 10007
  179955. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179956. * 1.0.6i 10007 10.6i
  179957. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179958. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179959. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179960. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179961. * 1.0.7 1 10007 (still compatible)
  179962. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179963. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179964. * 1.0.8 1 10008 2.1.0.8
  179965. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179966. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179967. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179968. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179969. * 1.0.9 1 10009 2.1.0.9
  179970. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179971. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179972. * 1.0.10 1 10010 2.1.0.10
  179973. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179974. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179975. * 1.0.11 1 10011 2.1.0.11
  179976. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179977. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179978. * 1.0.12 2 10012 2.1.0.12
  179979. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179980. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179981. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179982. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179983. * 1.2.0 3 10200 3.1.2.0
  179984. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179985. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179986. * 1.2.1 3 10201 3.1.2.1
  179987. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179988. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179989. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179990. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179991. * 1.0.13 10 10013 10.so.0.1.0.13
  179992. * 1.2.2 12 10202 12.so.0.1.2.2
  179993. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179994. * 1.2.3 12 10203 12.so.0.1.2.3
  179995. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179996. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179997. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179998. * 1.0.14 10 10014 10.so.0.1.0.14
  179999. * 1.2.4 13 10204 12.so.0.1.2.4
  180000. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180001. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180002. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180003. * 1.0.15 10 10015 10.so.0.1.0.15
  180004. * 1.2.5 13 10205 12.so.0.1.2.5
  180005. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180006. * 1.0.16 10 10016 10.so.0.1.0.16
  180007. * 1.2.6 13 10206 12.so.0.1.2.6
  180008. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180009. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180010. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180011. * 1.0.17 10 10017 10.so.0.1.0.17
  180012. * 1.2.7 13 10207 12.so.0.1.2.7
  180013. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180014. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180015. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180016. * 1.0.18 10 10018 10.so.0.1.0.18
  180017. * 1.2.8 13 10208 12.so.0.1.2.8
  180018. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180019. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180020. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180021. * 1.2.9 13 10209 12.so.0.9[.0]
  180022. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180023. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180024. * 1.2.10 13 10210 12.so.0.10[.0]
  180025. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180026. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180027. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180028. * 1.0.19 10 10019 10.so.0.19[.0]
  180029. * 1.2.11 13 10211 12.so.0.11[.0]
  180030. * 1.0.20 10 10020 10.so.0.20[.0]
  180031. * 1.2.12 13 10212 12.so.0.12[.0]
  180032. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180033. * 1.0.21 10 10021 10.so.0.21[.0]
  180034. * 1.2.13 13 10213 12.so.0.13[.0]
  180035. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180036. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180037. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180038. * 1.0.22 10 10022 10.so.0.22[.0]
  180039. * 1.2.14 13 10214 12.so.0.14[.0]
  180040. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180041. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180042. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180043. * 1.0.23 10 10023 10.so.0.23[.0]
  180044. * 1.2.15 13 10215 12.so.0.15[.0]
  180045. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180046. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180047. * 1.0.24 10 10024 10.so.0.24[.0]
  180048. * 1.2.16 13 10216 12.so.0.16[.0]
  180049. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180050. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180051. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180052. * 1.0.25 10 10025 10.so.0.25[.0]
  180053. * 1.2.17 13 10217 12.so.0.17[.0]
  180054. * 1.0.26 10 10026 10.so.0.26[.0]
  180055. * 1.2.18 13 10218 12.so.0.18[.0]
  180056. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180057. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180058. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180059. * 1.0.27 10 10027 10.so.0.27[.0]
  180060. * 1.2.19 13 10219 12.so.0.19[.0]
  180061. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180062. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180063. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180064. * 1.0.28 10 10028 10.so.0.28[.0]
  180065. * 1.2.20 13 10220 12.so.0.20[.0]
  180066. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180067. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180068. * 1.0.29 10 10029 10.so.0.29[.0]
  180069. * 1.2.21 13 10221 12.so.0.21[.0]
  180070. *
  180071. * Henceforth the source version will match the shared-library major
  180072. * and minor numbers; the shared-library major version number will be
  180073. * used for changes in backward compatibility, as it is intended. The
  180074. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180075. * for applications, is an unsigned integer of the form xyyzz corresponding
  180076. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180077. * were given the previous public release number plus a letter, until
  180078. * version 1.0.6j; from then on they were given the upcoming public
  180079. * release number plus "betaNN" or "rcN".
  180080. *
  180081. * Binary incompatibility exists only when applications make direct access
  180082. * to the info_ptr or png_ptr members through png.h, and the compiled
  180083. * application is loaded with a different version of the library.
  180084. *
  180085. * DLLNUM will change each time there are forward or backward changes
  180086. * in binary compatibility (e.g., when a new feature is added).
  180087. *
  180088. * See libpng.txt or libpng.3 for more information. The PNG specification
  180089. * is available as a W3C Recommendation and as an ISO Specification,
  180090. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180091. */
  180092. /*
  180093. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180094. *
  180095. * If you modify libpng you may insert additional notices immediately following
  180096. * this sentence.
  180097. *
  180098. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180099. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180100. * distributed according to the same disclaimer and license as libpng-1.2.5
  180101. * with the following individual added to the list of Contributing Authors:
  180102. *
  180103. * Cosmin Truta
  180104. *
  180105. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180106. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180107. * distributed according to the same disclaimer and license as libpng-1.0.6
  180108. * with the following individuals added to the list of Contributing Authors:
  180109. *
  180110. * Simon-Pierre Cadieux
  180111. * Eric S. Raymond
  180112. * Gilles Vollant
  180113. *
  180114. * and with the following additions to the disclaimer:
  180115. *
  180116. * There is no warranty against interference with your enjoyment of the
  180117. * library or against infringement. There is no warranty that our
  180118. * efforts or the library will fulfill any of your particular purposes
  180119. * or needs. This library is provided with all faults, and the entire
  180120. * risk of satisfactory quality, performance, accuracy, and effort is with
  180121. * the user.
  180122. *
  180123. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180124. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180125. * distributed according to the same disclaimer and license as libpng-0.96,
  180126. * with the following individuals added to the list of Contributing Authors:
  180127. *
  180128. * Tom Lane
  180129. * Glenn Randers-Pehrson
  180130. * Willem van Schaik
  180131. *
  180132. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180133. * Copyright (c) 1996, 1997 Andreas Dilger
  180134. * Distributed according to the same disclaimer and license as libpng-0.88,
  180135. * with the following individuals added to the list of Contributing Authors:
  180136. *
  180137. * John Bowler
  180138. * Kevin Bracey
  180139. * Sam Bushell
  180140. * Magnus Holmgren
  180141. * Greg Roelofs
  180142. * Tom Tanner
  180143. *
  180144. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180145. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180146. *
  180147. * For the purposes of this copyright and license, "Contributing Authors"
  180148. * is defined as the following set of individuals:
  180149. *
  180150. * Andreas Dilger
  180151. * Dave Martindale
  180152. * Guy Eric Schalnat
  180153. * Paul Schmidt
  180154. * Tim Wegner
  180155. *
  180156. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180157. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180158. * including, without limitation, the warranties of merchantability and of
  180159. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180160. * assume no liability for direct, indirect, incidental, special, exemplary,
  180161. * or consequential damages, which may result from the use of the PNG
  180162. * Reference Library, even if advised of the possibility of such damage.
  180163. *
  180164. * Permission is hereby granted to use, copy, modify, and distribute this
  180165. * source code, or portions hereof, for any purpose, without fee, subject
  180166. * to the following restrictions:
  180167. *
  180168. * 1. The origin of this source code must not be misrepresented.
  180169. *
  180170. * 2. Altered versions must be plainly marked as such and
  180171. * must not be misrepresented as being the original source.
  180172. *
  180173. * 3. This Copyright notice may not be removed or altered from
  180174. * any source or altered source distribution.
  180175. *
  180176. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180177. * fee, and encourage the use of this source code as a component to
  180178. * supporting the PNG file format in commercial products. If you use this
  180179. * source code in a product, acknowledgment is not required but would be
  180180. * appreciated.
  180181. */
  180182. /*
  180183. * A "png_get_copyright" function is available, for convenient use in "about"
  180184. * boxes and the like:
  180185. *
  180186. * printf("%s",png_get_copyright(NULL));
  180187. *
  180188. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180189. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180190. */
  180191. /*
  180192. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180193. * certification mark of the Open Source Initiative.
  180194. */
  180195. /*
  180196. * The contributing authors would like to thank all those who helped
  180197. * with testing, bug fixes, and patience. This wouldn't have been
  180198. * possible without all of you.
  180199. *
  180200. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180201. */
  180202. /*
  180203. * Y2K compliance in libpng:
  180204. * =========================
  180205. *
  180206. * October 4, 2007
  180207. *
  180208. * Since the PNG Development group is an ad-hoc body, we can't make
  180209. * an official declaration.
  180210. *
  180211. * This is your unofficial assurance that libpng from version 0.71 and
  180212. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180213. * versions were also Y2K compliant.
  180214. *
  180215. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180216. * that will hold years up to 65535. The other two hold the date in text
  180217. * format, and will hold years up to 9999.
  180218. *
  180219. * The integer is
  180220. * "png_uint_16 year" in png_time_struct.
  180221. *
  180222. * The strings are
  180223. * "png_charp time_buffer" in png_struct and
  180224. * "near_time_buffer", which is a local character string in png.c.
  180225. *
  180226. * There are seven time-related functions:
  180227. * png.c: png_convert_to_rfc_1123() in png.c
  180228. * (formerly png_convert_to_rfc_1152() in error)
  180229. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180230. * png_convert_from_time_t() in pngwrite.c
  180231. * png_get_tIME() in pngget.c
  180232. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180233. * png_set_tIME() in pngset.c
  180234. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180235. *
  180236. * All handle dates properly in a Y2K environment. The
  180237. * png_convert_from_time_t() function calls gmtime() to convert from system
  180238. * clock time, which returns (year - 1900), which we properly convert to
  180239. * the full 4-digit year. There is a possibility that applications using
  180240. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180241. * function, or that they are incorrectly passing only a 2-digit year
  180242. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180243. * but this is not under our control. The libpng documentation has always
  180244. * stated that it works with 4-digit years, and the APIs have been
  180245. * documented as such.
  180246. *
  180247. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180248. * integer to hold the year, and can hold years as large as 65535.
  180249. *
  180250. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180251. * no date-related code.
  180252. *
  180253. * Glenn Randers-Pehrson
  180254. * libpng maintainer
  180255. * PNG Development Group
  180256. */
  180257. #ifndef PNG_H
  180258. #define PNG_H
  180259. /* This is not the place to learn how to use libpng. The file libpng.txt
  180260. * describes how to use libpng, and the file example.c summarizes it
  180261. * with some code on which to build. This file is useful for looking
  180262. * at the actual function definitions and structure components.
  180263. */
  180264. /* Version information for png.h - this should match the version in png.c */
  180265. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180266. #define PNG_HEADER_VERSION_STRING \
  180267. " libpng version 1.2.21 - October 4, 2007\n"
  180268. #define PNG_LIBPNG_VER_SONUM 0
  180269. #define PNG_LIBPNG_VER_DLLNUM 13
  180270. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180271. #define PNG_LIBPNG_VER_MAJOR 1
  180272. #define PNG_LIBPNG_VER_MINOR 2
  180273. #define PNG_LIBPNG_VER_RELEASE 21
  180274. /* This should match the numeric part of the final component of
  180275. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180276. #define PNG_LIBPNG_VER_BUILD 0
  180277. /* Release Status */
  180278. #define PNG_LIBPNG_BUILD_ALPHA 1
  180279. #define PNG_LIBPNG_BUILD_BETA 2
  180280. #define PNG_LIBPNG_BUILD_RC 3
  180281. #define PNG_LIBPNG_BUILD_STABLE 4
  180282. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180283. /* Release-Specific Flags */
  180284. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180285. PNG_LIBPNG_BUILD_STABLE only */
  180286. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180287. PNG_LIBPNG_BUILD_SPECIAL */
  180288. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180289. PNG_LIBPNG_BUILD_PRIVATE */
  180290. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180291. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180292. * We must not include leading zeros.
  180293. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180294. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180295. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180296. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180297. #ifndef PNG_VERSION_INFO_ONLY
  180298. /* include the compression library's header */
  180299. #endif
  180300. /* include all user configurable info, including optional assembler routines */
  180301. /*** Start of inlined file: pngconf.h ***/
  180302. /* pngconf.h - machine configurable file for libpng
  180303. *
  180304. * libpng version 1.2.21 - October 4, 2007
  180305. * For conditions of distribution and use, see copyright notice in png.h
  180306. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180307. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180308. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180309. */
  180310. /* Any machine specific code is near the front of this file, so if you
  180311. * are configuring libpng for a machine, you may want to read the section
  180312. * starting here down to where it starts to typedef png_color, png_text,
  180313. * and png_info.
  180314. */
  180315. #ifndef PNGCONF_H
  180316. #define PNGCONF_H
  180317. #define PNG_1_2_X
  180318. // These are some Juce config settings that should remove any unnecessary code bloat..
  180319. #define PNG_NO_STDIO 1
  180320. #define PNG_DEBUG 0
  180321. #define PNG_NO_WARNINGS 1
  180322. #define PNG_NO_ERROR_TEXT 1
  180323. #define PNG_NO_ERROR_NUMBERS 1
  180324. #define PNG_NO_USER_MEM 1
  180325. #define PNG_NO_READ_iCCP 1
  180326. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180327. #define PNG_NO_READ_USER_CHUNKS 1
  180328. #define PNG_NO_READ_iTXt 1
  180329. #define PNG_NO_READ_sCAL 1
  180330. #define PNG_NO_READ_sPLT 1
  180331. #define png_error(a, b) png_err(a)
  180332. #define png_warning(a, b)
  180333. #define png_chunk_error(a, b) png_err(a)
  180334. #define png_chunk_warning(a, b)
  180335. /*
  180336. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180337. * includes the resource compiler for Windows DLL configurations.
  180338. */
  180339. #ifdef PNG_USER_CONFIG
  180340. # ifndef PNG_USER_PRIVATEBUILD
  180341. # define PNG_USER_PRIVATEBUILD
  180342. # endif
  180343. #include "pngusr.h"
  180344. #endif
  180345. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180346. #ifdef PNG_CONFIGURE_LIBPNG
  180347. #ifdef HAVE_CONFIG_H
  180348. #include "config.h"
  180349. #endif
  180350. #endif
  180351. /*
  180352. * Added at libpng-1.2.8
  180353. *
  180354. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180355. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180356. * the DLL was built>
  180357. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180358. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180359. * distinguish your DLL from those of the official release. These
  180360. * correspond to the trailing letters that come after the version
  180361. * number and must match your private DLL name>
  180362. * e.g. // private DLL "libpng13gx.dll"
  180363. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180364. *
  180365. * The following macros are also at your disposal if you want to complete the
  180366. * DLL VERSIONINFO structure.
  180367. * - PNG_USER_VERSIONINFO_COMMENTS
  180368. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180369. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180370. */
  180371. #ifdef __STDC__
  180372. #ifdef SPECIALBUILD
  180373. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180374. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180375. #endif
  180376. #ifdef PRIVATEBUILD
  180377. # pragma message("PRIVATEBUILD is deprecated.\
  180378. Use PNG_USER_PRIVATEBUILD instead.")
  180379. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180380. #endif
  180381. #endif /* __STDC__ */
  180382. #ifndef PNG_VERSION_INFO_ONLY
  180383. /* End of material added to libpng-1.2.8 */
  180384. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180385. Restored at libpng-1.2.21 */
  180386. # define PNG_WARN_UNINITIALIZED_ROW 1
  180387. /* End of material added at libpng-1.2.19/1.2.21 */
  180388. /* This is the size of the compression buffer, and thus the size of
  180389. * an IDAT chunk. Make this whatever size you feel is best for your
  180390. * machine. One of these will be allocated per png_struct. When this
  180391. * is full, it writes the data to the disk, and does some other
  180392. * calculations. Making this an extremely small size will slow
  180393. * the library down, but you may want to experiment to determine
  180394. * where it becomes significant, if you are concerned with memory
  180395. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180396. * this describes the size of the buffer available to read the data in.
  180397. * Unless this gets smaller than the size of a row (compressed),
  180398. * it should not make much difference how big this is.
  180399. */
  180400. #ifndef PNG_ZBUF_SIZE
  180401. # define PNG_ZBUF_SIZE 8192
  180402. #endif
  180403. /* Enable if you want a write-only libpng */
  180404. #ifndef PNG_NO_READ_SUPPORTED
  180405. # define PNG_READ_SUPPORTED
  180406. #endif
  180407. /* Enable if you want a read-only libpng */
  180408. #ifndef PNG_NO_WRITE_SUPPORTED
  180409. # define PNG_WRITE_SUPPORTED
  180410. #endif
  180411. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180412. support PNGs that are embedded in MNG datastreams */
  180413. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180414. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180415. # define PNG_MNG_FEATURES_SUPPORTED
  180416. # endif
  180417. #endif
  180418. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180419. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180420. # define PNG_FLOATING_POINT_SUPPORTED
  180421. # endif
  180422. #endif
  180423. /* If you are running on a machine where you cannot allocate more
  180424. * than 64K of memory at once, uncomment this. While libpng will not
  180425. * normally need that much memory in a chunk (unless you load up a very
  180426. * large file), zlib needs to know how big of a chunk it can use, and
  180427. * libpng thus makes sure to check any memory allocation to verify it
  180428. * will fit into memory.
  180429. #define PNG_MAX_MALLOC_64K
  180430. */
  180431. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180432. # define PNG_MAX_MALLOC_64K
  180433. #endif
  180434. /* Special munging to support doing things the 'cygwin' way:
  180435. * 'Normal' png-on-win32 defines/defaults:
  180436. * PNG_BUILD_DLL -- building dll
  180437. * PNG_USE_DLL -- building an application, linking to dll
  180438. * (no define) -- building static library, or building an
  180439. * application and linking to the static lib
  180440. * 'Cygwin' defines/defaults:
  180441. * PNG_BUILD_DLL -- (ignored) building the dll
  180442. * (no define) -- (ignored) building an application, linking to the dll
  180443. * PNG_STATIC -- (ignored) building the static lib, or building an
  180444. * application that links to the static lib.
  180445. * ALL_STATIC -- (ignored) building various static libs, or building an
  180446. * application that links to the static libs.
  180447. * Thus,
  180448. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180449. * this bit of #ifdefs will define the 'correct' config variables based on
  180450. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180451. * unnecessary.
  180452. *
  180453. * Also, the precedence order is:
  180454. * ALL_STATIC (since we can't #undef something outside our namespace)
  180455. * PNG_BUILD_DLL
  180456. * PNG_STATIC
  180457. * (nothing) == PNG_USE_DLL
  180458. *
  180459. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180460. * of auto-import in binutils, we no longer need to worry about
  180461. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180462. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180463. * to __declspec() stuff. However, we DO need to worry about
  180464. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180465. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180466. */
  180467. #if defined(__CYGWIN__)
  180468. # if defined(ALL_STATIC)
  180469. # if defined(PNG_BUILD_DLL)
  180470. # undef PNG_BUILD_DLL
  180471. # endif
  180472. # if defined(PNG_USE_DLL)
  180473. # undef PNG_USE_DLL
  180474. # endif
  180475. # if defined(PNG_DLL)
  180476. # undef PNG_DLL
  180477. # endif
  180478. # if !defined(PNG_STATIC)
  180479. # define PNG_STATIC
  180480. # endif
  180481. # else
  180482. # if defined (PNG_BUILD_DLL)
  180483. # if defined(PNG_STATIC)
  180484. # undef PNG_STATIC
  180485. # endif
  180486. # if defined(PNG_USE_DLL)
  180487. # undef PNG_USE_DLL
  180488. # endif
  180489. # if !defined(PNG_DLL)
  180490. # define PNG_DLL
  180491. # endif
  180492. # else
  180493. # if defined(PNG_STATIC)
  180494. # if defined(PNG_USE_DLL)
  180495. # undef PNG_USE_DLL
  180496. # endif
  180497. # if defined(PNG_DLL)
  180498. # undef PNG_DLL
  180499. # endif
  180500. # else
  180501. # if !defined(PNG_USE_DLL)
  180502. # define PNG_USE_DLL
  180503. # endif
  180504. # if !defined(PNG_DLL)
  180505. # define PNG_DLL
  180506. # endif
  180507. # endif
  180508. # endif
  180509. # endif
  180510. #endif
  180511. /* This protects us against compilers that run on a windowing system
  180512. * and thus don't have or would rather us not use the stdio types:
  180513. * stdin, stdout, and stderr. The only one currently used is stderr
  180514. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180515. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180516. * will also prevent these, plus will prevent the entire set of stdio
  180517. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180518. * unless (PNG_DEBUG > 0) has been #defined.
  180519. *
  180520. * #define PNG_NO_CONSOLE_IO
  180521. * #define PNG_NO_STDIO
  180522. */
  180523. #if defined(_WIN32_WCE)
  180524. # include <windows.h>
  180525. /* Console I/O functions are not supported on WindowsCE */
  180526. # define PNG_NO_CONSOLE_IO
  180527. # ifdef PNG_DEBUG
  180528. # undef PNG_DEBUG
  180529. # endif
  180530. #endif
  180531. #ifdef PNG_BUILD_DLL
  180532. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180533. # ifndef PNG_NO_CONSOLE_IO
  180534. # define PNG_NO_CONSOLE_IO
  180535. # endif
  180536. # endif
  180537. #endif
  180538. # ifdef PNG_NO_STDIO
  180539. # ifndef PNG_NO_CONSOLE_IO
  180540. # define PNG_NO_CONSOLE_IO
  180541. # endif
  180542. # ifdef PNG_DEBUG
  180543. # if (PNG_DEBUG > 0)
  180544. # include <stdio.h>
  180545. # endif
  180546. # endif
  180547. # else
  180548. # if !defined(_WIN32_WCE)
  180549. /* "stdio.h" functions are not supported on WindowsCE */
  180550. # include <stdio.h>
  180551. # endif
  180552. # endif
  180553. /* This macro protects us against machines that don't have function
  180554. * prototypes (ie K&R style headers). If your compiler does not handle
  180555. * function prototypes, define this macro and use the included ansi2knr.
  180556. * I've always been able to use _NO_PROTO as the indicator, but you may
  180557. * need to drag the empty declaration out in front of here, or change the
  180558. * ifdef to suit your own needs.
  180559. */
  180560. #ifndef PNGARG
  180561. #ifdef OF /* zlib prototype munger */
  180562. # define PNGARG(arglist) OF(arglist)
  180563. #else
  180564. #ifdef _NO_PROTO
  180565. # define PNGARG(arglist) ()
  180566. # ifndef PNG_TYPECAST_NULL
  180567. # define PNG_TYPECAST_NULL
  180568. # endif
  180569. #else
  180570. # define PNGARG(arglist) arglist
  180571. #endif /* _NO_PROTO */
  180572. #endif /* OF */
  180573. #endif /* PNGARG */
  180574. /* Try to determine if we are compiling on a Mac. Note that testing for
  180575. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180576. * on non-Mac platforms.
  180577. */
  180578. #ifndef MACOS
  180579. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180580. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180581. # define MACOS
  180582. # endif
  180583. #endif
  180584. /* enough people need this for various reasons to include it here */
  180585. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180586. # include <sys/types.h>
  180587. #endif
  180588. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180589. # define PNG_SETJMP_SUPPORTED
  180590. #endif
  180591. #ifdef PNG_SETJMP_SUPPORTED
  180592. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180593. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180594. */
  180595. # ifdef __linux__
  180596. # ifdef _BSD_SOURCE
  180597. # define PNG_SAVE_BSD_SOURCE
  180598. # undef _BSD_SOURCE
  180599. # endif
  180600. # ifdef _SETJMP_H
  180601. /* If you encounter a compiler error here, see the explanation
  180602. * near the end of INSTALL.
  180603. */
  180604. __png.h__ already includes setjmp.h;
  180605. __dont__ include it again.;
  180606. # endif
  180607. # endif /* __linux__ */
  180608. /* include setjmp.h for error handling */
  180609. # include <setjmp.h>
  180610. # ifdef __linux__
  180611. # ifdef PNG_SAVE_BSD_SOURCE
  180612. # define _BSD_SOURCE
  180613. # undef PNG_SAVE_BSD_SOURCE
  180614. # endif
  180615. # endif /* __linux__ */
  180616. #endif /* PNG_SETJMP_SUPPORTED */
  180617. #ifdef BSD
  180618. #if ! JUCE_MAC
  180619. # include <strings.h>
  180620. #endif
  180621. #else
  180622. # include <string.h>
  180623. #endif
  180624. /* Other defines for things like memory and the like can go here. */
  180625. #ifdef PNG_INTERNAL
  180626. #include <stdlib.h>
  180627. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180628. * aren't usually used outside the library (as far as I know), so it is
  180629. * debatable if they should be exported at all. In the future, when it is
  180630. * possible to have run-time registry of chunk-handling functions, some of
  180631. * these will be made available again.
  180632. #define PNG_EXTERN extern
  180633. */
  180634. #define PNG_EXTERN
  180635. /* Other defines specific to compilers can go here. Try to keep
  180636. * them inside an appropriate ifdef/endif pair for portability.
  180637. */
  180638. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180639. # if defined(MACOS)
  180640. /* We need to check that <math.h> hasn't already been included earlier
  180641. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180642. * <fp.h> if possible.
  180643. */
  180644. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180645. # include <fp.h>
  180646. # endif
  180647. # else
  180648. # include <math.h>
  180649. # endif
  180650. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180651. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180652. * MATH=68881
  180653. */
  180654. # include <m68881.h>
  180655. # endif
  180656. #endif
  180657. /* Codewarrior on NT has linking problems without this. */
  180658. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180659. # define PNG_ALWAYS_EXTERN
  180660. #endif
  180661. /* This provides the non-ANSI (far) memory allocation routines. */
  180662. #if defined(__TURBOC__) && defined(__MSDOS__)
  180663. # include <mem.h>
  180664. # include <alloc.h>
  180665. #endif
  180666. /* I have no idea why is this necessary... */
  180667. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180668. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180669. # include <malloc.h>
  180670. #endif
  180671. /* This controls how fine the dithering gets. As this allocates
  180672. * a largish chunk of memory (32K), those who are not as concerned
  180673. * with dithering quality can decrease some or all of these.
  180674. */
  180675. #ifndef PNG_DITHER_RED_BITS
  180676. # define PNG_DITHER_RED_BITS 5
  180677. #endif
  180678. #ifndef PNG_DITHER_GREEN_BITS
  180679. # define PNG_DITHER_GREEN_BITS 5
  180680. #endif
  180681. #ifndef PNG_DITHER_BLUE_BITS
  180682. # define PNG_DITHER_BLUE_BITS 5
  180683. #endif
  180684. /* This controls how fine the gamma correction becomes when you
  180685. * are only interested in 8 bits anyway. Increasing this value
  180686. * results in more memory being used, and more pow() functions
  180687. * being called to fill in the gamma tables. Don't set this value
  180688. * less then 8, and even that may not work (I haven't tested it).
  180689. */
  180690. #ifndef PNG_MAX_GAMMA_8
  180691. # define PNG_MAX_GAMMA_8 11
  180692. #endif
  180693. /* This controls how much a difference in gamma we can tolerate before
  180694. * we actually start doing gamma conversion.
  180695. */
  180696. #ifndef PNG_GAMMA_THRESHOLD
  180697. # define PNG_GAMMA_THRESHOLD 0.05
  180698. #endif
  180699. #endif /* PNG_INTERNAL */
  180700. /* The following uses const char * instead of char * for error
  180701. * and warning message functions, so some compilers won't complain.
  180702. * If you do not want to use const, define PNG_NO_CONST here.
  180703. */
  180704. #ifndef PNG_NO_CONST
  180705. # define PNG_CONST const
  180706. #else
  180707. # define PNG_CONST
  180708. #endif
  180709. /* The following defines give you the ability to remove code from the
  180710. * library that you will not be using. I wish I could figure out how to
  180711. * automate this, but I can't do that without making it seriously hard
  180712. * on the users. So if you are not using an ability, change the #define
  180713. * to and #undef, and that part of the library will not be compiled. If
  180714. * your linker can't find a function, you may want to make sure the
  180715. * ability is defined here. Some of these depend upon some others being
  180716. * defined. I haven't figured out all the interactions here, so you may
  180717. * have to experiment awhile to get everything to compile. If you are
  180718. * creating or using a shared library, you probably shouldn't touch this,
  180719. * as it will affect the size of the structures, and this will cause bad
  180720. * things to happen if the library and/or application ever change.
  180721. */
  180722. /* Any features you will not be using can be undef'ed here */
  180723. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180724. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180725. * on the compile line, then pick and choose which ones to define without
  180726. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180727. * if you only want to have a png-compliant reader/writer but don't need
  180728. * any of the extra transformations. This saves about 80 kbytes in a
  180729. * typical installation of the library. (PNG_NO_* form added in version
  180730. * 1.0.1c, for consistency)
  180731. */
  180732. /* The size of the png_text structure changed in libpng-1.0.6 when
  180733. * iTXt support was added. iTXt support was turned off by default through
  180734. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180735. * instead of calling png_set_text() and letting libpng malloc it. It
  180736. * was turned on by default in libpng-1.3.0.
  180737. */
  180738. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180739. # ifndef PNG_NO_iTXt_SUPPORTED
  180740. # define PNG_NO_iTXt_SUPPORTED
  180741. # endif
  180742. # ifndef PNG_NO_READ_iTXt
  180743. # define PNG_NO_READ_iTXt
  180744. # endif
  180745. # ifndef PNG_NO_WRITE_iTXt
  180746. # define PNG_NO_WRITE_iTXt
  180747. # endif
  180748. #endif
  180749. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180750. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180751. # define PNG_READ_iTXt
  180752. # endif
  180753. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180754. # define PNG_WRITE_iTXt
  180755. # endif
  180756. #endif
  180757. /* The following support, added after version 1.0.0, can be turned off here en
  180758. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180759. * with old applications that require the length of png_struct and png_info
  180760. * to remain unchanged.
  180761. */
  180762. #ifdef PNG_LEGACY_SUPPORTED
  180763. # define PNG_NO_FREE_ME
  180764. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180765. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180766. # define PNG_NO_READ_USER_CHUNKS
  180767. # define PNG_NO_READ_iCCP
  180768. # define PNG_NO_WRITE_iCCP
  180769. # define PNG_NO_READ_iTXt
  180770. # define PNG_NO_WRITE_iTXt
  180771. # define PNG_NO_READ_sCAL
  180772. # define PNG_NO_WRITE_sCAL
  180773. # define PNG_NO_READ_sPLT
  180774. # define PNG_NO_WRITE_sPLT
  180775. # define PNG_NO_INFO_IMAGE
  180776. # define PNG_NO_READ_RGB_TO_GRAY
  180777. # define PNG_NO_READ_USER_TRANSFORM
  180778. # define PNG_NO_WRITE_USER_TRANSFORM
  180779. # define PNG_NO_USER_MEM
  180780. # define PNG_NO_READ_EMPTY_PLTE
  180781. # define PNG_NO_MNG_FEATURES
  180782. # define PNG_NO_FIXED_POINT_SUPPORTED
  180783. #endif
  180784. /* Ignore attempt to turn off both floating and fixed point support */
  180785. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180786. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180787. # define PNG_FIXED_POINT_SUPPORTED
  180788. #endif
  180789. #ifndef PNG_NO_FREE_ME
  180790. # define PNG_FREE_ME_SUPPORTED
  180791. #endif
  180792. #if defined(PNG_READ_SUPPORTED)
  180793. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180794. !defined(PNG_NO_READ_TRANSFORMS)
  180795. # define PNG_READ_TRANSFORMS_SUPPORTED
  180796. #endif
  180797. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180798. # ifndef PNG_NO_READ_EXPAND
  180799. # define PNG_READ_EXPAND_SUPPORTED
  180800. # endif
  180801. # ifndef PNG_NO_READ_SHIFT
  180802. # define PNG_READ_SHIFT_SUPPORTED
  180803. # endif
  180804. # ifndef PNG_NO_READ_PACK
  180805. # define PNG_READ_PACK_SUPPORTED
  180806. # endif
  180807. # ifndef PNG_NO_READ_BGR
  180808. # define PNG_READ_BGR_SUPPORTED
  180809. # endif
  180810. # ifndef PNG_NO_READ_SWAP
  180811. # define PNG_READ_SWAP_SUPPORTED
  180812. # endif
  180813. # ifndef PNG_NO_READ_PACKSWAP
  180814. # define PNG_READ_PACKSWAP_SUPPORTED
  180815. # endif
  180816. # ifndef PNG_NO_READ_INVERT
  180817. # define PNG_READ_INVERT_SUPPORTED
  180818. # endif
  180819. # ifndef PNG_NO_READ_DITHER
  180820. # define PNG_READ_DITHER_SUPPORTED
  180821. # endif
  180822. # ifndef PNG_NO_READ_BACKGROUND
  180823. # define PNG_READ_BACKGROUND_SUPPORTED
  180824. # endif
  180825. # ifndef PNG_NO_READ_16_TO_8
  180826. # define PNG_READ_16_TO_8_SUPPORTED
  180827. # endif
  180828. # ifndef PNG_NO_READ_FILLER
  180829. # define PNG_READ_FILLER_SUPPORTED
  180830. # endif
  180831. # ifndef PNG_NO_READ_GAMMA
  180832. # define PNG_READ_GAMMA_SUPPORTED
  180833. # endif
  180834. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180835. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180836. # endif
  180837. # ifndef PNG_NO_READ_SWAP_ALPHA
  180838. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180839. # endif
  180840. # ifndef PNG_NO_READ_INVERT_ALPHA
  180841. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180842. # endif
  180843. # ifndef PNG_NO_READ_STRIP_ALPHA
  180844. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180845. # endif
  180846. # ifndef PNG_NO_READ_USER_TRANSFORM
  180847. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180848. # endif
  180849. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180850. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180851. # endif
  180852. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180853. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180854. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180855. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180856. #endif /* about interlacing capability! You'll */
  180857. /* still have interlacing unless you change the following line: */
  180858. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180859. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180860. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180861. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180862. # endif
  180863. #endif
  180864. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180865. /* Deprecated, will be removed from version 2.0.0.
  180866. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180867. #ifndef PNG_NO_READ_EMPTY_PLTE
  180868. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180869. #endif
  180870. #endif
  180871. #endif /* PNG_READ_SUPPORTED */
  180872. #if defined(PNG_WRITE_SUPPORTED)
  180873. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180874. !defined(PNG_NO_WRITE_TRANSFORMS)
  180875. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180876. #endif
  180877. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180878. # ifndef PNG_NO_WRITE_SHIFT
  180879. # define PNG_WRITE_SHIFT_SUPPORTED
  180880. # endif
  180881. # ifndef PNG_NO_WRITE_PACK
  180882. # define PNG_WRITE_PACK_SUPPORTED
  180883. # endif
  180884. # ifndef PNG_NO_WRITE_BGR
  180885. # define PNG_WRITE_BGR_SUPPORTED
  180886. # endif
  180887. # ifndef PNG_NO_WRITE_SWAP
  180888. # define PNG_WRITE_SWAP_SUPPORTED
  180889. # endif
  180890. # ifndef PNG_NO_WRITE_PACKSWAP
  180891. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180892. # endif
  180893. # ifndef PNG_NO_WRITE_INVERT
  180894. # define PNG_WRITE_INVERT_SUPPORTED
  180895. # endif
  180896. # ifndef PNG_NO_WRITE_FILLER
  180897. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180898. # endif
  180899. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180900. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180901. # endif
  180902. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180903. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180904. # endif
  180905. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180906. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180907. # endif
  180908. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180909. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180910. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180911. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180912. encoders, but can cause trouble
  180913. if left undefined */
  180914. #endif
  180915. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180916. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180917. defined(PNG_FLOATING_POINT_SUPPORTED)
  180918. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180919. #endif
  180920. #ifndef PNG_NO_WRITE_FLUSH
  180921. # define PNG_WRITE_FLUSH_SUPPORTED
  180922. #endif
  180923. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180924. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180925. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180926. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180927. #endif
  180928. #endif
  180929. #endif /* PNG_WRITE_SUPPORTED */
  180930. #ifndef PNG_1_0_X
  180931. # ifndef PNG_NO_ERROR_NUMBERS
  180932. # define PNG_ERROR_NUMBERS_SUPPORTED
  180933. # endif
  180934. #endif /* PNG_1_0_X */
  180935. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180936. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180937. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180938. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180939. # endif
  180940. #endif
  180941. #ifndef PNG_NO_STDIO
  180942. # define PNG_TIME_RFC1123_SUPPORTED
  180943. #endif
  180944. /* This adds extra functions in pngget.c for accessing data from the
  180945. * info pointer (added in version 0.99)
  180946. * png_get_image_width()
  180947. * png_get_image_height()
  180948. * png_get_bit_depth()
  180949. * png_get_color_type()
  180950. * png_get_compression_type()
  180951. * png_get_filter_type()
  180952. * png_get_interlace_type()
  180953. * png_get_pixel_aspect_ratio()
  180954. * png_get_pixels_per_meter()
  180955. * png_get_x_offset_pixels()
  180956. * png_get_y_offset_pixels()
  180957. * png_get_x_offset_microns()
  180958. * png_get_y_offset_microns()
  180959. */
  180960. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180961. # define PNG_EASY_ACCESS_SUPPORTED
  180962. #endif
  180963. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180964. * and removed from version 1.2.20. The following will be removed
  180965. * from libpng-1.4.0
  180966. */
  180967. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180968. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180969. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180970. # endif
  180971. #endif
  180972. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180973. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180974. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180975. # endif
  180976. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180977. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180978. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180979. # define PNG_NO_MMX_CODE
  180980. # endif
  180981. # endif
  180982. # if defined(__APPLE__)
  180983. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180984. # define PNG_NO_MMX_CODE
  180985. # endif
  180986. # endif
  180987. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180988. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180989. # define PNG_NO_MMX_CODE
  180990. # endif
  180991. # endif
  180992. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180993. # define PNG_MMX_CODE_SUPPORTED
  180994. # endif
  180995. #endif
  180996. /* end of obsolete code to be removed from libpng-1.4.0 */
  180997. #if !defined(PNG_1_0_X)
  180998. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180999. # define PNG_USER_MEM_SUPPORTED
  181000. #endif
  181001. #endif /* PNG_1_0_X */
  181002. /* Added at libpng-1.2.6 */
  181003. #if !defined(PNG_1_0_X)
  181004. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181005. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181006. # define PNG_SET_USER_LIMITS_SUPPORTED
  181007. #endif
  181008. #endif
  181009. #endif /* PNG_1_0_X */
  181010. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181011. * how large, set these limits to 0x7fffffffL
  181012. */
  181013. #ifndef PNG_USER_WIDTH_MAX
  181014. # define PNG_USER_WIDTH_MAX 1000000L
  181015. #endif
  181016. #ifndef PNG_USER_HEIGHT_MAX
  181017. # define PNG_USER_HEIGHT_MAX 1000000L
  181018. #endif
  181019. /* These are currently experimental features, define them if you want */
  181020. /* very little testing */
  181021. /*
  181022. #ifdef PNG_READ_SUPPORTED
  181023. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181024. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181025. # endif
  181026. #endif
  181027. */
  181028. /* This is only for PowerPC big-endian and 680x0 systems */
  181029. /* some testing */
  181030. /*
  181031. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181032. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181033. #endif
  181034. */
  181035. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181036. /*
  181037. #define PNG_NO_POINTER_INDEXING
  181038. */
  181039. /* These functions are turned off by default, as they will be phased out. */
  181040. /*
  181041. #define PNG_USELESS_TESTS_SUPPORTED
  181042. #define PNG_CORRECT_PALETTE_SUPPORTED
  181043. */
  181044. /* Any chunks you are not interested in, you can undef here. The
  181045. * ones that allocate memory may be expecially important (hIST,
  181046. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181047. * a bit smaller.
  181048. */
  181049. #if defined(PNG_READ_SUPPORTED) && \
  181050. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181051. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181052. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181053. #endif
  181054. #if defined(PNG_WRITE_SUPPORTED) && \
  181055. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181056. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181057. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181058. #endif
  181059. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181060. #ifdef PNG_NO_READ_TEXT
  181061. # define PNG_NO_READ_iTXt
  181062. # define PNG_NO_READ_tEXt
  181063. # define PNG_NO_READ_zTXt
  181064. #endif
  181065. #ifndef PNG_NO_READ_bKGD
  181066. # define PNG_READ_bKGD_SUPPORTED
  181067. # define PNG_bKGD_SUPPORTED
  181068. #endif
  181069. #ifndef PNG_NO_READ_cHRM
  181070. # define PNG_READ_cHRM_SUPPORTED
  181071. # define PNG_cHRM_SUPPORTED
  181072. #endif
  181073. #ifndef PNG_NO_READ_gAMA
  181074. # define PNG_READ_gAMA_SUPPORTED
  181075. # define PNG_gAMA_SUPPORTED
  181076. #endif
  181077. #ifndef PNG_NO_READ_hIST
  181078. # define PNG_READ_hIST_SUPPORTED
  181079. # define PNG_hIST_SUPPORTED
  181080. #endif
  181081. #ifndef PNG_NO_READ_iCCP
  181082. # define PNG_READ_iCCP_SUPPORTED
  181083. # define PNG_iCCP_SUPPORTED
  181084. #endif
  181085. #ifndef PNG_NO_READ_iTXt
  181086. # ifndef PNG_READ_iTXt_SUPPORTED
  181087. # define PNG_READ_iTXt_SUPPORTED
  181088. # endif
  181089. # ifndef PNG_iTXt_SUPPORTED
  181090. # define PNG_iTXt_SUPPORTED
  181091. # endif
  181092. #endif
  181093. #ifndef PNG_NO_READ_oFFs
  181094. # define PNG_READ_oFFs_SUPPORTED
  181095. # define PNG_oFFs_SUPPORTED
  181096. #endif
  181097. #ifndef PNG_NO_READ_pCAL
  181098. # define PNG_READ_pCAL_SUPPORTED
  181099. # define PNG_pCAL_SUPPORTED
  181100. #endif
  181101. #ifndef PNG_NO_READ_sCAL
  181102. # define PNG_READ_sCAL_SUPPORTED
  181103. # define PNG_sCAL_SUPPORTED
  181104. #endif
  181105. #ifndef PNG_NO_READ_pHYs
  181106. # define PNG_READ_pHYs_SUPPORTED
  181107. # define PNG_pHYs_SUPPORTED
  181108. #endif
  181109. #ifndef PNG_NO_READ_sBIT
  181110. # define PNG_READ_sBIT_SUPPORTED
  181111. # define PNG_sBIT_SUPPORTED
  181112. #endif
  181113. #ifndef PNG_NO_READ_sPLT
  181114. # define PNG_READ_sPLT_SUPPORTED
  181115. # define PNG_sPLT_SUPPORTED
  181116. #endif
  181117. #ifndef PNG_NO_READ_sRGB
  181118. # define PNG_READ_sRGB_SUPPORTED
  181119. # define PNG_sRGB_SUPPORTED
  181120. #endif
  181121. #ifndef PNG_NO_READ_tEXt
  181122. # define PNG_READ_tEXt_SUPPORTED
  181123. # define PNG_tEXt_SUPPORTED
  181124. #endif
  181125. #ifndef PNG_NO_READ_tIME
  181126. # define PNG_READ_tIME_SUPPORTED
  181127. # define PNG_tIME_SUPPORTED
  181128. #endif
  181129. #ifndef PNG_NO_READ_tRNS
  181130. # define PNG_READ_tRNS_SUPPORTED
  181131. # define PNG_tRNS_SUPPORTED
  181132. #endif
  181133. #ifndef PNG_NO_READ_zTXt
  181134. # define PNG_READ_zTXt_SUPPORTED
  181135. # define PNG_zTXt_SUPPORTED
  181136. #endif
  181137. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181138. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181139. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181140. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181141. # endif
  181142. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181143. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181144. # endif
  181145. #endif
  181146. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181147. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181148. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181149. # define PNG_USER_CHUNKS_SUPPORTED
  181150. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181151. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181152. # endif
  181153. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181154. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181155. # endif
  181156. #endif
  181157. #ifndef PNG_NO_READ_OPT_PLTE
  181158. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181159. #endif /* optional PLTE chunk in RGB and RGBA images */
  181160. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181161. defined(PNG_READ_zTXt_SUPPORTED)
  181162. # define PNG_READ_TEXT_SUPPORTED
  181163. # define PNG_TEXT_SUPPORTED
  181164. #endif
  181165. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181166. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181167. #ifdef PNG_NO_WRITE_TEXT
  181168. # define PNG_NO_WRITE_iTXt
  181169. # define PNG_NO_WRITE_tEXt
  181170. # define PNG_NO_WRITE_zTXt
  181171. #endif
  181172. #ifndef PNG_NO_WRITE_bKGD
  181173. # define PNG_WRITE_bKGD_SUPPORTED
  181174. # ifndef PNG_bKGD_SUPPORTED
  181175. # define PNG_bKGD_SUPPORTED
  181176. # endif
  181177. #endif
  181178. #ifndef PNG_NO_WRITE_cHRM
  181179. # define PNG_WRITE_cHRM_SUPPORTED
  181180. # ifndef PNG_cHRM_SUPPORTED
  181181. # define PNG_cHRM_SUPPORTED
  181182. # endif
  181183. #endif
  181184. #ifndef PNG_NO_WRITE_gAMA
  181185. # define PNG_WRITE_gAMA_SUPPORTED
  181186. # ifndef PNG_gAMA_SUPPORTED
  181187. # define PNG_gAMA_SUPPORTED
  181188. # endif
  181189. #endif
  181190. #ifndef PNG_NO_WRITE_hIST
  181191. # define PNG_WRITE_hIST_SUPPORTED
  181192. # ifndef PNG_hIST_SUPPORTED
  181193. # define PNG_hIST_SUPPORTED
  181194. # endif
  181195. #endif
  181196. #ifndef PNG_NO_WRITE_iCCP
  181197. # define PNG_WRITE_iCCP_SUPPORTED
  181198. # ifndef PNG_iCCP_SUPPORTED
  181199. # define PNG_iCCP_SUPPORTED
  181200. # endif
  181201. #endif
  181202. #ifndef PNG_NO_WRITE_iTXt
  181203. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181204. # define PNG_WRITE_iTXt_SUPPORTED
  181205. # endif
  181206. # ifndef PNG_iTXt_SUPPORTED
  181207. # define PNG_iTXt_SUPPORTED
  181208. # endif
  181209. #endif
  181210. #ifndef PNG_NO_WRITE_oFFs
  181211. # define PNG_WRITE_oFFs_SUPPORTED
  181212. # ifndef PNG_oFFs_SUPPORTED
  181213. # define PNG_oFFs_SUPPORTED
  181214. # endif
  181215. #endif
  181216. #ifndef PNG_NO_WRITE_pCAL
  181217. # define PNG_WRITE_pCAL_SUPPORTED
  181218. # ifndef PNG_pCAL_SUPPORTED
  181219. # define PNG_pCAL_SUPPORTED
  181220. # endif
  181221. #endif
  181222. #ifndef PNG_NO_WRITE_sCAL
  181223. # define PNG_WRITE_sCAL_SUPPORTED
  181224. # ifndef PNG_sCAL_SUPPORTED
  181225. # define PNG_sCAL_SUPPORTED
  181226. # endif
  181227. #endif
  181228. #ifndef PNG_NO_WRITE_pHYs
  181229. # define PNG_WRITE_pHYs_SUPPORTED
  181230. # ifndef PNG_pHYs_SUPPORTED
  181231. # define PNG_pHYs_SUPPORTED
  181232. # endif
  181233. #endif
  181234. #ifndef PNG_NO_WRITE_sBIT
  181235. # define PNG_WRITE_sBIT_SUPPORTED
  181236. # ifndef PNG_sBIT_SUPPORTED
  181237. # define PNG_sBIT_SUPPORTED
  181238. # endif
  181239. #endif
  181240. #ifndef PNG_NO_WRITE_sPLT
  181241. # define PNG_WRITE_sPLT_SUPPORTED
  181242. # ifndef PNG_sPLT_SUPPORTED
  181243. # define PNG_sPLT_SUPPORTED
  181244. # endif
  181245. #endif
  181246. #ifndef PNG_NO_WRITE_sRGB
  181247. # define PNG_WRITE_sRGB_SUPPORTED
  181248. # ifndef PNG_sRGB_SUPPORTED
  181249. # define PNG_sRGB_SUPPORTED
  181250. # endif
  181251. #endif
  181252. #ifndef PNG_NO_WRITE_tEXt
  181253. # define PNG_WRITE_tEXt_SUPPORTED
  181254. # ifndef PNG_tEXt_SUPPORTED
  181255. # define PNG_tEXt_SUPPORTED
  181256. # endif
  181257. #endif
  181258. #ifndef PNG_NO_WRITE_tIME
  181259. # define PNG_WRITE_tIME_SUPPORTED
  181260. # ifndef PNG_tIME_SUPPORTED
  181261. # define PNG_tIME_SUPPORTED
  181262. # endif
  181263. #endif
  181264. #ifndef PNG_NO_WRITE_tRNS
  181265. # define PNG_WRITE_tRNS_SUPPORTED
  181266. # ifndef PNG_tRNS_SUPPORTED
  181267. # define PNG_tRNS_SUPPORTED
  181268. # endif
  181269. #endif
  181270. #ifndef PNG_NO_WRITE_zTXt
  181271. # define PNG_WRITE_zTXt_SUPPORTED
  181272. # ifndef PNG_zTXt_SUPPORTED
  181273. # define PNG_zTXt_SUPPORTED
  181274. # endif
  181275. #endif
  181276. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181277. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181278. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181279. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181280. # endif
  181281. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181282. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181283. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181284. # endif
  181285. # endif
  181286. #endif
  181287. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181288. defined(PNG_WRITE_zTXt_SUPPORTED)
  181289. # define PNG_WRITE_TEXT_SUPPORTED
  181290. # ifndef PNG_TEXT_SUPPORTED
  181291. # define PNG_TEXT_SUPPORTED
  181292. # endif
  181293. #endif
  181294. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181295. /* Turn this off to disable png_read_png() and
  181296. * png_write_png() and leave the row_pointers member
  181297. * out of the info structure.
  181298. */
  181299. #ifndef PNG_NO_INFO_IMAGE
  181300. # define PNG_INFO_IMAGE_SUPPORTED
  181301. #endif
  181302. /* need the time information for reading tIME chunks */
  181303. #if defined(PNG_tIME_SUPPORTED)
  181304. # if !defined(_WIN32_WCE)
  181305. /* "time.h" functions are not supported on WindowsCE */
  181306. # include <time.h>
  181307. # endif
  181308. #endif
  181309. /* Some typedefs to get us started. These should be safe on most of the
  181310. * common platforms. The typedefs should be at least as large as the
  181311. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181312. * don't have to be exactly that size. Some compilers dislike passing
  181313. * unsigned shorts as function parameters, so you may be better off using
  181314. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181315. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181316. */
  181317. typedef unsigned long png_uint_32;
  181318. typedef long png_int_32;
  181319. typedef unsigned short png_uint_16;
  181320. typedef short png_int_16;
  181321. typedef unsigned char png_byte;
  181322. /* This is usually size_t. It is typedef'ed just in case you need it to
  181323. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181324. #ifdef PNG_SIZE_T
  181325. typedef PNG_SIZE_T png_size_t;
  181326. # define png_sizeof(x) png_convert_size(sizeof (x))
  181327. #else
  181328. typedef size_t png_size_t;
  181329. # define png_sizeof(x) sizeof (x)
  181330. #endif
  181331. /* The following is needed for medium model support. It cannot be in the
  181332. * PNG_INTERNAL section. Needs modification for other compilers besides
  181333. * MSC. Model independent support declares all arrays and pointers to be
  181334. * large using the far keyword. The zlib version used must also support
  181335. * model independent data. As of version zlib 1.0.4, the necessary changes
  181336. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181337. * changes that are needed. (Tim Wegner)
  181338. */
  181339. /* Separate compiler dependencies (problem here is that zlib.h always
  181340. defines FAR. (SJT) */
  181341. #ifdef __BORLANDC__
  181342. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181343. # define LDATA 1
  181344. # else
  181345. # define LDATA 0
  181346. # endif
  181347. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181348. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181349. # define PNG_MAX_MALLOC_64K
  181350. # if (LDATA != 1)
  181351. # ifndef FAR
  181352. # define FAR __far
  181353. # endif
  181354. # define USE_FAR_KEYWORD
  181355. # endif /* LDATA != 1 */
  181356. /* Possibly useful for moving data out of default segment.
  181357. * Uncomment it if you want. Could also define FARDATA as
  181358. * const if your compiler supports it. (SJT)
  181359. # define FARDATA FAR
  181360. */
  181361. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181362. #endif /* __BORLANDC__ */
  181363. /* Suggest testing for specific compiler first before testing for
  181364. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181365. * making reliance oncertain keywords suspect. (SJT)
  181366. */
  181367. /* MSC Medium model */
  181368. #if defined(FAR)
  181369. # if defined(M_I86MM)
  181370. # define USE_FAR_KEYWORD
  181371. # define FARDATA FAR
  181372. # include <dos.h>
  181373. # endif
  181374. #endif
  181375. /* SJT: default case */
  181376. #ifndef FAR
  181377. # define FAR
  181378. #endif
  181379. /* At this point FAR is always defined */
  181380. #ifndef FARDATA
  181381. # define FARDATA
  181382. #endif
  181383. /* Typedef for floating-point numbers that are converted
  181384. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181385. typedef png_int_32 png_fixed_point;
  181386. /* Add typedefs for pointers */
  181387. typedef void FAR * png_voidp;
  181388. typedef png_byte FAR * png_bytep;
  181389. typedef png_uint_32 FAR * png_uint_32p;
  181390. typedef png_int_32 FAR * png_int_32p;
  181391. typedef png_uint_16 FAR * png_uint_16p;
  181392. typedef png_int_16 FAR * png_int_16p;
  181393. typedef PNG_CONST char FAR * png_const_charp;
  181394. typedef char FAR * png_charp;
  181395. typedef png_fixed_point FAR * png_fixed_point_p;
  181396. #ifndef PNG_NO_STDIO
  181397. #if defined(_WIN32_WCE)
  181398. typedef HANDLE png_FILE_p;
  181399. #else
  181400. typedef FILE * png_FILE_p;
  181401. #endif
  181402. #endif
  181403. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181404. typedef double FAR * png_doublep;
  181405. #endif
  181406. /* Pointers to pointers; i.e. arrays */
  181407. typedef png_byte FAR * FAR * png_bytepp;
  181408. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181409. typedef png_int_32 FAR * FAR * png_int_32pp;
  181410. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181411. typedef png_int_16 FAR * FAR * png_int_16pp;
  181412. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181413. typedef char FAR * FAR * png_charpp;
  181414. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181415. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181416. typedef double FAR * FAR * png_doublepp;
  181417. #endif
  181418. /* Pointers to pointers to pointers; i.e., pointer to array */
  181419. typedef char FAR * FAR * FAR * png_charppp;
  181420. #if 0
  181421. /* SPC - Is this stuff deprecated? */
  181422. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181423. /* libpng typedefs for types in zlib. If zlib changes
  181424. * or another compression library is used, then change these.
  181425. * Eliminates need to change all the source files.
  181426. */
  181427. typedef charf * png_zcharp;
  181428. typedef charf * FAR * png_zcharpp;
  181429. typedef z_stream FAR * png_zstreamp;
  181430. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181431. /*
  181432. * Define PNG_BUILD_DLL if the module being built is a Windows
  181433. * LIBPNG DLL.
  181434. *
  181435. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181436. * It is equivalent to Microsoft predefined macro _DLL that is
  181437. * automatically defined when you compile using the share
  181438. * version of the CRT (C Run-Time library)
  181439. *
  181440. * The cygwin mods make this behavior a little different:
  181441. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181442. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181443. * -or- if you are building an application that you want to link to the
  181444. * static library.
  181445. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181446. * the other flags is defined.
  181447. */
  181448. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181449. # define PNG_DLL
  181450. #endif
  181451. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181452. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181453. * command-line override
  181454. */
  181455. #if defined(__CYGWIN__)
  181456. # if !defined(PNG_STATIC)
  181457. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181458. # undef PNG_USE_GLOBAL_ARRAYS
  181459. # endif
  181460. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181461. # define PNG_USE_LOCAL_ARRAYS
  181462. # endif
  181463. # else
  181464. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181465. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181466. # undef PNG_USE_GLOBAL_ARRAYS
  181467. # endif
  181468. # endif
  181469. # endif
  181470. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181471. # define PNG_USE_LOCAL_ARRAYS
  181472. # endif
  181473. #endif
  181474. /* Do not use global arrays (helps with building DLL's)
  181475. * They are no longer used in libpng itself, since version 1.0.5c,
  181476. * but might be required for some pre-1.0.5c applications.
  181477. */
  181478. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181479. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181480. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181481. # define PNG_USE_LOCAL_ARRAYS
  181482. # else
  181483. # define PNG_USE_GLOBAL_ARRAYS
  181484. # endif
  181485. #endif
  181486. #if defined(__CYGWIN__)
  181487. # undef PNGAPI
  181488. # define PNGAPI __cdecl
  181489. # undef PNG_IMPEXP
  181490. # define PNG_IMPEXP
  181491. #endif
  181492. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181493. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181494. * Don't ignore those warnings; you must also reset the default calling
  181495. * convention in your compiler to match your PNGAPI, and you must build
  181496. * zlib and your applications the same way you build libpng.
  181497. */
  181498. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181499. # ifndef PNG_NO_MODULEDEF
  181500. # define PNG_NO_MODULEDEF
  181501. # endif
  181502. #endif
  181503. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181504. # define PNG_IMPEXP
  181505. #endif
  181506. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181507. (( defined(_Windows) || defined(_WINDOWS) || \
  181508. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181509. # ifndef PNGAPI
  181510. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181511. # define PNGAPI __cdecl
  181512. # else
  181513. # define PNGAPI _cdecl
  181514. # endif
  181515. # endif
  181516. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181517. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181518. # define PNG_IMPEXP
  181519. # endif
  181520. # if !defined(PNG_IMPEXP)
  181521. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181522. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181523. /* Borland/Microsoft */
  181524. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181525. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181526. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181527. # else
  181528. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181529. # if defined(PNG_BUILD_DLL)
  181530. # define PNG_IMPEXP __export
  181531. # else
  181532. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181533. VC++ */
  181534. # endif /* Exists in Borland C++ for
  181535. C++ classes (== huge) */
  181536. # endif
  181537. # endif
  181538. # if !defined(PNG_IMPEXP)
  181539. # if defined(PNG_BUILD_DLL)
  181540. # define PNG_IMPEXP __declspec(dllexport)
  181541. # else
  181542. # define PNG_IMPEXP __declspec(dllimport)
  181543. # endif
  181544. # endif
  181545. # endif /* PNG_IMPEXP */
  181546. #else /* !(DLL || non-cygwin WINDOWS) */
  181547. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181548. # ifndef PNGAPI
  181549. # define PNGAPI _System
  181550. # endif
  181551. # else
  181552. # if 0 /* ... other platforms, with other meanings */
  181553. # endif
  181554. # endif
  181555. #endif
  181556. #ifndef PNGAPI
  181557. # define PNGAPI
  181558. #endif
  181559. #ifndef PNG_IMPEXP
  181560. # define PNG_IMPEXP
  181561. #endif
  181562. #ifdef PNG_BUILDSYMS
  181563. # ifndef PNG_EXPORT
  181564. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181565. # endif
  181566. # ifdef PNG_USE_GLOBAL_ARRAYS
  181567. # ifndef PNG_EXPORT_VAR
  181568. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181569. # endif
  181570. # endif
  181571. #endif
  181572. #ifndef PNG_EXPORT
  181573. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181574. #endif
  181575. #ifdef PNG_USE_GLOBAL_ARRAYS
  181576. # ifndef PNG_EXPORT_VAR
  181577. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181578. # endif
  181579. #endif
  181580. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181581. * functions that are passed far data must be model independent.
  181582. */
  181583. #ifndef PNG_ABORT
  181584. # define PNG_ABORT() abort()
  181585. #endif
  181586. #ifdef PNG_SETJMP_SUPPORTED
  181587. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181588. #else
  181589. # define png_jmpbuf(png_ptr) \
  181590. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181591. #endif
  181592. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181593. /* use this to make far-to-near assignments */
  181594. # define CHECK 1
  181595. # define NOCHECK 0
  181596. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181597. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181598. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181599. # define png_strcpy _fstrcpy
  181600. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181601. # define png_strlen _fstrlen
  181602. # define png_memcmp _fmemcmp /* SJT: added */
  181603. # define png_memcpy _fmemcpy
  181604. # define png_memset _fmemset
  181605. #else /* use the usual functions */
  181606. # define CVT_PTR(ptr) (ptr)
  181607. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181608. # ifndef PNG_NO_SNPRINTF
  181609. # ifdef _MSC_VER
  181610. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181611. # define png_snprintf2 _snprintf
  181612. # define png_snprintf6 _snprintf
  181613. # else
  181614. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181615. # define png_snprintf2 snprintf
  181616. # define png_snprintf6 snprintf
  181617. # endif
  181618. # else
  181619. /* You don't have or don't want to use snprintf(). Caution: Using
  181620. * sprintf instead of snprintf exposes your application to accidental
  181621. * or malevolent buffer overflows. If you don't have snprintf()
  181622. * as a general rule you should provide one (you can get one from
  181623. * Portable OpenSSH). */
  181624. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181625. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181626. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181627. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181628. # endif
  181629. # define png_strcpy strcpy
  181630. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181631. # define png_strlen strlen
  181632. # define png_memcmp memcmp /* SJT: added */
  181633. # define png_memcpy memcpy
  181634. # define png_memset memset
  181635. #endif
  181636. /* End of memory model independent support */
  181637. /* Just a little check that someone hasn't tried to define something
  181638. * contradictory.
  181639. */
  181640. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181641. # undef PNG_ZBUF_SIZE
  181642. # define PNG_ZBUF_SIZE 65536L
  181643. #endif
  181644. /* Added at libpng-1.2.8 */
  181645. #endif /* PNG_VERSION_INFO_ONLY */
  181646. #endif /* PNGCONF_H */
  181647. /*** End of inlined file: pngconf.h ***/
  181648. #ifdef _MSC_VER
  181649. #pragma warning (disable: 4996 4100)
  181650. #endif
  181651. /*
  181652. * Added at libpng-1.2.8 */
  181653. /* Ref MSDN: Private as priority over Special
  181654. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181655. * procedures. If this value is given, the StringFileInfo block must
  181656. * contain a PrivateBuild string.
  181657. *
  181658. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181659. * standard release procedures but is a variation of the standard
  181660. * file of the same version number. If this value is given, the
  181661. * StringFileInfo block must contain a SpecialBuild string.
  181662. */
  181663. #if defined(PNG_USER_PRIVATEBUILD)
  181664. # define PNG_LIBPNG_BUILD_TYPE \
  181665. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181666. #else
  181667. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181668. # define PNG_LIBPNG_BUILD_TYPE \
  181669. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181670. # else
  181671. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181672. # endif
  181673. #endif
  181674. #ifndef PNG_VERSION_INFO_ONLY
  181675. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181676. #ifdef __cplusplus
  181677. //extern "C" {
  181678. #endif /* __cplusplus */
  181679. /* This file is arranged in several sections. The first section contains
  181680. * structure and type definitions. The second section contains the external
  181681. * library functions, while the third has the internal library functions,
  181682. * which applications aren't expected to use directly.
  181683. */
  181684. #ifndef PNG_NO_TYPECAST_NULL
  181685. #define int_p_NULL (int *)NULL
  181686. #define png_bytep_NULL (png_bytep)NULL
  181687. #define png_bytepp_NULL (png_bytepp)NULL
  181688. #define png_doublep_NULL (png_doublep)NULL
  181689. #define png_error_ptr_NULL (png_error_ptr)NULL
  181690. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181691. #define png_free_ptr_NULL (png_free_ptr)NULL
  181692. #define png_infopp_NULL (png_infopp)NULL
  181693. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181694. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181695. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181696. #define png_structp_NULL (png_structp)NULL
  181697. #define png_uint_16p_NULL (png_uint_16p)NULL
  181698. #define png_voidp_NULL (png_voidp)NULL
  181699. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181700. #else
  181701. #define int_p_NULL NULL
  181702. #define png_bytep_NULL NULL
  181703. #define png_bytepp_NULL NULL
  181704. #define png_doublep_NULL NULL
  181705. #define png_error_ptr_NULL NULL
  181706. #define png_flush_ptr_NULL NULL
  181707. #define png_free_ptr_NULL NULL
  181708. #define png_infopp_NULL NULL
  181709. #define png_malloc_ptr_NULL NULL
  181710. #define png_read_status_ptr_NULL NULL
  181711. #define png_rw_ptr_NULL NULL
  181712. #define png_structp_NULL NULL
  181713. #define png_uint_16p_NULL NULL
  181714. #define png_voidp_NULL NULL
  181715. #define png_write_status_ptr_NULL NULL
  181716. #endif
  181717. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181718. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181719. /* Version information for C files, stored in png.c. This had better match
  181720. * the version above.
  181721. */
  181722. #ifdef PNG_USE_GLOBAL_ARRAYS
  181723. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181724. /* need room for 99.99.99beta99z */
  181725. #else
  181726. #define png_libpng_ver png_get_header_ver(NULL)
  181727. #endif
  181728. #ifdef PNG_USE_GLOBAL_ARRAYS
  181729. /* This was removed in version 1.0.5c */
  181730. /* Structures to facilitate easy interlacing. See png.c for more details */
  181731. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181732. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181733. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181734. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181735. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181736. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181737. /* This isn't currently used. If you need it, see png.c for more details.
  181738. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181739. */
  181740. #endif
  181741. #endif /* PNG_NO_EXTERN */
  181742. /* Three color definitions. The order of the red, green, and blue, (and the
  181743. * exact size) is not important, although the size of the fields need to
  181744. * be png_byte or png_uint_16 (as defined below).
  181745. */
  181746. typedef struct png_color_struct
  181747. {
  181748. png_byte red;
  181749. png_byte green;
  181750. png_byte blue;
  181751. } png_color;
  181752. typedef png_color FAR * png_colorp;
  181753. typedef png_color FAR * FAR * png_colorpp;
  181754. typedef struct png_color_16_struct
  181755. {
  181756. png_byte index; /* used for palette files */
  181757. png_uint_16 red; /* for use in red green blue files */
  181758. png_uint_16 green;
  181759. png_uint_16 blue;
  181760. png_uint_16 gray; /* for use in grayscale files */
  181761. } png_color_16;
  181762. typedef png_color_16 FAR * png_color_16p;
  181763. typedef png_color_16 FAR * FAR * png_color_16pp;
  181764. typedef struct png_color_8_struct
  181765. {
  181766. png_byte red; /* for use in red green blue files */
  181767. png_byte green;
  181768. png_byte blue;
  181769. png_byte gray; /* for use in grayscale files */
  181770. png_byte alpha; /* for alpha channel files */
  181771. } png_color_8;
  181772. typedef png_color_8 FAR * png_color_8p;
  181773. typedef png_color_8 FAR * FAR * png_color_8pp;
  181774. /*
  181775. * The following two structures are used for the in-core representation
  181776. * of sPLT chunks.
  181777. */
  181778. typedef struct png_sPLT_entry_struct
  181779. {
  181780. png_uint_16 red;
  181781. png_uint_16 green;
  181782. png_uint_16 blue;
  181783. png_uint_16 alpha;
  181784. png_uint_16 frequency;
  181785. } png_sPLT_entry;
  181786. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181787. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181788. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181789. * occupy the LSB of their respective members, and the MSB of each member
  181790. * is zero-filled. The frequency member always occupies the full 16 bits.
  181791. */
  181792. typedef struct png_sPLT_struct
  181793. {
  181794. png_charp name; /* palette name */
  181795. png_byte depth; /* depth of palette samples */
  181796. png_sPLT_entryp entries; /* palette entries */
  181797. png_int_32 nentries; /* number of palette entries */
  181798. } png_sPLT_t;
  181799. typedef png_sPLT_t FAR * png_sPLT_tp;
  181800. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181801. #ifdef PNG_TEXT_SUPPORTED
  181802. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181803. * and whether that contents is compressed or not. The "key" field
  181804. * points to a regular zero-terminated C string. The "text", "lang", and
  181805. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181806. * However, the * structure returned by png_get_text() will always contain
  181807. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181808. * so they can be safely used in printf() and other string-handling functions.
  181809. */
  181810. typedef struct png_text_struct
  181811. {
  181812. int compression; /* compression value:
  181813. -1: tEXt, none
  181814. 0: zTXt, deflate
  181815. 1: iTXt, none
  181816. 2: iTXt, deflate */
  181817. png_charp key; /* keyword, 1-79 character description of "text" */
  181818. png_charp text; /* comment, may be an empty string (ie "")
  181819. or a NULL pointer */
  181820. png_size_t text_length; /* length of the text string */
  181821. #ifdef PNG_iTXt_SUPPORTED
  181822. png_size_t itxt_length; /* length of the itxt string */
  181823. png_charp lang; /* language code, 0-79 characters
  181824. or a NULL pointer */
  181825. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181826. chars or a NULL pointer */
  181827. #endif
  181828. } png_text;
  181829. typedef png_text FAR * png_textp;
  181830. typedef png_text FAR * FAR * png_textpp;
  181831. #endif
  181832. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181833. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181834. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181835. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181836. #define PNG_TEXT_COMPRESSION_NONE -1
  181837. #define PNG_TEXT_COMPRESSION_zTXt 0
  181838. #define PNG_ITXT_COMPRESSION_NONE 1
  181839. #define PNG_ITXT_COMPRESSION_zTXt 2
  181840. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181841. /* png_time is a way to hold the time in an machine independent way.
  181842. * Two conversions are provided, both from time_t and struct tm. There
  181843. * is no portable way to convert to either of these structures, as far
  181844. * as I know. If you know of a portable way, send it to me. As a side
  181845. * note - PNG has always been Year 2000 compliant!
  181846. */
  181847. typedef struct png_time_struct
  181848. {
  181849. png_uint_16 year; /* full year, as in, 1995 */
  181850. png_byte month; /* month of year, 1 - 12 */
  181851. png_byte day; /* day of month, 1 - 31 */
  181852. png_byte hour; /* hour of day, 0 - 23 */
  181853. png_byte minute; /* minute of hour, 0 - 59 */
  181854. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181855. } png_time;
  181856. typedef png_time FAR * png_timep;
  181857. typedef png_time FAR * FAR * png_timepp;
  181858. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181859. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181860. * no specific support. The idea is that we can use this to queue
  181861. * up private chunks for output even though the library doesn't actually
  181862. * know about their semantics.
  181863. */
  181864. typedef struct png_unknown_chunk_t
  181865. {
  181866. png_byte name[5];
  181867. png_byte *data;
  181868. png_size_t size;
  181869. /* libpng-using applications should NOT directly modify this byte. */
  181870. png_byte location; /* mode of operation at read time */
  181871. }
  181872. png_unknown_chunk;
  181873. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181874. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181875. #endif
  181876. /* png_info is a structure that holds the information in a PNG file so
  181877. * that the application can find out the characteristics of the image.
  181878. * If you are reading the file, this structure will tell you what is
  181879. * in the PNG file. If you are writing the file, fill in the information
  181880. * you want to put into the PNG file, then call png_write_info().
  181881. * The names chosen should be very close to the PNG specification, so
  181882. * consult that document for information about the meaning of each field.
  181883. *
  181884. * With libpng < 0.95, it was only possible to directly set and read the
  181885. * the values in the png_info_struct, which meant that the contents and
  181886. * order of the values had to remain fixed. With libpng 0.95 and later,
  181887. * however, there are now functions that abstract the contents of
  181888. * png_info_struct from the application, so this makes it easier to use
  181889. * libpng with dynamic libraries, and even makes it possible to use
  181890. * libraries that don't have all of the libpng ancillary chunk-handing
  181891. * functionality.
  181892. *
  181893. * In any case, the order of the parameters in png_info_struct should NOT
  181894. * be changed for as long as possible to keep compatibility with applications
  181895. * that use the old direct-access method with png_info_struct.
  181896. *
  181897. * The following members may have allocated storage attached that should be
  181898. * cleaned up before the structure is discarded: palette, trans, text,
  181899. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181900. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181901. * are automatically freed when the info structure is deallocated, if they were
  181902. * allocated internally by libpng. This behavior can be changed by means
  181903. * of the png_data_freer() function.
  181904. *
  181905. * More allocation details: all the chunk-reading functions that
  181906. * change these members go through the corresponding png_set_*
  181907. * functions. A function to clear these members is available: see
  181908. * png_free_data(). The png_set_* functions do not depend on being
  181909. * able to point info structure members to any of the storage they are
  181910. * passed (they make their own copies), EXCEPT that the png_set_text
  181911. * functions use the same storage passed to them in the text_ptr or
  181912. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181913. * functions do not make their own copies.
  181914. */
  181915. typedef struct png_info_struct
  181916. {
  181917. /* the following are necessary for every PNG file */
  181918. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181919. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181920. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181921. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181922. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181923. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181924. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181925. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181926. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181927. /* The following three should have been named *_method not *_type */
  181928. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181929. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181930. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181931. /* The following is informational only on read, and not used on writes. */
  181932. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181933. png_byte pixel_depth; /* number of bits per pixel */
  181934. png_byte spare_byte; /* to align the data, and for future use */
  181935. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181936. /* The rest of the data is optional. If you are reading, check the
  181937. * valid field to see if the information in these are valid. If you
  181938. * are writing, set the valid field to those chunks you want written,
  181939. * and initialize the appropriate fields below.
  181940. */
  181941. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181942. /* The gAMA chunk describes the gamma characteristics of the system
  181943. * on which the image was created, normally in the range [1.0, 2.5].
  181944. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181945. */
  181946. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181947. #endif
  181948. #if defined(PNG_sRGB_SUPPORTED)
  181949. /* GR-P, 0.96a */
  181950. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181951. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181952. #endif
  181953. #if defined(PNG_TEXT_SUPPORTED)
  181954. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181955. * uncompressed, compressed, and optionally compressed forms, respectively.
  181956. * The data in "text" is an array of pointers to uncompressed,
  181957. * null-terminated C strings. Each chunk has a keyword that describes the
  181958. * textual data contained in that chunk. Keywords are not required to be
  181959. * unique, and the text string may be empty. Any number of text chunks may
  181960. * be in an image.
  181961. */
  181962. int num_text; /* number of comments read/to write */
  181963. int max_text; /* current size of text array */
  181964. png_textp text; /* array of comments read/to write */
  181965. #endif /* PNG_TEXT_SUPPORTED */
  181966. #if defined(PNG_tIME_SUPPORTED)
  181967. /* The tIME chunk holds the last time the displayed image data was
  181968. * modified. See the png_time struct for the contents of this struct.
  181969. */
  181970. png_time mod_time;
  181971. #endif
  181972. #if defined(PNG_sBIT_SUPPORTED)
  181973. /* The sBIT chunk specifies the number of significant high-order bits
  181974. * in the pixel data. Values are in the range [1, bit_depth], and are
  181975. * only specified for the channels in the pixel data. The contents of
  181976. * the low-order bits is not specified. Data is valid if
  181977. * (valid & PNG_INFO_sBIT) is non-zero.
  181978. */
  181979. png_color_8 sig_bit; /* significant bits in color channels */
  181980. #endif
  181981. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181982. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181983. /* The tRNS chunk supplies transparency data for paletted images and
  181984. * other image types that don't need a full alpha channel. There are
  181985. * "num_trans" transparency values for a paletted image, stored in the
  181986. * same order as the palette colors, starting from index 0. Values
  181987. * for the data are in the range [0, 255], ranging from fully transparent
  181988. * to fully opaque, respectively. For non-paletted images, there is a
  181989. * single color specified that should be treated as fully transparent.
  181990. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181991. */
  181992. png_bytep trans; /* transparent values for paletted image */
  181993. png_color_16 trans_values; /* transparent color for non-palette image */
  181994. #endif
  181995. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181996. /* The bKGD chunk gives the suggested image background color if the
  181997. * display program does not have its own background color and the image
  181998. * is needs to composited onto a background before display. The colors
  181999. * in "background" are normally in the same color space/depth as the
  182000. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182001. */
  182002. png_color_16 background;
  182003. #endif
  182004. #if defined(PNG_oFFs_SUPPORTED)
  182005. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182006. * and downwards from the top-left corner of the display, page, or other
  182007. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182008. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182009. */
  182010. png_int_32 x_offset; /* x offset on page */
  182011. png_int_32 y_offset; /* y offset on page */
  182012. png_byte offset_unit_type; /* offset units type */
  182013. #endif
  182014. #if defined(PNG_pHYs_SUPPORTED)
  182015. /* The pHYs chunk gives the physical pixel density of the image for
  182016. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182017. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182018. */
  182019. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182020. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182021. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182022. #endif
  182023. #if defined(PNG_hIST_SUPPORTED)
  182024. /* The hIST chunk contains the relative frequency or importance of the
  182025. * various palette entries, so that a viewer can intelligently select a
  182026. * reduced-color palette, if required. Data is an array of "num_palette"
  182027. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182028. * is non-zero.
  182029. */
  182030. png_uint_16p hist;
  182031. #endif
  182032. #ifdef PNG_cHRM_SUPPORTED
  182033. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182034. * on which the PNG was created. This data allows the viewer to do gamut
  182035. * mapping of the input image to ensure that the viewer sees the same
  182036. * colors in the image as the creator. Values are in the range
  182037. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182038. */
  182039. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182040. float x_white;
  182041. float y_white;
  182042. float x_red;
  182043. float y_red;
  182044. float x_green;
  182045. float y_green;
  182046. float x_blue;
  182047. float y_blue;
  182048. #endif
  182049. #endif
  182050. #if defined(PNG_pCAL_SUPPORTED)
  182051. /* The pCAL chunk describes a transformation between the stored pixel
  182052. * values and original physical data values used to create the image.
  182053. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182054. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182055. * (possibly non-linear) transformation function given by "pcal_type"
  182056. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182057. * defines below, and the PNG-Group's PNG extensions document for a
  182058. * complete description of the transformations and how they should be
  182059. * implemented, and for a description of the ASCII parameter strings.
  182060. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182061. */
  182062. png_charp pcal_purpose; /* pCAL chunk description string */
  182063. png_int_32 pcal_X0; /* minimum value */
  182064. png_int_32 pcal_X1; /* maximum value */
  182065. png_charp pcal_units; /* Latin-1 string giving physical units */
  182066. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182067. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182068. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182069. #endif
  182070. /* New members added in libpng-1.0.6 */
  182071. #ifdef PNG_FREE_ME_SUPPORTED
  182072. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182073. #endif
  182074. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182075. /* storage for unknown chunks that the library doesn't recognize. */
  182076. png_unknown_chunkp unknown_chunks;
  182077. png_size_t unknown_chunks_num;
  182078. #endif
  182079. #if defined(PNG_iCCP_SUPPORTED)
  182080. /* iCCP chunk data. */
  182081. png_charp iccp_name; /* profile name */
  182082. png_charp iccp_profile; /* International Color Consortium profile data */
  182083. /* Note to maintainer: should be png_bytep */
  182084. png_uint_32 iccp_proflen; /* ICC profile data length */
  182085. png_byte iccp_compression; /* Always zero */
  182086. #endif
  182087. #if defined(PNG_sPLT_SUPPORTED)
  182088. /* data on sPLT chunks (there may be more than one). */
  182089. png_sPLT_tp splt_palettes;
  182090. png_uint_32 splt_palettes_num;
  182091. #endif
  182092. #if defined(PNG_sCAL_SUPPORTED)
  182093. /* The sCAL chunk describes the actual physical dimensions of the
  182094. * subject matter of the graphic. The chunk contains a unit specification
  182095. * a byte value, and two ASCII strings representing floating-point
  182096. * values. The values are width and height corresponsing to one pixel
  182097. * in the image. This external representation is converted to double
  182098. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182099. */
  182100. png_byte scal_unit; /* unit of physical scale */
  182101. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182102. double scal_pixel_width; /* width of one pixel */
  182103. double scal_pixel_height; /* height of one pixel */
  182104. #endif
  182105. #ifdef PNG_FIXED_POINT_SUPPORTED
  182106. png_charp scal_s_width; /* string containing height */
  182107. png_charp scal_s_height; /* string containing width */
  182108. #endif
  182109. #endif
  182110. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182111. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182112. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182113. png_bytepp row_pointers; /* the image bits */
  182114. #endif
  182115. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182116. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182117. #endif
  182118. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182119. png_fixed_point int_x_white;
  182120. png_fixed_point int_y_white;
  182121. png_fixed_point int_x_red;
  182122. png_fixed_point int_y_red;
  182123. png_fixed_point int_x_green;
  182124. png_fixed_point int_y_green;
  182125. png_fixed_point int_x_blue;
  182126. png_fixed_point int_y_blue;
  182127. #endif
  182128. } png_info;
  182129. typedef png_info FAR * png_infop;
  182130. typedef png_info FAR * FAR * png_infopp;
  182131. /* Maximum positive integer used in PNG is (2^31)-1 */
  182132. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182133. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182134. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182135. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182136. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182137. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182138. #endif
  182139. /* These describe the color_type field in png_info. */
  182140. /* color type masks */
  182141. #define PNG_COLOR_MASK_PALETTE 1
  182142. #define PNG_COLOR_MASK_COLOR 2
  182143. #define PNG_COLOR_MASK_ALPHA 4
  182144. /* color types. Note that not all combinations are legal */
  182145. #define PNG_COLOR_TYPE_GRAY 0
  182146. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182147. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182148. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182149. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182150. /* aliases */
  182151. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182152. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182153. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182154. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182155. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182156. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182157. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182158. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182159. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182160. /* These are for the interlacing type. These values should NOT be changed. */
  182161. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182162. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182163. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182164. /* These are for the oFFs chunk. These values should NOT be changed. */
  182165. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182166. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182167. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182168. /* These are for the pCAL chunk. These values should NOT be changed. */
  182169. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182170. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182171. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182172. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182173. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182174. /* These are for the sCAL chunk. These values should NOT be changed. */
  182175. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182176. #define PNG_SCALE_METER 1 /* meters per pixel */
  182177. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182178. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182179. /* These are for the pHYs chunk. These values should NOT be changed. */
  182180. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182181. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182182. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182183. /* These are for the sRGB chunk. These values should NOT be changed. */
  182184. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182185. #define PNG_sRGB_INTENT_RELATIVE 1
  182186. #define PNG_sRGB_INTENT_SATURATION 2
  182187. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182188. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182189. /* This is for text chunks */
  182190. #define PNG_KEYWORD_MAX_LENGTH 79
  182191. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182192. #define PNG_MAX_PALETTE_LENGTH 256
  182193. /* These determine if an ancillary chunk's data has been successfully read
  182194. * from the PNG header, or if the application has filled in the corresponding
  182195. * data in the info_struct to be written into the output file. The values
  182196. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182197. */
  182198. #define PNG_INFO_gAMA 0x0001
  182199. #define PNG_INFO_sBIT 0x0002
  182200. #define PNG_INFO_cHRM 0x0004
  182201. #define PNG_INFO_PLTE 0x0008
  182202. #define PNG_INFO_tRNS 0x0010
  182203. #define PNG_INFO_bKGD 0x0020
  182204. #define PNG_INFO_hIST 0x0040
  182205. #define PNG_INFO_pHYs 0x0080
  182206. #define PNG_INFO_oFFs 0x0100
  182207. #define PNG_INFO_tIME 0x0200
  182208. #define PNG_INFO_pCAL 0x0400
  182209. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182210. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182211. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182212. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182213. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182214. /* This is used for the transformation routines, as some of them
  182215. * change these values for the row. It also should enable using
  182216. * the routines for other purposes.
  182217. */
  182218. typedef struct png_row_info_struct
  182219. {
  182220. png_uint_32 width; /* width of row */
  182221. png_uint_32 rowbytes; /* number of bytes in row */
  182222. png_byte color_type; /* color type of row */
  182223. png_byte bit_depth; /* bit depth of row */
  182224. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182225. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182226. } png_row_info;
  182227. typedef png_row_info FAR * png_row_infop;
  182228. typedef png_row_info FAR * FAR * png_row_infopp;
  182229. /* These are the function types for the I/O functions and for the functions
  182230. * that allow the user to override the default I/O functions with his or her
  182231. * own. The png_error_ptr type should match that of user-supplied warning
  182232. * and error functions, while the png_rw_ptr type should match that of the
  182233. * user read/write data functions.
  182234. */
  182235. typedef struct png_struct_def png_struct;
  182236. typedef png_struct FAR * png_structp;
  182237. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182238. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182239. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182240. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182241. int));
  182242. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182243. int));
  182244. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182245. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182246. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182247. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182248. png_uint_32, int));
  182249. #endif
  182250. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182251. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182252. defined(PNG_LEGACY_SUPPORTED)
  182253. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182254. png_row_infop, png_bytep));
  182255. #endif
  182256. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182257. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182258. #endif
  182259. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182260. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182261. #endif
  182262. /* Transform masks for the high-level interface */
  182263. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182264. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182265. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182266. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182267. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182268. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182269. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182270. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182271. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182272. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182273. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182274. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182275. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182276. /* Flags for MNG supported features */
  182277. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182278. #define PNG_FLAG_MNG_FILTER_64 0x04
  182279. #define PNG_ALL_MNG_FEATURES 0x05
  182280. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182281. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182282. /* The structure that holds the information to read and write PNG files.
  182283. * The only people who need to care about what is inside of this are the
  182284. * people who will be modifying the library for their own special needs.
  182285. * It should NOT be accessed directly by an application, except to store
  182286. * the jmp_buf.
  182287. */
  182288. struct png_struct_def
  182289. {
  182290. #ifdef PNG_SETJMP_SUPPORTED
  182291. jmp_buf jmpbuf; /* used in png_error */
  182292. #endif
  182293. png_error_ptr error_fn; /* function for printing errors and aborting */
  182294. png_error_ptr warning_fn; /* function for printing warnings */
  182295. png_voidp error_ptr; /* user supplied struct for error functions */
  182296. png_rw_ptr write_data_fn; /* function for writing output data */
  182297. png_rw_ptr read_data_fn; /* function for reading input data */
  182298. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182299. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182300. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182301. #endif
  182302. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182303. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182304. #endif
  182305. /* These were added in libpng-1.0.2 */
  182306. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182307. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182308. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182309. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182310. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182311. png_byte user_transform_channels; /* channels in user transformed pixels */
  182312. #endif
  182313. #endif
  182314. png_uint_32 mode; /* tells us where we are in the PNG file */
  182315. png_uint_32 flags; /* flags indicating various things to libpng */
  182316. png_uint_32 transformations; /* which transformations to perform */
  182317. z_stream zstream; /* pointer to decompression structure (below) */
  182318. png_bytep zbuf; /* buffer for zlib */
  182319. png_size_t zbuf_size; /* size of zbuf */
  182320. int zlib_level; /* holds zlib compression level */
  182321. int zlib_method; /* holds zlib compression method */
  182322. int zlib_window_bits; /* holds zlib compression window bits */
  182323. int zlib_mem_level; /* holds zlib compression memory level */
  182324. int zlib_strategy; /* holds zlib compression strategy */
  182325. png_uint_32 width; /* width of image in pixels */
  182326. png_uint_32 height; /* height of image in pixels */
  182327. png_uint_32 num_rows; /* number of rows in current pass */
  182328. png_uint_32 usr_width; /* width of row at start of write */
  182329. png_uint_32 rowbytes; /* size of row in bytes */
  182330. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182331. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182332. png_uint_32 row_number; /* current row in interlace pass */
  182333. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182334. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182335. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182336. png_bytep up_row; /* buffer to save "up" row when filtering */
  182337. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182338. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182339. png_row_info row_info; /* used for transformation routines */
  182340. png_uint_32 idat_size; /* current IDAT size for read */
  182341. png_uint_32 crc; /* current chunk CRC value */
  182342. png_colorp palette; /* palette from the input file */
  182343. png_uint_16 num_palette; /* number of color entries in palette */
  182344. png_uint_16 num_trans; /* number of transparency values */
  182345. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182346. png_byte compression; /* file compression type (always 0) */
  182347. png_byte filter; /* file filter type (always 0) */
  182348. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182349. png_byte pass; /* current interlace pass (0 - 6) */
  182350. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182351. png_byte color_type; /* color type of file */
  182352. png_byte bit_depth; /* bit depth of file */
  182353. png_byte usr_bit_depth; /* bit depth of users row */
  182354. png_byte pixel_depth; /* number of bits per pixel */
  182355. png_byte channels; /* number of channels in file */
  182356. png_byte usr_channels; /* channels at start of write */
  182357. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182358. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182359. #ifdef PNG_LEGACY_SUPPORTED
  182360. png_byte filler; /* filler byte for pixel expansion */
  182361. #else
  182362. png_uint_16 filler; /* filler bytes for pixel expansion */
  182363. #endif
  182364. #endif
  182365. #if defined(PNG_bKGD_SUPPORTED)
  182366. png_byte background_gamma_type;
  182367. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182368. float background_gamma;
  182369. # endif
  182370. png_color_16 background; /* background color in screen gamma space */
  182371. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182372. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182373. #endif
  182374. #endif /* PNG_bKGD_SUPPORTED */
  182375. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182376. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182377. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182378. png_uint_32 flush_rows; /* number of rows written since last flush */
  182379. #endif
  182380. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182381. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182382. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182383. float gamma; /* file gamma value */
  182384. float screen_gamma; /* screen gamma value (display_exponent) */
  182385. #endif
  182386. #endif
  182387. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182388. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182389. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182390. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182391. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182392. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182393. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182394. #endif
  182395. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182396. png_color_8 sig_bit; /* significant bits in each available channel */
  182397. #endif
  182398. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182399. png_color_8 shift; /* shift for significant bit tranformation */
  182400. #endif
  182401. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182402. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182403. png_bytep trans; /* transparency values for paletted files */
  182404. png_color_16 trans_values; /* transparency values for non-paletted files */
  182405. #endif
  182406. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182407. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182408. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182409. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182410. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182411. png_progressive_end_ptr end_fn; /* called after image is complete */
  182412. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182413. png_bytep save_buffer; /* buffer for previously read data */
  182414. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182415. png_bytep current_buffer; /* buffer for recently used data */
  182416. png_uint_32 push_length; /* size of current input chunk */
  182417. png_uint_32 skip_length; /* bytes to skip in input data */
  182418. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182419. png_size_t save_buffer_max; /* total size of save_buffer */
  182420. png_size_t buffer_size; /* total amount of available input data */
  182421. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182422. int process_mode; /* what push library is currently doing */
  182423. int cur_palette; /* current push library palette index */
  182424. # if defined(PNG_TEXT_SUPPORTED)
  182425. png_size_t current_text_size; /* current size of text input data */
  182426. png_size_t current_text_left; /* how much text left to read in input */
  182427. png_charp current_text; /* current text chunk buffer */
  182428. png_charp current_text_ptr; /* current location in current_text */
  182429. # endif /* PNG_TEXT_SUPPORTED */
  182430. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182431. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182432. /* for the Borland special 64K segment handler */
  182433. png_bytepp offset_table_ptr;
  182434. png_bytep offset_table;
  182435. png_uint_16 offset_table_number;
  182436. png_uint_16 offset_table_count;
  182437. png_uint_16 offset_table_count_free;
  182438. #endif
  182439. #if defined(PNG_READ_DITHER_SUPPORTED)
  182440. png_bytep palette_lookup; /* lookup table for dithering */
  182441. png_bytep dither_index; /* index translation for palette files */
  182442. #endif
  182443. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182444. png_uint_16p hist; /* histogram */
  182445. #endif
  182446. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182447. png_byte heuristic_method; /* heuristic for row filter selection */
  182448. png_byte num_prev_filters; /* number of weights for previous rows */
  182449. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182450. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182451. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182452. png_uint_16p filter_costs; /* relative filter calculation cost */
  182453. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182454. #endif
  182455. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182456. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182457. #endif
  182458. /* New members added in libpng-1.0.6 */
  182459. #ifdef PNG_FREE_ME_SUPPORTED
  182460. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182461. #endif
  182462. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182463. png_voidp user_chunk_ptr;
  182464. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182465. #endif
  182466. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182467. int num_chunk_list;
  182468. png_bytep chunk_list;
  182469. #endif
  182470. /* New members added in libpng-1.0.3 */
  182471. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182472. png_byte rgb_to_gray_status;
  182473. /* These were changed from png_byte in libpng-1.0.6 */
  182474. png_uint_16 rgb_to_gray_red_coeff;
  182475. png_uint_16 rgb_to_gray_green_coeff;
  182476. png_uint_16 rgb_to_gray_blue_coeff;
  182477. #endif
  182478. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182479. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182480. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182481. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182482. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182483. #ifdef PNG_1_0_X
  182484. png_byte mng_features_permitted;
  182485. #else
  182486. png_uint_32 mng_features_permitted;
  182487. #endif /* PNG_1_0_X */
  182488. #endif
  182489. /* New member added in libpng-1.0.7 */
  182490. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182491. png_fixed_point int_gamma;
  182492. #endif
  182493. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182494. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182495. png_byte filter_type;
  182496. #endif
  182497. #if defined(PNG_1_0_X)
  182498. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182499. png_uint_32 row_buf_size;
  182500. #endif
  182501. /* New members added in libpng-1.2.0 */
  182502. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182503. # if !defined(PNG_1_0_X)
  182504. # if defined(PNG_MMX_CODE_SUPPORTED)
  182505. png_byte mmx_bitdepth_threshold;
  182506. png_uint_32 mmx_rowbytes_threshold;
  182507. # endif
  182508. png_uint_32 asm_flags;
  182509. # endif
  182510. #endif
  182511. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182512. #ifdef PNG_USER_MEM_SUPPORTED
  182513. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182514. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182515. png_free_ptr free_fn; /* function for freeing memory */
  182516. #endif
  182517. /* New member added in libpng-1.0.13 and 1.2.0 */
  182518. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182519. #if defined(PNG_READ_DITHER_SUPPORTED)
  182520. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182521. png_bytep dither_sort; /* working sort array */
  182522. png_bytep index_to_palette; /* where the original index currently is */
  182523. /* in the palette */
  182524. png_bytep palette_to_index; /* which original index points to this */
  182525. /* palette color */
  182526. #endif
  182527. /* New members added in libpng-1.0.16 and 1.2.6 */
  182528. png_byte compression_type;
  182529. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182530. png_uint_32 user_width_max;
  182531. png_uint_32 user_height_max;
  182532. #endif
  182533. /* New member added in libpng-1.0.25 and 1.2.17 */
  182534. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182535. /* storage for unknown chunk that the library doesn't recognize. */
  182536. png_unknown_chunk unknown_chunk;
  182537. #endif
  182538. };
  182539. /* This triggers a compiler error in png.c, if png.c and png.h
  182540. * do not agree upon the version number.
  182541. */
  182542. typedef png_structp version_1_2_21;
  182543. typedef png_struct FAR * FAR * png_structpp;
  182544. /* Here are the function definitions most commonly used. This is not
  182545. * the place to find out how to use libpng. See libpng.txt for the
  182546. * full explanation, see example.c for the summary. This just provides
  182547. * a simple one line description of the use of each function.
  182548. */
  182549. /* Returns the version number of the library */
  182550. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182551. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182552. * Handling more than 8 bytes from the beginning of the file is an error.
  182553. */
  182554. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182555. int num_bytes));
  182556. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182557. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182558. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182559. * start > 7 will always fail (ie return non-zero).
  182560. */
  182561. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182562. png_size_t num_to_check));
  182563. /* Simple signature checking function. This is the same as calling
  182564. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182565. */
  182566. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182567. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182568. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182569. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182570. png_error_ptr error_fn, png_error_ptr warn_fn));
  182571. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182572. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182573. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182574. png_error_ptr error_fn, png_error_ptr warn_fn));
  182575. #ifdef PNG_WRITE_SUPPORTED
  182576. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182577. PNGARG((png_structp png_ptr));
  182578. #endif
  182579. #ifdef PNG_WRITE_SUPPORTED
  182580. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182581. PNGARG((png_structp png_ptr, png_uint_32 size));
  182582. #endif
  182583. /* Reset the compression stream */
  182584. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182585. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182586. #ifdef PNG_USER_MEM_SUPPORTED
  182587. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182588. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182589. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182590. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182591. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182592. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182593. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182594. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182595. #endif
  182596. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182597. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182598. png_bytep chunk_name, png_bytep data, png_size_t length));
  182599. /* Write the start of a PNG chunk - length and chunk name. */
  182600. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182601. png_bytep chunk_name, png_uint_32 length));
  182602. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182603. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182604. png_bytep data, png_size_t length));
  182605. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182606. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182607. /* Allocate and initialize the info structure */
  182608. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182609. PNGARG((png_structp png_ptr));
  182610. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182611. /* Initialize the info structure (old interface - DEPRECATED) */
  182612. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182613. #undef png_info_init
  182614. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182615. png_sizeof(png_info));
  182616. #endif
  182617. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182618. png_size_t png_info_struct_size));
  182619. /* Writes all the PNG information before the image. */
  182620. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182621. png_infop info_ptr));
  182622. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182623. png_infop info_ptr));
  182624. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182625. /* read the information before the actual image data. */
  182626. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182627. png_infop info_ptr));
  182628. #endif
  182629. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182630. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182631. PNGARG((png_structp png_ptr, png_timep ptime));
  182632. #endif
  182633. #if !defined(_WIN32_WCE)
  182634. /* "time.h" functions are not supported on WindowsCE */
  182635. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182636. /* convert from a struct tm to png_time */
  182637. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182638. struct tm FAR * ttime));
  182639. /* convert from time_t to png_time. Uses gmtime() */
  182640. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182641. time_t ttime));
  182642. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182643. #endif /* _WIN32_WCE */
  182644. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182645. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182646. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182647. #if !defined(PNG_1_0_X)
  182648. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182649. png_ptr));
  182650. #endif
  182651. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182652. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182653. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182654. /* Deprecated */
  182655. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182656. #endif
  182657. #endif
  182658. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182659. /* Use blue, green, red order for pixels. */
  182660. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182661. #endif
  182662. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182663. /* Expand the grayscale to 24-bit RGB if necessary. */
  182664. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182665. #endif
  182666. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182667. /* Reduce RGB to grayscale. */
  182668. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182669. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182670. int error_action, double red, double green ));
  182671. #endif
  182672. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182673. int error_action, png_fixed_point red, png_fixed_point green ));
  182674. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182675. png_ptr));
  182676. #endif
  182677. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182678. png_colorp palette));
  182679. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182680. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182681. #endif
  182682. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182683. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182684. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182685. #endif
  182686. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182687. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182688. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182689. #endif
  182690. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182691. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182692. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182693. png_uint_32 filler, int flags));
  182694. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182695. #define PNG_FILLER_BEFORE 0
  182696. #define PNG_FILLER_AFTER 1
  182697. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182698. #if !defined(PNG_1_0_X)
  182699. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182700. png_uint_32 filler, int flags));
  182701. #endif
  182702. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182703. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182704. /* Swap bytes in 16-bit depth files. */
  182705. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182706. #endif
  182707. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182708. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182709. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182710. #endif
  182711. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182712. /* Swap packing order of pixels in bytes. */
  182713. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182714. #endif
  182715. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182716. /* Converts files to legal bit depths. */
  182717. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182718. png_color_8p true_bits));
  182719. #endif
  182720. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182721. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182722. /* Have the code handle the interlacing. Returns the number of passes. */
  182723. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182724. #endif
  182725. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182726. /* Invert monochrome files */
  182727. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182728. #endif
  182729. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182730. /* Handle alpha and tRNS by replacing with a background color. */
  182731. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182732. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182733. png_color_16p background_color, int background_gamma_code,
  182734. int need_expand, double background_gamma));
  182735. #endif
  182736. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182737. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182738. #define PNG_BACKGROUND_GAMMA_FILE 2
  182739. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182740. #endif
  182741. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182742. /* strip the second byte of information from a 16-bit depth file. */
  182743. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182744. #endif
  182745. #if defined(PNG_READ_DITHER_SUPPORTED)
  182746. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182747. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182748. png_colorp palette, int num_palette, int maximum_colors,
  182749. png_uint_16p histogram, int full_dither));
  182750. #endif
  182751. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182752. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182753. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182754. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182755. double screen_gamma, double default_file_gamma));
  182756. #endif
  182757. #endif
  182758. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182759. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182760. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182761. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182762. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182763. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182764. int empty_plte_permitted));
  182765. #endif
  182766. #endif
  182767. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182768. /* Set how many lines between output flushes - 0 for no flushing */
  182769. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182770. /* Flush the current PNG output buffer */
  182771. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182772. #endif
  182773. /* optional update palette with requested transformations */
  182774. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182775. /* optional call to update the users info structure */
  182776. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182777. png_infop info_ptr));
  182778. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182779. /* read one or more rows of image data. */
  182780. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182781. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182782. #endif
  182783. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182784. /* read a row of data. */
  182785. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182786. png_bytep row,
  182787. png_bytep display_row));
  182788. #endif
  182789. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182790. /* read the whole image into memory at once. */
  182791. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182792. png_bytepp image));
  182793. #endif
  182794. /* write a row of image data */
  182795. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182796. png_bytep row));
  182797. /* write a few rows of image data */
  182798. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182799. png_bytepp row, png_uint_32 num_rows));
  182800. /* write the image data */
  182801. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182802. png_bytepp image));
  182803. /* writes the end of the PNG file. */
  182804. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182805. png_infop info_ptr));
  182806. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182807. /* read the end of the PNG file. */
  182808. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182809. png_infop info_ptr));
  182810. #endif
  182811. /* free any memory associated with the png_info_struct */
  182812. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182813. png_infopp info_ptr_ptr));
  182814. /* free any memory associated with the png_struct and the png_info_structs */
  182815. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182816. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182817. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182818. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182819. png_infop end_info_ptr));
  182820. /* free any memory associated with the png_struct and the png_info_structs */
  182821. extern PNG_EXPORT(void,png_destroy_write_struct)
  182822. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182823. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182824. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182825. /* set the libpng method of handling chunk CRC errors */
  182826. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182827. int crit_action, int ancil_action));
  182828. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182829. * ancillary and critical chunks, and whether to use the data contained
  182830. * therein. Note that it is impossible to "discard" data in a critical
  182831. * chunk. For versions prior to 0.90, the action was always error/quit,
  182832. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182833. * chunks is warn/discard. These values should NOT be changed.
  182834. *
  182835. * value action:critical action:ancillary
  182836. */
  182837. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182838. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182839. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182840. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182841. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182842. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182843. /* These functions give the user control over the scan-line filtering in
  182844. * libpng and the compression methods used by zlib. These functions are
  182845. * mainly useful for testing, as the defaults should work with most users.
  182846. * Those users who are tight on memory or want faster performance at the
  182847. * expense of compression can modify them. See the compression library
  182848. * header file (zlib.h) for an explination of the compression functions.
  182849. */
  182850. /* set the filtering method(s) used by libpng. Currently, the only valid
  182851. * value for "method" is 0.
  182852. */
  182853. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182854. int filters));
  182855. /* Flags for png_set_filter() to say which filters to use. The flags
  182856. * are chosen so that they don't conflict with real filter types
  182857. * below, in case they are supplied instead of the #defined constants.
  182858. * These values should NOT be changed.
  182859. */
  182860. #define PNG_NO_FILTERS 0x00
  182861. #define PNG_FILTER_NONE 0x08
  182862. #define PNG_FILTER_SUB 0x10
  182863. #define PNG_FILTER_UP 0x20
  182864. #define PNG_FILTER_AVG 0x40
  182865. #define PNG_FILTER_PAETH 0x80
  182866. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182867. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182868. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182869. * These defines should NOT be changed.
  182870. */
  182871. #define PNG_FILTER_VALUE_NONE 0
  182872. #define PNG_FILTER_VALUE_SUB 1
  182873. #define PNG_FILTER_VALUE_UP 2
  182874. #define PNG_FILTER_VALUE_AVG 3
  182875. #define PNG_FILTER_VALUE_PAETH 4
  182876. #define PNG_FILTER_VALUE_LAST 5
  182877. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182878. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182879. * defines, either the default (minimum-sum-of-absolute-differences), or
  182880. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182881. *
  182882. * Weights are factors >= 1.0, indicating how important it is to keep the
  182883. * filter type consistent between rows. Larger numbers mean the current
  182884. * filter is that many times as likely to be the same as the "num_weights"
  182885. * previous filters. This is cumulative for each previous row with a weight.
  182886. * There needs to be "num_weights" values in "filter_weights", or it can be
  182887. * NULL if the weights aren't being specified. Weights have no influence on
  182888. * the selection of the first row filter. Well chosen weights can (in theory)
  182889. * improve the compression for a given image.
  182890. *
  182891. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182892. * filter type. Higher costs indicate more decoding expense, and are
  182893. * therefore less likely to be selected over a filter with lower computational
  182894. * costs. There needs to be a value in "filter_costs" for each valid filter
  182895. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182896. * setting the costs. Costs try to improve the speed of decompression without
  182897. * unduly increasing the compressed image size.
  182898. *
  182899. * A negative weight or cost indicates the default value is to be used, and
  182900. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182901. * The default values for both weights and costs are currently 1.0, but may
  182902. * change if good general weighting/cost heuristics can be found. If both
  182903. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182904. * to the UNWEIGHTED method, but with added encoding time/computation.
  182905. */
  182906. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182907. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182908. int heuristic_method, int num_weights, png_doublep filter_weights,
  182909. png_doublep filter_costs));
  182910. #endif
  182911. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182912. /* Heuristic used for row filter selection. These defines should NOT be
  182913. * changed.
  182914. */
  182915. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182916. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182917. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182918. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182919. /* Set the library compression level. Currently, valid values range from
  182920. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182921. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182922. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182923. * for PNG images, and do considerably fewer caclulations. In the future,
  182924. * these values may not correspond directly to the zlib compression levels.
  182925. */
  182926. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182927. int level));
  182928. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182929. PNGARG((png_structp png_ptr, int mem_level));
  182930. extern PNG_EXPORT(void,png_set_compression_strategy)
  182931. PNGARG((png_structp png_ptr, int strategy));
  182932. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182933. PNGARG((png_structp png_ptr, int window_bits));
  182934. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182935. int method));
  182936. /* These next functions are called for input/output, memory, and error
  182937. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182938. * and call standard C I/O routines such as fread(), fwrite(), and
  182939. * fprintf(). These functions can be made to use other I/O routines
  182940. * at run time for those applications that need to handle I/O in a
  182941. * different manner by calling png_set_???_fn(). See libpng.txt for
  182942. * more information.
  182943. */
  182944. #if !defined(PNG_NO_STDIO)
  182945. /* Initialize the input/output for the PNG file to the default functions. */
  182946. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182947. #endif
  182948. /* Replace the (error and abort), and warning functions with user
  182949. * supplied functions. If no messages are to be printed you must still
  182950. * write and use replacement functions. The replacement error_fn should
  182951. * still do a longjmp to the last setjmp location if you are using this
  182952. * method of error handling. If error_fn or warning_fn is NULL, the
  182953. * default function will be used.
  182954. */
  182955. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182956. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182957. /* Return the user pointer associated with the error functions */
  182958. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182959. /* Replace the default data output functions with a user supplied one(s).
  182960. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182961. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182962. * output_flush_fn will be ignored (and thus can be NULL).
  182963. */
  182964. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182965. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182966. /* Replace the default data input function with a user supplied one. */
  182967. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182968. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182969. /* Return the user pointer associated with the I/O functions */
  182970. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182971. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182972. png_read_status_ptr read_row_fn));
  182973. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182974. png_write_status_ptr write_row_fn));
  182975. #ifdef PNG_USER_MEM_SUPPORTED
  182976. /* Replace the default memory allocation functions with user supplied one(s). */
  182977. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182978. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182979. /* Return the user pointer associated with the memory functions */
  182980. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182981. #endif
  182982. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182983. defined(PNG_LEGACY_SUPPORTED)
  182984. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182985. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182986. #endif
  182987. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182988. defined(PNG_LEGACY_SUPPORTED)
  182989. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182990. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182991. #endif
  182992. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182993. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182994. defined(PNG_LEGACY_SUPPORTED)
  182995. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182996. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182997. int user_transform_channels));
  182998. /* Return the user pointer associated with the user transform functions */
  182999. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183000. PNGARG((png_structp png_ptr));
  183001. #endif
  183002. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183003. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183004. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183005. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183006. png_ptr));
  183007. #endif
  183008. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183009. /* Sets the function callbacks for the push reader, and a pointer to a
  183010. * user-defined structure available to the callback functions.
  183011. */
  183012. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183013. png_voidp progressive_ptr,
  183014. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183015. png_progressive_end_ptr end_fn));
  183016. /* returns the user pointer associated with the push read functions */
  183017. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183018. PNGARG((png_structp png_ptr));
  183019. /* function to be called when data becomes available */
  183020. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183021. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183022. /* function that combines rows. Not very much different than the
  183023. * png_combine_row() call. Is this even used?????
  183024. */
  183025. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183026. png_bytep old_row, png_bytep new_row));
  183027. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183028. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183029. png_uint_32 size));
  183030. #if defined(PNG_1_0_X)
  183031. # define png_malloc_warn png_malloc
  183032. #else
  183033. /* Added at libpng version 1.2.4 */
  183034. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183035. png_uint_32 size));
  183036. #endif
  183037. /* frees a pointer allocated by png_malloc() */
  183038. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183039. #if defined(PNG_1_0_X)
  183040. /* Function to allocate memory for zlib. */
  183041. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183042. uInt size));
  183043. /* Function to free memory for zlib */
  183044. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183045. #endif
  183046. /* Free data that was allocated internally */
  183047. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183048. png_infop info_ptr, png_uint_32 free_me, int num));
  183049. #ifdef PNG_FREE_ME_SUPPORTED
  183050. /* Reassign responsibility for freeing existing data, whether allocated
  183051. * by libpng or by the application */
  183052. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183053. png_infop info_ptr, int freer, png_uint_32 mask));
  183054. #endif
  183055. /* assignments for png_data_freer */
  183056. #define PNG_DESTROY_WILL_FREE_DATA 1
  183057. #define PNG_SET_WILL_FREE_DATA 1
  183058. #define PNG_USER_WILL_FREE_DATA 2
  183059. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183060. #define PNG_FREE_HIST 0x0008
  183061. #define PNG_FREE_ICCP 0x0010
  183062. #define PNG_FREE_SPLT 0x0020
  183063. #define PNG_FREE_ROWS 0x0040
  183064. #define PNG_FREE_PCAL 0x0080
  183065. #define PNG_FREE_SCAL 0x0100
  183066. #define PNG_FREE_UNKN 0x0200
  183067. #define PNG_FREE_LIST 0x0400
  183068. #define PNG_FREE_PLTE 0x1000
  183069. #define PNG_FREE_TRNS 0x2000
  183070. #define PNG_FREE_TEXT 0x4000
  183071. #define PNG_FREE_ALL 0x7fff
  183072. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183073. #ifdef PNG_USER_MEM_SUPPORTED
  183074. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183075. png_uint_32 size));
  183076. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183077. png_voidp ptr));
  183078. #endif
  183079. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183080. png_voidp s1, png_voidp s2, png_uint_32 size));
  183081. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183082. png_voidp s1, int value, png_uint_32 size));
  183083. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183084. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183085. int check));
  183086. #endif /* USE_FAR_KEYWORD */
  183087. #ifndef PNG_NO_ERROR_TEXT
  183088. /* Fatal error in PNG image of libpng - can't continue */
  183089. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183090. png_const_charp error_message));
  183091. /* The same, but the chunk name is prepended to the error string. */
  183092. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183093. png_const_charp error_message));
  183094. #else
  183095. /* Fatal error in PNG image of libpng - can't continue */
  183096. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183097. #endif
  183098. #ifndef PNG_NO_WARNINGS
  183099. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183100. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183101. png_const_charp warning_message));
  183102. #ifdef PNG_READ_SUPPORTED
  183103. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183104. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183105. png_const_charp warning_message));
  183106. #endif /* PNG_READ_SUPPORTED */
  183107. #endif /* PNG_NO_WARNINGS */
  183108. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183109. * Similarly, the png_get_<chunk> calls are used to read values from the
  183110. * png_info_struct, either storing the parameters in the passed variables, or
  183111. * setting pointers into the png_info_struct where the data is stored. The
  183112. * png_get_<chunk> functions return a non-zero value if the data was available
  183113. * in info_ptr, or return zero and do not change any of the parameters if the
  183114. * data was not available.
  183115. *
  183116. * These functions should be used instead of directly accessing png_info
  183117. * to avoid problems with future changes in the size and internal layout of
  183118. * png_info_struct.
  183119. */
  183120. /* Returns "flag" if chunk data is valid in info_ptr. */
  183121. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183122. png_infop info_ptr, png_uint_32 flag));
  183123. /* Returns number of bytes needed to hold a transformed row. */
  183124. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183125. png_infop info_ptr));
  183126. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183127. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183128. returned from png_read_png(). */
  183129. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183130. png_infop info_ptr));
  183131. /* Set row_pointers, which is an array of pointers to scanlines for use
  183132. by png_write_png(). */
  183133. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183134. png_infop info_ptr, png_bytepp row_pointers));
  183135. #endif
  183136. /* Returns number of color channels in image. */
  183137. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183138. png_infop info_ptr));
  183139. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183140. /* Returns image width in pixels. */
  183141. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183142. png_ptr, png_infop info_ptr));
  183143. /* Returns image height in pixels. */
  183144. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183145. png_ptr, png_infop info_ptr));
  183146. /* Returns image bit_depth. */
  183147. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183148. png_ptr, png_infop info_ptr));
  183149. /* Returns image color_type. */
  183150. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183151. png_ptr, png_infop info_ptr));
  183152. /* Returns image filter_type. */
  183153. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183154. png_ptr, png_infop info_ptr));
  183155. /* Returns image interlace_type. */
  183156. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183157. png_ptr, png_infop info_ptr));
  183158. /* Returns image compression_type. */
  183159. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183160. png_ptr, png_infop info_ptr));
  183161. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183162. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183163. png_ptr, png_infop info_ptr));
  183164. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183165. png_ptr, png_infop info_ptr));
  183166. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183167. png_ptr, png_infop info_ptr));
  183168. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183169. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183170. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183171. png_ptr, png_infop info_ptr));
  183172. #endif
  183173. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183174. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183175. png_ptr, png_infop info_ptr));
  183176. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183177. png_ptr, png_infop info_ptr));
  183178. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183179. png_ptr, png_infop info_ptr));
  183180. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183181. png_ptr, png_infop info_ptr));
  183182. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183183. /* Returns pointer to signature string read from PNG header */
  183184. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183185. png_infop info_ptr));
  183186. #if defined(PNG_bKGD_SUPPORTED)
  183187. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183188. png_infop info_ptr, png_color_16p *background));
  183189. #endif
  183190. #if defined(PNG_bKGD_SUPPORTED)
  183191. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183192. png_infop info_ptr, png_color_16p background));
  183193. #endif
  183194. #if defined(PNG_cHRM_SUPPORTED)
  183195. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183196. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183197. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183198. double *red_y, double *green_x, double *green_y, double *blue_x,
  183199. double *blue_y));
  183200. #endif
  183201. #ifdef PNG_FIXED_POINT_SUPPORTED
  183202. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183203. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183204. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183205. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183206. *int_blue_x, png_fixed_point *int_blue_y));
  183207. #endif
  183208. #endif
  183209. #if defined(PNG_cHRM_SUPPORTED)
  183210. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183211. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183212. png_infop info_ptr, double white_x, double white_y, double red_x,
  183213. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183214. #endif
  183215. #ifdef PNG_FIXED_POINT_SUPPORTED
  183216. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183217. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183218. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183219. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183220. png_fixed_point int_blue_y));
  183221. #endif
  183222. #endif
  183223. #if defined(PNG_gAMA_SUPPORTED)
  183224. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183225. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183226. png_infop info_ptr, double *file_gamma));
  183227. #endif
  183228. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183229. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183230. #endif
  183231. #if defined(PNG_gAMA_SUPPORTED)
  183232. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183233. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183234. png_infop info_ptr, double file_gamma));
  183235. #endif
  183236. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183237. png_infop info_ptr, png_fixed_point int_file_gamma));
  183238. #endif
  183239. #if defined(PNG_hIST_SUPPORTED)
  183240. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183241. png_infop info_ptr, png_uint_16p *hist));
  183242. #endif
  183243. #if defined(PNG_hIST_SUPPORTED)
  183244. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183245. png_infop info_ptr, png_uint_16p hist));
  183246. #endif
  183247. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183248. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183249. int *bit_depth, int *color_type, int *interlace_method,
  183250. int *compression_method, int *filter_method));
  183251. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183252. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183253. int color_type, int interlace_method, int compression_method,
  183254. int filter_method));
  183255. #if defined(PNG_oFFs_SUPPORTED)
  183256. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183257. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183258. int *unit_type));
  183259. #endif
  183260. #if defined(PNG_oFFs_SUPPORTED)
  183261. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183262. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183263. int unit_type));
  183264. #endif
  183265. #if defined(PNG_pCAL_SUPPORTED)
  183266. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183267. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183268. int *type, int *nparams, png_charp *units, png_charpp *params));
  183269. #endif
  183270. #if defined(PNG_pCAL_SUPPORTED)
  183271. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183272. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183273. int type, int nparams, png_charp units, png_charpp params));
  183274. #endif
  183275. #if defined(PNG_pHYs_SUPPORTED)
  183276. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183277. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183278. #endif
  183279. #if defined(PNG_pHYs_SUPPORTED)
  183280. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183281. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183282. #endif
  183283. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183284. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183285. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183286. png_infop info_ptr, png_colorp palette, int num_palette));
  183287. #if defined(PNG_sBIT_SUPPORTED)
  183288. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183289. png_infop info_ptr, png_color_8p *sig_bit));
  183290. #endif
  183291. #if defined(PNG_sBIT_SUPPORTED)
  183292. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183293. png_infop info_ptr, png_color_8p sig_bit));
  183294. #endif
  183295. #if defined(PNG_sRGB_SUPPORTED)
  183296. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183297. png_infop info_ptr, int *intent));
  183298. #endif
  183299. #if defined(PNG_sRGB_SUPPORTED)
  183300. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183301. png_infop info_ptr, int intent));
  183302. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183303. png_infop info_ptr, int intent));
  183304. #endif
  183305. #if defined(PNG_iCCP_SUPPORTED)
  183306. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183307. png_infop info_ptr, png_charpp name, int *compression_type,
  183308. png_charpp profile, png_uint_32 *proflen));
  183309. /* Note to maintainer: profile should be png_bytepp */
  183310. #endif
  183311. #if defined(PNG_iCCP_SUPPORTED)
  183312. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183313. png_infop info_ptr, png_charp name, int compression_type,
  183314. png_charp profile, png_uint_32 proflen));
  183315. /* Note to maintainer: profile should be png_bytep */
  183316. #endif
  183317. #if defined(PNG_sPLT_SUPPORTED)
  183318. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183319. png_infop info_ptr, png_sPLT_tpp entries));
  183320. #endif
  183321. #if defined(PNG_sPLT_SUPPORTED)
  183322. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183323. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183324. #endif
  183325. #if defined(PNG_TEXT_SUPPORTED)
  183326. /* png_get_text also returns the number of text chunks in *num_text */
  183327. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183328. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183329. #endif
  183330. /*
  183331. * Note while png_set_text() will accept a structure whose text,
  183332. * language, and translated keywords are NULL pointers, the structure
  183333. * returned by png_get_text will always contain regular
  183334. * zero-terminated C strings. They might be empty strings but
  183335. * they will never be NULL pointers.
  183336. */
  183337. #if defined(PNG_TEXT_SUPPORTED)
  183338. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183339. png_infop info_ptr, png_textp text_ptr, int num_text));
  183340. #endif
  183341. #if defined(PNG_tIME_SUPPORTED)
  183342. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183343. png_infop info_ptr, png_timep *mod_time));
  183344. #endif
  183345. #if defined(PNG_tIME_SUPPORTED)
  183346. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183347. png_infop info_ptr, png_timep mod_time));
  183348. #endif
  183349. #if defined(PNG_tRNS_SUPPORTED)
  183350. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183351. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183352. png_color_16p *trans_values));
  183353. #endif
  183354. #if defined(PNG_tRNS_SUPPORTED)
  183355. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183356. png_infop info_ptr, png_bytep trans, int num_trans,
  183357. png_color_16p trans_values));
  183358. #endif
  183359. #if defined(PNG_tRNS_SUPPORTED)
  183360. #endif
  183361. #if defined(PNG_sCAL_SUPPORTED)
  183362. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183363. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183364. png_infop info_ptr, int *unit, double *width, double *height));
  183365. #else
  183366. #ifdef PNG_FIXED_POINT_SUPPORTED
  183367. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183368. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183369. #endif
  183370. #endif
  183371. #endif /* PNG_sCAL_SUPPORTED */
  183372. #if defined(PNG_sCAL_SUPPORTED)
  183373. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183374. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183375. png_infop info_ptr, int unit, double width, double height));
  183376. #else
  183377. #ifdef PNG_FIXED_POINT_SUPPORTED
  183378. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183379. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183380. #endif
  183381. #endif
  183382. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183383. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183384. /* provide a list of chunks and how they are to be handled, if the built-in
  183385. handling or default unknown chunk handling is not desired. Any chunks not
  183386. listed will be handled in the default manner. The IHDR and IEND chunks
  183387. must not be listed.
  183388. keep = 0: follow default behaviour
  183389. = 1: do not keep
  183390. = 2: keep only if safe-to-copy
  183391. = 3: keep even if unsafe-to-copy
  183392. */
  183393. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183394. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183395. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183396. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183397. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183398. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183399. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183400. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183401. #endif
  183402. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183403. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183404. chunk_name));
  183405. #endif
  183406. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183407. If you need to turn it off for a chunk that your application has freed,
  183408. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183409. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183410. png_infop info_ptr, int mask));
  183411. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183412. /* The "params" pointer is currently not used and is for future expansion. */
  183413. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183414. png_infop info_ptr,
  183415. int transforms,
  183416. png_voidp params));
  183417. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183418. png_infop info_ptr,
  183419. int transforms,
  183420. png_voidp params));
  183421. #endif
  183422. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183423. * numbers for PNG_DEBUG mean more debugging information. This has
  183424. * only been added since version 0.95 so it is not implemented throughout
  183425. * libpng yet, but more support will be added as needed.
  183426. */
  183427. #ifdef PNG_DEBUG
  183428. #if (PNG_DEBUG > 0)
  183429. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183430. #include <crtdbg.h>
  183431. #if (PNG_DEBUG > 1)
  183432. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183433. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183434. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183435. #endif
  183436. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183437. #ifndef PNG_DEBUG_FILE
  183438. #define PNG_DEBUG_FILE stderr
  183439. #endif /* PNG_DEBUG_FILE */
  183440. #if (PNG_DEBUG > 1)
  183441. #define png_debug(l,m) \
  183442. { \
  183443. int num_tabs=l; \
  183444. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183445. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183446. }
  183447. #define png_debug1(l,m,p1) \
  183448. { \
  183449. int num_tabs=l; \
  183450. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183451. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183452. }
  183453. #define png_debug2(l,m,p1,p2) \
  183454. { \
  183455. int num_tabs=l; \
  183456. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183457. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183458. }
  183459. #endif /* (PNG_DEBUG > 1) */
  183460. #endif /* _MSC_VER */
  183461. #endif /* (PNG_DEBUG > 0) */
  183462. #endif /* PNG_DEBUG */
  183463. #ifndef png_debug
  183464. #define png_debug(l, m)
  183465. #endif
  183466. #ifndef png_debug1
  183467. #define png_debug1(l, m, p1)
  183468. #endif
  183469. #ifndef png_debug2
  183470. #define png_debug2(l, m, p1, p2)
  183471. #endif
  183472. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183473. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183474. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183475. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183476. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183477. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183478. png_ptr, png_uint_32 mng_features_permitted));
  183479. #endif
  183480. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183481. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183482. #define PNG_HANDLE_CHUNK_NEVER 1
  183483. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183484. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183485. /* Added to version 1.2.0 */
  183486. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183487. #if defined(PNG_MMX_CODE_SUPPORTED)
  183488. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183489. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183490. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183491. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183492. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183493. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183494. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183495. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183496. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183497. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183498. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183499. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183500. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183501. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183502. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183503. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183504. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183505. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183506. | PNG_MMX_READ_FLAGS \
  183507. | PNG_MMX_WRITE_FLAGS )
  183508. #define PNG_SELECT_READ 1
  183509. #define PNG_SELECT_WRITE 2
  183510. #endif /* PNG_MMX_CODE_SUPPORTED */
  183511. #if !defined(PNG_1_0_X)
  183512. /* pngget.c */
  183513. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183514. PNGARG((int flag_select, int *compilerID));
  183515. /* pngget.c */
  183516. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183517. PNGARG((int flag_select));
  183518. /* pngget.c */
  183519. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183520. PNGARG((png_structp png_ptr));
  183521. /* pngget.c */
  183522. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183523. PNGARG((png_structp png_ptr));
  183524. /* pngget.c */
  183525. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183526. PNGARG((png_structp png_ptr));
  183527. /* pngset.c */
  183528. extern PNG_EXPORT(void,png_set_asm_flags)
  183529. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183530. /* pngset.c */
  183531. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183532. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183533. png_uint_32 mmx_rowbytes_threshold));
  183534. #endif /* PNG_1_0_X */
  183535. #if !defined(PNG_1_0_X)
  183536. /* png.c, pnggccrd.c, or pngvcrd.c */
  183537. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183538. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183539. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183540. * messages before passing them to the error or warning handler. */
  183541. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183542. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183543. png_ptr, png_uint_32 strip_mode));
  183544. #endif
  183545. #endif /* PNG_1_0_X */
  183546. /* Added at libpng-1.2.6 */
  183547. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183548. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183549. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183550. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183551. png_ptr));
  183552. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183553. png_ptr));
  183554. #endif
  183555. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183556. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183557. /* With these routines we avoid an integer divide, which will be slower on
  183558. * most machines. However, it does take more operations than the corresponding
  183559. * divide method, so it may be slower on a few RISC systems. There are two
  183560. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183561. *
  183562. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183563. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183564. * standard method.
  183565. *
  183566. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183567. */
  183568. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183569. # define png_composite(composite, fg, alpha, bg) \
  183570. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183571. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183572. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183573. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183574. # define png_composite_16(composite, fg, alpha, bg) \
  183575. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183576. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183577. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183578. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183579. #else /* standard method using integer division */
  183580. # define png_composite(composite, fg, alpha, bg) \
  183581. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183582. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183583. (png_uint_16)127) / 255)
  183584. # define png_composite_16(composite, fg, alpha, bg) \
  183585. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183586. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183587. (png_uint_32)32767) / (png_uint_32)65535L)
  183588. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183589. /* Inline macros to do direct reads of bytes from the input buffer. These
  183590. * require that you are using an architecture that uses PNG byte ordering
  183591. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183592. * in big-endian mode and 680x0 are the only ones that will support this.
  183593. * The x86 line of processors definitely do not. The png_get_int_32()
  183594. * routine also assumes we are using two's complement format for negative
  183595. * values, which is almost certainly true.
  183596. */
  183597. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183598. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183599. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183600. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183601. #else
  183602. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183603. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183604. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183605. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183606. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183607. PNGARG((png_structp png_ptr, png_bytep buf));
  183608. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183609. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183610. */
  183611. extern PNG_EXPORT(void,png_save_uint_32)
  183612. PNGARG((png_bytep buf, png_uint_32 i));
  183613. extern PNG_EXPORT(void,png_save_int_32)
  183614. PNGARG((png_bytep buf, png_int_32 i));
  183615. /* Place a 16-bit number into a buffer in PNG byte order.
  183616. * The parameter is declared unsigned int, not png_uint_16,
  183617. * just to avoid potential problems on pre-ANSI C compilers.
  183618. */
  183619. extern PNG_EXPORT(void,png_save_uint_16)
  183620. PNGARG((png_bytep buf, unsigned int i));
  183621. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183622. /* ************************************************************************* */
  183623. /* These next functions are used internally in the code. They generally
  183624. * shouldn't be used unless you are writing code to add or replace some
  183625. * functionality in libpng. More information about most functions can
  183626. * be found in the files where the functions are located.
  183627. */
  183628. /* Various modes of operation, that are visible to applications because
  183629. * they are used for unknown chunk location.
  183630. */
  183631. #define PNG_HAVE_IHDR 0x01
  183632. #define PNG_HAVE_PLTE 0x02
  183633. #define PNG_HAVE_IDAT 0x04
  183634. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183635. #define PNG_HAVE_IEND 0x10
  183636. #if defined(PNG_INTERNAL)
  183637. /* More modes of operation. Note that after an init, mode is set to
  183638. * zero automatically when the structure is created.
  183639. */
  183640. #define PNG_HAVE_gAMA 0x20
  183641. #define PNG_HAVE_cHRM 0x40
  183642. #define PNG_HAVE_sRGB 0x80
  183643. #define PNG_HAVE_CHUNK_HEADER 0x100
  183644. #define PNG_WROTE_tIME 0x200
  183645. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183646. #define PNG_BACKGROUND_IS_GRAY 0x800
  183647. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183648. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183649. /* flags for the transformations the PNG library does on the image data */
  183650. #define PNG_BGR 0x0001
  183651. #define PNG_INTERLACE 0x0002
  183652. #define PNG_PACK 0x0004
  183653. #define PNG_SHIFT 0x0008
  183654. #define PNG_SWAP_BYTES 0x0010
  183655. #define PNG_INVERT_MONO 0x0020
  183656. #define PNG_DITHER 0x0040
  183657. #define PNG_BACKGROUND 0x0080
  183658. #define PNG_BACKGROUND_EXPAND 0x0100
  183659. /* 0x0200 unused */
  183660. #define PNG_16_TO_8 0x0400
  183661. #define PNG_RGBA 0x0800
  183662. #define PNG_EXPAND 0x1000
  183663. #define PNG_GAMMA 0x2000
  183664. #define PNG_GRAY_TO_RGB 0x4000
  183665. #define PNG_FILLER 0x8000L
  183666. #define PNG_PACKSWAP 0x10000L
  183667. #define PNG_SWAP_ALPHA 0x20000L
  183668. #define PNG_STRIP_ALPHA 0x40000L
  183669. #define PNG_INVERT_ALPHA 0x80000L
  183670. #define PNG_USER_TRANSFORM 0x100000L
  183671. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183672. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183673. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183674. /* 0x800000L Unused */
  183675. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183676. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183677. /* 0x4000000L unused */
  183678. /* 0x8000000L unused */
  183679. /* 0x10000000L unused */
  183680. /* 0x20000000L unused */
  183681. /* 0x40000000L unused */
  183682. /* flags for png_create_struct */
  183683. #define PNG_STRUCT_PNG 0x0001
  183684. #define PNG_STRUCT_INFO 0x0002
  183685. /* Scaling factor for filter heuristic weighting calculations */
  183686. #define PNG_WEIGHT_SHIFT 8
  183687. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183688. #define PNG_COST_SHIFT 3
  183689. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183690. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183691. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183692. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183693. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183694. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183695. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183696. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183697. #define PNG_FLAG_ROW_INIT 0x0040
  183698. #define PNG_FLAG_FILLER_AFTER 0x0080
  183699. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183700. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183701. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183702. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183703. #define PNG_FLAG_FREE_PLTE 0x1000
  183704. #define PNG_FLAG_FREE_TRNS 0x2000
  183705. #define PNG_FLAG_FREE_HIST 0x4000
  183706. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183707. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183708. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183709. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183710. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183711. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183712. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183713. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183714. /* 0x800000L unused */
  183715. /* 0x1000000L unused */
  183716. /* 0x2000000L unused */
  183717. /* 0x4000000L unused */
  183718. /* 0x8000000L unused */
  183719. /* 0x10000000L unused */
  183720. /* 0x20000000L unused */
  183721. /* 0x40000000L unused */
  183722. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183723. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183724. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183725. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183726. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183727. PNG_FLAG_CRC_CRITICAL_MASK)
  183728. /* save typing and make code easier to understand */
  183729. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183730. abs((int)((c1).green) - (int)((c2).green)) + \
  183731. abs((int)((c1).blue) - (int)((c2).blue)))
  183732. /* Added to libpng-1.2.6 JB */
  183733. #define PNG_ROWBYTES(pixel_bits, width) \
  183734. ((pixel_bits) >= 8 ? \
  183735. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183736. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183737. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183738. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183739. "ideal" and "delta" should be constants, normally simple
  183740. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183741. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183742. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183743. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183744. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183745. /* place to hold the signature string for a PNG file. */
  183746. #ifdef PNG_USE_GLOBAL_ARRAYS
  183747. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183748. #else
  183749. #endif
  183750. #endif /* PNG_NO_EXTERN */
  183751. /* Constant strings for known chunk types. If you need to add a chunk,
  183752. * define the name here, and add an invocation of the macro in png.c and
  183753. * wherever it's needed.
  183754. */
  183755. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183756. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183757. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183758. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183759. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183760. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183761. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183762. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183763. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183764. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183765. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183766. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183767. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183768. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183769. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183770. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183771. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183772. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183773. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183774. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183775. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183776. #ifdef PNG_USE_GLOBAL_ARRAYS
  183777. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183778. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183779. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183780. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183781. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183782. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183783. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183784. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183785. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183786. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183787. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183788. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183789. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183790. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183791. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183792. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183793. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183794. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183795. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183796. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183797. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183798. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183799. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183800. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183801. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183802. */
  183803. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183804. #undef png_read_init
  183805. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183806. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183807. #endif
  183808. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183809. png_const_charp user_png_ver, png_size_t png_struct_size));
  183810. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183811. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183812. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183813. png_info_size));
  183814. #endif
  183815. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183816. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183817. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183818. */
  183819. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183820. #undef png_write_init
  183821. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183822. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183823. #endif
  183824. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183825. png_const_charp user_png_ver, png_size_t png_struct_size));
  183826. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183827. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183828. png_info_size));
  183829. /* Allocate memory for an internal libpng struct */
  183830. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183831. /* Free memory from internal libpng struct */
  183832. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183833. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183834. malloc_fn, png_voidp mem_ptr));
  183835. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183836. png_free_ptr free_fn, png_voidp mem_ptr));
  183837. /* Free any memory that info_ptr points to and reset struct. */
  183838. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183839. png_infop info_ptr));
  183840. #ifndef PNG_1_0_X
  183841. /* Function to allocate memory for zlib. */
  183842. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183843. /* Function to free memory for zlib */
  183844. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183845. #ifdef PNG_SIZE_T
  183846. /* Function to convert a sizeof an item to png_sizeof item */
  183847. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183848. #endif
  183849. /* Next four functions are used internally as callbacks. PNGAPI is required
  183850. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183851. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183852. png_bytep data, png_size_t length));
  183853. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183854. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183855. png_bytep buffer, png_size_t length));
  183856. #endif
  183857. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183858. png_bytep data, png_size_t length));
  183859. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183860. #if !defined(PNG_NO_STDIO)
  183861. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183862. #endif
  183863. #endif
  183864. #else /* PNG_1_0_X */
  183865. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183866. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183867. png_bytep buffer, png_size_t length));
  183868. #endif
  183869. #endif /* PNG_1_0_X */
  183870. /* Reset the CRC variable */
  183871. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183872. /* Write the "data" buffer to whatever output you are using. */
  183873. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183874. png_size_t length));
  183875. /* Read data from whatever input you are using into the "data" buffer */
  183876. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183877. png_size_t length));
  183878. /* Read bytes into buf, and update png_ptr->crc */
  183879. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183880. png_size_t length));
  183881. /* Decompress data in a chunk that uses compression */
  183882. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183883. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183884. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183885. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183886. png_size_t prefix_length, png_size_t *data_length));
  183887. #endif
  183888. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183889. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183890. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183891. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183892. /* Calculate the CRC over a section of data. Note that we are only
  183893. * passing a maximum of 64K on systems that have this as a memory limit,
  183894. * since this is the maximum buffer size we can specify.
  183895. */
  183896. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183897. png_size_t length));
  183898. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183899. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183900. #endif
  183901. /* simple function to write the signature */
  183902. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183903. /* write various chunks */
  183904. /* Write the IHDR chunk, and update the png_struct with the necessary
  183905. * information.
  183906. */
  183907. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183908. png_uint_32 height,
  183909. int bit_depth, int color_type, int compression_method, int filter_method,
  183910. int interlace_method));
  183911. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183912. png_uint_32 num_pal));
  183913. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183914. png_size_t length));
  183915. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183916. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183917. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183918. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183919. #endif
  183920. #ifdef PNG_FIXED_POINT_SUPPORTED
  183921. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183922. file_gamma));
  183923. #endif
  183924. #endif
  183925. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183926. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183927. int color_type));
  183928. #endif
  183929. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183930. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183931. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183932. double white_x, double white_y,
  183933. double red_x, double red_y, double green_x, double green_y,
  183934. double blue_x, double blue_y));
  183935. #endif
  183936. #ifdef PNG_FIXED_POINT_SUPPORTED
  183937. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183938. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183939. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183940. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183941. png_fixed_point int_blue_y));
  183942. #endif
  183943. #endif
  183944. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183945. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183946. int intent));
  183947. #endif
  183948. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183949. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183950. png_charp name, int compression_type,
  183951. png_charp profile, int proflen));
  183952. /* Note to maintainer: profile should be png_bytep */
  183953. #endif
  183954. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183955. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183956. png_sPLT_tp palette));
  183957. #endif
  183958. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183959. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183960. png_color_16p values, int number, int color_type));
  183961. #endif
  183962. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183963. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183964. png_color_16p values, int color_type));
  183965. #endif
  183966. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183967. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183968. int num_hist));
  183969. #endif
  183970. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183971. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183972. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183973. png_charp key, png_charpp new_key));
  183974. #endif
  183975. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183976. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183977. png_charp text, png_size_t text_len));
  183978. #endif
  183979. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183980. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183981. png_charp text, png_size_t text_len, int compression));
  183982. #endif
  183983. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183984. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183985. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183986. png_charp text));
  183987. #endif
  183988. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183989. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183990. png_infop info_ptr, png_textp text_ptr, int num_text));
  183991. #endif
  183992. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183993. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183994. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183995. #endif
  183996. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183997. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183998. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183999. png_charp units, png_charpp params));
  184000. #endif
  184001. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184002. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184003. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184004. int unit_type));
  184005. #endif
  184006. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184007. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184008. png_timep mod_time));
  184009. #endif
  184010. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184011. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184012. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184013. int unit, double width, double height));
  184014. #else
  184015. #ifdef PNG_FIXED_POINT_SUPPORTED
  184016. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184017. int unit, png_charp width, png_charp height));
  184018. #endif
  184019. #endif
  184020. #endif
  184021. /* Called when finished processing a row of data */
  184022. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184023. /* Internal use only. Called before first row of data */
  184024. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184025. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184026. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184027. #endif
  184028. /* combine a row of data, dealing with alpha, etc. if requested */
  184029. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184030. int mask));
  184031. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184032. /* expand an interlaced row */
  184033. /* OLD pre-1.0.9 interface:
  184034. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184035. png_bytep row, int pass, png_uint_32 transformations));
  184036. */
  184037. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184038. #endif
  184039. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184040. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184041. /* grab pixels out of a row for an interlaced pass */
  184042. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184043. png_bytep row, int pass));
  184044. #endif
  184045. /* unfilter a row */
  184046. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184047. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184048. /* Choose the best filter to use and filter the row data */
  184049. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184050. png_row_infop row_info));
  184051. /* Write out the filtered row. */
  184052. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184053. png_bytep filtered_row));
  184054. /* finish a row while reading, dealing with interlacing passes, etc. */
  184055. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184056. /* initialize the row buffers, etc. */
  184057. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184058. /* optional call to update the users info structure */
  184059. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184060. png_infop info_ptr));
  184061. /* these are the functions that do the transformations */
  184062. #if defined(PNG_READ_FILLER_SUPPORTED)
  184063. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184064. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184065. #endif
  184066. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184067. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184068. png_bytep row));
  184069. #endif
  184070. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184071. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184072. png_bytep row));
  184073. #endif
  184074. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184075. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184076. png_bytep row));
  184077. #endif
  184078. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184079. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184080. png_bytep row));
  184081. #endif
  184082. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184083. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184084. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184085. png_bytep row, png_uint_32 flags));
  184086. #endif
  184087. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184088. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184089. #endif
  184090. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184091. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184092. #endif
  184093. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184094. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184095. row_info, png_bytep row));
  184096. #endif
  184097. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184098. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184099. png_bytep row));
  184100. #endif
  184101. #if defined(PNG_READ_PACK_SUPPORTED)
  184102. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184103. #endif
  184104. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184105. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184106. png_color_8p sig_bits));
  184107. #endif
  184108. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184109. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184110. #endif
  184111. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184112. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184113. #endif
  184114. #if defined(PNG_READ_DITHER_SUPPORTED)
  184115. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184116. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184117. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184118. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184119. png_colorp palette, int num_palette));
  184120. # endif
  184121. #endif
  184122. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184123. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184124. #endif
  184125. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184126. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184127. png_bytep row, png_uint_32 bit_depth));
  184128. #endif
  184129. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184130. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184131. png_color_8p bit_depth));
  184132. #endif
  184133. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184134. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184135. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184136. png_color_16p trans_values, png_color_16p background,
  184137. png_color_16p background_1,
  184138. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184139. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184140. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184141. #else
  184142. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184143. png_color_16p trans_values, png_color_16p background));
  184144. #endif
  184145. #endif
  184146. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184147. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184148. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184149. int gamma_shift));
  184150. #endif
  184151. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184152. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184153. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184154. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184155. png_bytep row, png_color_16p trans_value));
  184156. #endif
  184157. /* The following decodes the appropriate chunks, and does error correction,
  184158. * then calls the appropriate callback for the chunk if it is valid.
  184159. */
  184160. /* decode the IHDR chunk */
  184161. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184162. png_uint_32 length));
  184163. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184164. png_uint_32 length));
  184165. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184166. png_uint_32 length));
  184167. #if defined(PNG_READ_bKGD_SUPPORTED)
  184168. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184169. png_uint_32 length));
  184170. #endif
  184171. #if defined(PNG_READ_cHRM_SUPPORTED)
  184172. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184173. png_uint_32 length));
  184174. #endif
  184175. #if defined(PNG_READ_gAMA_SUPPORTED)
  184176. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184177. png_uint_32 length));
  184178. #endif
  184179. #if defined(PNG_READ_hIST_SUPPORTED)
  184180. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184181. png_uint_32 length));
  184182. #endif
  184183. #if defined(PNG_READ_iCCP_SUPPORTED)
  184184. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184185. png_uint_32 length));
  184186. #endif /* PNG_READ_iCCP_SUPPORTED */
  184187. #if defined(PNG_READ_iTXt_SUPPORTED)
  184188. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184189. png_uint_32 length));
  184190. #endif
  184191. #if defined(PNG_READ_oFFs_SUPPORTED)
  184192. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184193. png_uint_32 length));
  184194. #endif
  184195. #if defined(PNG_READ_pCAL_SUPPORTED)
  184196. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184197. png_uint_32 length));
  184198. #endif
  184199. #if defined(PNG_READ_pHYs_SUPPORTED)
  184200. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184201. png_uint_32 length));
  184202. #endif
  184203. #if defined(PNG_READ_sBIT_SUPPORTED)
  184204. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184205. png_uint_32 length));
  184206. #endif
  184207. #if defined(PNG_READ_sCAL_SUPPORTED)
  184208. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184209. png_uint_32 length));
  184210. #endif
  184211. #if defined(PNG_READ_sPLT_SUPPORTED)
  184212. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184213. png_uint_32 length));
  184214. #endif /* PNG_READ_sPLT_SUPPORTED */
  184215. #if defined(PNG_READ_sRGB_SUPPORTED)
  184216. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184217. png_uint_32 length));
  184218. #endif
  184219. #if defined(PNG_READ_tEXt_SUPPORTED)
  184220. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184221. png_uint_32 length));
  184222. #endif
  184223. #if defined(PNG_READ_tIME_SUPPORTED)
  184224. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184225. png_uint_32 length));
  184226. #endif
  184227. #if defined(PNG_READ_tRNS_SUPPORTED)
  184228. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184229. png_uint_32 length));
  184230. #endif
  184231. #if defined(PNG_READ_zTXt_SUPPORTED)
  184232. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184233. png_uint_32 length));
  184234. #endif
  184235. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184236. png_infop info_ptr, png_uint_32 length));
  184237. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184238. png_bytep chunk_name));
  184239. /* handle the transformations for reading and writing */
  184240. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184241. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184242. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184243. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184244. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184245. png_infop info_ptr));
  184246. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184247. png_infop info_ptr));
  184248. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184249. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184250. png_uint_32 length));
  184251. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184252. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184253. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184254. png_bytep buffer, png_size_t buffer_length));
  184255. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184256. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184257. png_bytep buffer, png_size_t buffer_length));
  184258. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184259. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184260. png_infop info_ptr, png_uint_32 length));
  184261. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184262. png_infop info_ptr));
  184263. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184264. png_infop info_ptr));
  184265. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184266. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184267. png_infop info_ptr));
  184268. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184269. png_infop info_ptr));
  184270. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184271. #if defined(PNG_READ_tEXt_SUPPORTED)
  184272. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184273. png_infop info_ptr, png_uint_32 length));
  184274. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184275. png_infop info_ptr));
  184276. #endif
  184277. #if defined(PNG_READ_zTXt_SUPPORTED)
  184278. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184279. png_infop info_ptr, png_uint_32 length));
  184280. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184281. png_infop info_ptr));
  184282. #endif
  184283. #if defined(PNG_READ_iTXt_SUPPORTED)
  184284. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184285. png_infop info_ptr, png_uint_32 length));
  184286. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184287. png_infop info_ptr));
  184288. #endif
  184289. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184290. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184291. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184292. png_bytep row));
  184293. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184294. png_bytep row));
  184295. #endif
  184296. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184297. #if defined(PNG_MMX_CODE_SUPPORTED)
  184298. /* png.c */ /* PRIVATE */
  184299. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184300. #endif
  184301. #endif
  184302. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184303. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184304. png_infop info_ptr));
  184305. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184306. png_infop info_ptr));
  184307. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184308. png_infop info_ptr));
  184309. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184310. png_infop info_ptr));
  184311. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184312. png_infop info_ptr));
  184313. #if defined(PNG_pHYs_SUPPORTED)
  184314. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184315. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184316. #endif /* PNG_pHYs_SUPPORTED */
  184317. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184318. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184319. #endif /* PNG_INTERNAL */
  184320. #ifdef __cplusplus
  184321. //}
  184322. #endif
  184323. #endif /* PNG_VERSION_INFO_ONLY */
  184324. /* do not put anything past this line */
  184325. #endif /* PNG_H */
  184326. /*** End of inlined file: png.h ***/
  184327. #define PNG_NO_EXTERN
  184328. /*** Start of inlined file: png.c ***/
  184329. /* png.c - location for general purpose libpng functions
  184330. *
  184331. * Last changed in libpng 1.2.21 [October 4, 2007]
  184332. * For conditions of distribution and use, see copyright notice in png.h
  184333. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184334. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184335. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184336. */
  184337. #define PNG_INTERNAL
  184338. #define PNG_NO_EXTERN
  184339. /* Generate a compiler error if there is an old png.h in the search path. */
  184340. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184341. /* Version information for C files. This had better match the version
  184342. * string defined in png.h. */
  184343. #ifdef PNG_USE_GLOBAL_ARRAYS
  184344. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184345. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184346. #ifdef PNG_READ_SUPPORTED
  184347. /* png_sig was changed to a function in version 1.0.5c */
  184348. /* Place to hold the signature string for a PNG file. */
  184349. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184350. #endif /* PNG_READ_SUPPORTED */
  184351. /* Invoke global declarations for constant strings for known chunk types */
  184352. PNG_IHDR;
  184353. PNG_IDAT;
  184354. PNG_IEND;
  184355. PNG_PLTE;
  184356. PNG_bKGD;
  184357. PNG_cHRM;
  184358. PNG_gAMA;
  184359. PNG_hIST;
  184360. PNG_iCCP;
  184361. PNG_iTXt;
  184362. PNG_oFFs;
  184363. PNG_pCAL;
  184364. PNG_sCAL;
  184365. PNG_pHYs;
  184366. PNG_sBIT;
  184367. PNG_sPLT;
  184368. PNG_sRGB;
  184369. PNG_tEXt;
  184370. PNG_tIME;
  184371. PNG_tRNS;
  184372. PNG_zTXt;
  184373. #ifdef PNG_READ_SUPPORTED
  184374. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184375. /* start of interlace block */
  184376. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184377. /* offset to next interlace block */
  184378. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184379. /* start of interlace block in the y direction */
  184380. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184381. /* offset to next interlace block in the y direction */
  184382. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184383. /* Height of interlace block. This is not currently used - if you need
  184384. * it, uncomment it here and in png.h
  184385. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184386. */
  184387. /* Mask to determine which pixels are valid in a pass */
  184388. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184389. /* Mask to determine which pixels to overwrite while displaying */
  184390. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184391. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184392. #endif /* PNG_READ_SUPPORTED */
  184393. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184394. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184395. * of the PNG file signature. If the PNG data is embedded into another
  184396. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184397. * or write any of the magic bytes before it starts on the IHDR.
  184398. */
  184399. #ifdef PNG_READ_SUPPORTED
  184400. void PNGAPI
  184401. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184402. {
  184403. if(png_ptr == NULL) return;
  184404. png_debug(1, "in png_set_sig_bytes\n");
  184405. if (num_bytes > 8)
  184406. png_error(png_ptr, "Too many bytes for PNG signature.");
  184407. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184408. }
  184409. /* Checks whether the supplied bytes match the PNG signature. We allow
  184410. * checking less than the full 8-byte signature so that those apps that
  184411. * already read the first few bytes of a file to determine the file type
  184412. * can simply check the remaining bytes for extra assurance. Returns
  184413. * an integer less than, equal to, or greater than zero if sig is found,
  184414. * respectively, to be less than, to match, or be greater than the correct
  184415. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184416. */
  184417. int PNGAPI
  184418. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184419. {
  184420. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184421. if (num_to_check > 8)
  184422. num_to_check = 8;
  184423. else if (num_to_check < 1)
  184424. return (-1);
  184425. if (start > 7)
  184426. return (-1);
  184427. if (start + num_to_check > 8)
  184428. num_to_check = 8 - start;
  184429. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184430. }
  184431. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184432. /* (Obsolete) function to check signature bytes. It does not allow one
  184433. * to check a partial signature. This function might be removed in the
  184434. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184435. */
  184436. int PNGAPI
  184437. png_check_sig(png_bytep sig, int num)
  184438. {
  184439. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184440. }
  184441. #endif
  184442. #endif /* PNG_READ_SUPPORTED */
  184443. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184444. /* Function to allocate memory for zlib and clear it to 0. */
  184445. #ifdef PNG_1_0_X
  184446. voidpf PNGAPI
  184447. #else
  184448. voidpf /* private */
  184449. #endif
  184450. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184451. {
  184452. png_voidp ptr;
  184453. png_structp p=(png_structp)png_ptr;
  184454. png_uint_32 save_flags=p->flags;
  184455. png_uint_32 num_bytes;
  184456. if(png_ptr == NULL) return (NULL);
  184457. if (items > PNG_UINT_32_MAX/size)
  184458. {
  184459. png_warning (p, "Potential overflow in png_zalloc()");
  184460. return (NULL);
  184461. }
  184462. num_bytes = (png_uint_32)items * size;
  184463. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184464. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184465. p->flags=save_flags;
  184466. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184467. if (ptr == NULL)
  184468. return ((voidpf)ptr);
  184469. if (num_bytes > (png_uint_32)0x8000L)
  184470. {
  184471. png_memset(ptr, 0, (png_size_t)0x8000L);
  184472. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184473. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184474. }
  184475. else
  184476. {
  184477. png_memset(ptr, 0, (png_size_t)num_bytes);
  184478. }
  184479. #endif
  184480. return ((voidpf)ptr);
  184481. }
  184482. /* function to free memory for zlib */
  184483. #ifdef PNG_1_0_X
  184484. void PNGAPI
  184485. #else
  184486. void /* private */
  184487. #endif
  184488. png_zfree(voidpf png_ptr, voidpf ptr)
  184489. {
  184490. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184491. }
  184492. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184493. * in case CRC is > 32 bits to leave the top bits 0.
  184494. */
  184495. void /* PRIVATE */
  184496. png_reset_crc(png_structp png_ptr)
  184497. {
  184498. png_ptr->crc = crc32(0, Z_NULL, 0);
  184499. }
  184500. /* Calculate the CRC over a section of data. We can only pass as
  184501. * much data to this routine as the largest single buffer size. We
  184502. * also check that this data will actually be used before going to the
  184503. * trouble of calculating it.
  184504. */
  184505. void /* PRIVATE */
  184506. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184507. {
  184508. int need_crc = 1;
  184509. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184510. {
  184511. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184512. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184513. need_crc = 0;
  184514. }
  184515. else /* critical */
  184516. {
  184517. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184518. need_crc = 0;
  184519. }
  184520. if (need_crc)
  184521. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184522. }
  184523. /* Allocate the memory for an info_struct for the application. We don't
  184524. * really need the png_ptr, but it could potentially be useful in the
  184525. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184526. * and png_info_init() so that applications that want to use a shared
  184527. * libpng don't have to be recompiled if png_info changes size.
  184528. */
  184529. png_infop PNGAPI
  184530. png_create_info_struct(png_structp png_ptr)
  184531. {
  184532. png_infop info_ptr;
  184533. png_debug(1, "in png_create_info_struct\n");
  184534. if(png_ptr == NULL) return (NULL);
  184535. #ifdef PNG_USER_MEM_SUPPORTED
  184536. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184537. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184538. #else
  184539. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184540. #endif
  184541. if (info_ptr != NULL)
  184542. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184543. return (info_ptr);
  184544. }
  184545. /* This function frees the memory associated with a single info struct.
  184546. * Normally, one would use either png_destroy_read_struct() or
  184547. * png_destroy_write_struct() to free an info struct, but this may be
  184548. * useful for some applications.
  184549. */
  184550. void PNGAPI
  184551. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184552. {
  184553. png_infop info_ptr = NULL;
  184554. if(png_ptr == NULL) return;
  184555. png_debug(1, "in png_destroy_info_struct\n");
  184556. if (info_ptr_ptr != NULL)
  184557. info_ptr = *info_ptr_ptr;
  184558. if (info_ptr != NULL)
  184559. {
  184560. png_info_destroy(png_ptr, info_ptr);
  184561. #ifdef PNG_USER_MEM_SUPPORTED
  184562. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184563. png_ptr->mem_ptr);
  184564. #else
  184565. png_destroy_struct((png_voidp)info_ptr);
  184566. #endif
  184567. *info_ptr_ptr = NULL;
  184568. }
  184569. }
  184570. /* Initialize the info structure. This is now an internal function (0.89)
  184571. * and applications using it are urged to use png_create_info_struct()
  184572. * instead.
  184573. */
  184574. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184575. #undef png_info_init
  184576. void PNGAPI
  184577. png_info_init(png_infop info_ptr)
  184578. {
  184579. /* We only come here via pre-1.0.12-compiled applications */
  184580. png_info_init_3(&info_ptr, 0);
  184581. }
  184582. #endif
  184583. void PNGAPI
  184584. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184585. {
  184586. png_infop info_ptr = *ptr_ptr;
  184587. if(info_ptr == NULL) return;
  184588. png_debug(1, "in png_info_init_3\n");
  184589. if(png_sizeof(png_info) > png_info_struct_size)
  184590. {
  184591. png_destroy_struct(info_ptr);
  184592. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184593. *ptr_ptr = info_ptr;
  184594. }
  184595. /* set everything to 0 */
  184596. png_memset(info_ptr, 0, png_sizeof (png_info));
  184597. }
  184598. #ifdef PNG_FREE_ME_SUPPORTED
  184599. void PNGAPI
  184600. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184601. int freer, png_uint_32 mask)
  184602. {
  184603. png_debug(1, "in png_data_freer\n");
  184604. if (png_ptr == NULL || info_ptr == NULL)
  184605. return;
  184606. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184607. info_ptr->free_me |= mask;
  184608. else if(freer == PNG_USER_WILL_FREE_DATA)
  184609. info_ptr->free_me &= ~mask;
  184610. else
  184611. png_warning(png_ptr,
  184612. "Unknown freer parameter in png_data_freer.");
  184613. }
  184614. #endif
  184615. void PNGAPI
  184616. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184617. int num)
  184618. {
  184619. png_debug(1, "in png_free_data\n");
  184620. if (png_ptr == NULL || info_ptr == NULL)
  184621. return;
  184622. #if defined(PNG_TEXT_SUPPORTED)
  184623. /* free text item num or (if num == -1) all text items */
  184624. #ifdef PNG_FREE_ME_SUPPORTED
  184625. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184626. #else
  184627. if (mask & PNG_FREE_TEXT)
  184628. #endif
  184629. {
  184630. if (num != -1)
  184631. {
  184632. if (info_ptr->text && info_ptr->text[num].key)
  184633. {
  184634. png_free(png_ptr, info_ptr->text[num].key);
  184635. info_ptr->text[num].key = NULL;
  184636. }
  184637. }
  184638. else
  184639. {
  184640. int i;
  184641. for (i = 0; i < info_ptr->num_text; i++)
  184642. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184643. png_free(png_ptr, info_ptr->text);
  184644. info_ptr->text = NULL;
  184645. info_ptr->num_text=0;
  184646. }
  184647. }
  184648. #endif
  184649. #if defined(PNG_tRNS_SUPPORTED)
  184650. /* free any tRNS entry */
  184651. #ifdef PNG_FREE_ME_SUPPORTED
  184652. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184653. #else
  184654. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184655. #endif
  184656. {
  184657. png_free(png_ptr, info_ptr->trans);
  184658. info_ptr->valid &= ~PNG_INFO_tRNS;
  184659. #ifndef PNG_FREE_ME_SUPPORTED
  184660. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184661. #endif
  184662. info_ptr->trans = NULL;
  184663. }
  184664. #endif
  184665. #if defined(PNG_sCAL_SUPPORTED)
  184666. /* free any sCAL entry */
  184667. #ifdef PNG_FREE_ME_SUPPORTED
  184668. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184669. #else
  184670. if (mask & PNG_FREE_SCAL)
  184671. #endif
  184672. {
  184673. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184674. png_free(png_ptr, info_ptr->scal_s_width);
  184675. png_free(png_ptr, info_ptr->scal_s_height);
  184676. info_ptr->scal_s_width = NULL;
  184677. info_ptr->scal_s_height = NULL;
  184678. #endif
  184679. info_ptr->valid &= ~PNG_INFO_sCAL;
  184680. }
  184681. #endif
  184682. #if defined(PNG_pCAL_SUPPORTED)
  184683. /* free any pCAL entry */
  184684. #ifdef PNG_FREE_ME_SUPPORTED
  184685. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184686. #else
  184687. if (mask & PNG_FREE_PCAL)
  184688. #endif
  184689. {
  184690. png_free(png_ptr, info_ptr->pcal_purpose);
  184691. png_free(png_ptr, info_ptr->pcal_units);
  184692. info_ptr->pcal_purpose = NULL;
  184693. info_ptr->pcal_units = NULL;
  184694. if (info_ptr->pcal_params != NULL)
  184695. {
  184696. int i;
  184697. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184698. {
  184699. png_free(png_ptr, info_ptr->pcal_params[i]);
  184700. info_ptr->pcal_params[i]=NULL;
  184701. }
  184702. png_free(png_ptr, info_ptr->pcal_params);
  184703. info_ptr->pcal_params = NULL;
  184704. }
  184705. info_ptr->valid &= ~PNG_INFO_pCAL;
  184706. }
  184707. #endif
  184708. #if defined(PNG_iCCP_SUPPORTED)
  184709. /* free any iCCP entry */
  184710. #ifdef PNG_FREE_ME_SUPPORTED
  184711. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184712. #else
  184713. if (mask & PNG_FREE_ICCP)
  184714. #endif
  184715. {
  184716. png_free(png_ptr, info_ptr->iccp_name);
  184717. png_free(png_ptr, info_ptr->iccp_profile);
  184718. info_ptr->iccp_name = NULL;
  184719. info_ptr->iccp_profile = NULL;
  184720. info_ptr->valid &= ~PNG_INFO_iCCP;
  184721. }
  184722. #endif
  184723. #if defined(PNG_sPLT_SUPPORTED)
  184724. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184725. #ifdef PNG_FREE_ME_SUPPORTED
  184726. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184727. #else
  184728. if (mask & PNG_FREE_SPLT)
  184729. #endif
  184730. {
  184731. if (num != -1)
  184732. {
  184733. if(info_ptr->splt_palettes)
  184734. {
  184735. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184736. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184737. info_ptr->splt_palettes[num].name = NULL;
  184738. info_ptr->splt_palettes[num].entries = NULL;
  184739. }
  184740. }
  184741. else
  184742. {
  184743. if(info_ptr->splt_palettes_num)
  184744. {
  184745. int i;
  184746. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184747. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184748. png_free(png_ptr, info_ptr->splt_palettes);
  184749. info_ptr->splt_palettes = NULL;
  184750. info_ptr->splt_palettes_num = 0;
  184751. }
  184752. info_ptr->valid &= ~PNG_INFO_sPLT;
  184753. }
  184754. }
  184755. #endif
  184756. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184757. if(png_ptr->unknown_chunk.data)
  184758. {
  184759. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184760. png_ptr->unknown_chunk.data = NULL;
  184761. }
  184762. #ifdef PNG_FREE_ME_SUPPORTED
  184763. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184764. #else
  184765. if (mask & PNG_FREE_UNKN)
  184766. #endif
  184767. {
  184768. if (num != -1)
  184769. {
  184770. if(info_ptr->unknown_chunks)
  184771. {
  184772. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184773. info_ptr->unknown_chunks[num].data = NULL;
  184774. }
  184775. }
  184776. else
  184777. {
  184778. int i;
  184779. if(info_ptr->unknown_chunks_num)
  184780. {
  184781. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184782. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184783. png_free(png_ptr, info_ptr->unknown_chunks);
  184784. info_ptr->unknown_chunks = NULL;
  184785. info_ptr->unknown_chunks_num = 0;
  184786. }
  184787. }
  184788. }
  184789. #endif
  184790. #if defined(PNG_hIST_SUPPORTED)
  184791. /* free any hIST entry */
  184792. #ifdef PNG_FREE_ME_SUPPORTED
  184793. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184794. #else
  184795. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184796. #endif
  184797. {
  184798. png_free(png_ptr, info_ptr->hist);
  184799. info_ptr->hist = NULL;
  184800. info_ptr->valid &= ~PNG_INFO_hIST;
  184801. #ifndef PNG_FREE_ME_SUPPORTED
  184802. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184803. #endif
  184804. }
  184805. #endif
  184806. /* free any PLTE entry that was internally allocated */
  184807. #ifdef PNG_FREE_ME_SUPPORTED
  184808. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184809. #else
  184810. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184811. #endif
  184812. {
  184813. png_zfree(png_ptr, info_ptr->palette);
  184814. info_ptr->palette = NULL;
  184815. info_ptr->valid &= ~PNG_INFO_PLTE;
  184816. #ifndef PNG_FREE_ME_SUPPORTED
  184817. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184818. #endif
  184819. info_ptr->num_palette = 0;
  184820. }
  184821. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184822. /* free any image bits attached to the info structure */
  184823. #ifdef PNG_FREE_ME_SUPPORTED
  184824. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184825. #else
  184826. if (mask & PNG_FREE_ROWS)
  184827. #endif
  184828. {
  184829. if(info_ptr->row_pointers)
  184830. {
  184831. int row;
  184832. for (row = 0; row < (int)info_ptr->height; row++)
  184833. {
  184834. png_free(png_ptr, info_ptr->row_pointers[row]);
  184835. info_ptr->row_pointers[row]=NULL;
  184836. }
  184837. png_free(png_ptr, info_ptr->row_pointers);
  184838. info_ptr->row_pointers=NULL;
  184839. }
  184840. info_ptr->valid &= ~PNG_INFO_IDAT;
  184841. }
  184842. #endif
  184843. #ifdef PNG_FREE_ME_SUPPORTED
  184844. if(num == -1)
  184845. info_ptr->free_me &= ~mask;
  184846. else
  184847. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184848. #endif
  184849. }
  184850. /* This is an internal routine to free any memory that the info struct is
  184851. * pointing to before re-using it or freeing the struct itself. Recall
  184852. * that png_free() checks for NULL pointers for us.
  184853. */
  184854. void /* PRIVATE */
  184855. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184856. {
  184857. png_debug(1, "in png_info_destroy\n");
  184858. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184859. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184860. if (png_ptr->num_chunk_list)
  184861. {
  184862. png_free(png_ptr, png_ptr->chunk_list);
  184863. png_ptr->chunk_list=NULL;
  184864. png_ptr->num_chunk_list=0;
  184865. }
  184866. #endif
  184867. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184868. }
  184869. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184870. /* This function returns a pointer to the io_ptr associated with the user
  184871. * functions. The application should free any memory associated with this
  184872. * pointer before png_write_destroy() or png_read_destroy() are called.
  184873. */
  184874. png_voidp PNGAPI
  184875. png_get_io_ptr(png_structp png_ptr)
  184876. {
  184877. if(png_ptr == NULL) return (NULL);
  184878. return (png_ptr->io_ptr);
  184879. }
  184880. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184881. #if !defined(PNG_NO_STDIO)
  184882. /* Initialize the default input/output functions for the PNG file. If you
  184883. * use your own read or write routines, you can call either png_set_read_fn()
  184884. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184885. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184886. * necessarily available.
  184887. */
  184888. void PNGAPI
  184889. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184890. {
  184891. png_debug(1, "in png_init_io\n");
  184892. if(png_ptr == NULL) return;
  184893. png_ptr->io_ptr = (png_voidp)fp;
  184894. }
  184895. #endif
  184896. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184897. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184898. * a "Creation Time" or other text-based time string.
  184899. */
  184900. png_charp PNGAPI
  184901. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184902. {
  184903. static PNG_CONST char short_months[12][4] =
  184904. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184905. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184906. if(png_ptr == NULL) return (NULL);
  184907. if (png_ptr->time_buffer == NULL)
  184908. {
  184909. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184910. png_sizeof(char)));
  184911. }
  184912. #if defined(_WIN32_WCE)
  184913. {
  184914. wchar_t time_buf[29];
  184915. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184916. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184917. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184918. ptime->second % 61);
  184919. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184920. NULL, NULL);
  184921. }
  184922. #else
  184923. #ifdef USE_FAR_KEYWORD
  184924. {
  184925. char near_time_buf[29];
  184926. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184927. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184928. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184929. ptime->second % 61);
  184930. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184931. 29*png_sizeof(char));
  184932. }
  184933. #else
  184934. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184935. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184936. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184937. ptime->second % 61);
  184938. #endif
  184939. #endif /* _WIN32_WCE */
  184940. return ((png_charp)png_ptr->time_buffer);
  184941. }
  184942. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184943. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184944. png_charp PNGAPI
  184945. png_get_copyright(png_structp png_ptr)
  184946. {
  184947. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184948. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184949. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184950. Copyright (c) 1996-1997 Andreas Dilger\n\
  184951. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184952. }
  184953. /* The following return the library version as a short string in the
  184954. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184955. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184956. * is defined in png.h.
  184957. * Note: now there is no difference between png_get_libpng_ver() and
  184958. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184959. * it is guaranteed that png.c uses the correct version of png.h.
  184960. */
  184961. png_charp PNGAPI
  184962. png_get_libpng_ver(png_structp png_ptr)
  184963. {
  184964. /* Version of *.c files used when building libpng */
  184965. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184966. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184967. }
  184968. png_charp PNGAPI
  184969. png_get_header_ver(png_structp png_ptr)
  184970. {
  184971. /* Version of *.h files used when building libpng */
  184972. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184973. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184974. }
  184975. png_charp PNGAPI
  184976. png_get_header_version(png_structp png_ptr)
  184977. {
  184978. /* Returns longer string containing both version and date */
  184979. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184980. return ((png_charp) PNG_HEADER_VERSION_STRING
  184981. #ifndef PNG_READ_SUPPORTED
  184982. " (NO READ SUPPORT)"
  184983. #endif
  184984. "\n");
  184985. }
  184986. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184987. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184988. int PNGAPI
  184989. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184990. {
  184991. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184992. int i;
  184993. png_bytep p;
  184994. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184995. return 0;
  184996. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184997. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184998. if (!png_memcmp(chunk_name, p, 4))
  184999. return ((int)*(p+4));
  185000. return 0;
  185001. }
  185002. #endif
  185003. /* This function, added to libpng-1.0.6g, is untested. */
  185004. int PNGAPI
  185005. png_reset_zstream(png_structp png_ptr)
  185006. {
  185007. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185008. return (inflateReset(&png_ptr->zstream));
  185009. }
  185010. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185011. /* This function was added to libpng-1.0.7 */
  185012. png_uint_32 PNGAPI
  185013. png_access_version_number(void)
  185014. {
  185015. /* Version of *.c files used when building libpng */
  185016. return((png_uint_32) PNG_LIBPNG_VER);
  185017. }
  185018. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185019. #if !defined(PNG_1_0_X)
  185020. /* this function was added to libpng 1.2.0 */
  185021. int PNGAPI
  185022. png_mmx_support(void)
  185023. {
  185024. /* obsolete, to be removed from libpng-1.4.0 */
  185025. return -1;
  185026. }
  185027. #endif /* PNG_1_0_X */
  185028. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185029. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185030. #ifdef PNG_SIZE_T
  185031. /* Added at libpng version 1.2.6 */
  185032. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185033. png_size_t PNGAPI
  185034. png_convert_size(size_t size)
  185035. {
  185036. if (size > (png_size_t)-1)
  185037. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185038. return ((png_size_t)size);
  185039. }
  185040. #endif /* PNG_SIZE_T */
  185041. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185042. /*** End of inlined file: png.c ***/
  185043. /*** Start of inlined file: pngerror.c ***/
  185044. /* pngerror.c - stub functions for i/o and memory allocation
  185045. *
  185046. * Last changed in libpng 1.2.20 October 4, 2007
  185047. * For conditions of distribution and use, see copyright notice in png.h
  185048. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185049. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185050. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185051. *
  185052. * This file provides a location for all error handling. Users who
  185053. * need special error handling are expected to write replacement functions
  185054. * and use png_set_error_fn() to use those functions. See the instructions
  185055. * at each function.
  185056. */
  185057. #define PNG_INTERNAL
  185058. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185059. static void /* PRIVATE */
  185060. png_default_error PNGARG((png_structp png_ptr,
  185061. png_const_charp error_message));
  185062. #ifndef PNG_NO_WARNINGS
  185063. static void /* PRIVATE */
  185064. png_default_warning PNGARG((png_structp png_ptr,
  185065. png_const_charp warning_message));
  185066. #endif /* PNG_NO_WARNINGS */
  185067. /* This function is called whenever there is a fatal error. This function
  185068. * should not be changed. If there is a need to handle errors differently,
  185069. * you should supply a replacement error function and use png_set_error_fn()
  185070. * to replace the error function at run-time.
  185071. */
  185072. #ifndef PNG_NO_ERROR_TEXT
  185073. void PNGAPI
  185074. png_error(png_structp png_ptr, png_const_charp error_message)
  185075. {
  185076. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185077. char msg[16];
  185078. if (png_ptr != NULL)
  185079. {
  185080. if (png_ptr->flags&
  185081. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185082. {
  185083. if (*error_message == '#')
  185084. {
  185085. int offset;
  185086. for (offset=1; offset<15; offset++)
  185087. if (*(error_message+offset) == ' ')
  185088. break;
  185089. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185090. {
  185091. int i;
  185092. for (i=0; i<offset-1; i++)
  185093. msg[i]=error_message[i+1];
  185094. msg[i]='\0';
  185095. error_message=msg;
  185096. }
  185097. else
  185098. error_message+=offset;
  185099. }
  185100. else
  185101. {
  185102. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185103. {
  185104. msg[0]='0';
  185105. msg[1]='\0';
  185106. error_message=msg;
  185107. }
  185108. }
  185109. }
  185110. }
  185111. #endif
  185112. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185113. (*(png_ptr->error_fn))(png_ptr, error_message);
  185114. /* If the custom handler doesn't exist, or if it returns,
  185115. use the default handler, which will not return. */
  185116. png_default_error(png_ptr, error_message);
  185117. }
  185118. #else
  185119. void PNGAPI
  185120. png_err(png_structp png_ptr)
  185121. {
  185122. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185123. (*(png_ptr->error_fn))(png_ptr, '\0');
  185124. /* If the custom handler doesn't exist, or if it returns,
  185125. use the default handler, which will not return. */
  185126. png_default_error(png_ptr, '\0');
  185127. }
  185128. #endif /* PNG_NO_ERROR_TEXT */
  185129. #ifndef PNG_NO_WARNINGS
  185130. /* This function is called whenever there is a non-fatal error. This function
  185131. * should not be changed. If there is a need to handle warnings differently,
  185132. * you should supply a replacement warning function and use
  185133. * png_set_error_fn() to replace the warning function at run-time.
  185134. */
  185135. void PNGAPI
  185136. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185137. {
  185138. int offset = 0;
  185139. if (png_ptr != NULL)
  185140. {
  185141. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185142. if (png_ptr->flags&
  185143. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185144. #endif
  185145. {
  185146. if (*warning_message == '#')
  185147. {
  185148. for (offset=1; offset<15; offset++)
  185149. if (*(warning_message+offset) == ' ')
  185150. break;
  185151. }
  185152. }
  185153. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185154. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185155. }
  185156. else
  185157. png_default_warning(png_ptr, warning_message+offset);
  185158. }
  185159. #endif /* PNG_NO_WARNINGS */
  185160. /* These utilities are used internally to build an error message that relates
  185161. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185162. * this is used to prefix the message. The message is limited in length
  185163. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185164. * if the character is invalid.
  185165. */
  185166. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185167. /*static PNG_CONST char png_digit[16] = {
  185168. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185169. 'A', 'B', 'C', 'D', 'E', 'F'
  185170. };*/
  185171. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185172. static void /* PRIVATE */
  185173. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185174. error_message)
  185175. {
  185176. int iout = 0, iin = 0;
  185177. while (iin < 4)
  185178. {
  185179. int c = png_ptr->chunk_name[iin++];
  185180. if (isnonalpha(c))
  185181. {
  185182. buffer[iout++] = '[';
  185183. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185184. buffer[iout++] = png_digit[c & 0x0f];
  185185. buffer[iout++] = ']';
  185186. }
  185187. else
  185188. {
  185189. buffer[iout++] = (png_byte)c;
  185190. }
  185191. }
  185192. if (error_message == NULL)
  185193. buffer[iout] = 0;
  185194. else
  185195. {
  185196. buffer[iout++] = ':';
  185197. buffer[iout++] = ' ';
  185198. png_strncpy(buffer+iout, error_message, 63);
  185199. buffer[iout+63] = 0;
  185200. }
  185201. }
  185202. #ifdef PNG_READ_SUPPORTED
  185203. void PNGAPI
  185204. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185205. {
  185206. char msg[18+64];
  185207. if (png_ptr == NULL)
  185208. png_error(png_ptr, error_message);
  185209. else
  185210. {
  185211. png_format_buffer(png_ptr, msg, error_message);
  185212. png_error(png_ptr, msg);
  185213. }
  185214. }
  185215. #endif /* PNG_READ_SUPPORTED */
  185216. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185217. #ifndef PNG_NO_WARNINGS
  185218. void PNGAPI
  185219. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185220. {
  185221. char msg[18+64];
  185222. if (png_ptr == NULL)
  185223. png_warning(png_ptr, warning_message);
  185224. else
  185225. {
  185226. png_format_buffer(png_ptr, msg, warning_message);
  185227. png_warning(png_ptr, msg);
  185228. }
  185229. }
  185230. #endif /* PNG_NO_WARNINGS */
  185231. /* This is the default error handling function. Note that replacements for
  185232. * this function MUST NOT RETURN, or the program will likely crash. This
  185233. * function is used by default, or if the program supplies NULL for the
  185234. * error function pointer in png_set_error_fn().
  185235. */
  185236. static void /* PRIVATE */
  185237. png_default_error(png_structp, png_const_charp error_message)
  185238. {
  185239. #ifndef PNG_NO_CONSOLE_IO
  185240. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185241. if (*error_message == '#')
  185242. {
  185243. int offset;
  185244. char error_number[16];
  185245. for (offset=0; offset<15; offset++)
  185246. {
  185247. error_number[offset] = *(error_message+offset+1);
  185248. if (*(error_message+offset) == ' ')
  185249. break;
  185250. }
  185251. if((offset > 1) && (offset < 15))
  185252. {
  185253. error_number[offset-1]='\0';
  185254. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185255. error_message+offset);
  185256. }
  185257. else
  185258. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185259. }
  185260. else
  185261. #endif
  185262. fprintf(stderr, "libpng error: %s\n", error_message);
  185263. #endif
  185264. #ifdef PNG_SETJMP_SUPPORTED
  185265. if (png_ptr)
  185266. {
  185267. # ifdef USE_FAR_KEYWORD
  185268. {
  185269. jmp_buf jmpbuf;
  185270. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185271. longjmp(jmpbuf, 1);
  185272. }
  185273. # else
  185274. longjmp(png_ptr->jmpbuf, 1);
  185275. # endif
  185276. }
  185277. #else
  185278. PNG_ABORT();
  185279. #endif
  185280. #ifdef PNG_NO_CONSOLE_IO
  185281. error_message = error_message; /* make compiler happy */
  185282. #endif
  185283. }
  185284. #ifndef PNG_NO_WARNINGS
  185285. /* This function is called when there is a warning, but the library thinks
  185286. * it can continue anyway. Replacement functions don't have to do anything
  185287. * here if you don't want them to. In the default configuration, png_ptr is
  185288. * not used, but it is passed in case it may be useful.
  185289. */
  185290. static void /* PRIVATE */
  185291. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185292. {
  185293. #ifndef PNG_NO_CONSOLE_IO
  185294. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185295. if (*warning_message == '#')
  185296. {
  185297. int offset;
  185298. char warning_number[16];
  185299. for (offset=0; offset<15; offset++)
  185300. {
  185301. warning_number[offset]=*(warning_message+offset+1);
  185302. if (*(warning_message+offset) == ' ')
  185303. break;
  185304. }
  185305. if((offset > 1) && (offset < 15))
  185306. {
  185307. warning_number[offset-1]='\0';
  185308. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185309. warning_message+offset);
  185310. }
  185311. else
  185312. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185313. }
  185314. else
  185315. # endif
  185316. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185317. #else
  185318. warning_message = warning_message; /* make compiler happy */
  185319. #endif
  185320. png_ptr = png_ptr; /* make compiler happy */
  185321. }
  185322. #endif /* PNG_NO_WARNINGS */
  185323. /* This function is called when the application wants to use another method
  185324. * of handling errors and warnings. Note that the error function MUST NOT
  185325. * return to the calling routine or serious problems will occur. The return
  185326. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185327. */
  185328. void PNGAPI
  185329. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185330. png_error_ptr error_fn, png_error_ptr warning_fn)
  185331. {
  185332. if (png_ptr == NULL)
  185333. return;
  185334. png_ptr->error_ptr = error_ptr;
  185335. png_ptr->error_fn = error_fn;
  185336. png_ptr->warning_fn = warning_fn;
  185337. }
  185338. /* This function returns a pointer to the error_ptr associated with the user
  185339. * functions. The application should free any memory associated with this
  185340. * pointer before png_write_destroy and png_read_destroy are called.
  185341. */
  185342. png_voidp PNGAPI
  185343. png_get_error_ptr(png_structp png_ptr)
  185344. {
  185345. if (png_ptr == NULL)
  185346. return NULL;
  185347. return ((png_voidp)png_ptr->error_ptr);
  185348. }
  185349. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185350. void PNGAPI
  185351. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185352. {
  185353. if(png_ptr != NULL)
  185354. {
  185355. png_ptr->flags &=
  185356. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185357. }
  185358. }
  185359. #endif
  185360. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185361. /*** End of inlined file: pngerror.c ***/
  185362. /*** Start of inlined file: pngget.c ***/
  185363. /* pngget.c - retrieval of values from info struct
  185364. *
  185365. * Last changed in libpng 1.2.15 January 5, 2007
  185366. * For conditions of distribution and use, see copyright notice in png.h
  185367. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185368. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185369. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185370. */
  185371. #define PNG_INTERNAL
  185372. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185373. png_uint_32 PNGAPI
  185374. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185375. {
  185376. if (png_ptr != NULL && info_ptr != NULL)
  185377. return(info_ptr->valid & flag);
  185378. else
  185379. return(0);
  185380. }
  185381. png_uint_32 PNGAPI
  185382. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185383. {
  185384. if (png_ptr != NULL && info_ptr != NULL)
  185385. return(info_ptr->rowbytes);
  185386. else
  185387. return(0);
  185388. }
  185389. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185390. png_bytepp PNGAPI
  185391. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185392. {
  185393. if (png_ptr != NULL && info_ptr != NULL)
  185394. return(info_ptr->row_pointers);
  185395. else
  185396. return(0);
  185397. }
  185398. #endif
  185399. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185400. /* easy access to info, added in libpng-0.99 */
  185401. png_uint_32 PNGAPI
  185402. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185403. {
  185404. if (png_ptr != NULL && info_ptr != NULL)
  185405. {
  185406. return info_ptr->width;
  185407. }
  185408. return (0);
  185409. }
  185410. png_uint_32 PNGAPI
  185411. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185412. {
  185413. if (png_ptr != NULL && info_ptr != NULL)
  185414. {
  185415. return info_ptr->height;
  185416. }
  185417. return (0);
  185418. }
  185419. png_byte PNGAPI
  185420. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185421. {
  185422. if (png_ptr != NULL && info_ptr != NULL)
  185423. {
  185424. return info_ptr->bit_depth;
  185425. }
  185426. return (0);
  185427. }
  185428. png_byte PNGAPI
  185429. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185430. {
  185431. if (png_ptr != NULL && info_ptr != NULL)
  185432. {
  185433. return info_ptr->color_type;
  185434. }
  185435. return (0);
  185436. }
  185437. png_byte PNGAPI
  185438. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185439. {
  185440. if (png_ptr != NULL && info_ptr != NULL)
  185441. {
  185442. return info_ptr->filter_type;
  185443. }
  185444. return (0);
  185445. }
  185446. png_byte PNGAPI
  185447. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185448. {
  185449. if (png_ptr != NULL && info_ptr != NULL)
  185450. {
  185451. return info_ptr->interlace_type;
  185452. }
  185453. return (0);
  185454. }
  185455. png_byte PNGAPI
  185456. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185457. {
  185458. if (png_ptr != NULL && info_ptr != NULL)
  185459. {
  185460. return info_ptr->compression_type;
  185461. }
  185462. return (0);
  185463. }
  185464. png_uint_32 PNGAPI
  185465. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185466. {
  185467. if (png_ptr != NULL && info_ptr != NULL)
  185468. #if defined(PNG_pHYs_SUPPORTED)
  185469. if (info_ptr->valid & PNG_INFO_pHYs)
  185470. {
  185471. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185472. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185473. return (0);
  185474. else return (info_ptr->x_pixels_per_unit);
  185475. }
  185476. #else
  185477. return (0);
  185478. #endif
  185479. return (0);
  185480. }
  185481. png_uint_32 PNGAPI
  185482. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185483. {
  185484. if (png_ptr != NULL && info_ptr != NULL)
  185485. #if defined(PNG_pHYs_SUPPORTED)
  185486. if (info_ptr->valid & PNG_INFO_pHYs)
  185487. {
  185488. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185489. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185490. return (0);
  185491. else return (info_ptr->y_pixels_per_unit);
  185492. }
  185493. #else
  185494. return (0);
  185495. #endif
  185496. return (0);
  185497. }
  185498. png_uint_32 PNGAPI
  185499. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185500. {
  185501. if (png_ptr != NULL && info_ptr != NULL)
  185502. #if defined(PNG_pHYs_SUPPORTED)
  185503. if (info_ptr->valid & PNG_INFO_pHYs)
  185504. {
  185505. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185506. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185507. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185508. return (0);
  185509. else return (info_ptr->x_pixels_per_unit);
  185510. }
  185511. #else
  185512. return (0);
  185513. #endif
  185514. return (0);
  185515. }
  185516. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185517. float PNGAPI
  185518. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185519. {
  185520. if (png_ptr != NULL && info_ptr != NULL)
  185521. #if defined(PNG_pHYs_SUPPORTED)
  185522. if (info_ptr->valid & PNG_INFO_pHYs)
  185523. {
  185524. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185525. if (info_ptr->x_pixels_per_unit == 0)
  185526. return ((float)0.0);
  185527. else
  185528. return ((float)((float)info_ptr->y_pixels_per_unit
  185529. /(float)info_ptr->x_pixels_per_unit));
  185530. }
  185531. #else
  185532. return (0.0);
  185533. #endif
  185534. return ((float)0.0);
  185535. }
  185536. #endif
  185537. png_int_32 PNGAPI
  185538. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185539. {
  185540. if (png_ptr != NULL && info_ptr != NULL)
  185541. #if defined(PNG_oFFs_SUPPORTED)
  185542. if (info_ptr->valid & PNG_INFO_oFFs)
  185543. {
  185544. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185545. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185546. return (0);
  185547. else return (info_ptr->x_offset);
  185548. }
  185549. #else
  185550. return (0);
  185551. #endif
  185552. return (0);
  185553. }
  185554. png_int_32 PNGAPI
  185555. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185556. {
  185557. if (png_ptr != NULL && info_ptr != NULL)
  185558. #if defined(PNG_oFFs_SUPPORTED)
  185559. if (info_ptr->valid & PNG_INFO_oFFs)
  185560. {
  185561. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185562. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185563. return (0);
  185564. else return (info_ptr->y_offset);
  185565. }
  185566. #else
  185567. return (0);
  185568. #endif
  185569. return (0);
  185570. }
  185571. png_int_32 PNGAPI
  185572. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185573. {
  185574. if (png_ptr != NULL && info_ptr != NULL)
  185575. #if defined(PNG_oFFs_SUPPORTED)
  185576. if (info_ptr->valid & PNG_INFO_oFFs)
  185577. {
  185578. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185579. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185580. return (0);
  185581. else return (info_ptr->x_offset);
  185582. }
  185583. #else
  185584. return (0);
  185585. #endif
  185586. return (0);
  185587. }
  185588. png_int_32 PNGAPI
  185589. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185590. {
  185591. if (png_ptr != NULL && info_ptr != NULL)
  185592. #if defined(PNG_oFFs_SUPPORTED)
  185593. if (info_ptr->valid & PNG_INFO_oFFs)
  185594. {
  185595. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185596. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185597. return (0);
  185598. else return (info_ptr->y_offset);
  185599. }
  185600. #else
  185601. return (0);
  185602. #endif
  185603. return (0);
  185604. }
  185605. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185606. png_uint_32 PNGAPI
  185607. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185608. {
  185609. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185610. *.0254 +.5));
  185611. }
  185612. png_uint_32 PNGAPI
  185613. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185614. {
  185615. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185616. *.0254 +.5));
  185617. }
  185618. png_uint_32 PNGAPI
  185619. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185620. {
  185621. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185622. *.0254 +.5));
  185623. }
  185624. float PNGAPI
  185625. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185626. {
  185627. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185628. *.00003937);
  185629. }
  185630. float PNGAPI
  185631. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185632. {
  185633. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185634. *.00003937);
  185635. }
  185636. #if defined(PNG_pHYs_SUPPORTED)
  185637. png_uint_32 PNGAPI
  185638. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185639. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185640. {
  185641. png_uint_32 retval = 0;
  185642. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185643. {
  185644. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185645. if (res_x != NULL)
  185646. {
  185647. *res_x = info_ptr->x_pixels_per_unit;
  185648. retval |= PNG_INFO_pHYs;
  185649. }
  185650. if (res_y != NULL)
  185651. {
  185652. *res_y = info_ptr->y_pixels_per_unit;
  185653. retval |= PNG_INFO_pHYs;
  185654. }
  185655. if (unit_type != NULL)
  185656. {
  185657. *unit_type = (int)info_ptr->phys_unit_type;
  185658. retval |= PNG_INFO_pHYs;
  185659. if(*unit_type == 1)
  185660. {
  185661. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185662. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185663. }
  185664. }
  185665. }
  185666. return (retval);
  185667. }
  185668. #endif /* PNG_pHYs_SUPPORTED */
  185669. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185670. /* png_get_channels really belongs in here, too, but it's been around longer */
  185671. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185672. png_byte PNGAPI
  185673. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185674. {
  185675. if (png_ptr != NULL && info_ptr != NULL)
  185676. return(info_ptr->channels);
  185677. else
  185678. return (0);
  185679. }
  185680. png_bytep PNGAPI
  185681. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185682. {
  185683. if (png_ptr != NULL && info_ptr != NULL)
  185684. return(info_ptr->signature);
  185685. else
  185686. return (NULL);
  185687. }
  185688. #if defined(PNG_bKGD_SUPPORTED)
  185689. png_uint_32 PNGAPI
  185690. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185691. png_color_16p *background)
  185692. {
  185693. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185694. && background != NULL)
  185695. {
  185696. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185697. *background = &(info_ptr->background);
  185698. return (PNG_INFO_bKGD);
  185699. }
  185700. return (0);
  185701. }
  185702. #endif
  185703. #if defined(PNG_cHRM_SUPPORTED)
  185704. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185705. png_uint_32 PNGAPI
  185706. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185707. double *white_x, double *white_y, double *red_x, double *red_y,
  185708. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185709. {
  185710. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185711. {
  185712. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185713. if (white_x != NULL)
  185714. *white_x = (double)info_ptr->x_white;
  185715. if (white_y != NULL)
  185716. *white_y = (double)info_ptr->y_white;
  185717. if (red_x != NULL)
  185718. *red_x = (double)info_ptr->x_red;
  185719. if (red_y != NULL)
  185720. *red_y = (double)info_ptr->y_red;
  185721. if (green_x != NULL)
  185722. *green_x = (double)info_ptr->x_green;
  185723. if (green_y != NULL)
  185724. *green_y = (double)info_ptr->y_green;
  185725. if (blue_x != NULL)
  185726. *blue_x = (double)info_ptr->x_blue;
  185727. if (blue_y != NULL)
  185728. *blue_y = (double)info_ptr->y_blue;
  185729. return (PNG_INFO_cHRM);
  185730. }
  185731. return (0);
  185732. }
  185733. #endif
  185734. #ifdef PNG_FIXED_POINT_SUPPORTED
  185735. png_uint_32 PNGAPI
  185736. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185737. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185738. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185739. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185740. {
  185741. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185742. {
  185743. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185744. if (white_x != NULL)
  185745. *white_x = info_ptr->int_x_white;
  185746. if (white_y != NULL)
  185747. *white_y = info_ptr->int_y_white;
  185748. if (red_x != NULL)
  185749. *red_x = info_ptr->int_x_red;
  185750. if (red_y != NULL)
  185751. *red_y = info_ptr->int_y_red;
  185752. if (green_x != NULL)
  185753. *green_x = info_ptr->int_x_green;
  185754. if (green_y != NULL)
  185755. *green_y = info_ptr->int_y_green;
  185756. if (blue_x != NULL)
  185757. *blue_x = info_ptr->int_x_blue;
  185758. if (blue_y != NULL)
  185759. *blue_y = info_ptr->int_y_blue;
  185760. return (PNG_INFO_cHRM);
  185761. }
  185762. return (0);
  185763. }
  185764. #endif
  185765. #endif
  185766. #if defined(PNG_gAMA_SUPPORTED)
  185767. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185768. png_uint_32 PNGAPI
  185769. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185770. {
  185771. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185772. && file_gamma != NULL)
  185773. {
  185774. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185775. *file_gamma = (double)info_ptr->gamma;
  185776. return (PNG_INFO_gAMA);
  185777. }
  185778. return (0);
  185779. }
  185780. #endif
  185781. #ifdef PNG_FIXED_POINT_SUPPORTED
  185782. png_uint_32 PNGAPI
  185783. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185784. png_fixed_point *int_file_gamma)
  185785. {
  185786. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185787. && int_file_gamma != NULL)
  185788. {
  185789. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185790. *int_file_gamma = info_ptr->int_gamma;
  185791. return (PNG_INFO_gAMA);
  185792. }
  185793. return (0);
  185794. }
  185795. #endif
  185796. #endif
  185797. #if defined(PNG_sRGB_SUPPORTED)
  185798. png_uint_32 PNGAPI
  185799. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185800. {
  185801. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185802. && file_srgb_intent != NULL)
  185803. {
  185804. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185805. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185806. return (PNG_INFO_sRGB);
  185807. }
  185808. return (0);
  185809. }
  185810. #endif
  185811. #if defined(PNG_iCCP_SUPPORTED)
  185812. png_uint_32 PNGAPI
  185813. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185814. png_charpp name, int *compression_type,
  185815. png_charpp profile, png_uint_32 *proflen)
  185816. {
  185817. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185818. && name != NULL && profile != NULL && proflen != NULL)
  185819. {
  185820. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185821. *name = info_ptr->iccp_name;
  185822. *profile = info_ptr->iccp_profile;
  185823. /* compression_type is a dummy so the API won't have to change
  185824. if we introduce multiple compression types later. */
  185825. *proflen = (int)info_ptr->iccp_proflen;
  185826. *compression_type = (int)info_ptr->iccp_compression;
  185827. return (PNG_INFO_iCCP);
  185828. }
  185829. return (0);
  185830. }
  185831. #endif
  185832. #if defined(PNG_sPLT_SUPPORTED)
  185833. png_uint_32 PNGAPI
  185834. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185835. png_sPLT_tpp spalettes)
  185836. {
  185837. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185838. {
  185839. *spalettes = info_ptr->splt_palettes;
  185840. return ((png_uint_32)info_ptr->splt_palettes_num);
  185841. }
  185842. return (0);
  185843. }
  185844. #endif
  185845. #if defined(PNG_hIST_SUPPORTED)
  185846. png_uint_32 PNGAPI
  185847. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185848. {
  185849. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185850. && hist != NULL)
  185851. {
  185852. png_debug1(1, "in %s retrieval function\n", "hIST");
  185853. *hist = info_ptr->hist;
  185854. return (PNG_INFO_hIST);
  185855. }
  185856. return (0);
  185857. }
  185858. #endif
  185859. png_uint_32 PNGAPI
  185860. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185861. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185862. int *color_type, int *interlace_type, int *compression_type,
  185863. int *filter_type)
  185864. {
  185865. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185866. bit_depth != NULL && color_type != NULL)
  185867. {
  185868. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185869. *width = info_ptr->width;
  185870. *height = info_ptr->height;
  185871. *bit_depth = info_ptr->bit_depth;
  185872. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185873. png_error(png_ptr, "Invalid bit depth");
  185874. *color_type = info_ptr->color_type;
  185875. if (info_ptr->color_type > 6)
  185876. png_error(png_ptr, "Invalid color type");
  185877. if (compression_type != NULL)
  185878. *compression_type = info_ptr->compression_type;
  185879. if (filter_type != NULL)
  185880. *filter_type = info_ptr->filter_type;
  185881. if (interlace_type != NULL)
  185882. *interlace_type = info_ptr->interlace_type;
  185883. /* check for potential overflow of rowbytes */
  185884. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185885. png_error(png_ptr, "Invalid image width");
  185886. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185887. png_error(png_ptr, "Invalid image height");
  185888. if (info_ptr->width > (PNG_UINT_32_MAX
  185889. >> 3) /* 8-byte RGBA pixels */
  185890. - 64 /* bigrowbuf hack */
  185891. - 1 /* filter byte */
  185892. - 7*8 /* rounding of width to multiple of 8 pixels */
  185893. - 8) /* extra max_pixel_depth pad */
  185894. {
  185895. png_warning(png_ptr,
  185896. "Width too large for libpng to process image data.");
  185897. }
  185898. return (1);
  185899. }
  185900. return (0);
  185901. }
  185902. #if defined(PNG_oFFs_SUPPORTED)
  185903. png_uint_32 PNGAPI
  185904. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185905. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185906. {
  185907. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185908. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185909. {
  185910. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185911. *offset_x = info_ptr->x_offset;
  185912. *offset_y = info_ptr->y_offset;
  185913. *unit_type = (int)info_ptr->offset_unit_type;
  185914. return (PNG_INFO_oFFs);
  185915. }
  185916. return (0);
  185917. }
  185918. #endif
  185919. #if defined(PNG_pCAL_SUPPORTED)
  185920. png_uint_32 PNGAPI
  185921. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185922. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185923. png_charp *units, png_charpp *params)
  185924. {
  185925. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185926. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185927. nparams != NULL && units != NULL && params != NULL)
  185928. {
  185929. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185930. *purpose = info_ptr->pcal_purpose;
  185931. *X0 = info_ptr->pcal_X0;
  185932. *X1 = info_ptr->pcal_X1;
  185933. *type = (int)info_ptr->pcal_type;
  185934. *nparams = (int)info_ptr->pcal_nparams;
  185935. *units = info_ptr->pcal_units;
  185936. *params = info_ptr->pcal_params;
  185937. return (PNG_INFO_pCAL);
  185938. }
  185939. return (0);
  185940. }
  185941. #endif
  185942. #if defined(PNG_sCAL_SUPPORTED)
  185943. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185944. png_uint_32 PNGAPI
  185945. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185946. int *unit, double *width, double *height)
  185947. {
  185948. if (png_ptr != NULL && info_ptr != NULL &&
  185949. (info_ptr->valid & PNG_INFO_sCAL))
  185950. {
  185951. *unit = info_ptr->scal_unit;
  185952. *width = info_ptr->scal_pixel_width;
  185953. *height = info_ptr->scal_pixel_height;
  185954. return (PNG_INFO_sCAL);
  185955. }
  185956. return(0);
  185957. }
  185958. #else
  185959. #ifdef PNG_FIXED_POINT_SUPPORTED
  185960. png_uint_32 PNGAPI
  185961. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185962. int *unit, png_charpp width, png_charpp height)
  185963. {
  185964. if (png_ptr != NULL && info_ptr != NULL &&
  185965. (info_ptr->valid & PNG_INFO_sCAL))
  185966. {
  185967. *unit = info_ptr->scal_unit;
  185968. *width = info_ptr->scal_s_width;
  185969. *height = info_ptr->scal_s_height;
  185970. return (PNG_INFO_sCAL);
  185971. }
  185972. return(0);
  185973. }
  185974. #endif
  185975. #endif
  185976. #endif
  185977. #if defined(PNG_pHYs_SUPPORTED)
  185978. png_uint_32 PNGAPI
  185979. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185980. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185981. {
  185982. png_uint_32 retval = 0;
  185983. if (png_ptr != NULL && info_ptr != NULL &&
  185984. (info_ptr->valid & PNG_INFO_pHYs))
  185985. {
  185986. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185987. if (res_x != NULL)
  185988. {
  185989. *res_x = info_ptr->x_pixels_per_unit;
  185990. retval |= PNG_INFO_pHYs;
  185991. }
  185992. if (res_y != NULL)
  185993. {
  185994. *res_y = info_ptr->y_pixels_per_unit;
  185995. retval |= PNG_INFO_pHYs;
  185996. }
  185997. if (unit_type != NULL)
  185998. {
  185999. *unit_type = (int)info_ptr->phys_unit_type;
  186000. retval |= PNG_INFO_pHYs;
  186001. }
  186002. }
  186003. return (retval);
  186004. }
  186005. #endif
  186006. png_uint_32 PNGAPI
  186007. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186008. int *num_palette)
  186009. {
  186010. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186011. && palette != NULL)
  186012. {
  186013. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186014. *palette = info_ptr->palette;
  186015. *num_palette = info_ptr->num_palette;
  186016. png_debug1(3, "num_palette = %d\n", *num_palette);
  186017. return (PNG_INFO_PLTE);
  186018. }
  186019. return (0);
  186020. }
  186021. #if defined(PNG_sBIT_SUPPORTED)
  186022. png_uint_32 PNGAPI
  186023. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186024. {
  186025. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186026. && sig_bit != NULL)
  186027. {
  186028. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186029. *sig_bit = &(info_ptr->sig_bit);
  186030. return (PNG_INFO_sBIT);
  186031. }
  186032. return (0);
  186033. }
  186034. #endif
  186035. #if defined(PNG_TEXT_SUPPORTED)
  186036. png_uint_32 PNGAPI
  186037. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186038. int *num_text)
  186039. {
  186040. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186041. {
  186042. png_debug1(1, "in %s retrieval function\n",
  186043. (png_ptr->chunk_name[0] == '\0' ? "text"
  186044. : (png_const_charp)png_ptr->chunk_name));
  186045. if (text_ptr != NULL)
  186046. *text_ptr = info_ptr->text;
  186047. if (num_text != NULL)
  186048. *num_text = info_ptr->num_text;
  186049. return ((png_uint_32)info_ptr->num_text);
  186050. }
  186051. if (num_text != NULL)
  186052. *num_text = 0;
  186053. return(0);
  186054. }
  186055. #endif
  186056. #if defined(PNG_tIME_SUPPORTED)
  186057. png_uint_32 PNGAPI
  186058. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186059. {
  186060. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186061. && mod_time != NULL)
  186062. {
  186063. png_debug1(1, "in %s retrieval function\n", "tIME");
  186064. *mod_time = &(info_ptr->mod_time);
  186065. return (PNG_INFO_tIME);
  186066. }
  186067. return (0);
  186068. }
  186069. #endif
  186070. #if defined(PNG_tRNS_SUPPORTED)
  186071. png_uint_32 PNGAPI
  186072. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186073. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186074. {
  186075. png_uint_32 retval = 0;
  186076. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186077. {
  186078. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186079. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186080. {
  186081. if (trans != NULL)
  186082. {
  186083. *trans = info_ptr->trans;
  186084. retval |= PNG_INFO_tRNS;
  186085. }
  186086. if (trans_values != NULL)
  186087. *trans_values = &(info_ptr->trans_values);
  186088. }
  186089. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186090. {
  186091. if (trans_values != NULL)
  186092. {
  186093. *trans_values = &(info_ptr->trans_values);
  186094. retval |= PNG_INFO_tRNS;
  186095. }
  186096. if(trans != NULL)
  186097. *trans = NULL;
  186098. }
  186099. if(num_trans != NULL)
  186100. {
  186101. *num_trans = info_ptr->num_trans;
  186102. retval |= PNG_INFO_tRNS;
  186103. }
  186104. }
  186105. return (retval);
  186106. }
  186107. #endif
  186108. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186109. png_uint_32 PNGAPI
  186110. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186111. png_unknown_chunkpp unknowns)
  186112. {
  186113. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186114. {
  186115. *unknowns = info_ptr->unknown_chunks;
  186116. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186117. }
  186118. return (0);
  186119. }
  186120. #endif
  186121. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186122. png_byte PNGAPI
  186123. png_get_rgb_to_gray_status (png_structp png_ptr)
  186124. {
  186125. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186126. }
  186127. #endif
  186128. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186129. png_voidp PNGAPI
  186130. png_get_user_chunk_ptr(png_structp png_ptr)
  186131. {
  186132. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186133. }
  186134. #endif
  186135. #ifdef PNG_WRITE_SUPPORTED
  186136. png_uint_32 PNGAPI
  186137. png_get_compression_buffer_size(png_structp png_ptr)
  186138. {
  186139. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186140. }
  186141. #endif
  186142. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186143. #ifndef PNG_1_0_X
  186144. /* this function was added to libpng 1.2.0 and should exist by default */
  186145. png_uint_32 PNGAPI
  186146. png_get_asm_flags (png_structp png_ptr)
  186147. {
  186148. /* obsolete, to be removed from libpng-1.4.0 */
  186149. return (png_ptr? 0L: 0L);
  186150. }
  186151. /* this function was added to libpng 1.2.0 and should exist by default */
  186152. png_uint_32 PNGAPI
  186153. png_get_asm_flagmask (int flag_select)
  186154. {
  186155. /* obsolete, to be removed from libpng-1.4.0 */
  186156. flag_select=flag_select;
  186157. return 0L;
  186158. }
  186159. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186160. /* this function was added to libpng 1.2.0 */
  186161. png_uint_32 PNGAPI
  186162. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186163. {
  186164. /* obsolete, to be removed from libpng-1.4.0 */
  186165. flag_select=flag_select;
  186166. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186167. return 0L;
  186168. }
  186169. /* this function was added to libpng 1.2.0 */
  186170. png_byte PNGAPI
  186171. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186172. {
  186173. /* obsolete, to be removed from libpng-1.4.0 */
  186174. return (png_ptr? 0: 0);
  186175. }
  186176. /* this function was added to libpng 1.2.0 */
  186177. png_uint_32 PNGAPI
  186178. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186179. {
  186180. /* obsolete, to be removed from libpng-1.4.0 */
  186181. return (png_ptr? 0L: 0L);
  186182. }
  186183. #endif /* ?PNG_1_0_X */
  186184. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186185. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186186. /* these functions were added to libpng 1.2.6 */
  186187. png_uint_32 PNGAPI
  186188. png_get_user_width_max (png_structp png_ptr)
  186189. {
  186190. return (png_ptr? png_ptr->user_width_max : 0);
  186191. }
  186192. png_uint_32 PNGAPI
  186193. png_get_user_height_max (png_structp png_ptr)
  186194. {
  186195. return (png_ptr? png_ptr->user_height_max : 0);
  186196. }
  186197. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186198. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186199. /*** End of inlined file: pngget.c ***/
  186200. /*** Start of inlined file: pngmem.c ***/
  186201. /* pngmem.c - stub functions for memory allocation
  186202. *
  186203. * Last changed in libpng 1.2.13 November 13, 2006
  186204. * For conditions of distribution and use, see copyright notice in png.h
  186205. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186206. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186207. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186208. *
  186209. * This file provides a location for all memory allocation. Users who
  186210. * need special memory handling are expected to supply replacement
  186211. * functions for png_malloc() and png_free(), and to use
  186212. * png_create_read_struct_2() and png_create_write_struct_2() to
  186213. * identify the replacement functions.
  186214. */
  186215. #define PNG_INTERNAL
  186216. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186217. /* Borland DOS special memory handler */
  186218. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186219. /* if you change this, be sure to change the one in png.h also */
  186220. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186221. by a single call to calloc() if this is thought to improve performance. */
  186222. png_voidp /* PRIVATE */
  186223. png_create_struct(int type)
  186224. {
  186225. #ifdef PNG_USER_MEM_SUPPORTED
  186226. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186227. }
  186228. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186229. png_voidp /* PRIVATE */
  186230. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186231. {
  186232. #endif /* PNG_USER_MEM_SUPPORTED */
  186233. png_size_t size;
  186234. png_voidp struct_ptr;
  186235. if (type == PNG_STRUCT_INFO)
  186236. size = png_sizeof(png_info);
  186237. else if (type == PNG_STRUCT_PNG)
  186238. size = png_sizeof(png_struct);
  186239. else
  186240. return (png_get_copyright(NULL));
  186241. #ifdef PNG_USER_MEM_SUPPORTED
  186242. if(malloc_fn != NULL)
  186243. {
  186244. png_struct dummy_struct;
  186245. png_structp png_ptr = &dummy_struct;
  186246. png_ptr->mem_ptr=mem_ptr;
  186247. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186248. }
  186249. else
  186250. #endif /* PNG_USER_MEM_SUPPORTED */
  186251. struct_ptr = (png_voidp)farmalloc(size);
  186252. if (struct_ptr != NULL)
  186253. png_memset(struct_ptr, 0, size);
  186254. return (struct_ptr);
  186255. }
  186256. /* Free memory allocated by a png_create_struct() call */
  186257. void /* PRIVATE */
  186258. png_destroy_struct(png_voidp struct_ptr)
  186259. {
  186260. #ifdef PNG_USER_MEM_SUPPORTED
  186261. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186262. }
  186263. /* Free memory allocated by a png_create_struct() call */
  186264. void /* PRIVATE */
  186265. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186266. png_voidp mem_ptr)
  186267. {
  186268. #endif
  186269. if (struct_ptr != NULL)
  186270. {
  186271. #ifdef PNG_USER_MEM_SUPPORTED
  186272. if(free_fn != NULL)
  186273. {
  186274. png_struct dummy_struct;
  186275. png_structp png_ptr = &dummy_struct;
  186276. png_ptr->mem_ptr=mem_ptr;
  186277. (*(free_fn))(png_ptr, struct_ptr);
  186278. return;
  186279. }
  186280. #endif /* PNG_USER_MEM_SUPPORTED */
  186281. farfree (struct_ptr);
  186282. }
  186283. }
  186284. /* Allocate memory. For reasonable files, size should never exceed
  186285. * 64K. However, zlib may allocate more then 64K if you don't tell
  186286. * it not to. See zconf.h and png.h for more information. zlib does
  186287. * need to allocate exactly 64K, so whatever you call here must
  186288. * have the ability to do that.
  186289. *
  186290. * Borland seems to have a problem in DOS mode for exactly 64K.
  186291. * It gives you a segment with an offset of 8 (perhaps to store its
  186292. * memory stuff). zlib doesn't like this at all, so we have to
  186293. * detect and deal with it. This code should not be needed in
  186294. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186295. * been updated by Alexander Lehmann for version 0.89 to waste less
  186296. * memory.
  186297. *
  186298. * Note that we can't use png_size_t for the "size" declaration,
  186299. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186300. * result, we would be truncating potentially larger memory requests
  186301. * (which should cause a fatal error) and introducing major problems.
  186302. */
  186303. png_voidp PNGAPI
  186304. png_malloc(png_structp png_ptr, png_uint_32 size)
  186305. {
  186306. png_voidp ret;
  186307. if (png_ptr == NULL || size == 0)
  186308. return (NULL);
  186309. #ifdef PNG_USER_MEM_SUPPORTED
  186310. if(png_ptr->malloc_fn != NULL)
  186311. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186312. else
  186313. ret = (png_malloc_default(png_ptr, size));
  186314. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186315. png_error(png_ptr, "Out of memory!");
  186316. return (ret);
  186317. }
  186318. png_voidp PNGAPI
  186319. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186320. {
  186321. png_voidp ret;
  186322. #endif /* PNG_USER_MEM_SUPPORTED */
  186323. if (png_ptr == NULL || size == 0)
  186324. return (NULL);
  186325. #ifdef PNG_MAX_MALLOC_64K
  186326. if (size > (png_uint_32)65536L)
  186327. {
  186328. png_warning(png_ptr, "Cannot Allocate > 64K");
  186329. ret = NULL;
  186330. }
  186331. else
  186332. #endif
  186333. if (size != (size_t)size)
  186334. ret = NULL;
  186335. else if (size == (png_uint_32)65536L)
  186336. {
  186337. if (png_ptr->offset_table == NULL)
  186338. {
  186339. /* try to see if we need to do any of this fancy stuff */
  186340. ret = farmalloc(size);
  186341. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186342. {
  186343. int num_blocks;
  186344. png_uint_32 total_size;
  186345. png_bytep table;
  186346. int i;
  186347. png_byte huge * hptr;
  186348. if (ret != NULL)
  186349. {
  186350. farfree(ret);
  186351. ret = NULL;
  186352. }
  186353. if(png_ptr->zlib_window_bits > 14)
  186354. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186355. else
  186356. num_blocks = 1;
  186357. if (png_ptr->zlib_mem_level >= 7)
  186358. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186359. else
  186360. num_blocks++;
  186361. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186362. table = farmalloc(total_size);
  186363. if (table == NULL)
  186364. {
  186365. #ifndef PNG_USER_MEM_SUPPORTED
  186366. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186367. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186368. else
  186369. png_warning(png_ptr, "Out Of Memory.");
  186370. #endif
  186371. return (NULL);
  186372. }
  186373. if ((png_size_t)table & 0xfff0)
  186374. {
  186375. #ifndef PNG_USER_MEM_SUPPORTED
  186376. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186377. png_error(png_ptr,
  186378. "Farmalloc didn't return normalized pointer");
  186379. else
  186380. png_warning(png_ptr,
  186381. "Farmalloc didn't return normalized pointer");
  186382. #endif
  186383. return (NULL);
  186384. }
  186385. png_ptr->offset_table = table;
  186386. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186387. png_sizeof (png_bytep));
  186388. if (png_ptr->offset_table_ptr == NULL)
  186389. {
  186390. #ifndef PNG_USER_MEM_SUPPORTED
  186391. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186392. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186393. else
  186394. png_warning(png_ptr, "Out Of memory.");
  186395. #endif
  186396. return (NULL);
  186397. }
  186398. hptr = (png_byte huge *)table;
  186399. if ((png_size_t)hptr & 0xf)
  186400. {
  186401. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186402. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186403. }
  186404. for (i = 0; i < num_blocks; i++)
  186405. {
  186406. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186407. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186408. }
  186409. png_ptr->offset_table_number = num_blocks;
  186410. png_ptr->offset_table_count = 0;
  186411. png_ptr->offset_table_count_free = 0;
  186412. }
  186413. }
  186414. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186415. {
  186416. #ifndef PNG_USER_MEM_SUPPORTED
  186417. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186418. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186419. else
  186420. png_warning(png_ptr, "Out of Memory.");
  186421. #endif
  186422. return (NULL);
  186423. }
  186424. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186425. }
  186426. else
  186427. ret = farmalloc(size);
  186428. #ifndef PNG_USER_MEM_SUPPORTED
  186429. if (ret == NULL)
  186430. {
  186431. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186432. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186433. else
  186434. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186435. }
  186436. #endif
  186437. return (ret);
  186438. }
  186439. /* free a pointer allocated by png_malloc(). In the default
  186440. configuration, png_ptr is not used, but is passed in case it
  186441. is needed. If ptr is NULL, return without taking any action. */
  186442. void PNGAPI
  186443. png_free(png_structp png_ptr, png_voidp ptr)
  186444. {
  186445. if (png_ptr == NULL || ptr == NULL)
  186446. return;
  186447. #ifdef PNG_USER_MEM_SUPPORTED
  186448. if (png_ptr->free_fn != NULL)
  186449. {
  186450. (*(png_ptr->free_fn))(png_ptr, ptr);
  186451. return;
  186452. }
  186453. else png_free_default(png_ptr, ptr);
  186454. }
  186455. void PNGAPI
  186456. png_free_default(png_structp png_ptr, png_voidp ptr)
  186457. {
  186458. #endif /* PNG_USER_MEM_SUPPORTED */
  186459. if(png_ptr == NULL) return;
  186460. if (png_ptr->offset_table != NULL)
  186461. {
  186462. int i;
  186463. for (i = 0; i < png_ptr->offset_table_count; i++)
  186464. {
  186465. if (ptr == png_ptr->offset_table_ptr[i])
  186466. {
  186467. ptr = NULL;
  186468. png_ptr->offset_table_count_free++;
  186469. break;
  186470. }
  186471. }
  186472. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186473. {
  186474. farfree(png_ptr->offset_table);
  186475. farfree(png_ptr->offset_table_ptr);
  186476. png_ptr->offset_table = NULL;
  186477. png_ptr->offset_table_ptr = NULL;
  186478. }
  186479. }
  186480. if (ptr != NULL)
  186481. {
  186482. farfree(ptr);
  186483. }
  186484. }
  186485. #else /* Not the Borland DOS special memory handler */
  186486. /* Allocate memory for a png_struct or a png_info. The malloc and
  186487. memset can be replaced by a single call to calloc() if this is thought
  186488. to improve performance noticably. */
  186489. png_voidp /* PRIVATE */
  186490. png_create_struct(int type)
  186491. {
  186492. #ifdef PNG_USER_MEM_SUPPORTED
  186493. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186494. }
  186495. /* Allocate memory for a png_struct or a png_info. The malloc and
  186496. memset can be replaced by a single call to calloc() if this is thought
  186497. to improve performance noticably. */
  186498. png_voidp /* PRIVATE */
  186499. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186500. {
  186501. #endif /* PNG_USER_MEM_SUPPORTED */
  186502. png_size_t size;
  186503. png_voidp struct_ptr;
  186504. if (type == PNG_STRUCT_INFO)
  186505. size = png_sizeof(png_info);
  186506. else if (type == PNG_STRUCT_PNG)
  186507. size = png_sizeof(png_struct);
  186508. else
  186509. return (NULL);
  186510. #ifdef PNG_USER_MEM_SUPPORTED
  186511. if(malloc_fn != NULL)
  186512. {
  186513. png_struct dummy_struct;
  186514. png_structp png_ptr = &dummy_struct;
  186515. png_ptr->mem_ptr=mem_ptr;
  186516. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186517. if (struct_ptr != NULL)
  186518. png_memset(struct_ptr, 0, size);
  186519. return (struct_ptr);
  186520. }
  186521. #endif /* PNG_USER_MEM_SUPPORTED */
  186522. #if defined(__TURBOC__) && !defined(__FLAT__)
  186523. struct_ptr = (png_voidp)farmalloc(size);
  186524. #else
  186525. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186526. struct_ptr = (png_voidp)halloc(size,1);
  186527. # else
  186528. struct_ptr = (png_voidp)malloc(size);
  186529. # endif
  186530. #endif
  186531. if (struct_ptr != NULL)
  186532. png_memset(struct_ptr, 0, size);
  186533. return (struct_ptr);
  186534. }
  186535. /* Free memory allocated by a png_create_struct() call */
  186536. void /* PRIVATE */
  186537. png_destroy_struct(png_voidp struct_ptr)
  186538. {
  186539. #ifdef PNG_USER_MEM_SUPPORTED
  186540. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186541. }
  186542. /* Free memory allocated by a png_create_struct() call */
  186543. void /* PRIVATE */
  186544. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186545. png_voidp mem_ptr)
  186546. {
  186547. #endif /* PNG_USER_MEM_SUPPORTED */
  186548. if (struct_ptr != NULL)
  186549. {
  186550. #ifdef PNG_USER_MEM_SUPPORTED
  186551. if(free_fn != NULL)
  186552. {
  186553. png_struct dummy_struct;
  186554. png_structp png_ptr = &dummy_struct;
  186555. png_ptr->mem_ptr=mem_ptr;
  186556. (*(free_fn))(png_ptr, struct_ptr);
  186557. return;
  186558. }
  186559. #endif /* PNG_USER_MEM_SUPPORTED */
  186560. #if defined(__TURBOC__) && !defined(__FLAT__)
  186561. farfree(struct_ptr);
  186562. #else
  186563. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186564. hfree(struct_ptr);
  186565. # else
  186566. free(struct_ptr);
  186567. # endif
  186568. #endif
  186569. }
  186570. }
  186571. /* Allocate memory. For reasonable files, size should never exceed
  186572. 64K. However, zlib may allocate more then 64K if you don't tell
  186573. it not to. See zconf.h and png.h for more information. zlib does
  186574. need to allocate exactly 64K, so whatever you call here must
  186575. have the ability to do that. */
  186576. png_voidp PNGAPI
  186577. png_malloc(png_structp png_ptr, png_uint_32 size)
  186578. {
  186579. png_voidp ret;
  186580. #ifdef PNG_USER_MEM_SUPPORTED
  186581. if (png_ptr == NULL || size == 0)
  186582. return (NULL);
  186583. if(png_ptr->malloc_fn != NULL)
  186584. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186585. else
  186586. ret = (png_malloc_default(png_ptr, size));
  186587. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186588. png_error(png_ptr, "Out of Memory!");
  186589. return (ret);
  186590. }
  186591. png_voidp PNGAPI
  186592. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186593. {
  186594. png_voidp ret;
  186595. #endif /* PNG_USER_MEM_SUPPORTED */
  186596. if (png_ptr == NULL || size == 0)
  186597. return (NULL);
  186598. #ifdef PNG_MAX_MALLOC_64K
  186599. if (size > (png_uint_32)65536L)
  186600. {
  186601. #ifndef PNG_USER_MEM_SUPPORTED
  186602. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186603. png_error(png_ptr, "Cannot Allocate > 64K");
  186604. else
  186605. #endif
  186606. return NULL;
  186607. }
  186608. #endif
  186609. /* Check for overflow */
  186610. #if defined(__TURBOC__) && !defined(__FLAT__)
  186611. if (size != (unsigned long)size)
  186612. ret = NULL;
  186613. else
  186614. ret = farmalloc(size);
  186615. #else
  186616. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186617. if (size != (unsigned long)size)
  186618. ret = NULL;
  186619. else
  186620. ret = halloc(size, 1);
  186621. # else
  186622. if (size != (size_t)size)
  186623. ret = NULL;
  186624. else
  186625. ret = malloc((size_t)size);
  186626. # endif
  186627. #endif
  186628. #ifndef PNG_USER_MEM_SUPPORTED
  186629. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186630. png_error(png_ptr, "Out of Memory");
  186631. #endif
  186632. return (ret);
  186633. }
  186634. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186635. without taking any action. */
  186636. void PNGAPI
  186637. png_free(png_structp png_ptr, png_voidp ptr)
  186638. {
  186639. if (png_ptr == NULL || ptr == NULL)
  186640. return;
  186641. #ifdef PNG_USER_MEM_SUPPORTED
  186642. if (png_ptr->free_fn != NULL)
  186643. {
  186644. (*(png_ptr->free_fn))(png_ptr, ptr);
  186645. return;
  186646. }
  186647. else png_free_default(png_ptr, ptr);
  186648. }
  186649. void PNGAPI
  186650. png_free_default(png_structp png_ptr, png_voidp ptr)
  186651. {
  186652. if (png_ptr == NULL || ptr == NULL)
  186653. return;
  186654. #endif /* PNG_USER_MEM_SUPPORTED */
  186655. #if defined(__TURBOC__) && !defined(__FLAT__)
  186656. farfree(ptr);
  186657. #else
  186658. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186659. hfree(ptr);
  186660. # else
  186661. free(ptr);
  186662. # endif
  186663. #endif
  186664. }
  186665. #endif /* Not Borland DOS special memory handler */
  186666. #if defined(PNG_1_0_X)
  186667. # define png_malloc_warn png_malloc
  186668. #else
  186669. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186670. * function will set up png_malloc() to issue a png_warning and return NULL
  186671. * instead of issuing a png_error, if it fails to allocate the requested
  186672. * memory.
  186673. */
  186674. png_voidp PNGAPI
  186675. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186676. {
  186677. png_voidp ptr;
  186678. png_uint_32 save_flags;
  186679. if(png_ptr == NULL) return (NULL);
  186680. save_flags=png_ptr->flags;
  186681. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186682. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186683. png_ptr->flags=save_flags;
  186684. return(ptr);
  186685. }
  186686. #endif
  186687. png_voidp PNGAPI
  186688. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186689. png_uint_32 length)
  186690. {
  186691. png_size_t size;
  186692. size = (png_size_t)length;
  186693. if ((png_uint_32)size != length)
  186694. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186695. return(png_memcpy (s1, s2, size));
  186696. }
  186697. png_voidp PNGAPI
  186698. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186699. png_uint_32 length)
  186700. {
  186701. png_size_t size;
  186702. size = (png_size_t)length;
  186703. if ((png_uint_32)size != length)
  186704. png_error(png_ptr,"Overflow in png_memset_check.");
  186705. return (png_memset (s1, value, size));
  186706. }
  186707. #ifdef PNG_USER_MEM_SUPPORTED
  186708. /* This function is called when the application wants to use another method
  186709. * of allocating and freeing memory.
  186710. */
  186711. void PNGAPI
  186712. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186713. malloc_fn, png_free_ptr free_fn)
  186714. {
  186715. if(png_ptr != NULL) {
  186716. png_ptr->mem_ptr = mem_ptr;
  186717. png_ptr->malloc_fn = malloc_fn;
  186718. png_ptr->free_fn = free_fn;
  186719. }
  186720. }
  186721. /* This function returns a pointer to the mem_ptr associated with the user
  186722. * functions. The application should free any memory associated with this
  186723. * pointer before png_write_destroy and png_read_destroy are called.
  186724. */
  186725. png_voidp PNGAPI
  186726. png_get_mem_ptr(png_structp png_ptr)
  186727. {
  186728. if(png_ptr == NULL) return (NULL);
  186729. return ((png_voidp)png_ptr->mem_ptr);
  186730. }
  186731. #endif /* PNG_USER_MEM_SUPPORTED */
  186732. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186733. /*** End of inlined file: pngmem.c ***/
  186734. /*** Start of inlined file: pngread.c ***/
  186735. /* pngread.c - read a PNG file
  186736. *
  186737. * Last changed in libpng 1.2.20 September 7, 2007
  186738. * For conditions of distribution and use, see copyright notice in png.h
  186739. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186740. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186741. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186742. *
  186743. * This file contains routines that an application calls directly to
  186744. * read a PNG file or stream.
  186745. */
  186746. #define PNG_INTERNAL
  186747. #if defined(PNG_READ_SUPPORTED)
  186748. /* Create a PNG structure for reading, and allocate any memory needed. */
  186749. png_structp PNGAPI
  186750. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186751. png_error_ptr error_fn, png_error_ptr warn_fn)
  186752. {
  186753. #ifdef PNG_USER_MEM_SUPPORTED
  186754. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186755. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186756. }
  186757. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186758. png_structp PNGAPI
  186759. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186760. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186761. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186762. {
  186763. #endif /* PNG_USER_MEM_SUPPORTED */
  186764. png_structp png_ptr;
  186765. #ifdef PNG_SETJMP_SUPPORTED
  186766. #ifdef USE_FAR_KEYWORD
  186767. jmp_buf jmpbuf;
  186768. #endif
  186769. #endif
  186770. int i;
  186771. png_debug(1, "in png_create_read_struct\n");
  186772. #ifdef PNG_USER_MEM_SUPPORTED
  186773. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186774. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186775. #else
  186776. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186777. #endif
  186778. if (png_ptr == NULL)
  186779. return (NULL);
  186780. /* added at libpng-1.2.6 */
  186781. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186782. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186783. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186784. #endif
  186785. #ifdef PNG_SETJMP_SUPPORTED
  186786. #ifdef USE_FAR_KEYWORD
  186787. if (setjmp(jmpbuf))
  186788. #else
  186789. if (setjmp(png_ptr->jmpbuf))
  186790. #endif
  186791. {
  186792. png_free(png_ptr, png_ptr->zbuf);
  186793. png_ptr->zbuf=NULL;
  186794. #ifdef PNG_USER_MEM_SUPPORTED
  186795. png_destroy_struct_2((png_voidp)png_ptr,
  186796. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186797. #else
  186798. png_destroy_struct((png_voidp)png_ptr);
  186799. #endif
  186800. return (NULL);
  186801. }
  186802. #ifdef USE_FAR_KEYWORD
  186803. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186804. #endif
  186805. #endif
  186806. #ifdef PNG_USER_MEM_SUPPORTED
  186807. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186808. #endif
  186809. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186810. i=0;
  186811. do
  186812. {
  186813. if(user_png_ver[i] != png_libpng_ver[i])
  186814. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186815. } while (png_libpng_ver[i++]);
  186816. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186817. {
  186818. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186819. * we must recompile any applications that use any older library version.
  186820. * For versions after libpng 1.0, we will be compatible, so we need
  186821. * only check the first digit.
  186822. */
  186823. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186824. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186825. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186826. {
  186827. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186828. char msg[80];
  186829. if (user_png_ver)
  186830. {
  186831. png_snprintf(msg, 80,
  186832. "Application was compiled with png.h from libpng-%.20s",
  186833. user_png_ver);
  186834. png_warning(png_ptr, msg);
  186835. }
  186836. png_snprintf(msg, 80,
  186837. "Application is running with png.c from libpng-%.20s",
  186838. png_libpng_ver);
  186839. png_warning(png_ptr, msg);
  186840. #endif
  186841. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186842. png_ptr->flags=0;
  186843. #endif
  186844. png_error(png_ptr,
  186845. "Incompatible libpng version in application and library");
  186846. }
  186847. }
  186848. /* initialize zbuf - compression buffer */
  186849. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186850. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186851. (png_uint_32)png_ptr->zbuf_size);
  186852. png_ptr->zstream.zalloc = png_zalloc;
  186853. png_ptr->zstream.zfree = png_zfree;
  186854. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186855. switch (inflateInit(&png_ptr->zstream))
  186856. {
  186857. case Z_OK: /* Do nothing */ break;
  186858. case Z_MEM_ERROR:
  186859. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186860. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186861. default: png_error(png_ptr, "Unknown zlib error");
  186862. }
  186863. png_ptr->zstream.next_out = png_ptr->zbuf;
  186864. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186865. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186866. #ifdef PNG_SETJMP_SUPPORTED
  186867. /* Applications that neglect to set up their own setjmp() and then encounter
  186868. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186869. abort instead of returning. */
  186870. #ifdef USE_FAR_KEYWORD
  186871. if (setjmp(jmpbuf))
  186872. PNG_ABORT();
  186873. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186874. #else
  186875. if (setjmp(png_ptr->jmpbuf))
  186876. PNG_ABORT();
  186877. #endif
  186878. #endif
  186879. return (png_ptr);
  186880. }
  186881. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186882. /* Initialize PNG structure for reading, and allocate any memory needed.
  186883. This interface is deprecated in favour of the png_create_read_struct(),
  186884. and it will disappear as of libpng-1.3.0. */
  186885. #undef png_read_init
  186886. void PNGAPI
  186887. png_read_init(png_structp png_ptr)
  186888. {
  186889. /* We only come here via pre-1.0.7-compiled applications */
  186890. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186891. }
  186892. void PNGAPI
  186893. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186894. png_size_t png_struct_size, png_size_t png_info_size)
  186895. {
  186896. /* We only come here via pre-1.0.12-compiled applications */
  186897. if(png_ptr == NULL) return;
  186898. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186899. if(png_sizeof(png_struct) > png_struct_size ||
  186900. png_sizeof(png_info) > png_info_size)
  186901. {
  186902. char msg[80];
  186903. png_ptr->warning_fn=NULL;
  186904. if (user_png_ver)
  186905. {
  186906. png_snprintf(msg, 80,
  186907. "Application was compiled with png.h from libpng-%.20s",
  186908. user_png_ver);
  186909. png_warning(png_ptr, msg);
  186910. }
  186911. png_snprintf(msg, 80,
  186912. "Application is running with png.c from libpng-%.20s",
  186913. png_libpng_ver);
  186914. png_warning(png_ptr, msg);
  186915. }
  186916. #endif
  186917. if(png_sizeof(png_struct) > png_struct_size)
  186918. {
  186919. png_ptr->error_fn=NULL;
  186920. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186921. png_ptr->flags=0;
  186922. #endif
  186923. png_error(png_ptr,
  186924. "The png struct allocated by the application for reading is too small.");
  186925. }
  186926. if(png_sizeof(png_info) > png_info_size)
  186927. {
  186928. png_ptr->error_fn=NULL;
  186929. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186930. png_ptr->flags=0;
  186931. #endif
  186932. png_error(png_ptr,
  186933. "The info struct allocated by application for reading is too small.");
  186934. }
  186935. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186936. }
  186937. #endif /* PNG_1_0_X || PNG_1_2_X */
  186938. void PNGAPI
  186939. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186940. png_size_t png_struct_size)
  186941. {
  186942. #ifdef PNG_SETJMP_SUPPORTED
  186943. jmp_buf tmp_jmp; /* to save current jump buffer */
  186944. #endif
  186945. int i=0;
  186946. png_structp png_ptr=*ptr_ptr;
  186947. if(png_ptr == NULL) return;
  186948. do
  186949. {
  186950. if(user_png_ver[i] != png_libpng_ver[i])
  186951. {
  186952. #ifdef PNG_LEGACY_SUPPORTED
  186953. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186954. #else
  186955. png_ptr->warning_fn=NULL;
  186956. png_warning(png_ptr,
  186957. "Application uses deprecated png_read_init() and should be recompiled.");
  186958. break;
  186959. #endif
  186960. }
  186961. } while (png_libpng_ver[i++]);
  186962. png_debug(1, "in png_read_init_3\n");
  186963. #ifdef PNG_SETJMP_SUPPORTED
  186964. /* save jump buffer and error functions */
  186965. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186966. #endif
  186967. if(png_sizeof(png_struct) > png_struct_size)
  186968. {
  186969. png_destroy_struct(png_ptr);
  186970. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186971. png_ptr = *ptr_ptr;
  186972. }
  186973. /* reset all variables to 0 */
  186974. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186975. #ifdef PNG_SETJMP_SUPPORTED
  186976. /* restore jump buffer */
  186977. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186978. #endif
  186979. /* added at libpng-1.2.6 */
  186980. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186981. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186982. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186983. #endif
  186984. /* initialize zbuf - compression buffer */
  186985. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186986. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186987. (png_uint_32)png_ptr->zbuf_size);
  186988. png_ptr->zstream.zalloc = png_zalloc;
  186989. png_ptr->zstream.zfree = png_zfree;
  186990. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186991. switch (inflateInit(&png_ptr->zstream))
  186992. {
  186993. case Z_OK: /* Do nothing */ break;
  186994. case Z_MEM_ERROR:
  186995. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186996. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186997. default: png_error(png_ptr, "Unknown zlib error");
  186998. }
  186999. png_ptr->zstream.next_out = png_ptr->zbuf;
  187000. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187001. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187002. }
  187003. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187004. /* Read the information before the actual image data. This has been
  187005. * changed in v0.90 to allow reading a file that already has the magic
  187006. * bytes read from the stream. You can tell libpng how many bytes have
  187007. * been read from the beginning of the stream (up to the maximum of 8)
  187008. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187009. * here. The application can then have access to the signature bytes we
  187010. * read if it is determined that this isn't a valid PNG file.
  187011. */
  187012. void PNGAPI
  187013. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187014. {
  187015. if(png_ptr == NULL) return;
  187016. png_debug(1, "in png_read_info\n");
  187017. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187018. if (png_ptr->sig_bytes < 8)
  187019. {
  187020. png_size_t num_checked = png_ptr->sig_bytes,
  187021. num_to_check = 8 - num_checked;
  187022. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187023. png_ptr->sig_bytes = 8;
  187024. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187025. {
  187026. if (num_checked < 4 &&
  187027. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187028. png_error(png_ptr, "Not a PNG file");
  187029. else
  187030. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187031. }
  187032. if (num_checked < 3)
  187033. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187034. }
  187035. for(;;)
  187036. {
  187037. #ifdef PNG_USE_LOCAL_ARRAYS
  187038. PNG_CONST PNG_IHDR;
  187039. PNG_CONST PNG_IDAT;
  187040. PNG_CONST PNG_IEND;
  187041. PNG_CONST PNG_PLTE;
  187042. #if defined(PNG_READ_bKGD_SUPPORTED)
  187043. PNG_CONST PNG_bKGD;
  187044. #endif
  187045. #if defined(PNG_READ_cHRM_SUPPORTED)
  187046. PNG_CONST PNG_cHRM;
  187047. #endif
  187048. #if defined(PNG_READ_gAMA_SUPPORTED)
  187049. PNG_CONST PNG_gAMA;
  187050. #endif
  187051. #if defined(PNG_READ_hIST_SUPPORTED)
  187052. PNG_CONST PNG_hIST;
  187053. #endif
  187054. #if defined(PNG_READ_iCCP_SUPPORTED)
  187055. PNG_CONST PNG_iCCP;
  187056. #endif
  187057. #if defined(PNG_READ_iTXt_SUPPORTED)
  187058. PNG_CONST PNG_iTXt;
  187059. #endif
  187060. #if defined(PNG_READ_oFFs_SUPPORTED)
  187061. PNG_CONST PNG_oFFs;
  187062. #endif
  187063. #if defined(PNG_READ_pCAL_SUPPORTED)
  187064. PNG_CONST PNG_pCAL;
  187065. #endif
  187066. #if defined(PNG_READ_pHYs_SUPPORTED)
  187067. PNG_CONST PNG_pHYs;
  187068. #endif
  187069. #if defined(PNG_READ_sBIT_SUPPORTED)
  187070. PNG_CONST PNG_sBIT;
  187071. #endif
  187072. #if defined(PNG_READ_sCAL_SUPPORTED)
  187073. PNG_CONST PNG_sCAL;
  187074. #endif
  187075. #if defined(PNG_READ_sPLT_SUPPORTED)
  187076. PNG_CONST PNG_sPLT;
  187077. #endif
  187078. #if defined(PNG_READ_sRGB_SUPPORTED)
  187079. PNG_CONST PNG_sRGB;
  187080. #endif
  187081. #if defined(PNG_READ_tEXt_SUPPORTED)
  187082. PNG_CONST PNG_tEXt;
  187083. #endif
  187084. #if defined(PNG_READ_tIME_SUPPORTED)
  187085. PNG_CONST PNG_tIME;
  187086. #endif
  187087. #if defined(PNG_READ_tRNS_SUPPORTED)
  187088. PNG_CONST PNG_tRNS;
  187089. #endif
  187090. #if defined(PNG_READ_zTXt_SUPPORTED)
  187091. PNG_CONST PNG_zTXt;
  187092. #endif
  187093. #endif /* PNG_USE_LOCAL_ARRAYS */
  187094. png_byte chunk_length[4];
  187095. png_uint_32 length;
  187096. png_read_data(png_ptr, chunk_length, 4);
  187097. length = png_get_uint_31(png_ptr,chunk_length);
  187098. png_reset_crc(png_ptr);
  187099. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187100. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187101. length);
  187102. /* This should be a binary subdivision search or a hash for
  187103. * matching the chunk name rather than a linear search.
  187104. */
  187105. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187106. if(png_ptr->mode & PNG_AFTER_IDAT)
  187107. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187108. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187109. png_handle_IHDR(png_ptr, info_ptr, length);
  187110. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187111. png_handle_IEND(png_ptr, info_ptr, length);
  187112. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187113. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187114. {
  187115. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187116. png_ptr->mode |= PNG_HAVE_IDAT;
  187117. png_handle_unknown(png_ptr, info_ptr, length);
  187118. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187119. png_ptr->mode |= PNG_HAVE_PLTE;
  187120. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187121. {
  187122. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187123. png_error(png_ptr, "Missing IHDR before IDAT");
  187124. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187125. !(png_ptr->mode & PNG_HAVE_PLTE))
  187126. png_error(png_ptr, "Missing PLTE before IDAT");
  187127. break;
  187128. }
  187129. }
  187130. #endif
  187131. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187132. png_handle_PLTE(png_ptr, info_ptr, length);
  187133. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187134. {
  187135. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187136. png_error(png_ptr, "Missing IHDR before IDAT");
  187137. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187138. !(png_ptr->mode & PNG_HAVE_PLTE))
  187139. png_error(png_ptr, "Missing PLTE before IDAT");
  187140. png_ptr->idat_size = length;
  187141. png_ptr->mode |= PNG_HAVE_IDAT;
  187142. break;
  187143. }
  187144. #if defined(PNG_READ_bKGD_SUPPORTED)
  187145. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187146. png_handle_bKGD(png_ptr, info_ptr, length);
  187147. #endif
  187148. #if defined(PNG_READ_cHRM_SUPPORTED)
  187149. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187150. png_handle_cHRM(png_ptr, info_ptr, length);
  187151. #endif
  187152. #if defined(PNG_READ_gAMA_SUPPORTED)
  187153. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187154. png_handle_gAMA(png_ptr, info_ptr, length);
  187155. #endif
  187156. #if defined(PNG_READ_hIST_SUPPORTED)
  187157. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187158. png_handle_hIST(png_ptr, info_ptr, length);
  187159. #endif
  187160. #if defined(PNG_READ_oFFs_SUPPORTED)
  187161. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187162. png_handle_oFFs(png_ptr, info_ptr, length);
  187163. #endif
  187164. #if defined(PNG_READ_pCAL_SUPPORTED)
  187165. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187166. png_handle_pCAL(png_ptr, info_ptr, length);
  187167. #endif
  187168. #if defined(PNG_READ_sCAL_SUPPORTED)
  187169. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187170. png_handle_sCAL(png_ptr, info_ptr, length);
  187171. #endif
  187172. #if defined(PNG_READ_pHYs_SUPPORTED)
  187173. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187174. png_handle_pHYs(png_ptr, info_ptr, length);
  187175. #endif
  187176. #if defined(PNG_READ_sBIT_SUPPORTED)
  187177. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187178. png_handle_sBIT(png_ptr, info_ptr, length);
  187179. #endif
  187180. #if defined(PNG_READ_sRGB_SUPPORTED)
  187181. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187182. png_handle_sRGB(png_ptr, info_ptr, length);
  187183. #endif
  187184. #if defined(PNG_READ_iCCP_SUPPORTED)
  187185. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187186. png_handle_iCCP(png_ptr, info_ptr, length);
  187187. #endif
  187188. #if defined(PNG_READ_sPLT_SUPPORTED)
  187189. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187190. png_handle_sPLT(png_ptr, info_ptr, length);
  187191. #endif
  187192. #if defined(PNG_READ_tEXt_SUPPORTED)
  187193. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187194. png_handle_tEXt(png_ptr, info_ptr, length);
  187195. #endif
  187196. #if defined(PNG_READ_tIME_SUPPORTED)
  187197. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187198. png_handle_tIME(png_ptr, info_ptr, length);
  187199. #endif
  187200. #if defined(PNG_READ_tRNS_SUPPORTED)
  187201. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187202. png_handle_tRNS(png_ptr, info_ptr, length);
  187203. #endif
  187204. #if defined(PNG_READ_zTXt_SUPPORTED)
  187205. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187206. png_handle_zTXt(png_ptr, info_ptr, length);
  187207. #endif
  187208. #if defined(PNG_READ_iTXt_SUPPORTED)
  187209. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187210. png_handle_iTXt(png_ptr, info_ptr, length);
  187211. #endif
  187212. else
  187213. png_handle_unknown(png_ptr, info_ptr, length);
  187214. }
  187215. }
  187216. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187217. /* optional call to update the users info_ptr structure */
  187218. void PNGAPI
  187219. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187220. {
  187221. png_debug(1, "in png_read_update_info\n");
  187222. if(png_ptr == NULL) return;
  187223. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187224. png_read_start_row(png_ptr);
  187225. else
  187226. png_warning(png_ptr,
  187227. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187228. png_read_transform_info(png_ptr, info_ptr);
  187229. }
  187230. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187231. /* Initialize palette, background, etc, after transformations
  187232. * are set, but before any reading takes place. This allows
  187233. * the user to obtain a gamma-corrected palette, for example.
  187234. * If the user doesn't call this, we will do it ourselves.
  187235. */
  187236. void PNGAPI
  187237. png_start_read_image(png_structp png_ptr)
  187238. {
  187239. png_debug(1, "in png_start_read_image\n");
  187240. if(png_ptr == NULL) return;
  187241. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187242. png_read_start_row(png_ptr);
  187243. }
  187244. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187245. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187246. void PNGAPI
  187247. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187248. {
  187249. #ifdef PNG_USE_LOCAL_ARRAYS
  187250. PNG_CONST PNG_IDAT;
  187251. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187252. 0xff};
  187253. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187254. #endif
  187255. int ret;
  187256. if(png_ptr == NULL) return;
  187257. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187258. png_ptr->row_number, png_ptr->pass);
  187259. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187260. png_read_start_row(png_ptr);
  187261. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187262. {
  187263. /* check for transforms that have been set but were defined out */
  187264. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187265. if (png_ptr->transformations & PNG_INVERT_MONO)
  187266. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187267. #endif
  187268. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187269. if (png_ptr->transformations & PNG_FILLER)
  187270. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187271. #endif
  187272. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187273. if (png_ptr->transformations & PNG_PACKSWAP)
  187274. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187275. #endif
  187276. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187277. if (png_ptr->transformations & PNG_PACK)
  187278. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187279. #endif
  187280. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187281. if (png_ptr->transformations & PNG_SHIFT)
  187282. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187283. #endif
  187284. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187285. if (png_ptr->transformations & PNG_BGR)
  187286. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187287. #endif
  187288. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187289. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187290. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187291. #endif
  187292. }
  187293. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187294. /* if interlaced and we do not need a new row, combine row and return */
  187295. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187296. {
  187297. switch (png_ptr->pass)
  187298. {
  187299. case 0:
  187300. if (png_ptr->row_number & 0x07)
  187301. {
  187302. if (dsp_row != NULL)
  187303. png_combine_row(png_ptr, dsp_row,
  187304. png_pass_dsp_mask[png_ptr->pass]);
  187305. png_read_finish_row(png_ptr);
  187306. return;
  187307. }
  187308. break;
  187309. case 1:
  187310. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187311. {
  187312. if (dsp_row != NULL)
  187313. png_combine_row(png_ptr, dsp_row,
  187314. png_pass_dsp_mask[png_ptr->pass]);
  187315. png_read_finish_row(png_ptr);
  187316. return;
  187317. }
  187318. break;
  187319. case 2:
  187320. if ((png_ptr->row_number & 0x07) != 4)
  187321. {
  187322. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187323. png_combine_row(png_ptr, dsp_row,
  187324. png_pass_dsp_mask[png_ptr->pass]);
  187325. png_read_finish_row(png_ptr);
  187326. return;
  187327. }
  187328. break;
  187329. case 3:
  187330. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187331. {
  187332. if (dsp_row != NULL)
  187333. png_combine_row(png_ptr, dsp_row,
  187334. png_pass_dsp_mask[png_ptr->pass]);
  187335. png_read_finish_row(png_ptr);
  187336. return;
  187337. }
  187338. break;
  187339. case 4:
  187340. if ((png_ptr->row_number & 3) != 2)
  187341. {
  187342. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187343. png_combine_row(png_ptr, dsp_row,
  187344. png_pass_dsp_mask[png_ptr->pass]);
  187345. png_read_finish_row(png_ptr);
  187346. return;
  187347. }
  187348. break;
  187349. case 5:
  187350. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187351. {
  187352. if (dsp_row != NULL)
  187353. png_combine_row(png_ptr, dsp_row,
  187354. png_pass_dsp_mask[png_ptr->pass]);
  187355. png_read_finish_row(png_ptr);
  187356. return;
  187357. }
  187358. break;
  187359. case 6:
  187360. if (!(png_ptr->row_number & 1))
  187361. {
  187362. png_read_finish_row(png_ptr);
  187363. return;
  187364. }
  187365. break;
  187366. }
  187367. }
  187368. #endif
  187369. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187370. png_error(png_ptr, "Invalid attempt to read row data");
  187371. png_ptr->zstream.next_out = png_ptr->row_buf;
  187372. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187373. do
  187374. {
  187375. if (!(png_ptr->zstream.avail_in))
  187376. {
  187377. while (!png_ptr->idat_size)
  187378. {
  187379. png_byte chunk_length[4];
  187380. png_crc_finish(png_ptr, 0);
  187381. png_read_data(png_ptr, chunk_length, 4);
  187382. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187383. png_reset_crc(png_ptr);
  187384. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187385. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187386. png_error(png_ptr, "Not enough image data");
  187387. }
  187388. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187389. png_ptr->zstream.next_in = png_ptr->zbuf;
  187390. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187391. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187392. png_crc_read(png_ptr, png_ptr->zbuf,
  187393. (png_size_t)png_ptr->zstream.avail_in);
  187394. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187395. }
  187396. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187397. if (ret == Z_STREAM_END)
  187398. {
  187399. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187400. png_ptr->idat_size)
  187401. png_error(png_ptr, "Extra compressed data");
  187402. png_ptr->mode |= PNG_AFTER_IDAT;
  187403. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187404. break;
  187405. }
  187406. if (ret != Z_OK)
  187407. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187408. "Decompression error");
  187409. } while (png_ptr->zstream.avail_out);
  187410. png_ptr->row_info.color_type = png_ptr->color_type;
  187411. png_ptr->row_info.width = png_ptr->iwidth;
  187412. png_ptr->row_info.channels = png_ptr->channels;
  187413. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187414. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187415. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187416. png_ptr->row_info.width);
  187417. if(png_ptr->row_buf[0])
  187418. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187419. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187420. (int)(png_ptr->row_buf[0]));
  187421. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187422. png_ptr->rowbytes + 1);
  187423. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187424. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187425. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187426. {
  187427. /* Intrapixel differencing */
  187428. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187429. }
  187430. #endif
  187431. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187432. png_do_read_transformations(png_ptr);
  187433. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187434. /* blow up interlaced rows to full size */
  187435. if (png_ptr->interlaced &&
  187436. (png_ptr->transformations & PNG_INTERLACE))
  187437. {
  187438. if (png_ptr->pass < 6)
  187439. /* old interface (pre-1.0.9):
  187440. png_do_read_interlace(&(png_ptr->row_info),
  187441. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187442. */
  187443. png_do_read_interlace(png_ptr);
  187444. if (dsp_row != NULL)
  187445. png_combine_row(png_ptr, dsp_row,
  187446. png_pass_dsp_mask[png_ptr->pass]);
  187447. if (row != NULL)
  187448. png_combine_row(png_ptr, row,
  187449. png_pass_mask[png_ptr->pass]);
  187450. }
  187451. else
  187452. #endif
  187453. {
  187454. if (row != NULL)
  187455. png_combine_row(png_ptr, row, 0xff);
  187456. if (dsp_row != NULL)
  187457. png_combine_row(png_ptr, dsp_row, 0xff);
  187458. }
  187459. png_read_finish_row(png_ptr);
  187460. if (png_ptr->read_row_fn != NULL)
  187461. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187462. }
  187463. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187464. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187465. /* Read one or more rows of image data. If the image is interlaced,
  187466. * and png_set_interlace_handling() has been called, the rows need to
  187467. * contain the contents of the rows from the previous pass. If the
  187468. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187469. * called, the rows contents must be initialized to the contents of the
  187470. * screen.
  187471. *
  187472. * "row" holds the actual image, and pixels are placed in it
  187473. * as they arrive. If the image is displayed after each pass, it will
  187474. * appear to "sparkle" in. "display_row" can be used to display a
  187475. * "chunky" progressive image, with finer detail added as it becomes
  187476. * available. If you do not want this "chunky" display, you may pass
  187477. * NULL for display_row. If you do not want the sparkle display, and
  187478. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187479. * If you have called png_handle_alpha(), and the image has either an
  187480. * alpha channel or a transparency chunk, you must provide a buffer for
  187481. * rows. In this case, you do not have to provide a display_row buffer
  187482. * also, but you may. If the image is not interlaced, or if you have
  187483. * not called png_set_interlace_handling(), the display_row buffer will
  187484. * be ignored, so pass NULL to it.
  187485. *
  187486. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187487. */
  187488. void PNGAPI
  187489. png_read_rows(png_structp png_ptr, png_bytepp row,
  187490. png_bytepp display_row, png_uint_32 num_rows)
  187491. {
  187492. png_uint_32 i;
  187493. png_bytepp rp;
  187494. png_bytepp dp;
  187495. png_debug(1, "in png_read_rows\n");
  187496. if(png_ptr == NULL) return;
  187497. rp = row;
  187498. dp = display_row;
  187499. if (rp != NULL && dp != NULL)
  187500. for (i = 0; i < num_rows; i++)
  187501. {
  187502. png_bytep rptr = *rp++;
  187503. png_bytep dptr = *dp++;
  187504. png_read_row(png_ptr, rptr, dptr);
  187505. }
  187506. else if(rp != NULL)
  187507. for (i = 0; i < num_rows; i++)
  187508. {
  187509. png_bytep rptr = *rp;
  187510. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187511. rp++;
  187512. }
  187513. else if(dp != NULL)
  187514. for (i = 0; i < num_rows; i++)
  187515. {
  187516. png_bytep dptr = *dp;
  187517. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187518. dp++;
  187519. }
  187520. }
  187521. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187522. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187523. /* Read the entire image. If the image has an alpha channel or a tRNS
  187524. * chunk, and you have called png_handle_alpha()[*], you will need to
  187525. * initialize the image to the current image that PNG will be overlaying.
  187526. * We set the num_rows again here, in case it was incorrectly set in
  187527. * png_read_start_row() by a call to png_read_update_info() or
  187528. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187529. * prior to either of these functions like it should have been. You can
  187530. * only call this function once. If you desire to have an image for
  187531. * each pass of a interlaced image, use png_read_rows() instead.
  187532. *
  187533. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187534. */
  187535. void PNGAPI
  187536. png_read_image(png_structp png_ptr, png_bytepp image)
  187537. {
  187538. png_uint_32 i,image_height;
  187539. int pass, j;
  187540. png_bytepp rp;
  187541. png_debug(1, "in png_read_image\n");
  187542. if(png_ptr == NULL) return;
  187543. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187544. pass = png_set_interlace_handling(png_ptr);
  187545. #else
  187546. if (png_ptr->interlaced)
  187547. png_error(png_ptr,
  187548. "Cannot read interlaced image -- interlace handler disabled.");
  187549. pass = 1;
  187550. #endif
  187551. image_height=png_ptr->height;
  187552. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187553. for (j = 0; j < pass; j++)
  187554. {
  187555. rp = image;
  187556. for (i = 0; i < image_height; i++)
  187557. {
  187558. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187559. rp++;
  187560. }
  187561. }
  187562. }
  187563. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187564. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187565. /* Read the end of the PNG file. Will not read past the end of the
  187566. * file, will verify the end is accurate, and will read any comments
  187567. * or time information at the end of the file, if info is not NULL.
  187568. */
  187569. void PNGAPI
  187570. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187571. {
  187572. png_byte chunk_length[4];
  187573. png_uint_32 length;
  187574. png_debug(1, "in png_read_end\n");
  187575. if(png_ptr == NULL) return;
  187576. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187577. do
  187578. {
  187579. #ifdef PNG_USE_LOCAL_ARRAYS
  187580. PNG_CONST PNG_IHDR;
  187581. PNG_CONST PNG_IDAT;
  187582. PNG_CONST PNG_IEND;
  187583. PNG_CONST PNG_PLTE;
  187584. #if defined(PNG_READ_bKGD_SUPPORTED)
  187585. PNG_CONST PNG_bKGD;
  187586. #endif
  187587. #if defined(PNG_READ_cHRM_SUPPORTED)
  187588. PNG_CONST PNG_cHRM;
  187589. #endif
  187590. #if defined(PNG_READ_gAMA_SUPPORTED)
  187591. PNG_CONST PNG_gAMA;
  187592. #endif
  187593. #if defined(PNG_READ_hIST_SUPPORTED)
  187594. PNG_CONST PNG_hIST;
  187595. #endif
  187596. #if defined(PNG_READ_iCCP_SUPPORTED)
  187597. PNG_CONST PNG_iCCP;
  187598. #endif
  187599. #if defined(PNG_READ_iTXt_SUPPORTED)
  187600. PNG_CONST PNG_iTXt;
  187601. #endif
  187602. #if defined(PNG_READ_oFFs_SUPPORTED)
  187603. PNG_CONST PNG_oFFs;
  187604. #endif
  187605. #if defined(PNG_READ_pCAL_SUPPORTED)
  187606. PNG_CONST PNG_pCAL;
  187607. #endif
  187608. #if defined(PNG_READ_pHYs_SUPPORTED)
  187609. PNG_CONST PNG_pHYs;
  187610. #endif
  187611. #if defined(PNG_READ_sBIT_SUPPORTED)
  187612. PNG_CONST PNG_sBIT;
  187613. #endif
  187614. #if defined(PNG_READ_sCAL_SUPPORTED)
  187615. PNG_CONST PNG_sCAL;
  187616. #endif
  187617. #if defined(PNG_READ_sPLT_SUPPORTED)
  187618. PNG_CONST PNG_sPLT;
  187619. #endif
  187620. #if defined(PNG_READ_sRGB_SUPPORTED)
  187621. PNG_CONST PNG_sRGB;
  187622. #endif
  187623. #if defined(PNG_READ_tEXt_SUPPORTED)
  187624. PNG_CONST PNG_tEXt;
  187625. #endif
  187626. #if defined(PNG_READ_tIME_SUPPORTED)
  187627. PNG_CONST PNG_tIME;
  187628. #endif
  187629. #if defined(PNG_READ_tRNS_SUPPORTED)
  187630. PNG_CONST PNG_tRNS;
  187631. #endif
  187632. #if defined(PNG_READ_zTXt_SUPPORTED)
  187633. PNG_CONST PNG_zTXt;
  187634. #endif
  187635. #endif /* PNG_USE_LOCAL_ARRAYS */
  187636. png_read_data(png_ptr, chunk_length, 4);
  187637. length = png_get_uint_31(png_ptr,chunk_length);
  187638. png_reset_crc(png_ptr);
  187639. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187640. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187641. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187642. png_handle_IHDR(png_ptr, info_ptr, length);
  187643. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187644. png_handle_IEND(png_ptr, info_ptr, length);
  187645. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187646. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187647. {
  187648. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187649. {
  187650. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187651. png_error(png_ptr, "Too many IDAT's found");
  187652. }
  187653. png_handle_unknown(png_ptr, info_ptr, length);
  187654. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187655. png_ptr->mode |= PNG_HAVE_PLTE;
  187656. }
  187657. #endif
  187658. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187659. {
  187660. /* Zero length IDATs are legal after the last IDAT has been
  187661. * read, but not after other chunks have been read.
  187662. */
  187663. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187664. png_error(png_ptr, "Too many IDAT's found");
  187665. png_crc_finish(png_ptr, length);
  187666. }
  187667. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187668. png_handle_PLTE(png_ptr, info_ptr, length);
  187669. #if defined(PNG_READ_bKGD_SUPPORTED)
  187670. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187671. png_handle_bKGD(png_ptr, info_ptr, length);
  187672. #endif
  187673. #if defined(PNG_READ_cHRM_SUPPORTED)
  187674. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187675. png_handle_cHRM(png_ptr, info_ptr, length);
  187676. #endif
  187677. #if defined(PNG_READ_gAMA_SUPPORTED)
  187678. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187679. png_handle_gAMA(png_ptr, info_ptr, length);
  187680. #endif
  187681. #if defined(PNG_READ_hIST_SUPPORTED)
  187682. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187683. png_handle_hIST(png_ptr, info_ptr, length);
  187684. #endif
  187685. #if defined(PNG_READ_oFFs_SUPPORTED)
  187686. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187687. png_handle_oFFs(png_ptr, info_ptr, length);
  187688. #endif
  187689. #if defined(PNG_READ_pCAL_SUPPORTED)
  187690. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187691. png_handle_pCAL(png_ptr, info_ptr, length);
  187692. #endif
  187693. #if defined(PNG_READ_sCAL_SUPPORTED)
  187694. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187695. png_handle_sCAL(png_ptr, info_ptr, length);
  187696. #endif
  187697. #if defined(PNG_READ_pHYs_SUPPORTED)
  187698. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187699. png_handle_pHYs(png_ptr, info_ptr, length);
  187700. #endif
  187701. #if defined(PNG_READ_sBIT_SUPPORTED)
  187702. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187703. png_handle_sBIT(png_ptr, info_ptr, length);
  187704. #endif
  187705. #if defined(PNG_READ_sRGB_SUPPORTED)
  187706. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187707. png_handle_sRGB(png_ptr, info_ptr, length);
  187708. #endif
  187709. #if defined(PNG_READ_iCCP_SUPPORTED)
  187710. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187711. png_handle_iCCP(png_ptr, info_ptr, length);
  187712. #endif
  187713. #if defined(PNG_READ_sPLT_SUPPORTED)
  187714. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187715. png_handle_sPLT(png_ptr, info_ptr, length);
  187716. #endif
  187717. #if defined(PNG_READ_tEXt_SUPPORTED)
  187718. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187719. png_handle_tEXt(png_ptr, info_ptr, length);
  187720. #endif
  187721. #if defined(PNG_READ_tIME_SUPPORTED)
  187722. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187723. png_handle_tIME(png_ptr, info_ptr, length);
  187724. #endif
  187725. #if defined(PNG_READ_tRNS_SUPPORTED)
  187726. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187727. png_handle_tRNS(png_ptr, info_ptr, length);
  187728. #endif
  187729. #if defined(PNG_READ_zTXt_SUPPORTED)
  187730. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187731. png_handle_zTXt(png_ptr, info_ptr, length);
  187732. #endif
  187733. #if defined(PNG_READ_iTXt_SUPPORTED)
  187734. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187735. png_handle_iTXt(png_ptr, info_ptr, length);
  187736. #endif
  187737. else
  187738. png_handle_unknown(png_ptr, info_ptr, length);
  187739. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187740. }
  187741. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187742. /* free all memory used by the read */
  187743. void PNGAPI
  187744. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187745. png_infopp end_info_ptr_ptr)
  187746. {
  187747. png_structp png_ptr = NULL;
  187748. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187749. #ifdef PNG_USER_MEM_SUPPORTED
  187750. png_free_ptr free_fn;
  187751. png_voidp mem_ptr;
  187752. #endif
  187753. png_debug(1, "in png_destroy_read_struct\n");
  187754. if (png_ptr_ptr != NULL)
  187755. png_ptr = *png_ptr_ptr;
  187756. if (info_ptr_ptr != NULL)
  187757. info_ptr = *info_ptr_ptr;
  187758. if (end_info_ptr_ptr != NULL)
  187759. end_info_ptr = *end_info_ptr_ptr;
  187760. #ifdef PNG_USER_MEM_SUPPORTED
  187761. free_fn = png_ptr->free_fn;
  187762. mem_ptr = png_ptr->mem_ptr;
  187763. #endif
  187764. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187765. if (info_ptr != NULL)
  187766. {
  187767. #if defined(PNG_TEXT_SUPPORTED)
  187768. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187769. #endif
  187770. #ifdef PNG_USER_MEM_SUPPORTED
  187771. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187772. (png_voidp)mem_ptr);
  187773. #else
  187774. png_destroy_struct((png_voidp)info_ptr);
  187775. #endif
  187776. *info_ptr_ptr = NULL;
  187777. }
  187778. if (end_info_ptr != NULL)
  187779. {
  187780. #if defined(PNG_READ_TEXT_SUPPORTED)
  187781. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187782. #endif
  187783. #ifdef PNG_USER_MEM_SUPPORTED
  187784. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187785. (png_voidp)mem_ptr);
  187786. #else
  187787. png_destroy_struct((png_voidp)end_info_ptr);
  187788. #endif
  187789. *end_info_ptr_ptr = NULL;
  187790. }
  187791. if (png_ptr != NULL)
  187792. {
  187793. #ifdef PNG_USER_MEM_SUPPORTED
  187794. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187795. (png_voidp)mem_ptr);
  187796. #else
  187797. png_destroy_struct((png_voidp)png_ptr);
  187798. #endif
  187799. *png_ptr_ptr = NULL;
  187800. }
  187801. }
  187802. /* free all memory used by the read (old method) */
  187803. void /* PRIVATE */
  187804. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187805. {
  187806. #ifdef PNG_SETJMP_SUPPORTED
  187807. jmp_buf tmp_jmp;
  187808. #endif
  187809. png_error_ptr error_fn;
  187810. png_error_ptr warning_fn;
  187811. png_voidp error_ptr;
  187812. #ifdef PNG_USER_MEM_SUPPORTED
  187813. png_free_ptr free_fn;
  187814. #endif
  187815. png_debug(1, "in png_read_destroy\n");
  187816. if (info_ptr != NULL)
  187817. png_info_destroy(png_ptr, info_ptr);
  187818. if (end_info_ptr != NULL)
  187819. png_info_destroy(png_ptr, end_info_ptr);
  187820. png_free(png_ptr, png_ptr->zbuf);
  187821. png_free(png_ptr, png_ptr->big_row_buf);
  187822. png_free(png_ptr, png_ptr->prev_row);
  187823. #if defined(PNG_READ_DITHER_SUPPORTED)
  187824. png_free(png_ptr, png_ptr->palette_lookup);
  187825. png_free(png_ptr, png_ptr->dither_index);
  187826. #endif
  187827. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187828. png_free(png_ptr, png_ptr->gamma_table);
  187829. #endif
  187830. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187831. png_free(png_ptr, png_ptr->gamma_from_1);
  187832. png_free(png_ptr, png_ptr->gamma_to_1);
  187833. #endif
  187834. #ifdef PNG_FREE_ME_SUPPORTED
  187835. if (png_ptr->free_me & PNG_FREE_PLTE)
  187836. png_zfree(png_ptr, png_ptr->palette);
  187837. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187838. #else
  187839. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187840. png_zfree(png_ptr, png_ptr->palette);
  187841. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187842. #endif
  187843. #if defined(PNG_tRNS_SUPPORTED) || \
  187844. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187845. #ifdef PNG_FREE_ME_SUPPORTED
  187846. if (png_ptr->free_me & PNG_FREE_TRNS)
  187847. png_free(png_ptr, png_ptr->trans);
  187848. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187849. #else
  187850. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187851. png_free(png_ptr, png_ptr->trans);
  187852. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187853. #endif
  187854. #endif
  187855. #if defined(PNG_READ_hIST_SUPPORTED)
  187856. #ifdef PNG_FREE_ME_SUPPORTED
  187857. if (png_ptr->free_me & PNG_FREE_HIST)
  187858. png_free(png_ptr, png_ptr->hist);
  187859. png_ptr->free_me &= ~PNG_FREE_HIST;
  187860. #else
  187861. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187862. png_free(png_ptr, png_ptr->hist);
  187863. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187864. #endif
  187865. #endif
  187866. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187867. if (png_ptr->gamma_16_table != NULL)
  187868. {
  187869. int i;
  187870. int istop = (1 << (8 - png_ptr->gamma_shift));
  187871. for (i = 0; i < istop; i++)
  187872. {
  187873. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187874. }
  187875. png_free(png_ptr, png_ptr->gamma_16_table);
  187876. }
  187877. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187878. if (png_ptr->gamma_16_from_1 != NULL)
  187879. {
  187880. int i;
  187881. int istop = (1 << (8 - png_ptr->gamma_shift));
  187882. for (i = 0; i < istop; i++)
  187883. {
  187884. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187885. }
  187886. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187887. }
  187888. if (png_ptr->gamma_16_to_1 != NULL)
  187889. {
  187890. int i;
  187891. int istop = (1 << (8 - png_ptr->gamma_shift));
  187892. for (i = 0; i < istop; i++)
  187893. {
  187894. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187895. }
  187896. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187897. }
  187898. #endif
  187899. #endif
  187900. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187901. png_free(png_ptr, png_ptr->time_buffer);
  187902. #endif
  187903. inflateEnd(&png_ptr->zstream);
  187904. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187905. png_free(png_ptr, png_ptr->save_buffer);
  187906. #endif
  187907. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187908. #ifdef PNG_TEXT_SUPPORTED
  187909. png_free(png_ptr, png_ptr->current_text);
  187910. #endif /* PNG_TEXT_SUPPORTED */
  187911. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187912. /* Save the important info out of the png_struct, in case it is
  187913. * being used again.
  187914. */
  187915. #ifdef PNG_SETJMP_SUPPORTED
  187916. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187917. #endif
  187918. error_fn = png_ptr->error_fn;
  187919. warning_fn = png_ptr->warning_fn;
  187920. error_ptr = png_ptr->error_ptr;
  187921. #ifdef PNG_USER_MEM_SUPPORTED
  187922. free_fn = png_ptr->free_fn;
  187923. #endif
  187924. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187925. png_ptr->error_fn = error_fn;
  187926. png_ptr->warning_fn = warning_fn;
  187927. png_ptr->error_ptr = error_ptr;
  187928. #ifdef PNG_USER_MEM_SUPPORTED
  187929. png_ptr->free_fn = free_fn;
  187930. #endif
  187931. #ifdef PNG_SETJMP_SUPPORTED
  187932. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187933. #endif
  187934. }
  187935. void PNGAPI
  187936. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187937. {
  187938. if(png_ptr == NULL) return;
  187939. png_ptr->read_row_fn = read_row_fn;
  187940. }
  187941. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187942. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187943. void PNGAPI
  187944. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187945. int transforms,
  187946. voidp params)
  187947. {
  187948. int row;
  187949. if(png_ptr == NULL) return;
  187950. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187951. /* invert the alpha channel from opacity to transparency
  187952. */
  187953. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187954. png_set_invert_alpha(png_ptr);
  187955. #endif
  187956. /* png_read_info() gives us all of the information from the
  187957. * PNG file before the first IDAT (image data chunk).
  187958. */
  187959. png_read_info(png_ptr, info_ptr);
  187960. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187961. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187962. /* -------------- image transformations start here ------------------- */
  187963. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187964. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187965. */
  187966. if (transforms & PNG_TRANSFORM_STRIP_16)
  187967. png_set_strip_16(png_ptr);
  187968. #endif
  187969. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187970. /* Strip alpha bytes from the input data without combining with
  187971. * the background (not recommended).
  187972. */
  187973. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187974. png_set_strip_alpha(png_ptr);
  187975. #endif
  187976. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187977. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187978. * byte into separate bytes (useful for paletted and grayscale images).
  187979. */
  187980. if (transforms & PNG_TRANSFORM_PACKING)
  187981. png_set_packing(png_ptr);
  187982. #endif
  187983. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187984. /* Change the order of packed pixels to least significant bit first
  187985. * (not useful if you are using png_set_packing).
  187986. */
  187987. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187988. png_set_packswap(png_ptr);
  187989. #endif
  187990. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187991. /* Expand paletted colors into true RGB triplets
  187992. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187993. * Expand paletted or RGB images with transparency to full alpha
  187994. * channels so the data will be available as RGBA quartets.
  187995. */
  187996. if (transforms & PNG_TRANSFORM_EXPAND)
  187997. if ((png_ptr->bit_depth < 8) ||
  187998. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187999. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188000. png_set_expand(png_ptr);
  188001. #endif
  188002. /* We don't handle background color or gamma transformation or dithering.
  188003. */
  188004. #if defined(PNG_READ_INVERT_SUPPORTED)
  188005. /* invert monochrome files to have 0 as white and 1 as black
  188006. */
  188007. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188008. png_set_invert_mono(png_ptr);
  188009. #endif
  188010. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188011. /* If you want to shift the pixel values from the range [0,255] or
  188012. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188013. * colors were originally in:
  188014. */
  188015. if ((transforms & PNG_TRANSFORM_SHIFT)
  188016. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188017. {
  188018. png_color_8p sig_bit;
  188019. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188020. png_set_shift(png_ptr, sig_bit);
  188021. }
  188022. #endif
  188023. #if defined(PNG_READ_BGR_SUPPORTED)
  188024. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188025. */
  188026. if (transforms & PNG_TRANSFORM_BGR)
  188027. png_set_bgr(png_ptr);
  188028. #endif
  188029. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188030. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188031. */
  188032. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188033. png_set_swap_alpha(png_ptr);
  188034. #endif
  188035. #if defined(PNG_READ_SWAP_SUPPORTED)
  188036. /* swap bytes of 16 bit files to least significant byte first
  188037. */
  188038. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188039. png_set_swap(png_ptr);
  188040. #endif
  188041. /* We don't handle adding filler bytes */
  188042. /* Optional call to gamma correct and add the background to the palette
  188043. * and update info structure. REQUIRED if you are expecting libpng to
  188044. * update the palette for you (i.e., you selected such a transform above).
  188045. */
  188046. png_read_update_info(png_ptr, info_ptr);
  188047. /* -------------- image transformations end here ------------------- */
  188048. #ifdef PNG_FREE_ME_SUPPORTED
  188049. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188050. #endif
  188051. if(info_ptr->row_pointers == NULL)
  188052. {
  188053. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188054. info_ptr->height * png_sizeof(png_bytep));
  188055. #ifdef PNG_FREE_ME_SUPPORTED
  188056. info_ptr->free_me |= PNG_FREE_ROWS;
  188057. #endif
  188058. for (row = 0; row < (int)info_ptr->height; row++)
  188059. {
  188060. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188061. png_get_rowbytes(png_ptr, info_ptr));
  188062. }
  188063. }
  188064. png_read_image(png_ptr, info_ptr->row_pointers);
  188065. info_ptr->valid |= PNG_INFO_IDAT;
  188066. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188067. png_read_end(png_ptr, info_ptr);
  188068. transforms = transforms; /* quiet compiler warnings */
  188069. params = params;
  188070. }
  188071. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188072. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188073. #endif /* PNG_READ_SUPPORTED */
  188074. /*** End of inlined file: pngread.c ***/
  188075. /*** Start of inlined file: pngpread.c ***/
  188076. /* pngpread.c - read a png file in push mode
  188077. *
  188078. * Last changed in libpng 1.2.21 October 4, 2007
  188079. * For conditions of distribution and use, see copyright notice in png.h
  188080. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188081. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188082. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188083. */
  188084. #define PNG_INTERNAL
  188085. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188086. /* push model modes */
  188087. #define PNG_READ_SIG_MODE 0
  188088. #define PNG_READ_CHUNK_MODE 1
  188089. #define PNG_READ_IDAT_MODE 2
  188090. #define PNG_SKIP_MODE 3
  188091. #define PNG_READ_tEXt_MODE 4
  188092. #define PNG_READ_zTXt_MODE 5
  188093. #define PNG_READ_DONE_MODE 6
  188094. #define PNG_READ_iTXt_MODE 7
  188095. #define PNG_ERROR_MODE 8
  188096. void PNGAPI
  188097. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188098. png_bytep buffer, png_size_t buffer_size)
  188099. {
  188100. if(png_ptr == NULL) return;
  188101. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188102. while (png_ptr->buffer_size)
  188103. {
  188104. png_process_some_data(png_ptr, info_ptr);
  188105. }
  188106. }
  188107. /* What we do with the incoming data depends on what we were previously
  188108. * doing before we ran out of data...
  188109. */
  188110. void /* PRIVATE */
  188111. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188112. {
  188113. if(png_ptr == NULL) return;
  188114. switch (png_ptr->process_mode)
  188115. {
  188116. case PNG_READ_SIG_MODE:
  188117. {
  188118. png_push_read_sig(png_ptr, info_ptr);
  188119. break;
  188120. }
  188121. case PNG_READ_CHUNK_MODE:
  188122. {
  188123. png_push_read_chunk(png_ptr, info_ptr);
  188124. break;
  188125. }
  188126. case PNG_READ_IDAT_MODE:
  188127. {
  188128. png_push_read_IDAT(png_ptr);
  188129. break;
  188130. }
  188131. #if defined(PNG_READ_tEXt_SUPPORTED)
  188132. case PNG_READ_tEXt_MODE:
  188133. {
  188134. png_push_read_tEXt(png_ptr, info_ptr);
  188135. break;
  188136. }
  188137. #endif
  188138. #if defined(PNG_READ_zTXt_SUPPORTED)
  188139. case PNG_READ_zTXt_MODE:
  188140. {
  188141. png_push_read_zTXt(png_ptr, info_ptr);
  188142. break;
  188143. }
  188144. #endif
  188145. #if defined(PNG_READ_iTXt_SUPPORTED)
  188146. case PNG_READ_iTXt_MODE:
  188147. {
  188148. png_push_read_iTXt(png_ptr, info_ptr);
  188149. break;
  188150. }
  188151. #endif
  188152. case PNG_SKIP_MODE:
  188153. {
  188154. png_push_crc_finish(png_ptr);
  188155. break;
  188156. }
  188157. default:
  188158. {
  188159. png_ptr->buffer_size = 0;
  188160. break;
  188161. }
  188162. }
  188163. }
  188164. /* Read any remaining signature bytes from the stream and compare them with
  188165. * the correct PNG signature. It is possible that this routine is called
  188166. * with bytes already read from the signature, either because they have been
  188167. * checked by the calling application, or because of multiple calls to this
  188168. * routine.
  188169. */
  188170. void /* PRIVATE */
  188171. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188172. {
  188173. png_size_t num_checked = png_ptr->sig_bytes,
  188174. num_to_check = 8 - num_checked;
  188175. if (png_ptr->buffer_size < num_to_check)
  188176. {
  188177. num_to_check = png_ptr->buffer_size;
  188178. }
  188179. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188180. num_to_check);
  188181. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188182. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188183. {
  188184. if (num_checked < 4 &&
  188185. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188186. png_error(png_ptr, "Not a PNG file");
  188187. else
  188188. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188189. }
  188190. else
  188191. {
  188192. if (png_ptr->sig_bytes >= 8)
  188193. {
  188194. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188195. }
  188196. }
  188197. }
  188198. void /* PRIVATE */
  188199. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188200. {
  188201. #ifdef PNG_USE_LOCAL_ARRAYS
  188202. PNG_CONST PNG_IHDR;
  188203. PNG_CONST PNG_IDAT;
  188204. PNG_CONST PNG_IEND;
  188205. PNG_CONST PNG_PLTE;
  188206. #if defined(PNG_READ_bKGD_SUPPORTED)
  188207. PNG_CONST PNG_bKGD;
  188208. #endif
  188209. #if defined(PNG_READ_cHRM_SUPPORTED)
  188210. PNG_CONST PNG_cHRM;
  188211. #endif
  188212. #if defined(PNG_READ_gAMA_SUPPORTED)
  188213. PNG_CONST PNG_gAMA;
  188214. #endif
  188215. #if defined(PNG_READ_hIST_SUPPORTED)
  188216. PNG_CONST PNG_hIST;
  188217. #endif
  188218. #if defined(PNG_READ_iCCP_SUPPORTED)
  188219. PNG_CONST PNG_iCCP;
  188220. #endif
  188221. #if defined(PNG_READ_iTXt_SUPPORTED)
  188222. PNG_CONST PNG_iTXt;
  188223. #endif
  188224. #if defined(PNG_READ_oFFs_SUPPORTED)
  188225. PNG_CONST PNG_oFFs;
  188226. #endif
  188227. #if defined(PNG_READ_pCAL_SUPPORTED)
  188228. PNG_CONST PNG_pCAL;
  188229. #endif
  188230. #if defined(PNG_READ_pHYs_SUPPORTED)
  188231. PNG_CONST PNG_pHYs;
  188232. #endif
  188233. #if defined(PNG_READ_sBIT_SUPPORTED)
  188234. PNG_CONST PNG_sBIT;
  188235. #endif
  188236. #if defined(PNG_READ_sCAL_SUPPORTED)
  188237. PNG_CONST PNG_sCAL;
  188238. #endif
  188239. #if defined(PNG_READ_sRGB_SUPPORTED)
  188240. PNG_CONST PNG_sRGB;
  188241. #endif
  188242. #if defined(PNG_READ_sPLT_SUPPORTED)
  188243. PNG_CONST PNG_sPLT;
  188244. #endif
  188245. #if defined(PNG_READ_tEXt_SUPPORTED)
  188246. PNG_CONST PNG_tEXt;
  188247. #endif
  188248. #if defined(PNG_READ_tIME_SUPPORTED)
  188249. PNG_CONST PNG_tIME;
  188250. #endif
  188251. #if defined(PNG_READ_tRNS_SUPPORTED)
  188252. PNG_CONST PNG_tRNS;
  188253. #endif
  188254. #if defined(PNG_READ_zTXt_SUPPORTED)
  188255. PNG_CONST PNG_zTXt;
  188256. #endif
  188257. #endif /* PNG_USE_LOCAL_ARRAYS */
  188258. /* First we make sure we have enough data for the 4 byte chunk name
  188259. * and the 4 byte chunk length before proceeding with decoding the
  188260. * chunk data. To fully decode each of these chunks, we also make
  188261. * sure we have enough data in the buffer for the 4 byte CRC at the
  188262. * end of every chunk (except IDAT, which is handled separately).
  188263. */
  188264. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188265. {
  188266. png_byte chunk_length[4];
  188267. if (png_ptr->buffer_size < 8)
  188268. {
  188269. png_push_save_buffer(png_ptr);
  188270. return;
  188271. }
  188272. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188273. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188274. png_reset_crc(png_ptr);
  188275. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188276. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188277. }
  188278. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188279. if(png_ptr->mode & PNG_AFTER_IDAT)
  188280. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188281. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188282. {
  188283. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188284. {
  188285. png_push_save_buffer(png_ptr);
  188286. return;
  188287. }
  188288. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188289. }
  188290. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188291. {
  188292. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188293. {
  188294. png_push_save_buffer(png_ptr);
  188295. return;
  188296. }
  188297. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188298. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188299. png_push_have_end(png_ptr, info_ptr);
  188300. }
  188301. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188302. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188303. {
  188304. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188305. {
  188306. png_push_save_buffer(png_ptr);
  188307. return;
  188308. }
  188309. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188310. png_ptr->mode |= PNG_HAVE_IDAT;
  188311. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188312. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188313. png_ptr->mode |= PNG_HAVE_PLTE;
  188314. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188315. {
  188316. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188317. png_error(png_ptr, "Missing IHDR before IDAT");
  188318. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188319. !(png_ptr->mode & PNG_HAVE_PLTE))
  188320. png_error(png_ptr, "Missing PLTE before IDAT");
  188321. }
  188322. }
  188323. #endif
  188324. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188325. {
  188326. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188327. {
  188328. png_push_save_buffer(png_ptr);
  188329. return;
  188330. }
  188331. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188332. }
  188333. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188334. {
  188335. /* If we reach an IDAT chunk, this means we have read all of the
  188336. * header chunks, and we can start reading the image (or if this
  188337. * is called after the image has been read - we have an error).
  188338. */
  188339. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188340. png_error(png_ptr, "Missing IHDR before IDAT");
  188341. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188342. !(png_ptr->mode & PNG_HAVE_PLTE))
  188343. png_error(png_ptr, "Missing PLTE before IDAT");
  188344. if (png_ptr->mode & PNG_HAVE_IDAT)
  188345. {
  188346. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188347. if (png_ptr->push_length == 0)
  188348. return;
  188349. if (png_ptr->mode & PNG_AFTER_IDAT)
  188350. png_error(png_ptr, "Too many IDAT's found");
  188351. }
  188352. png_ptr->idat_size = png_ptr->push_length;
  188353. png_ptr->mode |= PNG_HAVE_IDAT;
  188354. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188355. png_push_have_info(png_ptr, info_ptr);
  188356. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188357. png_ptr->zstream.next_out = png_ptr->row_buf;
  188358. return;
  188359. }
  188360. #if defined(PNG_READ_gAMA_SUPPORTED)
  188361. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188362. {
  188363. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188364. {
  188365. png_push_save_buffer(png_ptr);
  188366. return;
  188367. }
  188368. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188369. }
  188370. #endif
  188371. #if defined(PNG_READ_sBIT_SUPPORTED)
  188372. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188373. {
  188374. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188375. {
  188376. png_push_save_buffer(png_ptr);
  188377. return;
  188378. }
  188379. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188380. }
  188381. #endif
  188382. #if defined(PNG_READ_cHRM_SUPPORTED)
  188383. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188384. {
  188385. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188386. {
  188387. png_push_save_buffer(png_ptr);
  188388. return;
  188389. }
  188390. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188391. }
  188392. #endif
  188393. #if defined(PNG_READ_sRGB_SUPPORTED)
  188394. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188395. {
  188396. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188397. {
  188398. png_push_save_buffer(png_ptr);
  188399. return;
  188400. }
  188401. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188402. }
  188403. #endif
  188404. #if defined(PNG_READ_iCCP_SUPPORTED)
  188405. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188406. {
  188407. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188408. {
  188409. png_push_save_buffer(png_ptr);
  188410. return;
  188411. }
  188412. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188413. }
  188414. #endif
  188415. #if defined(PNG_READ_sPLT_SUPPORTED)
  188416. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188417. {
  188418. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188419. {
  188420. png_push_save_buffer(png_ptr);
  188421. return;
  188422. }
  188423. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188424. }
  188425. #endif
  188426. #if defined(PNG_READ_tRNS_SUPPORTED)
  188427. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188428. {
  188429. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188430. {
  188431. png_push_save_buffer(png_ptr);
  188432. return;
  188433. }
  188434. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188435. }
  188436. #endif
  188437. #if defined(PNG_READ_bKGD_SUPPORTED)
  188438. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188439. {
  188440. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188441. {
  188442. png_push_save_buffer(png_ptr);
  188443. return;
  188444. }
  188445. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188446. }
  188447. #endif
  188448. #if defined(PNG_READ_hIST_SUPPORTED)
  188449. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188450. {
  188451. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188452. {
  188453. png_push_save_buffer(png_ptr);
  188454. return;
  188455. }
  188456. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188457. }
  188458. #endif
  188459. #if defined(PNG_READ_pHYs_SUPPORTED)
  188460. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188461. {
  188462. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188463. {
  188464. png_push_save_buffer(png_ptr);
  188465. return;
  188466. }
  188467. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188468. }
  188469. #endif
  188470. #if defined(PNG_READ_oFFs_SUPPORTED)
  188471. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188472. {
  188473. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188474. {
  188475. png_push_save_buffer(png_ptr);
  188476. return;
  188477. }
  188478. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188479. }
  188480. #endif
  188481. #if defined(PNG_READ_pCAL_SUPPORTED)
  188482. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188483. {
  188484. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188485. {
  188486. png_push_save_buffer(png_ptr);
  188487. return;
  188488. }
  188489. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188490. }
  188491. #endif
  188492. #if defined(PNG_READ_sCAL_SUPPORTED)
  188493. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188494. {
  188495. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188496. {
  188497. png_push_save_buffer(png_ptr);
  188498. return;
  188499. }
  188500. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188501. }
  188502. #endif
  188503. #if defined(PNG_READ_tIME_SUPPORTED)
  188504. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188505. {
  188506. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188507. {
  188508. png_push_save_buffer(png_ptr);
  188509. return;
  188510. }
  188511. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188512. }
  188513. #endif
  188514. #if defined(PNG_READ_tEXt_SUPPORTED)
  188515. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 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_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188523. }
  188524. #endif
  188525. #if defined(PNG_READ_zTXt_SUPPORTED)
  188526. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188527. {
  188528. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188529. {
  188530. png_push_save_buffer(png_ptr);
  188531. return;
  188532. }
  188533. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188534. }
  188535. #endif
  188536. #if defined(PNG_READ_iTXt_SUPPORTED)
  188537. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188538. {
  188539. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188540. {
  188541. png_push_save_buffer(png_ptr);
  188542. return;
  188543. }
  188544. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188545. }
  188546. #endif
  188547. else
  188548. {
  188549. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188550. {
  188551. png_push_save_buffer(png_ptr);
  188552. return;
  188553. }
  188554. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188555. }
  188556. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188557. }
  188558. void /* PRIVATE */
  188559. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188560. {
  188561. png_ptr->process_mode = PNG_SKIP_MODE;
  188562. png_ptr->skip_length = skip;
  188563. }
  188564. void /* PRIVATE */
  188565. png_push_crc_finish(png_structp png_ptr)
  188566. {
  188567. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188568. {
  188569. png_size_t save_size;
  188570. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188571. save_size = (png_size_t)png_ptr->skip_length;
  188572. else
  188573. save_size = png_ptr->save_buffer_size;
  188574. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188575. png_ptr->skip_length -= save_size;
  188576. png_ptr->buffer_size -= save_size;
  188577. png_ptr->save_buffer_size -= save_size;
  188578. png_ptr->save_buffer_ptr += save_size;
  188579. }
  188580. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188581. {
  188582. png_size_t save_size;
  188583. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188584. save_size = (png_size_t)png_ptr->skip_length;
  188585. else
  188586. save_size = png_ptr->current_buffer_size;
  188587. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188588. png_ptr->skip_length -= save_size;
  188589. png_ptr->buffer_size -= save_size;
  188590. png_ptr->current_buffer_size -= save_size;
  188591. png_ptr->current_buffer_ptr += save_size;
  188592. }
  188593. if (!png_ptr->skip_length)
  188594. {
  188595. if (png_ptr->buffer_size < 4)
  188596. {
  188597. png_push_save_buffer(png_ptr);
  188598. return;
  188599. }
  188600. png_crc_finish(png_ptr, 0);
  188601. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188602. }
  188603. }
  188604. void PNGAPI
  188605. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188606. {
  188607. png_bytep ptr;
  188608. if(png_ptr == NULL) return;
  188609. ptr = buffer;
  188610. if (png_ptr->save_buffer_size)
  188611. {
  188612. png_size_t save_size;
  188613. if (length < png_ptr->save_buffer_size)
  188614. save_size = length;
  188615. else
  188616. save_size = png_ptr->save_buffer_size;
  188617. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188618. length -= save_size;
  188619. ptr += save_size;
  188620. png_ptr->buffer_size -= save_size;
  188621. png_ptr->save_buffer_size -= save_size;
  188622. png_ptr->save_buffer_ptr += save_size;
  188623. }
  188624. if (length && png_ptr->current_buffer_size)
  188625. {
  188626. png_size_t save_size;
  188627. if (length < png_ptr->current_buffer_size)
  188628. save_size = length;
  188629. else
  188630. save_size = png_ptr->current_buffer_size;
  188631. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188632. png_ptr->buffer_size -= save_size;
  188633. png_ptr->current_buffer_size -= save_size;
  188634. png_ptr->current_buffer_ptr += save_size;
  188635. }
  188636. }
  188637. void /* PRIVATE */
  188638. png_push_save_buffer(png_structp png_ptr)
  188639. {
  188640. if (png_ptr->save_buffer_size)
  188641. {
  188642. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188643. {
  188644. png_size_t i,istop;
  188645. png_bytep sp;
  188646. png_bytep dp;
  188647. istop = png_ptr->save_buffer_size;
  188648. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188649. i < istop; i++, sp++, dp++)
  188650. {
  188651. *dp = *sp;
  188652. }
  188653. }
  188654. }
  188655. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188656. png_ptr->save_buffer_max)
  188657. {
  188658. png_size_t new_max;
  188659. png_bytep old_buffer;
  188660. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188661. (png_ptr->current_buffer_size + 256))
  188662. {
  188663. png_error(png_ptr, "Potential overflow of save_buffer");
  188664. }
  188665. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188666. old_buffer = png_ptr->save_buffer;
  188667. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188668. (png_uint_32)new_max);
  188669. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188670. png_free(png_ptr, old_buffer);
  188671. png_ptr->save_buffer_max = new_max;
  188672. }
  188673. if (png_ptr->current_buffer_size)
  188674. {
  188675. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188676. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188677. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188678. png_ptr->current_buffer_size = 0;
  188679. }
  188680. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188681. png_ptr->buffer_size = 0;
  188682. }
  188683. void /* PRIVATE */
  188684. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188685. png_size_t buffer_length)
  188686. {
  188687. png_ptr->current_buffer = buffer;
  188688. png_ptr->current_buffer_size = buffer_length;
  188689. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188690. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188691. }
  188692. void /* PRIVATE */
  188693. png_push_read_IDAT(png_structp png_ptr)
  188694. {
  188695. #ifdef PNG_USE_LOCAL_ARRAYS
  188696. PNG_CONST PNG_IDAT;
  188697. #endif
  188698. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188699. {
  188700. png_byte chunk_length[4];
  188701. if (png_ptr->buffer_size < 8)
  188702. {
  188703. png_push_save_buffer(png_ptr);
  188704. return;
  188705. }
  188706. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188707. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188708. png_reset_crc(png_ptr);
  188709. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188710. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188711. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188712. {
  188713. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188714. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188715. png_error(png_ptr, "Not enough compressed data");
  188716. return;
  188717. }
  188718. png_ptr->idat_size = png_ptr->push_length;
  188719. }
  188720. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188721. {
  188722. png_size_t save_size;
  188723. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188724. {
  188725. save_size = (png_size_t)png_ptr->idat_size;
  188726. /* check for overflow */
  188727. if((png_uint_32)save_size != png_ptr->idat_size)
  188728. png_error(png_ptr, "save_size overflowed in pngpread");
  188729. }
  188730. else
  188731. save_size = png_ptr->save_buffer_size;
  188732. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188733. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188734. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188735. png_ptr->idat_size -= save_size;
  188736. png_ptr->buffer_size -= save_size;
  188737. png_ptr->save_buffer_size -= save_size;
  188738. png_ptr->save_buffer_ptr += save_size;
  188739. }
  188740. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188741. {
  188742. png_size_t save_size;
  188743. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188744. {
  188745. save_size = (png_size_t)png_ptr->idat_size;
  188746. /* check for overflow */
  188747. if((png_uint_32)save_size != png_ptr->idat_size)
  188748. png_error(png_ptr, "save_size overflowed in pngpread");
  188749. }
  188750. else
  188751. save_size = png_ptr->current_buffer_size;
  188752. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188753. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188754. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188755. png_ptr->idat_size -= save_size;
  188756. png_ptr->buffer_size -= save_size;
  188757. png_ptr->current_buffer_size -= save_size;
  188758. png_ptr->current_buffer_ptr += save_size;
  188759. }
  188760. if (!png_ptr->idat_size)
  188761. {
  188762. if (png_ptr->buffer_size < 4)
  188763. {
  188764. png_push_save_buffer(png_ptr);
  188765. return;
  188766. }
  188767. png_crc_finish(png_ptr, 0);
  188768. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188769. png_ptr->mode |= PNG_AFTER_IDAT;
  188770. }
  188771. }
  188772. void /* PRIVATE */
  188773. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188774. png_size_t buffer_length)
  188775. {
  188776. int ret;
  188777. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188778. png_error(png_ptr, "Extra compression data");
  188779. png_ptr->zstream.next_in = buffer;
  188780. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188781. for(;;)
  188782. {
  188783. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188784. if (ret != Z_OK)
  188785. {
  188786. if (ret == Z_STREAM_END)
  188787. {
  188788. if (png_ptr->zstream.avail_in)
  188789. png_error(png_ptr, "Extra compressed data");
  188790. if (!(png_ptr->zstream.avail_out))
  188791. {
  188792. png_push_process_row(png_ptr);
  188793. }
  188794. png_ptr->mode |= PNG_AFTER_IDAT;
  188795. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188796. break;
  188797. }
  188798. else if (ret == Z_BUF_ERROR)
  188799. break;
  188800. else
  188801. png_error(png_ptr, "Decompression Error");
  188802. }
  188803. if (!(png_ptr->zstream.avail_out))
  188804. {
  188805. if ((
  188806. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188807. png_ptr->interlaced && png_ptr->pass > 6) ||
  188808. (!png_ptr->interlaced &&
  188809. #endif
  188810. png_ptr->row_number == png_ptr->num_rows))
  188811. {
  188812. if (png_ptr->zstream.avail_in)
  188813. {
  188814. png_warning(png_ptr, "Too much data in IDAT chunks");
  188815. }
  188816. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188817. break;
  188818. }
  188819. png_push_process_row(png_ptr);
  188820. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188821. png_ptr->zstream.next_out = png_ptr->row_buf;
  188822. }
  188823. else
  188824. break;
  188825. }
  188826. }
  188827. void /* PRIVATE */
  188828. png_push_process_row(png_structp png_ptr)
  188829. {
  188830. png_ptr->row_info.color_type = png_ptr->color_type;
  188831. png_ptr->row_info.width = png_ptr->iwidth;
  188832. png_ptr->row_info.channels = png_ptr->channels;
  188833. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188834. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188835. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188836. png_ptr->row_info.width);
  188837. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188838. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188839. (int)(png_ptr->row_buf[0]));
  188840. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188841. png_ptr->rowbytes + 1);
  188842. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188843. png_do_read_transformations(png_ptr);
  188844. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188845. /* blow up interlaced rows to full size */
  188846. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188847. {
  188848. if (png_ptr->pass < 6)
  188849. /* old interface (pre-1.0.9):
  188850. png_do_read_interlace(&(png_ptr->row_info),
  188851. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188852. */
  188853. png_do_read_interlace(png_ptr);
  188854. switch (png_ptr->pass)
  188855. {
  188856. case 0:
  188857. {
  188858. int i;
  188859. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188860. {
  188861. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188862. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188863. }
  188864. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188865. {
  188866. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188867. {
  188868. png_push_have_row(png_ptr, png_bytep_NULL);
  188869. png_read_push_finish_row(png_ptr);
  188870. }
  188871. }
  188872. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188873. {
  188874. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188875. {
  188876. png_push_have_row(png_ptr, png_bytep_NULL);
  188877. png_read_push_finish_row(png_ptr);
  188878. }
  188879. }
  188880. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188881. {
  188882. png_push_have_row(png_ptr, png_bytep_NULL);
  188883. png_read_push_finish_row(png_ptr);
  188884. }
  188885. break;
  188886. }
  188887. case 1:
  188888. {
  188889. int i;
  188890. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188891. {
  188892. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188893. png_read_push_finish_row(png_ptr);
  188894. }
  188895. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188896. {
  188897. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188898. {
  188899. png_push_have_row(png_ptr, png_bytep_NULL);
  188900. png_read_push_finish_row(png_ptr);
  188901. }
  188902. }
  188903. break;
  188904. }
  188905. case 2:
  188906. {
  188907. int i;
  188908. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188909. {
  188910. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188911. png_read_push_finish_row(png_ptr);
  188912. }
  188913. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188914. {
  188915. png_push_have_row(png_ptr, png_bytep_NULL);
  188916. png_read_push_finish_row(png_ptr);
  188917. }
  188918. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188919. {
  188920. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188921. {
  188922. png_push_have_row(png_ptr, png_bytep_NULL);
  188923. png_read_push_finish_row(png_ptr);
  188924. }
  188925. }
  188926. break;
  188927. }
  188928. case 3:
  188929. {
  188930. int i;
  188931. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188932. {
  188933. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188934. png_read_push_finish_row(png_ptr);
  188935. }
  188936. if (png_ptr->pass == 4) /* skip top two generated rows */
  188937. {
  188938. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188939. {
  188940. png_push_have_row(png_ptr, png_bytep_NULL);
  188941. png_read_push_finish_row(png_ptr);
  188942. }
  188943. }
  188944. break;
  188945. }
  188946. case 4:
  188947. {
  188948. int i;
  188949. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188950. {
  188951. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188952. png_read_push_finish_row(png_ptr);
  188953. }
  188954. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188955. {
  188956. png_push_have_row(png_ptr, png_bytep_NULL);
  188957. png_read_push_finish_row(png_ptr);
  188958. }
  188959. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188960. {
  188961. png_push_have_row(png_ptr, png_bytep_NULL);
  188962. png_read_push_finish_row(png_ptr);
  188963. }
  188964. break;
  188965. }
  188966. case 5:
  188967. {
  188968. int i;
  188969. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188970. {
  188971. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188972. png_read_push_finish_row(png_ptr);
  188973. }
  188974. if (png_ptr->pass == 6) /* skip top generated row */
  188975. {
  188976. png_push_have_row(png_ptr, png_bytep_NULL);
  188977. png_read_push_finish_row(png_ptr);
  188978. }
  188979. break;
  188980. }
  188981. case 6:
  188982. {
  188983. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188984. png_read_push_finish_row(png_ptr);
  188985. if (png_ptr->pass != 6)
  188986. break;
  188987. png_push_have_row(png_ptr, png_bytep_NULL);
  188988. png_read_push_finish_row(png_ptr);
  188989. }
  188990. }
  188991. }
  188992. else
  188993. #endif
  188994. {
  188995. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188996. png_read_push_finish_row(png_ptr);
  188997. }
  188998. }
  188999. void /* PRIVATE */
  189000. png_read_push_finish_row(png_structp png_ptr)
  189001. {
  189002. #ifdef PNG_USE_LOCAL_ARRAYS
  189003. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189004. /* start of interlace block */
  189005. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189006. /* offset to next interlace block */
  189007. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189008. /* start of interlace block in the y direction */
  189009. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189010. /* offset to next interlace block in the y direction */
  189011. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189012. /* Height of interlace block. This is not currently used - if you need
  189013. * it, uncomment it here and in png.h
  189014. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189015. */
  189016. #endif
  189017. png_ptr->row_number++;
  189018. if (png_ptr->row_number < png_ptr->num_rows)
  189019. return;
  189020. if (png_ptr->interlaced)
  189021. {
  189022. png_ptr->row_number = 0;
  189023. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189024. png_ptr->rowbytes + 1);
  189025. do
  189026. {
  189027. png_ptr->pass++;
  189028. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189029. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189030. (png_ptr->pass == 5 && png_ptr->width < 2))
  189031. png_ptr->pass++;
  189032. if (png_ptr->pass > 7)
  189033. png_ptr->pass--;
  189034. if (png_ptr->pass >= 7)
  189035. break;
  189036. png_ptr->iwidth = (png_ptr->width +
  189037. png_pass_inc[png_ptr->pass] - 1 -
  189038. png_pass_start[png_ptr->pass]) /
  189039. png_pass_inc[png_ptr->pass];
  189040. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189041. png_ptr->iwidth) + 1;
  189042. if (png_ptr->transformations & PNG_INTERLACE)
  189043. break;
  189044. png_ptr->num_rows = (png_ptr->height +
  189045. png_pass_yinc[png_ptr->pass] - 1 -
  189046. png_pass_ystart[png_ptr->pass]) /
  189047. png_pass_yinc[png_ptr->pass];
  189048. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189049. }
  189050. }
  189051. #if defined(PNG_READ_tEXt_SUPPORTED)
  189052. void /* PRIVATE */
  189053. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189054. length)
  189055. {
  189056. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189057. {
  189058. png_error(png_ptr, "Out of place tEXt");
  189059. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189060. }
  189061. #ifdef PNG_MAX_MALLOC_64K
  189062. png_ptr->skip_length = 0; /* This may not be necessary */
  189063. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189064. {
  189065. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189066. png_ptr->skip_length = length - (png_uint_32)65535L;
  189067. length = (png_uint_32)65535L;
  189068. }
  189069. #endif
  189070. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189071. (png_uint_32)(length+1));
  189072. png_ptr->current_text[length] = '\0';
  189073. png_ptr->current_text_ptr = png_ptr->current_text;
  189074. png_ptr->current_text_size = (png_size_t)length;
  189075. png_ptr->current_text_left = (png_size_t)length;
  189076. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189077. }
  189078. void /* PRIVATE */
  189079. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189080. {
  189081. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189082. {
  189083. png_size_t text_size;
  189084. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189085. text_size = png_ptr->buffer_size;
  189086. else
  189087. text_size = png_ptr->current_text_left;
  189088. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189089. png_ptr->current_text_left -= text_size;
  189090. png_ptr->current_text_ptr += text_size;
  189091. }
  189092. if (!(png_ptr->current_text_left))
  189093. {
  189094. png_textp text_ptr;
  189095. png_charp text;
  189096. png_charp key;
  189097. int ret;
  189098. if (png_ptr->buffer_size < 4)
  189099. {
  189100. png_push_save_buffer(png_ptr);
  189101. return;
  189102. }
  189103. png_push_crc_finish(png_ptr);
  189104. #if defined(PNG_MAX_MALLOC_64K)
  189105. if (png_ptr->skip_length)
  189106. return;
  189107. #endif
  189108. key = png_ptr->current_text;
  189109. for (text = key; *text; text++)
  189110. /* empty loop */ ;
  189111. if (text < key + png_ptr->current_text_size)
  189112. text++;
  189113. text_ptr = (png_textp)png_malloc(png_ptr,
  189114. (png_uint_32)png_sizeof(png_text));
  189115. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189116. text_ptr->key = key;
  189117. #ifdef PNG_iTXt_SUPPORTED
  189118. text_ptr->lang = NULL;
  189119. text_ptr->lang_key = NULL;
  189120. #endif
  189121. text_ptr->text = text;
  189122. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189123. png_free(png_ptr, key);
  189124. png_free(png_ptr, text_ptr);
  189125. png_ptr->current_text = NULL;
  189126. if (ret)
  189127. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189128. }
  189129. }
  189130. #endif
  189131. #if defined(PNG_READ_zTXt_SUPPORTED)
  189132. void /* PRIVATE */
  189133. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189134. length)
  189135. {
  189136. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189137. {
  189138. png_error(png_ptr, "Out of place zTXt");
  189139. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189140. }
  189141. #ifdef PNG_MAX_MALLOC_64K
  189142. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189143. * to be able to store the uncompressed data. Actually, the threshold
  189144. * is probably around 32K, but it isn't as definite as 64K is.
  189145. */
  189146. if (length > (png_uint_32)65535L)
  189147. {
  189148. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189149. png_push_crc_skip(png_ptr, length);
  189150. return;
  189151. }
  189152. #endif
  189153. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189154. (png_uint_32)(length+1));
  189155. png_ptr->current_text[length] = '\0';
  189156. png_ptr->current_text_ptr = png_ptr->current_text;
  189157. png_ptr->current_text_size = (png_size_t)length;
  189158. png_ptr->current_text_left = (png_size_t)length;
  189159. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189160. }
  189161. void /* PRIVATE */
  189162. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189163. {
  189164. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189165. {
  189166. png_size_t text_size;
  189167. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189168. text_size = png_ptr->buffer_size;
  189169. else
  189170. text_size = png_ptr->current_text_left;
  189171. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189172. png_ptr->current_text_left -= text_size;
  189173. png_ptr->current_text_ptr += text_size;
  189174. }
  189175. if (!(png_ptr->current_text_left))
  189176. {
  189177. png_textp text_ptr;
  189178. png_charp text;
  189179. png_charp key;
  189180. int ret;
  189181. png_size_t text_size, key_size;
  189182. if (png_ptr->buffer_size < 4)
  189183. {
  189184. png_push_save_buffer(png_ptr);
  189185. return;
  189186. }
  189187. png_push_crc_finish(png_ptr);
  189188. key = png_ptr->current_text;
  189189. for (text = key; *text; text++)
  189190. /* empty loop */ ;
  189191. /* zTXt can't have zero text */
  189192. if (text >= key + png_ptr->current_text_size)
  189193. {
  189194. png_ptr->current_text = NULL;
  189195. png_free(png_ptr, key);
  189196. return;
  189197. }
  189198. text++;
  189199. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189200. {
  189201. png_ptr->current_text = NULL;
  189202. png_free(png_ptr, key);
  189203. return;
  189204. }
  189205. text++;
  189206. png_ptr->zstream.next_in = (png_bytep )text;
  189207. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189208. (text - key));
  189209. png_ptr->zstream.next_out = png_ptr->zbuf;
  189210. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189211. key_size = text - key;
  189212. text_size = 0;
  189213. text = NULL;
  189214. ret = Z_STREAM_END;
  189215. while (png_ptr->zstream.avail_in)
  189216. {
  189217. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189218. if (ret != Z_OK && ret != Z_STREAM_END)
  189219. {
  189220. inflateReset(&png_ptr->zstream);
  189221. png_ptr->zstream.avail_in = 0;
  189222. png_ptr->current_text = NULL;
  189223. png_free(png_ptr, key);
  189224. png_free(png_ptr, text);
  189225. return;
  189226. }
  189227. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189228. {
  189229. if (text == NULL)
  189230. {
  189231. text = (png_charp)png_malloc(png_ptr,
  189232. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189233. + key_size + 1));
  189234. png_memcpy(text + key_size, png_ptr->zbuf,
  189235. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189236. png_memcpy(text, key, key_size);
  189237. text_size = key_size + png_ptr->zbuf_size -
  189238. png_ptr->zstream.avail_out;
  189239. *(text + text_size) = '\0';
  189240. }
  189241. else
  189242. {
  189243. png_charp tmp;
  189244. tmp = text;
  189245. text = (png_charp)png_malloc(png_ptr, text_size +
  189246. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189247. + 1));
  189248. png_memcpy(text, tmp, text_size);
  189249. png_free(png_ptr, tmp);
  189250. png_memcpy(text + text_size, png_ptr->zbuf,
  189251. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189252. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189253. *(text + text_size) = '\0';
  189254. }
  189255. if (ret != Z_STREAM_END)
  189256. {
  189257. png_ptr->zstream.next_out = png_ptr->zbuf;
  189258. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189259. }
  189260. }
  189261. else
  189262. {
  189263. break;
  189264. }
  189265. if (ret == Z_STREAM_END)
  189266. break;
  189267. }
  189268. inflateReset(&png_ptr->zstream);
  189269. png_ptr->zstream.avail_in = 0;
  189270. if (ret != Z_STREAM_END)
  189271. {
  189272. png_ptr->current_text = NULL;
  189273. png_free(png_ptr, key);
  189274. png_free(png_ptr, text);
  189275. return;
  189276. }
  189277. png_ptr->current_text = NULL;
  189278. png_free(png_ptr, key);
  189279. key = text;
  189280. text += key_size;
  189281. text_ptr = (png_textp)png_malloc(png_ptr,
  189282. (png_uint_32)png_sizeof(png_text));
  189283. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189284. text_ptr->key = key;
  189285. #ifdef PNG_iTXt_SUPPORTED
  189286. text_ptr->lang = NULL;
  189287. text_ptr->lang_key = NULL;
  189288. #endif
  189289. text_ptr->text = text;
  189290. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189291. png_free(png_ptr, key);
  189292. png_free(png_ptr, text_ptr);
  189293. if (ret)
  189294. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189295. }
  189296. }
  189297. #endif
  189298. #if defined(PNG_READ_iTXt_SUPPORTED)
  189299. void /* PRIVATE */
  189300. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189301. length)
  189302. {
  189303. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189304. {
  189305. png_error(png_ptr, "Out of place iTXt");
  189306. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189307. }
  189308. #ifdef PNG_MAX_MALLOC_64K
  189309. png_ptr->skip_length = 0; /* This may not be necessary */
  189310. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189311. {
  189312. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189313. png_ptr->skip_length = length - (png_uint_32)65535L;
  189314. length = (png_uint_32)65535L;
  189315. }
  189316. #endif
  189317. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189318. (png_uint_32)(length+1));
  189319. png_ptr->current_text[length] = '\0';
  189320. png_ptr->current_text_ptr = png_ptr->current_text;
  189321. png_ptr->current_text_size = (png_size_t)length;
  189322. png_ptr->current_text_left = (png_size_t)length;
  189323. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189324. }
  189325. void /* PRIVATE */
  189326. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189327. {
  189328. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189329. {
  189330. png_size_t text_size;
  189331. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189332. text_size = png_ptr->buffer_size;
  189333. else
  189334. text_size = png_ptr->current_text_left;
  189335. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189336. png_ptr->current_text_left -= text_size;
  189337. png_ptr->current_text_ptr += text_size;
  189338. }
  189339. if (!(png_ptr->current_text_left))
  189340. {
  189341. png_textp text_ptr;
  189342. png_charp key;
  189343. int comp_flag;
  189344. png_charp lang;
  189345. png_charp lang_key;
  189346. png_charp text;
  189347. int ret;
  189348. if (png_ptr->buffer_size < 4)
  189349. {
  189350. png_push_save_buffer(png_ptr);
  189351. return;
  189352. }
  189353. png_push_crc_finish(png_ptr);
  189354. #if defined(PNG_MAX_MALLOC_64K)
  189355. if (png_ptr->skip_length)
  189356. return;
  189357. #endif
  189358. key = png_ptr->current_text;
  189359. for (lang = key; *lang; lang++)
  189360. /* empty loop */ ;
  189361. if (lang < key + png_ptr->current_text_size - 3)
  189362. lang++;
  189363. comp_flag = *lang++;
  189364. lang++; /* skip comp_type, always zero */
  189365. for (lang_key = lang; *lang_key; lang_key++)
  189366. /* empty loop */ ;
  189367. lang_key++; /* skip NUL separator */
  189368. text=lang_key;
  189369. if (lang_key < key + png_ptr->current_text_size - 1)
  189370. {
  189371. for (; *text; text++)
  189372. /* empty loop */ ;
  189373. }
  189374. if (text < key + png_ptr->current_text_size)
  189375. text++;
  189376. text_ptr = (png_textp)png_malloc(png_ptr,
  189377. (png_uint_32)png_sizeof(png_text));
  189378. text_ptr->compression = comp_flag + 2;
  189379. text_ptr->key = key;
  189380. text_ptr->lang = lang;
  189381. text_ptr->lang_key = lang_key;
  189382. text_ptr->text = text;
  189383. text_ptr->text_length = 0;
  189384. text_ptr->itxt_length = png_strlen(text);
  189385. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189386. png_ptr->current_text = NULL;
  189387. png_free(png_ptr, text_ptr);
  189388. if (ret)
  189389. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189390. }
  189391. }
  189392. #endif
  189393. /* This function is called when we haven't found a handler for this
  189394. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189395. * name or a critical chunk), the chunk is (currently) silently ignored.
  189396. */
  189397. void /* PRIVATE */
  189398. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189399. length)
  189400. {
  189401. png_uint_32 skip=0;
  189402. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189403. if (!(png_ptr->chunk_name[0] & 0x20))
  189404. {
  189405. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189406. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189407. PNG_HANDLE_CHUNK_ALWAYS
  189408. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189409. && png_ptr->read_user_chunk_fn == NULL
  189410. #endif
  189411. )
  189412. #endif
  189413. png_chunk_error(png_ptr, "unknown critical chunk");
  189414. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189415. }
  189416. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189417. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189418. {
  189419. #ifdef PNG_MAX_MALLOC_64K
  189420. if (length > (png_uint_32)65535L)
  189421. {
  189422. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189423. skip = length - (png_uint_32)65535L;
  189424. length = (png_uint_32)65535L;
  189425. }
  189426. #endif
  189427. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189428. (png_charp)png_ptr->chunk_name, 5);
  189429. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189430. png_ptr->unknown_chunk.size = (png_size_t)length;
  189431. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189432. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189433. if(png_ptr->read_user_chunk_fn != NULL)
  189434. {
  189435. /* callback to user unknown chunk handler */
  189436. int ret;
  189437. ret = (*(png_ptr->read_user_chunk_fn))
  189438. (png_ptr, &png_ptr->unknown_chunk);
  189439. if (ret < 0)
  189440. png_chunk_error(png_ptr, "error in user chunk");
  189441. if (ret == 0)
  189442. {
  189443. if (!(png_ptr->chunk_name[0] & 0x20))
  189444. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189445. PNG_HANDLE_CHUNK_ALWAYS)
  189446. png_chunk_error(png_ptr, "unknown critical chunk");
  189447. png_set_unknown_chunks(png_ptr, info_ptr,
  189448. &png_ptr->unknown_chunk, 1);
  189449. }
  189450. }
  189451. #else
  189452. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189453. #endif
  189454. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189455. png_ptr->unknown_chunk.data = NULL;
  189456. }
  189457. else
  189458. #endif
  189459. skip=length;
  189460. png_push_crc_skip(png_ptr, skip);
  189461. }
  189462. void /* PRIVATE */
  189463. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189464. {
  189465. if (png_ptr->info_fn != NULL)
  189466. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189467. }
  189468. void /* PRIVATE */
  189469. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189470. {
  189471. if (png_ptr->end_fn != NULL)
  189472. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189473. }
  189474. void /* PRIVATE */
  189475. png_push_have_row(png_structp png_ptr, png_bytep row)
  189476. {
  189477. if (png_ptr->row_fn != NULL)
  189478. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189479. (int)png_ptr->pass);
  189480. }
  189481. void PNGAPI
  189482. png_progressive_combine_row (png_structp png_ptr,
  189483. png_bytep old_row, png_bytep new_row)
  189484. {
  189485. #ifdef PNG_USE_LOCAL_ARRAYS
  189486. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189487. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189488. #endif
  189489. if(png_ptr == NULL) return;
  189490. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189491. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189492. }
  189493. void PNGAPI
  189494. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189495. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189496. png_progressive_end_ptr end_fn)
  189497. {
  189498. if(png_ptr == NULL) return;
  189499. png_ptr->info_fn = info_fn;
  189500. png_ptr->row_fn = row_fn;
  189501. png_ptr->end_fn = end_fn;
  189502. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189503. }
  189504. png_voidp PNGAPI
  189505. png_get_progressive_ptr(png_structp png_ptr)
  189506. {
  189507. if(png_ptr == NULL) return (NULL);
  189508. return png_ptr->io_ptr;
  189509. }
  189510. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189511. /*** End of inlined file: pngpread.c ***/
  189512. /*** Start of inlined file: pngrio.c ***/
  189513. /* pngrio.c - functions for data input
  189514. *
  189515. * Last changed in libpng 1.2.13 November 13, 2006
  189516. * For conditions of distribution and use, see copyright notice in png.h
  189517. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189518. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189519. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189520. *
  189521. * This file provides a location for all input. Users who need
  189522. * special handling are expected to write a function that has the same
  189523. * arguments as this and performs a similar function, but that possibly
  189524. * has a different input method. Note that you shouldn't change this
  189525. * function, but rather write a replacement function and then make
  189526. * libpng use it at run time with png_set_read_fn(...).
  189527. */
  189528. #define PNG_INTERNAL
  189529. #if defined(PNG_READ_SUPPORTED)
  189530. /* Read the data from whatever input you are using. The default routine
  189531. reads from a file pointer. Note that this routine sometimes gets called
  189532. with very small lengths, so you should implement some kind of simple
  189533. buffering if you are using unbuffered reads. This should never be asked
  189534. to read more then 64K on a 16 bit machine. */
  189535. void /* PRIVATE */
  189536. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189537. {
  189538. png_debug1(4,"reading %d bytes\n", (int)length);
  189539. if (png_ptr->read_data_fn != NULL)
  189540. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189541. else
  189542. png_error(png_ptr, "Call to NULL read function");
  189543. }
  189544. #if !defined(PNG_NO_STDIO)
  189545. /* This is the function that does the actual reading of data. If you are
  189546. not reading from a standard C stream, you should create a replacement
  189547. read_data function and use it at run time with png_set_read_fn(), rather
  189548. than changing the library. */
  189549. #ifndef USE_FAR_KEYWORD
  189550. void PNGAPI
  189551. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189552. {
  189553. png_size_t check;
  189554. if(png_ptr == NULL) return;
  189555. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189556. * instead of an int, which is what fread() actually returns.
  189557. */
  189558. #if defined(_WIN32_WCE)
  189559. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189560. check = 0;
  189561. #else
  189562. check = (png_size_t)fread(data, (png_size_t)1, length,
  189563. (png_FILE_p)png_ptr->io_ptr);
  189564. #endif
  189565. if (check != length)
  189566. png_error(png_ptr, "Read Error");
  189567. }
  189568. #else
  189569. /* this is the model-independent version. Since the standard I/O library
  189570. can't handle far buffers in the medium and small models, we have to copy
  189571. the data.
  189572. */
  189573. #define NEAR_BUF_SIZE 1024
  189574. #define MIN(a,b) (a <= b ? a : b)
  189575. static void PNGAPI
  189576. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189577. {
  189578. int check;
  189579. png_byte *n_data;
  189580. png_FILE_p io_ptr;
  189581. if(png_ptr == NULL) return;
  189582. /* Check if data really is near. If so, use usual code. */
  189583. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189584. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189585. if ((png_bytep)n_data == data)
  189586. {
  189587. #if defined(_WIN32_WCE)
  189588. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189589. check = 0;
  189590. #else
  189591. check = fread(n_data, 1, length, io_ptr);
  189592. #endif
  189593. }
  189594. else
  189595. {
  189596. png_byte buf[NEAR_BUF_SIZE];
  189597. png_size_t read, remaining, err;
  189598. check = 0;
  189599. remaining = length;
  189600. do
  189601. {
  189602. read = MIN(NEAR_BUF_SIZE, remaining);
  189603. #if defined(_WIN32_WCE)
  189604. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189605. err = 0;
  189606. #else
  189607. err = fread(buf, (png_size_t)1, read, io_ptr);
  189608. #endif
  189609. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189610. if(err != read)
  189611. break;
  189612. else
  189613. check += err;
  189614. data += read;
  189615. remaining -= read;
  189616. }
  189617. while (remaining != 0);
  189618. }
  189619. if ((png_uint_32)check != (png_uint_32)length)
  189620. png_error(png_ptr, "read Error");
  189621. }
  189622. #endif
  189623. #endif
  189624. /* This function allows the application to supply a new input function
  189625. for libpng if standard C streams aren't being used.
  189626. This function takes as its arguments:
  189627. png_ptr - pointer to a png input data structure
  189628. io_ptr - pointer to user supplied structure containing info about
  189629. the input functions. May be NULL.
  189630. read_data_fn - pointer to a new input function that takes as its
  189631. arguments a pointer to a png_struct, a pointer to
  189632. a location where input data can be stored, and a 32-bit
  189633. unsigned int that is the number of bytes to be read.
  189634. To exit and output any fatal error messages the new write
  189635. function should call png_error(png_ptr, "Error msg"). */
  189636. void PNGAPI
  189637. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189638. png_rw_ptr read_data_fn)
  189639. {
  189640. if(png_ptr == NULL) return;
  189641. png_ptr->io_ptr = io_ptr;
  189642. #if !defined(PNG_NO_STDIO)
  189643. if (read_data_fn != NULL)
  189644. png_ptr->read_data_fn = read_data_fn;
  189645. else
  189646. png_ptr->read_data_fn = png_default_read_data;
  189647. #else
  189648. png_ptr->read_data_fn = read_data_fn;
  189649. #endif
  189650. /* It is an error to write to a read device */
  189651. if (png_ptr->write_data_fn != NULL)
  189652. {
  189653. png_ptr->write_data_fn = NULL;
  189654. png_warning(png_ptr,
  189655. "It's an error to set both read_data_fn and write_data_fn in the ");
  189656. png_warning(png_ptr,
  189657. "same structure. Resetting write_data_fn to NULL.");
  189658. }
  189659. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189660. png_ptr->output_flush_fn = NULL;
  189661. #endif
  189662. }
  189663. #endif /* PNG_READ_SUPPORTED */
  189664. /*** End of inlined file: pngrio.c ***/
  189665. /*** Start of inlined file: pngrtran.c ***/
  189666. /* pngrtran.c - transforms the data in a row for PNG readers
  189667. *
  189668. * Last changed in libpng 1.2.21 [October 4, 2007]
  189669. * For conditions of distribution and use, see copyright notice in png.h
  189670. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189671. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189672. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189673. *
  189674. * This file contains functions optionally called by an application
  189675. * in order to tell libpng how to handle data when reading a PNG.
  189676. * Transformations that are used in both reading and writing are
  189677. * in pngtrans.c.
  189678. */
  189679. #define PNG_INTERNAL
  189680. #if defined(PNG_READ_SUPPORTED)
  189681. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189682. void PNGAPI
  189683. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189684. {
  189685. png_debug(1, "in png_set_crc_action\n");
  189686. /* Tell libpng how we react to CRC errors in critical chunks */
  189687. if(png_ptr == NULL) return;
  189688. switch (crit_action)
  189689. {
  189690. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189691. break;
  189692. case PNG_CRC_WARN_USE: /* warn/use data */
  189693. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189694. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189695. break;
  189696. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189697. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189698. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189699. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189700. break;
  189701. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189702. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189703. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189704. case PNG_CRC_DEFAULT:
  189705. default:
  189706. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189707. break;
  189708. }
  189709. switch (ancil_action)
  189710. {
  189711. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189712. break;
  189713. case PNG_CRC_WARN_USE: /* warn/use data */
  189714. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189715. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189716. break;
  189717. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189718. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189719. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189720. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189721. break;
  189722. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189723. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189724. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189725. break;
  189726. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189727. case PNG_CRC_DEFAULT:
  189728. default:
  189729. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189730. break;
  189731. }
  189732. }
  189733. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189734. defined(PNG_FLOATING_POINT_SUPPORTED)
  189735. /* handle alpha and tRNS via a background color */
  189736. void PNGAPI
  189737. png_set_background(png_structp png_ptr,
  189738. png_color_16p background_color, int background_gamma_code,
  189739. int need_expand, double background_gamma)
  189740. {
  189741. png_debug(1, "in png_set_background\n");
  189742. if(png_ptr == NULL) return;
  189743. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189744. {
  189745. png_warning(png_ptr, "Application must supply a known background gamma");
  189746. return;
  189747. }
  189748. png_ptr->transformations |= PNG_BACKGROUND;
  189749. png_memcpy(&(png_ptr->background), background_color,
  189750. png_sizeof(png_color_16));
  189751. png_ptr->background_gamma = (float)background_gamma;
  189752. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189753. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189754. }
  189755. #endif
  189756. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189757. /* strip 16 bit depth files to 8 bit depth */
  189758. void PNGAPI
  189759. png_set_strip_16(png_structp png_ptr)
  189760. {
  189761. png_debug(1, "in png_set_strip_16\n");
  189762. if(png_ptr == NULL) return;
  189763. png_ptr->transformations |= PNG_16_TO_8;
  189764. }
  189765. #endif
  189766. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189767. void PNGAPI
  189768. png_set_strip_alpha(png_structp png_ptr)
  189769. {
  189770. png_debug(1, "in png_set_strip_alpha\n");
  189771. if(png_ptr == NULL) return;
  189772. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189773. }
  189774. #endif
  189775. #if defined(PNG_READ_DITHER_SUPPORTED)
  189776. /* Dither file to 8 bit. Supply a palette, the current number
  189777. * of elements in the palette, the maximum number of elements
  189778. * allowed, and a histogram if possible. If the current number
  189779. * of colors is greater then the maximum number, the palette will be
  189780. * modified to fit in the maximum number. "full_dither" indicates
  189781. * whether we need a dithering cube set up for RGB images, or if we
  189782. * simply are reducing the number of colors in a paletted image.
  189783. */
  189784. typedef struct png_dsort_struct
  189785. {
  189786. struct png_dsort_struct FAR * next;
  189787. png_byte left;
  189788. png_byte right;
  189789. } png_dsort;
  189790. typedef png_dsort FAR * png_dsortp;
  189791. typedef png_dsort FAR * FAR * png_dsortpp;
  189792. void PNGAPI
  189793. png_set_dither(png_structp png_ptr, png_colorp palette,
  189794. int num_palette, int maximum_colors, png_uint_16p histogram,
  189795. int full_dither)
  189796. {
  189797. png_debug(1, "in png_set_dither\n");
  189798. if(png_ptr == NULL) return;
  189799. png_ptr->transformations |= PNG_DITHER;
  189800. if (!full_dither)
  189801. {
  189802. int i;
  189803. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189804. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189805. for (i = 0; i < num_palette; i++)
  189806. png_ptr->dither_index[i] = (png_byte)i;
  189807. }
  189808. if (num_palette > maximum_colors)
  189809. {
  189810. if (histogram != NULL)
  189811. {
  189812. /* This is easy enough, just throw out the least used colors.
  189813. Perhaps not the best solution, but good enough. */
  189814. int i;
  189815. /* initialize an array to sort colors */
  189816. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189817. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189818. /* initialize the dither_sort array */
  189819. for (i = 0; i < num_palette; i++)
  189820. png_ptr->dither_sort[i] = (png_byte)i;
  189821. /* Find the least used palette entries by starting a
  189822. bubble sort, and running it until we have sorted
  189823. out enough colors. Note that we don't care about
  189824. sorting all the colors, just finding which are
  189825. least used. */
  189826. for (i = num_palette - 1; i >= maximum_colors; i--)
  189827. {
  189828. int done; /* to stop early if the list is pre-sorted */
  189829. int j;
  189830. done = 1;
  189831. for (j = 0; j < i; j++)
  189832. {
  189833. if (histogram[png_ptr->dither_sort[j]]
  189834. < histogram[png_ptr->dither_sort[j + 1]])
  189835. {
  189836. png_byte t;
  189837. t = png_ptr->dither_sort[j];
  189838. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189839. png_ptr->dither_sort[j + 1] = t;
  189840. done = 0;
  189841. }
  189842. }
  189843. if (done)
  189844. break;
  189845. }
  189846. /* swap the palette around, and set up a table, if necessary */
  189847. if (full_dither)
  189848. {
  189849. int j = num_palette;
  189850. /* put all the useful colors within the max, but don't
  189851. move the others */
  189852. for (i = 0; i < maximum_colors; i++)
  189853. {
  189854. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189855. {
  189856. do
  189857. j--;
  189858. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189859. palette[i] = palette[j];
  189860. }
  189861. }
  189862. }
  189863. else
  189864. {
  189865. int j = num_palette;
  189866. /* move all the used colors inside the max limit, and
  189867. develop a translation table */
  189868. for (i = 0; i < maximum_colors; i++)
  189869. {
  189870. /* only move the colors we need to */
  189871. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189872. {
  189873. png_color tmp_color;
  189874. do
  189875. j--;
  189876. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189877. tmp_color = palette[j];
  189878. palette[j] = palette[i];
  189879. palette[i] = tmp_color;
  189880. /* indicate where the color went */
  189881. png_ptr->dither_index[j] = (png_byte)i;
  189882. png_ptr->dither_index[i] = (png_byte)j;
  189883. }
  189884. }
  189885. /* find closest color for those colors we are not using */
  189886. for (i = 0; i < num_palette; i++)
  189887. {
  189888. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189889. {
  189890. int min_d, k, min_k, d_index;
  189891. /* find the closest color to one we threw out */
  189892. d_index = png_ptr->dither_index[i];
  189893. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189894. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189895. {
  189896. int d;
  189897. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189898. if (d < min_d)
  189899. {
  189900. min_d = d;
  189901. min_k = k;
  189902. }
  189903. }
  189904. /* point to closest color */
  189905. png_ptr->dither_index[i] = (png_byte)min_k;
  189906. }
  189907. }
  189908. }
  189909. png_free(png_ptr, png_ptr->dither_sort);
  189910. png_ptr->dither_sort=NULL;
  189911. }
  189912. else
  189913. {
  189914. /* This is much harder to do simply (and quickly). Perhaps
  189915. we need to go through a median cut routine, but those
  189916. don't always behave themselves with only a few colors
  189917. as input. So we will just find the closest two colors,
  189918. and throw out one of them (chosen somewhat randomly).
  189919. [We don't understand this at all, so if someone wants to
  189920. work on improving it, be our guest - AED, GRP]
  189921. */
  189922. int i;
  189923. int max_d;
  189924. int num_new_palette;
  189925. png_dsortp t;
  189926. png_dsortpp hash;
  189927. t=NULL;
  189928. /* initialize palette index arrays */
  189929. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189930. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189931. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189932. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189933. /* initialize the sort array */
  189934. for (i = 0; i < num_palette; i++)
  189935. {
  189936. png_ptr->index_to_palette[i] = (png_byte)i;
  189937. png_ptr->palette_to_index[i] = (png_byte)i;
  189938. }
  189939. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189940. png_sizeof (png_dsortp)));
  189941. for (i = 0; i < 769; i++)
  189942. hash[i] = NULL;
  189943. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189944. num_new_palette = num_palette;
  189945. /* initial wild guess at how far apart the farthest pixel
  189946. pair we will be eliminating will be. Larger
  189947. numbers mean more areas will be allocated, Smaller
  189948. numbers run the risk of not saving enough data, and
  189949. having to do this all over again.
  189950. I have not done extensive checking on this number.
  189951. */
  189952. max_d = 96;
  189953. while (num_new_palette > maximum_colors)
  189954. {
  189955. for (i = 0; i < num_new_palette - 1; i++)
  189956. {
  189957. int j;
  189958. for (j = i + 1; j < num_new_palette; j++)
  189959. {
  189960. int d;
  189961. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189962. if (d <= max_d)
  189963. {
  189964. t = (png_dsortp)png_malloc_warn(png_ptr,
  189965. (png_uint_32)(png_sizeof(png_dsort)));
  189966. if (t == NULL)
  189967. break;
  189968. t->next = hash[d];
  189969. t->left = (png_byte)i;
  189970. t->right = (png_byte)j;
  189971. hash[d] = t;
  189972. }
  189973. }
  189974. if (t == NULL)
  189975. break;
  189976. }
  189977. if (t != NULL)
  189978. for (i = 0; i <= max_d; i++)
  189979. {
  189980. if (hash[i] != NULL)
  189981. {
  189982. png_dsortp p;
  189983. for (p = hash[i]; p; p = p->next)
  189984. {
  189985. if ((int)png_ptr->index_to_palette[p->left]
  189986. < num_new_palette &&
  189987. (int)png_ptr->index_to_palette[p->right]
  189988. < num_new_palette)
  189989. {
  189990. int j, next_j;
  189991. if (num_new_palette & 0x01)
  189992. {
  189993. j = p->left;
  189994. next_j = p->right;
  189995. }
  189996. else
  189997. {
  189998. j = p->right;
  189999. next_j = p->left;
  190000. }
  190001. num_new_palette--;
  190002. palette[png_ptr->index_to_palette[j]]
  190003. = palette[num_new_palette];
  190004. if (!full_dither)
  190005. {
  190006. int k;
  190007. for (k = 0; k < num_palette; k++)
  190008. {
  190009. if (png_ptr->dither_index[k] ==
  190010. png_ptr->index_to_palette[j])
  190011. png_ptr->dither_index[k] =
  190012. png_ptr->index_to_palette[next_j];
  190013. if ((int)png_ptr->dither_index[k] ==
  190014. num_new_palette)
  190015. png_ptr->dither_index[k] =
  190016. png_ptr->index_to_palette[j];
  190017. }
  190018. }
  190019. png_ptr->index_to_palette[png_ptr->palette_to_index
  190020. [num_new_palette]] = png_ptr->index_to_palette[j];
  190021. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190022. = png_ptr->palette_to_index[num_new_palette];
  190023. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190024. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190025. }
  190026. if (num_new_palette <= maximum_colors)
  190027. break;
  190028. }
  190029. if (num_new_palette <= maximum_colors)
  190030. break;
  190031. }
  190032. }
  190033. for (i = 0; i < 769; i++)
  190034. {
  190035. if (hash[i] != NULL)
  190036. {
  190037. png_dsortp p = hash[i];
  190038. while (p)
  190039. {
  190040. t = p->next;
  190041. png_free(png_ptr, p);
  190042. p = t;
  190043. }
  190044. }
  190045. hash[i] = 0;
  190046. }
  190047. max_d += 96;
  190048. }
  190049. png_free(png_ptr, hash);
  190050. png_free(png_ptr, png_ptr->palette_to_index);
  190051. png_free(png_ptr, png_ptr->index_to_palette);
  190052. png_ptr->palette_to_index=NULL;
  190053. png_ptr->index_to_palette=NULL;
  190054. }
  190055. num_palette = maximum_colors;
  190056. }
  190057. if (png_ptr->palette == NULL)
  190058. {
  190059. png_ptr->palette = palette;
  190060. }
  190061. png_ptr->num_palette = (png_uint_16)num_palette;
  190062. if (full_dither)
  190063. {
  190064. int i;
  190065. png_bytep distance;
  190066. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190067. PNG_DITHER_BLUE_BITS;
  190068. int num_red = (1 << PNG_DITHER_RED_BITS);
  190069. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190070. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190071. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190072. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190073. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190074. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190075. png_sizeof (png_byte));
  190076. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190077. png_sizeof(png_byte)));
  190078. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190079. for (i = 0; i < num_palette; i++)
  190080. {
  190081. int ir, ig, ib;
  190082. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190083. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190084. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190085. for (ir = 0; ir < num_red; ir++)
  190086. {
  190087. /* int dr = abs(ir - r); */
  190088. int dr = ((ir > r) ? ir - r : r - ir);
  190089. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190090. for (ig = 0; ig < num_green; ig++)
  190091. {
  190092. /* int dg = abs(ig - g); */
  190093. int dg = ((ig > g) ? ig - g : g - ig);
  190094. int dt = dr + dg;
  190095. int dm = ((dr > dg) ? dr : dg);
  190096. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190097. for (ib = 0; ib < num_blue; ib++)
  190098. {
  190099. int d_index = index_g | ib;
  190100. /* int db = abs(ib - b); */
  190101. int db = ((ib > b) ? ib - b : b - ib);
  190102. int dmax = ((dm > db) ? dm : db);
  190103. int d = dmax + dt + db;
  190104. if (d < (int)distance[d_index])
  190105. {
  190106. distance[d_index] = (png_byte)d;
  190107. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190108. }
  190109. }
  190110. }
  190111. }
  190112. }
  190113. png_free(png_ptr, distance);
  190114. }
  190115. }
  190116. #endif
  190117. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190118. /* Transform the image from the file_gamma to the screen_gamma. We
  190119. * only do transformations on images where the file_gamma and screen_gamma
  190120. * are not close reciprocals, otherwise it slows things down slightly, and
  190121. * also needlessly introduces small errors.
  190122. *
  190123. * We will turn off gamma transformation later if no semitransparent entries
  190124. * are present in the tRNS array for palette images. We can't do it here
  190125. * because we don't necessarily have the tRNS chunk yet.
  190126. */
  190127. void PNGAPI
  190128. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190129. {
  190130. png_debug(1, "in png_set_gamma\n");
  190131. if(png_ptr == NULL) return;
  190132. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190133. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190134. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190135. png_ptr->transformations |= PNG_GAMMA;
  190136. png_ptr->gamma = (float)file_gamma;
  190137. png_ptr->screen_gamma = (float)scrn_gamma;
  190138. }
  190139. #endif
  190140. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190141. /* Expand paletted images to RGB, expand grayscale images of
  190142. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190143. * to alpha channels.
  190144. */
  190145. void PNGAPI
  190146. png_set_expand(png_structp png_ptr)
  190147. {
  190148. png_debug(1, "in png_set_expand\n");
  190149. if(png_ptr == NULL) return;
  190150. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190151. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190152. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190153. #endif
  190154. }
  190155. /* GRR 19990627: the following three functions currently are identical
  190156. * to png_set_expand(). However, it is entirely reasonable that someone
  190157. * might wish to expand an indexed image to RGB but *not* expand a single,
  190158. * fully transparent palette entry to a full alpha channel--perhaps instead
  190159. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190160. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190161. * IOW, a future version of the library may make the transformations flag
  190162. * a bit more fine-grained, with separate bits for each of these three
  190163. * functions.
  190164. *
  190165. * More to the point, these functions make it obvious what libpng will be
  190166. * doing, whereas "expand" can (and does) mean any number of things.
  190167. *
  190168. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190169. * to expand only the sample depth but not to expand the tRNS to alpha.
  190170. */
  190171. /* Expand paletted images to RGB. */
  190172. void PNGAPI
  190173. png_set_palette_to_rgb(png_structp png_ptr)
  190174. {
  190175. png_debug(1, "in png_set_palette_to_rgb\n");
  190176. if(png_ptr == NULL) return;
  190177. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190178. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190179. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190180. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190181. #endif
  190182. }
  190183. #if !defined(PNG_1_0_X)
  190184. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190185. void PNGAPI
  190186. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190187. {
  190188. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190189. if(png_ptr == NULL) return;
  190190. png_ptr->transformations |= PNG_EXPAND;
  190191. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190192. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190193. #endif
  190194. }
  190195. #endif
  190196. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190197. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190198. /* Deprecated as of libpng-1.2.9 */
  190199. void PNGAPI
  190200. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190201. {
  190202. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190203. if(png_ptr == NULL) return;
  190204. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190205. }
  190206. #endif
  190207. /* Expand tRNS chunks to alpha channels. */
  190208. void PNGAPI
  190209. png_set_tRNS_to_alpha(png_structp png_ptr)
  190210. {
  190211. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190212. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190213. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190214. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190215. #endif
  190216. }
  190217. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190218. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190219. void PNGAPI
  190220. png_set_gray_to_rgb(png_structp png_ptr)
  190221. {
  190222. png_debug(1, "in png_set_gray_to_rgb\n");
  190223. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190224. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190225. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190226. #endif
  190227. }
  190228. #endif
  190229. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190230. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190231. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190232. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190233. */
  190234. void PNGAPI
  190235. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190236. double green)
  190237. {
  190238. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190239. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190240. if(png_ptr == NULL) return;
  190241. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190242. }
  190243. #endif
  190244. void PNGAPI
  190245. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190246. png_fixed_point red, png_fixed_point green)
  190247. {
  190248. png_debug(1, "in png_set_rgb_to_gray\n");
  190249. if(png_ptr == NULL) return;
  190250. switch(error_action)
  190251. {
  190252. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190253. break;
  190254. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190255. break;
  190256. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190257. }
  190258. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190259. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190260. png_ptr->transformations |= PNG_EXPAND;
  190261. #else
  190262. {
  190263. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190264. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190265. }
  190266. #endif
  190267. {
  190268. png_uint_16 red_int, green_int;
  190269. if(red < 0 || green < 0)
  190270. {
  190271. red_int = 6968; /* .212671 * 32768 + .5 */
  190272. green_int = 23434; /* .715160 * 32768 + .5 */
  190273. }
  190274. else if(red + green < 100000L)
  190275. {
  190276. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190277. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190278. }
  190279. else
  190280. {
  190281. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190282. red_int = 6968;
  190283. green_int = 23434;
  190284. }
  190285. png_ptr->rgb_to_gray_red_coeff = red_int;
  190286. png_ptr->rgb_to_gray_green_coeff = green_int;
  190287. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190288. }
  190289. }
  190290. #endif
  190291. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190292. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190293. defined(PNG_LEGACY_SUPPORTED)
  190294. void PNGAPI
  190295. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190296. read_user_transform_fn)
  190297. {
  190298. png_debug(1, "in png_set_read_user_transform_fn\n");
  190299. if(png_ptr == NULL) return;
  190300. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190301. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190302. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190303. #endif
  190304. #ifdef PNG_LEGACY_SUPPORTED
  190305. if(read_user_transform_fn)
  190306. png_warning(png_ptr,
  190307. "This version of libpng does not support user transforms");
  190308. #endif
  190309. }
  190310. #endif
  190311. /* Initialize everything needed for the read. This includes modifying
  190312. * the palette.
  190313. */
  190314. void /* PRIVATE */
  190315. png_init_read_transformations(png_structp png_ptr)
  190316. {
  190317. png_debug(1, "in png_init_read_transformations\n");
  190318. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190319. if(png_ptr != NULL)
  190320. #endif
  190321. {
  190322. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190323. || defined(PNG_READ_GAMMA_SUPPORTED)
  190324. int color_type = png_ptr->color_type;
  190325. #endif
  190326. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190327. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190328. /* Detect gray background and attempt to enable optimization
  190329. * for gray --> RGB case */
  190330. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190331. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190332. * background color might actually be gray yet not be flagged as such.
  190333. * This is not a problem for the current code, which uses
  190334. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190335. * png_do_gray_to_rgb() transformation.
  190336. */
  190337. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190338. !(color_type & PNG_COLOR_MASK_COLOR))
  190339. {
  190340. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190341. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190342. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190343. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190344. png_ptr->background.red == png_ptr->background.green &&
  190345. png_ptr->background.red == png_ptr->background.blue)
  190346. {
  190347. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190348. png_ptr->background.gray = png_ptr->background.red;
  190349. }
  190350. #endif
  190351. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190352. (png_ptr->transformations & PNG_EXPAND))
  190353. {
  190354. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190355. {
  190356. /* expand background and tRNS chunks */
  190357. switch (png_ptr->bit_depth)
  190358. {
  190359. case 1:
  190360. png_ptr->background.gray *= (png_uint_16)0xff;
  190361. png_ptr->background.red = png_ptr->background.green
  190362. = png_ptr->background.blue = png_ptr->background.gray;
  190363. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190364. {
  190365. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190366. png_ptr->trans_values.red = png_ptr->trans_values.green
  190367. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190368. }
  190369. break;
  190370. case 2:
  190371. png_ptr->background.gray *= (png_uint_16)0x55;
  190372. png_ptr->background.red = png_ptr->background.green
  190373. = png_ptr->background.blue = png_ptr->background.gray;
  190374. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190375. {
  190376. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190377. png_ptr->trans_values.red = png_ptr->trans_values.green
  190378. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190379. }
  190380. break;
  190381. case 4:
  190382. png_ptr->background.gray *= (png_uint_16)0x11;
  190383. png_ptr->background.red = png_ptr->background.green
  190384. = png_ptr->background.blue = png_ptr->background.gray;
  190385. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190386. {
  190387. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190388. png_ptr->trans_values.red = png_ptr->trans_values.green
  190389. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190390. }
  190391. break;
  190392. case 8:
  190393. case 16:
  190394. png_ptr->background.red = png_ptr->background.green
  190395. = png_ptr->background.blue = png_ptr->background.gray;
  190396. break;
  190397. }
  190398. }
  190399. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190400. {
  190401. png_ptr->background.red =
  190402. png_ptr->palette[png_ptr->background.index].red;
  190403. png_ptr->background.green =
  190404. png_ptr->palette[png_ptr->background.index].green;
  190405. png_ptr->background.blue =
  190406. png_ptr->palette[png_ptr->background.index].blue;
  190407. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190408. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190409. {
  190410. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190411. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190412. #endif
  190413. {
  190414. /* invert the alpha channel (in tRNS) unless the pixels are
  190415. going to be expanded, in which case leave it for later */
  190416. int i,istop;
  190417. istop=(int)png_ptr->num_trans;
  190418. for (i=0; i<istop; i++)
  190419. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190420. }
  190421. }
  190422. #endif
  190423. }
  190424. }
  190425. #endif
  190426. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190427. png_ptr->background_1 = png_ptr->background;
  190428. #endif
  190429. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190430. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190431. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190432. < PNG_GAMMA_THRESHOLD))
  190433. {
  190434. int i,k;
  190435. k=0;
  190436. for (i=0; i<png_ptr->num_trans; i++)
  190437. {
  190438. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190439. k=1; /* partial transparency is present */
  190440. }
  190441. if (k == 0)
  190442. png_ptr->transformations &= (~PNG_GAMMA);
  190443. }
  190444. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190445. png_ptr->gamma != 0.0)
  190446. {
  190447. png_build_gamma_table(png_ptr);
  190448. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190449. if (png_ptr->transformations & PNG_BACKGROUND)
  190450. {
  190451. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190452. {
  190453. /* could skip if no transparency and
  190454. */
  190455. png_color back, back_1;
  190456. png_colorp palette = png_ptr->palette;
  190457. int num_palette = png_ptr->num_palette;
  190458. int i;
  190459. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190460. {
  190461. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190462. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190463. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190464. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190465. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190466. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190467. }
  190468. else
  190469. {
  190470. double g, gs;
  190471. switch (png_ptr->background_gamma_type)
  190472. {
  190473. case PNG_BACKGROUND_GAMMA_SCREEN:
  190474. g = (png_ptr->screen_gamma);
  190475. gs = 1.0;
  190476. break;
  190477. case PNG_BACKGROUND_GAMMA_FILE:
  190478. g = 1.0 / (png_ptr->gamma);
  190479. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190480. break;
  190481. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190482. g = 1.0 / (png_ptr->background_gamma);
  190483. gs = 1.0 / (png_ptr->background_gamma *
  190484. png_ptr->screen_gamma);
  190485. break;
  190486. default:
  190487. g = 1.0; /* back_1 */
  190488. gs = 1.0; /* back */
  190489. }
  190490. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190491. {
  190492. back.red = (png_byte)png_ptr->background.red;
  190493. back.green = (png_byte)png_ptr->background.green;
  190494. back.blue = (png_byte)png_ptr->background.blue;
  190495. }
  190496. else
  190497. {
  190498. back.red = (png_byte)(pow(
  190499. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190500. back.green = (png_byte)(pow(
  190501. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190502. back.blue = (png_byte)(pow(
  190503. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190504. }
  190505. back_1.red = (png_byte)(pow(
  190506. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190507. back_1.green = (png_byte)(pow(
  190508. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190509. back_1.blue = (png_byte)(pow(
  190510. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190511. }
  190512. for (i = 0; i < num_palette; i++)
  190513. {
  190514. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190515. {
  190516. if (png_ptr->trans[i] == 0)
  190517. {
  190518. palette[i] = back;
  190519. }
  190520. else /* if (png_ptr->trans[i] != 0xff) */
  190521. {
  190522. png_byte v, w;
  190523. v = png_ptr->gamma_to_1[palette[i].red];
  190524. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190525. palette[i].red = png_ptr->gamma_from_1[w];
  190526. v = png_ptr->gamma_to_1[palette[i].green];
  190527. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190528. palette[i].green = png_ptr->gamma_from_1[w];
  190529. v = png_ptr->gamma_to_1[palette[i].blue];
  190530. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190531. palette[i].blue = png_ptr->gamma_from_1[w];
  190532. }
  190533. }
  190534. else
  190535. {
  190536. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190537. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190538. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190539. }
  190540. }
  190541. }
  190542. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190543. else
  190544. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190545. {
  190546. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190547. double g = 1.0;
  190548. double gs = 1.0;
  190549. switch (png_ptr->background_gamma_type)
  190550. {
  190551. case PNG_BACKGROUND_GAMMA_SCREEN:
  190552. g = (png_ptr->screen_gamma);
  190553. gs = 1.0;
  190554. break;
  190555. case PNG_BACKGROUND_GAMMA_FILE:
  190556. g = 1.0 / (png_ptr->gamma);
  190557. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190558. break;
  190559. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190560. g = 1.0 / (png_ptr->background_gamma);
  190561. gs = 1.0 / (png_ptr->background_gamma *
  190562. png_ptr->screen_gamma);
  190563. break;
  190564. }
  190565. png_ptr->background_1.gray = (png_uint_16)(pow(
  190566. (double)png_ptr->background.gray / m, g) * m + .5);
  190567. png_ptr->background.gray = (png_uint_16)(pow(
  190568. (double)png_ptr->background.gray / m, gs) * m + .5);
  190569. if ((png_ptr->background.red != png_ptr->background.green) ||
  190570. (png_ptr->background.red != png_ptr->background.blue) ||
  190571. (png_ptr->background.red != png_ptr->background.gray))
  190572. {
  190573. /* RGB or RGBA with color background */
  190574. png_ptr->background_1.red = (png_uint_16)(pow(
  190575. (double)png_ptr->background.red / m, g) * m + .5);
  190576. png_ptr->background_1.green = (png_uint_16)(pow(
  190577. (double)png_ptr->background.green / m, g) * m + .5);
  190578. png_ptr->background_1.blue = (png_uint_16)(pow(
  190579. (double)png_ptr->background.blue / m, g) * m + .5);
  190580. png_ptr->background.red = (png_uint_16)(pow(
  190581. (double)png_ptr->background.red / m, gs) * m + .5);
  190582. png_ptr->background.green = (png_uint_16)(pow(
  190583. (double)png_ptr->background.green / m, gs) * m + .5);
  190584. png_ptr->background.blue = (png_uint_16)(pow(
  190585. (double)png_ptr->background.blue / m, gs) * m + .5);
  190586. }
  190587. else
  190588. {
  190589. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190590. png_ptr->background_1.red = png_ptr->background_1.green
  190591. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190592. png_ptr->background.red = png_ptr->background.green
  190593. = png_ptr->background.blue = png_ptr->background.gray;
  190594. }
  190595. }
  190596. }
  190597. else
  190598. /* transformation does not include PNG_BACKGROUND */
  190599. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190600. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190601. {
  190602. png_colorp palette = png_ptr->palette;
  190603. int num_palette = png_ptr->num_palette;
  190604. int i;
  190605. for (i = 0; i < num_palette; i++)
  190606. {
  190607. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190608. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190609. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190610. }
  190611. }
  190612. }
  190613. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190614. else
  190615. #endif
  190616. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190617. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190618. /* No GAMMA transformation */
  190619. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190620. (color_type == PNG_COLOR_TYPE_PALETTE))
  190621. {
  190622. int i;
  190623. int istop = (int)png_ptr->num_trans;
  190624. png_color back;
  190625. png_colorp palette = png_ptr->palette;
  190626. back.red = (png_byte)png_ptr->background.red;
  190627. back.green = (png_byte)png_ptr->background.green;
  190628. back.blue = (png_byte)png_ptr->background.blue;
  190629. for (i = 0; i < istop; i++)
  190630. {
  190631. if (png_ptr->trans[i] == 0)
  190632. {
  190633. palette[i] = back;
  190634. }
  190635. else if (png_ptr->trans[i] != 0xff)
  190636. {
  190637. /* The png_composite() macro is defined in png.h */
  190638. png_composite(palette[i].red, palette[i].red,
  190639. png_ptr->trans[i], back.red);
  190640. png_composite(palette[i].green, palette[i].green,
  190641. png_ptr->trans[i], back.green);
  190642. png_composite(palette[i].blue, palette[i].blue,
  190643. png_ptr->trans[i], back.blue);
  190644. }
  190645. }
  190646. }
  190647. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190648. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190649. if ((png_ptr->transformations & PNG_SHIFT) &&
  190650. (color_type == PNG_COLOR_TYPE_PALETTE))
  190651. {
  190652. png_uint_16 i;
  190653. png_uint_16 istop = png_ptr->num_palette;
  190654. int sr = 8 - png_ptr->sig_bit.red;
  190655. int sg = 8 - png_ptr->sig_bit.green;
  190656. int sb = 8 - png_ptr->sig_bit.blue;
  190657. if (sr < 0 || sr > 8)
  190658. sr = 0;
  190659. if (sg < 0 || sg > 8)
  190660. sg = 0;
  190661. if (sb < 0 || sb > 8)
  190662. sb = 0;
  190663. for (i = 0; i < istop; i++)
  190664. {
  190665. png_ptr->palette[i].red >>= sr;
  190666. png_ptr->palette[i].green >>= sg;
  190667. png_ptr->palette[i].blue >>= sb;
  190668. }
  190669. }
  190670. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190671. }
  190672. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190673. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190674. if(png_ptr)
  190675. return;
  190676. #endif
  190677. }
  190678. /* Modify the info structure to reflect the transformations. The
  190679. * info should be updated so a PNG file could be written with it,
  190680. * assuming the transformations result in valid PNG data.
  190681. */
  190682. void /* PRIVATE */
  190683. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190684. {
  190685. png_debug(1, "in png_read_transform_info\n");
  190686. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190687. if (png_ptr->transformations & PNG_EXPAND)
  190688. {
  190689. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190690. {
  190691. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190692. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190693. else
  190694. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190695. info_ptr->bit_depth = 8;
  190696. info_ptr->num_trans = 0;
  190697. }
  190698. else
  190699. {
  190700. if (png_ptr->num_trans)
  190701. {
  190702. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190703. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190704. else
  190705. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190706. }
  190707. if (info_ptr->bit_depth < 8)
  190708. info_ptr->bit_depth = 8;
  190709. info_ptr->num_trans = 0;
  190710. }
  190711. }
  190712. #endif
  190713. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190714. if (png_ptr->transformations & PNG_BACKGROUND)
  190715. {
  190716. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190717. info_ptr->num_trans = 0;
  190718. info_ptr->background = png_ptr->background;
  190719. }
  190720. #endif
  190721. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190722. if (png_ptr->transformations & PNG_GAMMA)
  190723. {
  190724. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190725. info_ptr->gamma = png_ptr->gamma;
  190726. #endif
  190727. #ifdef PNG_FIXED_POINT_SUPPORTED
  190728. info_ptr->int_gamma = png_ptr->int_gamma;
  190729. #endif
  190730. }
  190731. #endif
  190732. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190733. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190734. info_ptr->bit_depth = 8;
  190735. #endif
  190736. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190737. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190738. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190739. #endif
  190740. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190741. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190742. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190743. #endif
  190744. #if defined(PNG_READ_DITHER_SUPPORTED)
  190745. if (png_ptr->transformations & PNG_DITHER)
  190746. {
  190747. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190748. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190749. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190750. {
  190751. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190752. }
  190753. }
  190754. #endif
  190755. #if defined(PNG_READ_PACK_SUPPORTED)
  190756. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190757. info_ptr->bit_depth = 8;
  190758. #endif
  190759. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190760. info_ptr->channels = 1;
  190761. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190762. info_ptr->channels = 3;
  190763. else
  190764. info_ptr->channels = 1;
  190765. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190766. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190767. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190768. #endif
  190769. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190770. info_ptr->channels++;
  190771. #if defined(PNG_READ_FILLER_SUPPORTED)
  190772. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190773. if ((png_ptr->transformations & PNG_FILLER) &&
  190774. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190775. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190776. {
  190777. info_ptr->channels++;
  190778. /* if adding a true alpha channel not just filler */
  190779. #if !defined(PNG_1_0_X)
  190780. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190781. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190782. #endif
  190783. }
  190784. #endif
  190785. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190786. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190787. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190788. {
  190789. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190790. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190791. if(info_ptr->channels < png_ptr->user_transform_channels)
  190792. info_ptr->channels = png_ptr->user_transform_channels;
  190793. }
  190794. #endif
  190795. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190796. info_ptr->bit_depth);
  190797. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190798. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190799. if(png_ptr)
  190800. return;
  190801. #endif
  190802. }
  190803. /* Transform the row. The order of transformations is significant,
  190804. * and is very touchy. If you add a transformation, take care to
  190805. * decide how it fits in with the other transformations here.
  190806. */
  190807. void /* PRIVATE */
  190808. png_do_read_transformations(png_structp png_ptr)
  190809. {
  190810. png_debug(1, "in png_do_read_transformations\n");
  190811. if (png_ptr->row_buf == NULL)
  190812. {
  190813. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190814. char msg[50];
  190815. png_snprintf2(msg, 50,
  190816. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190817. png_ptr->pass);
  190818. png_error(png_ptr, msg);
  190819. #else
  190820. png_error(png_ptr, "NULL row buffer");
  190821. #endif
  190822. }
  190823. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190824. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190825. /* Application has failed to call either png_read_start_image()
  190826. * or png_read_update_info() after setting transforms that expand
  190827. * pixels. This check added to libpng-1.2.19 */
  190828. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190829. png_error(png_ptr, "Uninitialized row");
  190830. #else
  190831. png_warning(png_ptr, "Uninitialized row");
  190832. #endif
  190833. #endif
  190834. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190835. if (png_ptr->transformations & PNG_EXPAND)
  190836. {
  190837. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190838. {
  190839. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190840. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190841. }
  190842. else
  190843. {
  190844. if (png_ptr->num_trans &&
  190845. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190846. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190847. &(png_ptr->trans_values));
  190848. else
  190849. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190850. NULL);
  190851. }
  190852. }
  190853. #endif
  190854. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190855. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190856. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190857. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190858. #endif
  190859. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190860. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190861. {
  190862. int rgb_error =
  190863. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190864. if(rgb_error)
  190865. {
  190866. png_ptr->rgb_to_gray_status=1;
  190867. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190868. PNG_RGB_TO_GRAY_WARN)
  190869. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190870. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190871. PNG_RGB_TO_GRAY_ERR)
  190872. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190873. }
  190874. }
  190875. #endif
  190876. /*
  190877. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190878. In most cases, the "simple transparency" should be done prior to doing
  190879. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190880. pixel is transparent. You would also need to make sure that the
  190881. transparency information is upgraded to RGB.
  190882. To summarize, the current flow is:
  190883. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190884. with background "in place" if transparent,
  190885. convert to RGB if necessary
  190886. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190887. convert to RGB if necessary
  190888. To support RGB backgrounds for gray images we need:
  190889. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190890. 3 or 6 bytes and composite with background
  190891. "in place" if transparent (3x compare/pixel
  190892. compared to doing composite with gray bkgrnd)
  190893. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190894. remove alpha bytes (3x float operations/pixel
  190895. compared with composite on gray background)
  190896. Greg's change will do this. The reason it wasn't done before is for
  190897. performance, as this increases the per-pixel operations. If we would check
  190898. in advance if the background was gray or RGB, and position the gray-to-RGB
  190899. transform appropriately, then it would save a lot of work/time.
  190900. */
  190901. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190902. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190903. * for performance reasons */
  190904. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190905. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190906. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190907. #endif
  190908. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190909. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190910. ((png_ptr->num_trans != 0 ) ||
  190911. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190912. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190913. &(png_ptr->trans_values), &(png_ptr->background)
  190914. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190915. , &(png_ptr->background_1),
  190916. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190917. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190918. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190919. png_ptr->gamma_shift
  190920. #endif
  190921. );
  190922. #endif
  190923. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190924. if ((png_ptr->transformations & PNG_GAMMA) &&
  190925. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190926. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190927. ((png_ptr->num_trans != 0) ||
  190928. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190929. #endif
  190930. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190931. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190932. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190933. png_ptr->gamma_shift);
  190934. #endif
  190935. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190936. if (png_ptr->transformations & PNG_16_TO_8)
  190937. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190938. #endif
  190939. #if defined(PNG_READ_DITHER_SUPPORTED)
  190940. if (png_ptr->transformations & PNG_DITHER)
  190941. {
  190942. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190943. png_ptr->palette_lookup, png_ptr->dither_index);
  190944. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190945. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190946. }
  190947. #endif
  190948. #if defined(PNG_READ_INVERT_SUPPORTED)
  190949. if (png_ptr->transformations & PNG_INVERT_MONO)
  190950. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190951. #endif
  190952. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190953. if (png_ptr->transformations & PNG_SHIFT)
  190954. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190955. &(png_ptr->shift));
  190956. #endif
  190957. #if defined(PNG_READ_PACK_SUPPORTED)
  190958. if (png_ptr->transformations & PNG_PACK)
  190959. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190960. #endif
  190961. #if defined(PNG_READ_BGR_SUPPORTED)
  190962. if (png_ptr->transformations & PNG_BGR)
  190963. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190964. #endif
  190965. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190966. if (png_ptr->transformations & PNG_PACKSWAP)
  190967. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190968. #endif
  190969. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190970. /* if gray -> RGB, do so now only if we did not do so above */
  190971. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190972. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190973. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190974. #endif
  190975. #if defined(PNG_READ_FILLER_SUPPORTED)
  190976. if (png_ptr->transformations & PNG_FILLER)
  190977. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190978. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190979. #endif
  190980. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190981. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190982. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190983. #endif
  190984. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190985. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190986. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190987. #endif
  190988. #if defined(PNG_READ_SWAP_SUPPORTED)
  190989. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190990. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190991. #endif
  190992. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190993. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190994. {
  190995. if(png_ptr->read_user_transform_fn != NULL)
  190996. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190997. (png_ptr, /* png_ptr */
  190998. &(png_ptr->row_info), /* row_info: */
  190999. /* png_uint_32 width; width of row */
  191000. /* png_uint_32 rowbytes; number of bytes in row */
  191001. /* png_byte color_type; color type of pixels */
  191002. /* png_byte bit_depth; bit depth of samples */
  191003. /* png_byte channels; number of channels (1-4) */
  191004. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191005. png_ptr->row_buf + 1); /* start of pixel data for row */
  191006. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191007. if(png_ptr->user_transform_depth)
  191008. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191009. if(png_ptr->user_transform_channels)
  191010. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191011. #endif
  191012. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191013. png_ptr->row_info.channels);
  191014. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191015. png_ptr->row_info.width);
  191016. }
  191017. #endif
  191018. }
  191019. #if defined(PNG_READ_PACK_SUPPORTED)
  191020. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191021. * without changing the actual values. Thus, if you had a row with
  191022. * a bit depth of 1, you would end up with bytes that only contained
  191023. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191024. * png_do_shift() after this.
  191025. */
  191026. void /* PRIVATE */
  191027. png_do_unpack(png_row_infop row_info, png_bytep row)
  191028. {
  191029. png_debug(1, "in png_do_unpack\n");
  191030. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191031. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191032. #else
  191033. if (row_info->bit_depth < 8)
  191034. #endif
  191035. {
  191036. png_uint_32 i;
  191037. png_uint_32 row_width=row_info->width;
  191038. switch (row_info->bit_depth)
  191039. {
  191040. case 1:
  191041. {
  191042. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191043. png_bytep dp = row + (png_size_t)row_width - 1;
  191044. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191045. for (i = 0; i < row_width; i++)
  191046. {
  191047. *dp = (png_byte)((*sp >> shift) & 0x01);
  191048. if (shift == 7)
  191049. {
  191050. shift = 0;
  191051. sp--;
  191052. }
  191053. else
  191054. shift++;
  191055. dp--;
  191056. }
  191057. break;
  191058. }
  191059. case 2:
  191060. {
  191061. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191062. png_bytep dp = row + (png_size_t)row_width - 1;
  191063. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191064. for (i = 0; i < row_width; i++)
  191065. {
  191066. *dp = (png_byte)((*sp >> shift) & 0x03);
  191067. if (shift == 6)
  191068. {
  191069. shift = 0;
  191070. sp--;
  191071. }
  191072. else
  191073. shift += 2;
  191074. dp--;
  191075. }
  191076. break;
  191077. }
  191078. case 4:
  191079. {
  191080. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191081. png_bytep dp = row + (png_size_t)row_width - 1;
  191082. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191083. for (i = 0; i < row_width; i++)
  191084. {
  191085. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191086. if (shift == 4)
  191087. {
  191088. shift = 0;
  191089. sp--;
  191090. }
  191091. else
  191092. shift = 4;
  191093. dp--;
  191094. }
  191095. break;
  191096. }
  191097. }
  191098. row_info->bit_depth = 8;
  191099. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191100. row_info->rowbytes = row_width * row_info->channels;
  191101. }
  191102. }
  191103. #endif
  191104. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191105. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191106. * pixels back to their significant bits values. Thus, if you have
  191107. * a row of bit depth 8, but only 5 are significant, this will shift
  191108. * the values back to 0 through 31.
  191109. */
  191110. void /* PRIVATE */
  191111. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191112. {
  191113. png_debug(1, "in png_do_unshift\n");
  191114. if (
  191115. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191116. row != NULL && row_info != NULL && sig_bits != NULL &&
  191117. #endif
  191118. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191119. {
  191120. int shift[4];
  191121. int channels = 0;
  191122. int c;
  191123. png_uint_16 value = 0;
  191124. png_uint_32 row_width = row_info->width;
  191125. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191126. {
  191127. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191128. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191129. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191130. }
  191131. else
  191132. {
  191133. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191134. }
  191135. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191136. {
  191137. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191138. }
  191139. for (c = 0; c < channels; c++)
  191140. {
  191141. if (shift[c] <= 0)
  191142. shift[c] = 0;
  191143. else
  191144. value = 1;
  191145. }
  191146. if (!value)
  191147. return;
  191148. switch (row_info->bit_depth)
  191149. {
  191150. case 2:
  191151. {
  191152. png_bytep bp;
  191153. png_uint_32 i;
  191154. png_uint_32 istop = row_info->rowbytes;
  191155. for (bp = row, i = 0; i < istop; i++)
  191156. {
  191157. *bp >>= 1;
  191158. *bp++ &= 0x55;
  191159. }
  191160. break;
  191161. }
  191162. case 4:
  191163. {
  191164. png_bytep bp = row;
  191165. png_uint_32 i;
  191166. png_uint_32 istop = row_info->rowbytes;
  191167. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191168. (png_byte)((int)0xf >> shift[0]));
  191169. for (i = 0; i < istop; i++)
  191170. {
  191171. *bp >>= shift[0];
  191172. *bp++ &= mask;
  191173. }
  191174. break;
  191175. }
  191176. case 8:
  191177. {
  191178. png_bytep bp = row;
  191179. png_uint_32 i;
  191180. png_uint_32 istop = row_width * channels;
  191181. for (i = 0; i < istop; i++)
  191182. {
  191183. *bp++ >>= shift[i%channels];
  191184. }
  191185. break;
  191186. }
  191187. case 16:
  191188. {
  191189. png_bytep bp = row;
  191190. png_uint_32 i;
  191191. png_uint_32 istop = channels * row_width;
  191192. for (i = 0; i < istop; i++)
  191193. {
  191194. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191195. value >>= shift[i%channels];
  191196. *bp++ = (png_byte)(value >> 8);
  191197. *bp++ = (png_byte)(value & 0xff);
  191198. }
  191199. break;
  191200. }
  191201. }
  191202. }
  191203. }
  191204. #endif
  191205. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191206. /* chop rows of bit depth 16 down to 8 */
  191207. void /* PRIVATE */
  191208. png_do_chop(png_row_infop row_info, png_bytep row)
  191209. {
  191210. png_debug(1, "in png_do_chop\n");
  191211. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191212. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191213. #else
  191214. if (row_info->bit_depth == 16)
  191215. #endif
  191216. {
  191217. png_bytep sp = row;
  191218. png_bytep dp = row;
  191219. png_uint_32 i;
  191220. png_uint_32 istop = row_info->width * row_info->channels;
  191221. for (i = 0; i<istop; i++, sp += 2, dp++)
  191222. {
  191223. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191224. /* This does a more accurate scaling of the 16-bit color
  191225. * value, rather than a simple low-byte truncation.
  191226. *
  191227. * What the ideal calculation should be:
  191228. * *dp = (((((png_uint_32)(*sp) << 8) |
  191229. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191230. *
  191231. * GRR: no, I think this is what it really should be:
  191232. * *dp = (((((png_uint_32)(*sp) << 8) |
  191233. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191234. *
  191235. * GRR: here's the exact calculation with shifts:
  191236. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191237. * *dp = (temp - (temp >> 8)) >> 8;
  191238. *
  191239. * Approximate calculation with shift/add instead of multiply/divide:
  191240. * *dp = ((((png_uint_32)(*sp) << 8) |
  191241. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191242. *
  191243. * What we actually do to avoid extra shifting and conversion:
  191244. */
  191245. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191246. #else
  191247. /* Simply discard the low order byte */
  191248. *dp = *sp;
  191249. #endif
  191250. }
  191251. row_info->bit_depth = 8;
  191252. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191253. row_info->rowbytes = row_info->width * row_info->channels;
  191254. }
  191255. }
  191256. #endif
  191257. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191258. void /* PRIVATE */
  191259. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191260. {
  191261. png_debug(1, "in png_do_read_swap_alpha\n");
  191262. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191263. if (row != NULL && row_info != NULL)
  191264. #endif
  191265. {
  191266. png_uint_32 row_width = row_info->width;
  191267. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191268. {
  191269. /* This converts from RGBA to ARGB */
  191270. if (row_info->bit_depth == 8)
  191271. {
  191272. png_bytep sp = row + row_info->rowbytes;
  191273. png_bytep dp = sp;
  191274. png_byte save;
  191275. png_uint_32 i;
  191276. for (i = 0; i < row_width; i++)
  191277. {
  191278. save = *(--sp);
  191279. *(--dp) = *(--sp);
  191280. *(--dp) = *(--sp);
  191281. *(--dp) = *(--sp);
  191282. *(--dp) = save;
  191283. }
  191284. }
  191285. /* This converts from RRGGBBAA to AARRGGBB */
  191286. else
  191287. {
  191288. png_bytep sp = row + row_info->rowbytes;
  191289. png_bytep dp = sp;
  191290. png_byte save[2];
  191291. png_uint_32 i;
  191292. for (i = 0; i < row_width; i++)
  191293. {
  191294. save[0] = *(--sp);
  191295. save[1] = *(--sp);
  191296. *(--dp) = *(--sp);
  191297. *(--dp) = *(--sp);
  191298. *(--dp) = *(--sp);
  191299. *(--dp) = *(--sp);
  191300. *(--dp) = *(--sp);
  191301. *(--dp) = *(--sp);
  191302. *(--dp) = save[0];
  191303. *(--dp) = save[1];
  191304. }
  191305. }
  191306. }
  191307. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191308. {
  191309. /* This converts from GA to AG */
  191310. if (row_info->bit_depth == 8)
  191311. {
  191312. png_bytep sp = row + row_info->rowbytes;
  191313. png_bytep dp = sp;
  191314. png_byte save;
  191315. png_uint_32 i;
  191316. for (i = 0; i < row_width; i++)
  191317. {
  191318. save = *(--sp);
  191319. *(--dp) = *(--sp);
  191320. *(--dp) = save;
  191321. }
  191322. }
  191323. /* This converts from GGAA to AAGG */
  191324. else
  191325. {
  191326. png_bytep sp = row + row_info->rowbytes;
  191327. png_bytep dp = sp;
  191328. png_byte save[2];
  191329. png_uint_32 i;
  191330. for (i = 0; i < row_width; i++)
  191331. {
  191332. save[0] = *(--sp);
  191333. save[1] = *(--sp);
  191334. *(--dp) = *(--sp);
  191335. *(--dp) = *(--sp);
  191336. *(--dp) = save[0];
  191337. *(--dp) = save[1];
  191338. }
  191339. }
  191340. }
  191341. }
  191342. }
  191343. #endif
  191344. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191345. void /* PRIVATE */
  191346. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191347. {
  191348. png_debug(1, "in png_do_read_invert_alpha\n");
  191349. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191350. if (row != NULL && row_info != NULL)
  191351. #endif
  191352. {
  191353. png_uint_32 row_width = row_info->width;
  191354. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191355. {
  191356. /* This inverts the alpha channel in RGBA */
  191357. if (row_info->bit_depth == 8)
  191358. {
  191359. png_bytep sp = row + row_info->rowbytes;
  191360. png_bytep dp = sp;
  191361. png_uint_32 i;
  191362. for (i = 0; i < row_width; i++)
  191363. {
  191364. *(--dp) = (png_byte)(255 - *(--sp));
  191365. /* This does nothing:
  191366. *(--dp) = *(--sp);
  191367. *(--dp) = *(--sp);
  191368. *(--dp) = *(--sp);
  191369. We can replace it with:
  191370. */
  191371. sp-=3;
  191372. dp=sp;
  191373. }
  191374. }
  191375. /* This inverts the alpha channel in RRGGBBAA */
  191376. else
  191377. {
  191378. png_bytep sp = row + row_info->rowbytes;
  191379. png_bytep dp = sp;
  191380. png_uint_32 i;
  191381. for (i = 0; i < row_width; i++)
  191382. {
  191383. *(--dp) = (png_byte)(255 - *(--sp));
  191384. *(--dp) = (png_byte)(255 - *(--sp));
  191385. /* This does nothing:
  191386. *(--dp) = *(--sp);
  191387. *(--dp) = *(--sp);
  191388. *(--dp) = *(--sp);
  191389. *(--dp) = *(--sp);
  191390. *(--dp) = *(--sp);
  191391. *(--dp) = *(--sp);
  191392. We can replace it with:
  191393. */
  191394. sp-=6;
  191395. dp=sp;
  191396. }
  191397. }
  191398. }
  191399. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191400. {
  191401. /* This inverts the alpha channel in GA */
  191402. if (row_info->bit_depth == 8)
  191403. {
  191404. png_bytep sp = row + row_info->rowbytes;
  191405. png_bytep dp = sp;
  191406. png_uint_32 i;
  191407. for (i = 0; i < row_width; i++)
  191408. {
  191409. *(--dp) = (png_byte)(255 - *(--sp));
  191410. *(--dp) = *(--sp);
  191411. }
  191412. }
  191413. /* This inverts the alpha channel in GGAA */
  191414. else
  191415. {
  191416. png_bytep sp = row + row_info->rowbytes;
  191417. png_bytep dp = sp;
  191418. png_uint_32 i;
  191419. for (i = 0; i < row_width; i++)
  191420. {
  191421. *(--dp) = (png_byte)(255 - *(--sp));
  191422. *(--dp) = (png_byte)(255 - *(--sp));
  191423. /*
  191424. *(--dp) = *(--sp);
  191425. *(--dp) = *(--sp);
  191426. */
  191427. sp-=2;
  191428. dp=sp;
  191429. }
  191430. }
  191431. }
  191432. }
  191433. }
  191434. #endif
  191435. #if defined(PNG_READ_FILLER_SUPPORTED)
  191436. /* Add filler channel if we have RGB color */
  191437. void /* PRIVATE */
  191438. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191439. png_uint_32 filler, png_uint_32 flags)
  191440. {
  191441. png_uint_32 i;
  191442. png_uint_32 row_width = row_info->width;
  191443. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191444. png_byte lo_filler = (png_byte)(filler & 0xff);
  191445. png_debug(1, "in png_do_read_filler\n");
  191446. if (
  191447. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191448. row != NULL && row_info != NULL &&
  191449. #endif
  191450. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191451. {
  191452. if(row_info->bit_depth == 8)
  191453. {
  191454. /* This changes the data from G to GX */
  191455. if (flags & PNG_FLAG_FILLER_AFTER)
  191456. {
  191457. png_bytep sp = row + (png_size_t)row_width;
  191458. png_bytep dp = sp + (png_size_t)row_width;
  191459. for (i = 1; i < row_width; i++)
  191460. {
  191461. *(--dp) = lo_filler;
  191462. *(--dp) = *(--sp);
  191463. }
  191464. *(--dp) = lo_filler;
  191465. row_info->channels = 2;
  191466. row_info->pixel_depth = 16;
  191467. row_info->rowbytes = row_width * 2;
  191468. }
  191469. /* This changes the data from G to XG */
  191470. else
  191471. {
  191472. png_bytep sp = row + (png_size_t)row_width;
  191473. png_bytep dp = sp + (png_size_t)row_width;
  191474. for (i = 0; i < row_width; i++)
  191475. {
  191476. *(--dp) = *(--sp);
  191477. *(--dp) = lo_filler;
  191478. }
  191479. row_info->channels = 2;
  191480. row_info->pixel_depth = 16;
  191481. row_info->rowbytes = row_width * 2;
  191482. }
  191483. }
  191484. else if(row_info->bit_depth == 16)
  191485. {
  191486. /* This changes the data from GG to GGXX */
  191487. if (flags & PNG_FLAG_FILLER_AFTER)
  191488. {
  191489. png_bytep sp = row + (png_size_t)row_width * 2;
  191490. png_bytep dp = sp + (png_size_t)row_width * 2;
  191491. for (i = 1; i < row_width; i++)
  191492. {
  191493. *(--dp) = hi_filler;
  191494. *(--dp) = lo_filler;
  191495. *(--dp) = *(--sp);
  191496. *(--dp) = *(--sp);
  191497. }
  191498. *(--dp) = hi_filler;
  191499. *(--dp) = lo_filler;
  191500. row_info->channels = 2;
  191501. row_info->pixel_depth = 32;
  191502. row_info->rowbytes = row_width * 4;
  191503. }
  191504. /* This changes the data from GG to XXGG */
  191505. else
  191506. {
  191507. png_bytep sp = row + (png_size_t)row_width * 2;
  191508. png_bytep dp = sp + (png_size_t)row_width * 2;
  191509. for (i = 0; i < row_width; i++)
  191510. {
  191511. *(--dp) = *(--sp);
  191512. *(--dp) = *(--sp);
  191513. *(--dp) = hi_filler;
  191514. *(--dp) = lo_filler;
  191515. }
  191516. row_info->channels = 2;
  191517. row_info->pixel_depth = 32;
  191518. row_info->rowbytes = row_width * 4;
  191519. }
  191520. }
  191521. } /* COLOR_TYPE == GRAY */
  191522. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191523. {
  191524. if(row_info->bit_depth == 8)
  191525. {
  191526. /* This changes the data from RGB to RGBX */
  191527. if (flags & PNG_FLAG_FILLER_AFTER)
  191528. {
  191529. png_bytep sp = row + (png_size_t)row_width * 3;
  191530. png_bytep dp = sp + (png_size_t)row_width;
  191531. for (i = 1; i < row_width; i++)
  191532. {
  191533. *(--dp) = lo_filler;
  191534. *(--dp) = *(--sp);
  191535. *(--dp) = *(--sp);
  191536. *(--dp) = *(--sp);
  191537. }
  191538. *(--dp) = lo_filler;
  191539. row_info->channels = 4;
  191540. row_info->pixel_depth = 32;
  191541. row_info->rowbytes = row_width * 4;
  191542. }
  191543. /* This changes the data from RGB to XRGB */
  191544. else
  191545. {
  191546. png_bytep sp = row + (png_size_t)row_width * 3;
  191547. png_bytep dp = sp + (png_size_t)row_width;
  191548. for (i = 0; i < row_width; i++)
  191549. {
  191550. *(--dp) = *(--sp);
  191551. *(--dp) = *(--sp);
  191552. *(--dp) = *(--sp);
  191553. *(--dp) = lo_filler;
  191554. }
  191555. row_info->channels = 4;
  191556. row_info->pixel_depth = 32;
  191557. row_info->rowbytes = row_width * 4;
  191558. }
  191559. }
  191560. else if(row_info->bit_depth == 16)
  191561. {
  191562. /* This changes the data from RRGGBB to RRGGBBXX */
  191563. if (flags & PNG_FLAG_FILLER_AFTER)
  191564. {
  191565. png_bytep sp = row + (png_size_t)row_width * 6;
  191566. png_bytep dp = sp + (png_size_t)row_width * 2;
  191567. for (i = 1; i < row_width; i++)
  191568. {
  191569. *(--dp) = hi_filler;
  191570. *(--dp) = lo_filler;
  191571. *(--dp) = *(--sp);
  191572. *(--dp) = *(--sp);
  191573. *(--dp) = *(--sp);
  191574. *(--dp) = *(--sp);
  191575. *(--dp) = *(--sp);
  191576. *(--dp) = *(--sp);
  191577. }
  191578. *(--dp) = hi_filler;
  191579. *(--dp) = lo_filler;
  191580. row_info->channels = 4;
  191581. row_info->pixel_depth = 64;
  191582. row_info->rowbytes = row_width * 8;
  191583. }
  191584. /* This changes the data from RRGGBB to XXRRGGBB */
  191585. else
  191586. {
  191587. png_bytep sp = row + (png_size_t)row_width * 6;
  191588. png_bytep dp = sp + (png_size_t)row_width * 2;
  191589. for (i = 0; i < row_width; i++)
  191590. {
  191591. *(--dp) = *(--sp);
  191592. *(--dp) = *(--sp);
  191593. *(--dp) = *(--sp);
  191594. *(--dp) = *(--sp);
  191595. *(--dp) = *(--sp);
  191596. *(--dp) = *(--sp);
  191597. *(--dp) = hi_filler;
  191598. *(--dp) = lo_filler;
  191599. }
  191600. row_info->channels = 4;
  191601. row_info->pixel_depth = 64;
  191602. row_info->rowbytes = row_width * 8;
  191603. }
  191604. }
  191605. } /* COLOR_TYPE == RGB */
  191606. }
  191607. #endif
  191608. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191609. /* expand grayscale files to RGB, with or without alpha */
  191610. void /* PRIVATE */
  191611. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191612. {
  191613. png_uint_32 i;
  191614. png_uint_32 row_width = row_info->width;
  191615. png_debug(1, "in png_do_gray_to_rgb\n");
  191616. if (row_info->bit_depth >= 8 &&
  191617. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191618. row != NULL && row_info != NULL &&
  191619. #endif
  191620. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191621. {
  191622. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191623. {
  191624. if (row_info->bit_depth == 8)
  191625. {
  191626. png_bytep sp = row + (png_size_t)row_width - 1;
  191627. png_bytep dp = sp + (png_size_t)row_width * 2;
  191628. for (i = 0; i < row_width; i++)
  191629. {
  191630. *(dp--) = *sp;
  191631. *(dp--) = *sp;
  191632. *(dp--) = *(sp--);
  191633. }
  191634. }
  191635. else
  191636. {
  191637. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191638. png_bytep dp = sp + (png_size_t)row_width * 4;
  191639. for (i = 0; i < row_width; i++)
  191640. {
  191641. *(dp--) = *sp;
  191642. *(dp--) = *(sp - 1);
  191643. *(dp--) = *sp;
  191644. *(dp--) = *(sp - 1);
  191645. *(dp--) = *(sp--);
  191646. *(dp--) = *(sp--);
  191647. }
  191648. }
  191649. }
  191650. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191651. {
  191652. if (row_info->bit_depth == 8)
  191653. {
  191654. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191655. png_bytep dp = sp + (png_size_t)row_width * 2;
  191656. for (i = 0; i < row_width; i++)
  191657. {
  191658. *(dp--) = *(sp--);
  191659. *(dp--) = *sp;
  191660. *(dp--) = *sp;
  191661. *(dp--) = *(sp--);
  191662. }
  191663. }
  191664. else
  191665. {
  191666. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191667. png_bytep dp = sp + (png_size_t)row_width * 4;
  191668. for (i = 0; i < row_width; i++)
  191669. {
  191670. *(dp--) = *(sp--);
  191671. *(dp--) = *(sp--);
  191672. *(dp--) = *sp;
  191673. *(dp--) = *(sp - 1);
  191674. *(dp--) = *sp;
  191675. *(dp--) = *(sp - 1);
  191676. *(dp--) = *(sp--);
  191677. *(dp--) = *(sp--);
  191678. }
  191679. }
  191680. }
  191681. row_info->channels += (png_byte)2;
  191682. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191683. row_info->pixel_depth = (png_byte)(row_info->channels *
  191684. row_info->bit_depth);
  191685. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191686. }
  191687. }
  191688. #endif
  191689. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191690. /* reduce RGB files to grayscale, with or without alpha
  191691. * using the equation given in Poynton's ColorFAQ at
  191692. * <http://www.inforamp.net/~poynton/>
  191693. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191694. *
  191695. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191696. *
  191697. * We approximate this with
  191698. *
  191699. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191700. *
  191701. * which can be expressed with integers as
  191702. *
  191703. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191704. *
  191705. * The calculation is to be done in a linear colorspace.
  191706. *
  191707. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191708. */
  191709. int /* PRIVATE */
  191710. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191711. {
  191712. png_uint_32 i;
  191713. png_uint_32 row_width = row_info->width;
  191714. int rgb_error = 0;
  191715. png_debug(1, "in png_do_rgb_to_gray\n");
  191716. if (
  191717. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191718. row != NULL && row_info != NULL &&
  191719. #endif
  191720. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191721. {
  191722. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191723. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191724. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191725. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191726. {
  191727. if (row_info->bit_depth == 8)
  191728. {
  191729. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191730. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191731. {
  191732. png_bytep sp = row;
  191733. png_bytep dp = row;
  191734. for (i = 0; i < row_width; i++)
  191735. {
  191736. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191737. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191738. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191739. if(red != green || red != blue)
  191740. {
  191741. rgb_error |= 1;
  191742. *(dp++) = png_ptr->gamma_from_1[
  191743. (rc*red+gc*green+bc*blue)>>15];
  191744. }
  191745. else
  191746. *(dp++) = *(sp-1);
  191747. }
  191748. }
  191749. else
  191750. #endif
  191751. {
  191752. png_bytep sp = row;
  191753. png_bytep dp = row;
  191754. for (i = 0; i < row_width; i++)
  191755. {
  191756. png_byte red = *(sp++);
  191757. png_byte green = *(sp++);
  191758. png_byte blue = *(sp++);
  191759. if(red != green || red != blue)
  191760. {
  191761. rgb_error |= 1;
  191762. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191763. }
  191764. else
  191765. *(dp++) = *(sp-1);
  191766. }
  191767. }
  191768. }
  191769. else /* RGB bit_depth == 16 */
  191770. {
  191771. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191772. if (png_ptr->gamma_16_to_1 != NULL &&
  191773. png_ptr->gamma_16_from_1 != NULL)
  191774. {
  191775. png_bytep sp = row;
  191776. png_bytep dp = row;
  191777. for (i = 0; i < row_width; i++)
  191778. {
  191779. png_uint_16 red, green, blue, w;
  191780. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191781. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191782. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191783. if(red == green && red == blue)
  191784. w = red;
  191785. else
  191786. {
  191787. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191788. png_ptr->gamma_shift][red>>8];
  191789. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191790. png_ptr->gamma_shift][green>>8];
  191791. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191792. png_ptr->gamma_shift][blue>>8];
  191793. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191794. + bc*blue_1)>>15);
  191795. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191796. png_ptr->gamma_shift][gray16 >> 8];
  191797. rgb_error |= 1;
  191798. }
  191799. *(dp++) = (png_byte)((w>>8) & 0xff);
  191800. *(dp++) = (png_byte)(w & 0xff);
  191801. }
  191802. }
  191803. else
  191804. #endif
  191805. {
  191806. png_bytep sp = row;
  191807. png_bytep dp = row;
  191808. for (i = 0; i < row_width; i++)
  191809. {
  191810. png_uint_16 red, green, blue, gray16;
  191811. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191812. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191813. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191814. if(red != green || red != blue)
  191815. rgb_error |= 1;
  191816. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191817. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191818. *(dp++) = (png_byte)(gray16 & 0xff);
  191819. }
  191820. }
  191821. }
  191822. }
  191823. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191824. {
  191825. if (row_info->bit_depth == 8)
  191826. {
  191827. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191828. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191829. {
  191830. png_bytep sp = row;
  191831. png_bytep dp = row;
  191832. for (i = 0; i < row_width; i++)
  191833. {
  191834. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191835. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191836. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191837. if(red != green || red != blue)
  191838. rgb_error |= 1;
  191839. *(dp++) = png_ptr->gamma_from_1
  191840. [(rc*red + gc*green + bc*blue)>>15];
  191841. *(dp++) = *(sp++); /* alpha */
  191842. }
  191843. }
  191844. else
  191845. #endif
  191846. {
  191847. png_bytep sp = row;
  191848. png_bytep dp = row;
  191849. for (i = 0; i < row_width; i++)
  191850. {
  191851. png_byte red = *(sp++);
  191852. png_byte green = *(sp++);
  191853. png_byte blue = *(sp++);
  191854. if(red != green || red != blue)
  191855. rgb_error |= 1;
  191856. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191857. *(dp++) = *(sp++); /* alpha */
  191858. }
  191859. }
  191860. }
  191861. else /* RGBA bit_depth == 16 */
  191862. {
  191863. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191864. if (png_ptr->gamma_16_to_1 != NULL &&
  191865. png_ptr->gamma_16_from_1 != NULL)
  191866. {
  191867. png_bytep sp = row;
  191868. png_bytep dp = row;
  191869. for (i = 0; i < row_width; i++)
  191870. {
  191871. png_uint_16 red, green, blue, w;
  191872. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191873. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191874. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191875. if(red == green && red == blue)
  191876. w = red;
  191877. else
  191878. {
  191879. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191880. png_ptr->gamma_shift][red>>8];
  191881. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191882. png_ptr->gamma_shift][green>>8];
  191883. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191884. png_ptr->gamma_shift][blue>>8];
  191885. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191886. + gc * green_1 + bc * blue_1)>>15);
  191887. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191888. png_ptr->gamma_shift][gray16 >> 8];
  191889. rgb_error |= 1;
  191890. }
  191891. *(dp++) = (png_byte)((w>>8) & 0xff);
  191892. *(dp++) = (png_byte)(w & 0xff);
  191893. *(dp++) = *(sp++); /* alpha */
  191894. *(dp++) = *(sp++);
  191895. }
  191896. }
  191897. else
  191898. #endif
  191899. {
  191900. png_bytep sp = row;
  191901. png_bytep dp = row;
  191902. for (i = 0; i < row_width; i++)
  191903. {
  191904. png_uint_16 red, green, blue, gray16;
  191905. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191906. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191907. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191908. if(red != green || red != blue)
  191909. rgb_error |= 1;
  191910. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191911. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191912. *(dp++) = (png_byte)(gray16 & 0xff);
  191913. *(dp++) = *(sp++); /* alpha */
  191914. *(dp++) = *(sp++);
  191915. }
  191916. }
  191917. }
  191918. }
  191919. row_info->channels -= (png_byte)2;
  191920. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191921. row_info->pixel_depth = (png_byte)(row_info->channels *
  191922. row_info->bit_depth);
  191923. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191924. }
  191925. return rgb_error;
  191926. }
  191927. #endif
  191928. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191929. * large of png_color. This lets grayscale images be treated as
  191930. * paletted. Most useful for gamma correction and simplification
  191931. * of code.
  191932. */
  191933. void PNGAPI
  191934. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191935. {
  191936. int num_palette;
  191937. int color_inc;
  191938. int i;
  191939. int v;
  191940. png_debug(1, "in png_do_build_grayscale_palette\n");
  191941. if (palette == NULL)
  191942. return;
  191943. switch (bit_depth)
  191944. {
  191945. case 1:
  191946. num_palette = 2;
  191947. color_inc = 0xff;
  191948. break;
  191949. case 2:
  191950. num_palette = 4;
  191951. color_inc = 0x55;
  191952. break;
  191953. case 4:
  191954. num_palette = 16;
  191955. color_inc = 0x11;
  191956. break;
  191957. case 8:
  191958. num_palette = 256;
  191959. color_inc = 1;
  191960. break;
  191961. default:
  191962. num_palette = 0;
  191963. color_inc = 0;
  191964. break;
  191965. }
  191966. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191967. {
  191968. palette[i].red = (png_byte)v;
  191969. palette[i].green = (png_byte)v;
  191970. palette[i].blue = (png_byte)v;
  191971. }
  191972. }
  191973. /* This function is currently unused. Do we really need it? */
  191974. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191975. void /* PRIVATE */
  191976. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191977. int num_palette)
  191978. {
  191979. png_debug(1, "in png_correct_palette\n");
  191980. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191981. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191982. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191983. {
  191984. png_color back, back_1;
  191985. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191986. {
  191987. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191988. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191989. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191990. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191991. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191992. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191993. }
  191994. else
  191995. {
  191996. double g;
  191997. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191998. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191999. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192000. {
  192001. back.red = png_ptr->background.red;
  192002. back.green = png_ptr->background.green;
  192003. back.blue = png_ptr->background.blue;
  192004. }
  192005. else
  192006. {
  192007. back.red =
  192008. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192009. 255.0 + 0.5);
  192010. back.green =
  192011. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192012. 255.0 + 0.5);
  192013. back.blue =
  192014. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192015. 255.0 + 0.5);
  192016. }
  192017. g = 1.0 / png_ptr->background_gamma;
  192018. back_1.red =
  192019. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192020. 255.0 + 0.5);
  192021. back_1.green =
  192022. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192023. 255.0 + 0.5);
  192024. back_1.blue =
  192025. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192026. 255.0 + 0.5);
  192027. }
  192028. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192029. {
  192030. png_uint_32 i;
  192031. for (i = 0; i < (png_uint_32)num_palette; i++)
  192032. {
  192033. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192034. {
  192035. palette[i] = back;
  192036. }
  192037. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192038. {
  192039. png_byte v, w;
  192040. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192041. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192042. palette[i].red = png_ptr->gamma_from_1[w];
  192043. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192044. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192045. palette[i].green = png_ptr->gamma_from_1[w];
  192046. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192047. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192048. palette[i].blue = png_ptr->gamma_from_1[w];
  192049. }
  192050. else
  192051. {
  192052. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192053. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192054. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192055. }
  192056. }
  192057. }
  192058. else
  192059. {
  192060. int i;
  192061. for (i = 0; i < num_palette; i++)
  192062. {
  192063. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192064. {
  192065. palette[i] = back;
  192066. }
  192067. else
  192068. {
  192069. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192070. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192071. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192072. }
  192073. }
  192074. }
  192075. }
  192076. else
  192077. #endif
  192078. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192079. if (png_ptr->transformations & PNG_GAMMA)
  192080. {
  192081. int i;
  192082. for (i = 0; i < num_palette; i++)
  192083. {
  192084. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192085. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192086. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192087. }
  192088. }
  192089. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192090. else
  192091. #endif
  192092. #endif
  192093. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192094. if (png_ptr->transformations & PNG_BACKGROUND)
  192095. {
  192096. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192097. {
  192098. png_color back;
  192099. back.red = (png_byte)png_ptr->background.red;
  192100. back.green = (png_byte)png_ptr->background.green;
  192101. back.blue = (png_byte)png_ptr->background.blue;
  192102. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192103. {
  192104. if (png_ptr->trans[i] == 0)
  192105. {
  192106. palette[i].red = back.red;
  192107. palette[i].green = back.green;
  192108. palette[i].blue = back.blue;
  192109. }
  192110. else if (png_ptr->trans[i] != 0xff)
  192111. {
  192112. png_composite(palette[i].red, png_ptr->palette[i].red,
  192113. png_ptr->trans[i], back.red);
  192114. png_composite(palette[i].green, png_ptr->palette[i].green,
  192115. png_ptr->trans[i], back.green);
  192116. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192117. png_ptr->trans[i], back.blue);
  192118. }
  192119. }
  192120. }
  192121. else /* assume grayscale palette (what else could it be?) */
  192122. {
  192123. int i;
  192124. for (i = 0; i < num_palette; i++)
  192125. {
  192126. if (i == (png_byte)png_ptr->trans_values.gray)
  192127. {
  192128. palette[i].red = (png_byte)png_ptr->background.red;
  192129. palette[i].green = (png_byte)png_ptr->background.green;
  192130. palette[i].blue = (png_byte)png_ptr->background.blue;
  192131. }
  192132. }
  192133. }
  192134. }
  192135. #endif
  192136. }
  192137. #endif
  192138. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192139. /* Replace any alpha or transparency with the supplied background color.
  192140. * "background" is already in the screen gamma, while "background_1" is
  192141. * at a gamma of 1.0. Paletted files have already been taken care of.
  192142. */
  192143. void /* PRIVATE */
  192144. png_do_background(png_row_infop row_info, png_bytep row,
  192145. png_color_16p trans_values, png_color_16p background
  192146. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192147. , png_color_16p background_1,
  192148. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192149. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192150. png_uint_16pp gamma_16_to_1, int gamma_shift
  192151. #endif
  192152. )
  192153. {
  192154. png_bytep sp, dp;
  192155. png_uint_32 i;
  192156. png_uint_32 row_width=row_info->width;
  192157. int shift;
  192158. png_debug(1, "in png_do_background\n");
  192159. if (background != NULL &&
  192160. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192161. row != NULL && row_info != NULL &&
  192162. #endif
  192163. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192164. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192165. {
  192166. switch (row_info->color_type)
  192167. {
  192168. case PNG_COLOR_TYPE_GRAY:
  192169. {
  192170. switch (row_info->bit_depth)
  192171. {
  192172. case 1:
  192173. {
  192174. sp = row;
  192175. shift = 7;
  192176. for (i = 0; i < row_width; i++)
  192177. {
  192178. if ((png_uint_16)((*sp >> shift) & 0x01)
  192179. == trans_values->gray)
  192180. {
  192181. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192182. *sp |= (png_byte)(background->gray << shift);
  192183. }
  192184. if (!shift)
  192185. {
  192186. shift = 7;
  192187. sp++;
  192188. }
  192189. else
  192190. shift--;
  192191. }
  192192. break;
  192193. }
  192194. case 2:
  192195. {
  192196. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192197. if (gamma_table != NULL)
  192198. {
  192199. sp = row;
  192200. shift = 6;
  192201. for (i = 0; i < row_width; i++)
  192202. {
  192203. if ((png_uint_16)((*sp >> shift) & 0x03)
  192204. == trans_values->gray)
  192205. {
  192206. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192207. *sp |= (png_byte)(background->gray << shift);
  192208. }
  192209. else
  192210. {
  192211. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192212. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192213. (p << 4) | (p << 6)] >> 6) & 0x03);
  192214. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192215. *sp |= (png_byte)(g << shift);
  192216. }
  192217. if (!shift)
  192218. {
  192219. shift = 6;
  192220. sp++;
  192221. }
  192222. else
  192223. shift -= 2;
  192224. }
  192225. }
  192226. else
  192227. #endif
  192228. {
  192229. sp = row;
  192230. shift = 6;
  192231. for (i = 0; i < row_width; i++)
  192232. {
  192233. if ((png_uint_16)((*sp >> shift) & 0x03)
  192234. == trans_values->gray)
  192235. {
  192236. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192237. *sp |= (png_byte)(background->gray << shift);
  192238. }
  192239. if (!shift)
  192240. {
  192241. shift = 6;
  192242. sp++;
  192243. }
  192244. else
  192245. shift -= 2;
  192246. }
  192247. }
  192248. break;
  192249. }
  192250. case 4:
  192251. {
  192252. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192253. if (gamma_table != NULL)
  192254. {
  192255. sp = row;
  192256. shift = 4;
  192257. for (i = 0; i < row_width; i++)
  192258. {
  192259. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192260. == trans_values->gray)
  192261. {
  192262. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192263. *sp |= (png_byte)(background->gray << shift);
  192264. }
  192265. else
  192266. {
  192267. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192268. png_byte g = (png_byte)((gamma_table[p |
  192269. (p << 4)] >> 4) & 0x0f);
  192270. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192271. *sp |= (png_byte)(g << shift);
  192272. }
  192273. if (!shift)
  192274. {
  192275. shift = 4;
  192276. sp++;
  192277. }
  192278. else
  192279. shift -= 4;
  192280. }
  192281. }
  192282. else
  192283. #endif
  192284. {
  192285. sp = row;
  192286. shift = 4;
  192287. for (i = 0; i < row_width; i++)
  192288. {
  192289. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192290. == trans_values->gray)
  192291. {
  192292. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192293. *sp |= (png_byte)(background->gray << shift);
  192294. }
  192295. if (!shift)
  192296. {
  192297. shift = 4;
  192298. sp++;
  192299. }
  192300. else
  192301. shift -= 4;
  192302. }
  192303. }
  192304. break;
  192305. }
  192306. case 8:
  192307. {
  192308. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192309. if (gamma_table != NULL)
  192310. {
  192311. sp = row;
  192312. for (i = 0; i < row_width; i++, sp++)
  192313. {
  192314. if (*sp == trans_values->gray)
  192315. {
  192316. *sp = (png_byte)background->gray;
  192317. }
  192318. else
  192319. {
  192320. *sp = gamma_table[*sp];
  192321. }
  192322. }
  192323. }
  192324. else
  192325. #endif
  192326. {
  192327. sp = row;
  192328. for (i = 0; i < row_width; i++, sp++)
  192329. {
  192330. if (*sp == trans_values->gray)
  192331. {
  192332. *sp = (png_byte)background->gray;
  192333. }
  192334. }
  192335. }
  192336. break;
  192337. }
  192338. case 16:
  192339. {
  192340. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192341. if (gamma_16 != NULL)
  192342. {
  192343. sp = row;
  192344. for (i = 0; i < row_width; i++, sp += 2)
  192345. {
  192346. png_uint_16 v;
  192347. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192348. if (v == trans_values->gray)
  192349. {
  192350. /* background is already in screen gamma */
  192351. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192352. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192353. }
  192354. else
  192355. {
  192356. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192357. *sp = (png_byte)((v >> 8) & 0xff);
  192358. *(sp + 1) = (png_byte)(v & 0xff);
  192359. }
  192360. }
  192361. }
  192362. else
  192363. #endif
  192364. {
  192365. sp = row;
  192366. for (i = 0; i < row_width; i++, sp += 2)
  192367. {
  192368. png_uint_16 v;
  192369. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192370. if (v == trans_values->gray)
  192371. {
  192372. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192373. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192374. }
  192375. }
  192376. }
  192377. break;
  192378. }
  192379. }
  192380. break;
  192381. }
  192382. case PNG_COLOR_TYPE_RGB:
  192383. {
  192384. if (row_info->bit_depth == 8)
  192385. {
  192386. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192387. if (gamma_table != NULL)
  192388. {
  192389. sp = row;
  192390. for (i = 0; i < row_width; i++, sp += 3)
  192391. {
  192392. if (*sp == trans_values->red &&
  192393. *(sp + 1) == trans_values->green &&
  192394. *(sp + 2) == trans_values->blue)
  192395. {
  192396. *sp = (png_byte)background->red;
  192397. *(sp + 1) = (png_byte)background->green;
  192398. *(sp + 2) = (png_byte)background->blue;
  192399. }
  192400. else
  192401. {
  192402. *sp = gamma_table[*sp];
  192403. *(sp + 1) = gamma_table[*(sp + 1)];
  192404. *(sp + 2) = gamma_table[*(sp + 2)];
  192405. }
  192406. }
  192407. }
  192408. else
  192409. #endif
  192410. {
  192411. sp = row;
  192412. for (i = 0; i < row_width; i++, sp += 3)
  192413. {
  192414. if (*sp == trans_values->red &&
  192415. *(sp + 1) == trans_values->green &&
  192416. *(sp + 2) == trans_values->blue)
  192417. {
  192418. *sp = (png_byte)background->red;
  192419. *(sp + 1) = (png_byte)background->green;
  192420. *(sp + 2) = (png_byte)background->blue;
  192421. }
  192422. }
  192423. }
  192424. }
  192425. else /* if (row_info->bit_depth == 16) */
  192426. {
  192427. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192428. if (gamma_16 != NULL)
  192429. {
  192430. sp = row;
  192431. for (i = 0; i < row_width; i++, sp += 6)
  192432. {
  192433. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192434. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192435. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192436. if (r == trans_values->red && g == trans_values->green &&
  192437. b == trans_values->blue)
  192438. {
  192439. /* background is already in screen gamma */
  192440. *sp = (png_byte)((background->red >> 8) & 0xff);
  192441. *(sp + 1) = (png_byte)(background->red & 0xff);
  192442. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192443. *(sp + 3) = (png_byte)(background->green & 0xff);
  192444. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192445. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192446. }
  192447. else
  192448. {
  192449. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192450. *sp = (png_byte)((v >> 8) & 0xff);
  192451. *(sp + 1) = (png_byte)(v & 0xff);
  192452. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192453. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192454. *(sp + 3) = (png_byte)(v & 0xff);
  192455. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192456. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192457. *(sp + 5) = (png_byte)(v & 0xff);
  192458. }
  192459. }
  192460. }
  192461. else
  192462. #endif
  192463. {
  192464. sp = row;
  192465. for (i = 0; i < row_width; i++, sp += 6)
  192466. {
  192467. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192468. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192469. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192470. if (r == trans_values->red && g == trans_values->green &&
  192471. b == trans_values->blue)
  192472. {
  192473. *sp = (png_byte)((background->red >> 8) & 0xff);
  192474. *(sp + 1) = (png_byte)(background->red & 0xff);
  192475. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192476. *(sp + 3) = (png_byte)(background->green & 0xff);
  192477. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192478. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192479. }
  192480. }
  192481. }
  192482. }
  192483. break;
  192484. }
  192485. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192486. {
  192487. if (row_info->bit_depth == 8)
  192488. {
  192489. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192490. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192491. gamma_table != NULL)
  192492. {
  192493. sp = row;
  192494. dp = row;
  192495. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192496. {
  192497. png_uint_16 a = *(sp + 1);
  192498. if (a == 0xff)
  192499. {
  192500. *dp = gamma_table[*sp];
  192501. }
  192502. else if (a == 0)
  192503. {
  192504. /* background is already in screen gamma */
  192505. *dp = (png_byte)background->gray;
  192506. }
  192507. else
  192508. {
  192509. png_byte v, w;
  192510. v = gamma_to_1[*sp];
  192511. png_composite(w, v, a, background_1->gray);
  192512. *dp = gamma_from_1[w];
  192513. }
  192514. }
  192515. }
  192516. else
  192517. #endif
  192518. {
  192519. sp = row;
  192520. dp = row;
  192521. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192522. {
  192523. png_byte a = *(sp + 1);
  192524. if (a == 0xff)
  192525. {
  192526. *dp = *sp;
  192527. }
  192528. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192529. else if (a == 0)
  192530. {
  192531. *dp = (png_byte)background->gray;
  192532. }
  192533. else
  192534. {
  192535. png_composite(*dp, *sp, a, background_1->gray);
  192536. }
  192537. #else
  192538. *dp = (png_byte)background->gray;
  192539. #endif
  192540. }
  192541. }
  192542. }
  192543. else /* if (png_ptr->bit_depth == 16) */
  192544. {
  192545. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192546. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192547. gamma_16_to_1 != NULL)
  192548. {
  192549. sp = row;
  192550. dp = row;
  192551. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192552. {
  192553. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192554. if (a == (png_uint_16)0xffff)
  192555. {
  192556. png_uint_16 v;
  192557. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192558. *dp = (png_byte)((v >> 8) & 0xff);
  192559. *(dp + 1) = (png_byte)(v & 0xff);
  192560. }
  192561. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192562. else if (a == 0)
  192563. #else
  192564. else
  192565. #endif
  192566. {
  192567. /* background is already in screen gamma */
  192568. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192569. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192570. }
  192571. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192572. else
  192573. {
  192574. png_uint_16 g, v, w;
  192575. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192576. png_composite_16(v, g, a, background_1->gray);
  192577. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192578. *dp = (png_byte)((w >> 8) & 0xff);
  192579. *(dp + 1) = (png_byte)(w & 0xff);
  192580. }
  192581. #endif
  192582. }
  192583. }
  192584. else
  192585. #endif
  192586. {
  192587. sp = row;
  192588. dp = row;
  192589. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192590. {
  192591. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192592. if (a == (png_uint_16)0xffff)
  192593. {
  192594. png_memcpy(dp, sp, 2);
  192595. }
  192596. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192597. else if (a == 0)
  192598. #else
  192599. else
  192600. #endif
  192601. {
  192602. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192603. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192604. }
  192605. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192606. else
  192607. {
  192608. png_uint_16 g, v;
  192609. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192610. png_composite_16(v, g, a, background_1->gray);
  192611. *dp = (png_byte)((v >> 8) & 0xff);
  192612. *(dp + 1) = (png_byte)(v & 0xff);
  192613. }
  192614. #endif
  192615. }
  192616. }
  192617. }
  192618. break;
  192619. }
  192620. case PNG_COLOR_TYPE_RGB_ALPHA:
  192621. {
  192622. if (row_info->bit_depth == 8)
  192623. {
  192624. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192625. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192626. gamma_table != NULL)
  192627. {
  192628. sp = row;
  192629. dp = row;
  192630. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192631. {
  192632. png_byte a = *(sp + 3);
  192633. if (a == 0xff)
  192634. {
  192635. *dp = gamma_table[*sp];
  192636. *(dp + 1) = gamma_table[*(sp + 1)];
  192637. *(dp + 2) = gamma_table[*(sp + 2)];
  192638. }
  192639. else if (a == 0)
  192640. {
  192641. /* background is already in screen gamma */
  192642. *dp = (png_byte)background->red;
  192643. *(dp + 1) = (png_byte)background->green;
  192644. *(dp + 2) = (png_byte)background->blue;
  192645. }
  192646. else
  192647. {
  192648. png_byte v, w;
  192649. v = gamma_to_1[*sp];
  192650. png_composite(w, v, a, background_1->red);
  192651. *dp = gamma_from_1[w];
  192652. v = gamma_to_1[*(sp + 1)];
  192653. png_composite(w, v, a, background_1->green);
  192654. *(dp + 1) = gamma_from_1[w];
  192655. v = gamma_to_1[*(sp + 2)];
  192656. png_composite(w, v, a, background_1->blue);
  192657. *(dp + 2) = gamma_from_1[w];
  192658. }
  192659. }
  192660. }
  192661. else
  192662. #endif
  192663. {
  192664. sp = row;
  192665. dp = row;
  192666. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192667. {
  192668. png_byte a = *(sp + 3);
  192669. if (a == 0xff)
  192670. {
  192671. *dp = *sp;
  192672. *(dp + 1) = *(sp + 1);
  192673. *(dp + 2) = *(sp + 2);
  192674. }
  192675. else if (a == 0)
  192676. {
  192677. *dp = (png_byte)background->red;
  192678. *(dp + 1) = (png_byte)background->green;
  192679. *(dp + 2) = (png_byte)background->blue;
  192680. }
  192681. else
  192682. {
  192683. png_composite(*dp, *sp, a, background->red);
  192684. png_composite(*(dp + 1), *(sp + 1), a,
  192685. background->green);
  192686. png_composite(*(dp + 2), *(sp + 2), a,
  192687. background->blue);
  192688. }
  192689. }
  192690. }
  192691. }
  192692. else /* if (row_info->bit_depth == 16) */
  192693. {
  192694. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192695. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192696. gamma_16_to_1 != NULL)
  192697. {
  192698. sp = row;
  192699. dp = row;
  192700. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192701. {
  192702. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192703. << 8) + (png_uint_16)(*(sp + 7)));
  192704. if (a == (png_uint_16)0xffff)
  192705. {
  192706. png_uint_16 v;
  192707. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192708. *dp = (png_byte)((v >> 8) & 0xff);
  192709. *(dp + 1) = (png_byte)(v & 0xff);
  192710. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192711. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192712. *(dp + 3) = (png_byte)(v & 0xff);
  192713. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192714. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192715. *(dp + 5) = (png_byte)(v & 0xff);
  192716. }
  192717. else if (a == 0)
  192718. {
  192719. /* background is already in screen gamma */
  192720. *dp = (png_byte)((background->red >> 8) & 0xff);
  192721. *(dp + 1) = (png_byte)(background->red & 0xff);
  192722. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192723. *(dp + 3) = (png_byte)(background->green & 0xff);
  192724. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192725. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192726. }
  192727. else
  192728. {
  192729. png_uint_16 v, w, x;
  192730. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192731. png_composite_16(w, v, a, background_1->red);
  192732. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192733. *dp = (png_byte)((x >> 8) & 0xff);
  192734. *(dp + 1) = (png_byte)(x & 0xff);
  192735. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192736. png_composite_16(w, v, a, background_1->green);
  192737. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192738. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192739. *(dp + 3) = (png_byte)(x & 0xff);
  192740. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192741. png_composite_16(w, v, a, background_1->blue);
  192742. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192743. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192744. *(dp + 5) = (png_byte)(x & 0xff);
  192745. }
  192746. }
  192747. }
  192748. else
  192749. #endif
  192750. {
  192751. sp = row;
  192752. dp = row;
  192753. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192754. {
  192755. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192756. << 8) + (png_uint_16)(*(sp + 7)));
  192757. if (a == (png_uint_16)0xffff)
  192758. {
  192759. png_memcpy(dp, sp, 6);
  192760. }
  192761. else if (a == 0)
  192762. {
  192763. *dp = (png_byte)((background->red >> 8) & 0xff);
  192764. *(dp + 1) = (png_byte)(background->red & 0xff);
  192765. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192766. *(dp + 3) = (png_byte)(background->green & 0xff);
  192767. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192768. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192769. }
  192770. else
  192771. {
  192772. png_uint_16 v;
  192773. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192774. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192775. + *(sp + 3));
  192776. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192777. + *(sp + 5));
  192778. png_composite_16(v, r, a, background->red);
  192779. *dp = (png_byte)((v >> 8) & 0xff);
  192780. *(dp + 1) = (png_byte)(v & 0xff);
  192781. png_composite_16(v, g, a, background->green);
  192782. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192783. *(dp + 3) = (png_byte)(v & 0xff);
  192784. png_composite_16(v, b, a, background->blue);
  192785. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192786. *(dp + 5) = (png_byte)(v & 0xff);
  192787. }
  192788. }
  192789. }
  192790. }
  192791. break;
  192792. }
  192793. }
  192794. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192795. {
  192796. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192797. row_info->channels--;
  192798. row_info->pixel_depth = (png_byte)(row_info->channels *
  192799. row_info->bit_depth);
  192800. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192801. }
  192802. }
  192803. }
  192804. #endif
  192805. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192806. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192807. * you do this after you deal with the transparency issue on grayscale
  192808. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192809. * is 16, use gamma_16_table and gamma_shift. Build these with
  192810. * build_gamma_table().
  192811. */
  192812. void /* PRIVATE */
  192813. png_do_gamma(png_row_infop row_info, png_bytep row,
  192814. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192815. int gamma_shift)
  192816. {
  192817. png_bytep sp;
  192818. png_uint_32 i;
  192819. png_uint_32 row_width=row_info->width;
  192820. png_debug(1, "in png_do_gamma\n");
  192821. if (
  192822. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192823. row != NULL && row_info != NULL &&
  192824. #endif
  192825. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192826. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192827. {
  192828. switch (row_info->color_type)
  192829. {
  192830. case PNG_COLOR_TYPE_RGB:
  192831. {
  192832. if (row_info->bit_depth == 8)
  192833. {
  192834. sp = row;
  192835. for (i = 0; i < row_width; i++)
  192836. {
  192837. *sp = gamma_table[*sp];
  192838. sp++;
  192839. *sp = gamma_table[*sp];
  192840. sp++;
  192841. *sp = gamma_table[*sp];
  192842. sp++;
  192843. }
  192844. }
  192845. else /* if (row_info->bit_depth == 16) */
  192846. {
  192847. sp = row;
  192848. for (i = 0; i < row_width; i++)
  192849. {
  192850. png_uint_16 v;
  192851. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192852. *sp = (png_byte)((v >> 8) & 0xff);
  192853. *(sp + 1) = (png_byte)(v & 0xff);
  192854. sp += 2;
  192855. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192856. *sp = (png_byte)((v >> 8) & 0xff);
  192857. *(sp + 1) = (png_byte)(v & 0xff);
  192858. sp += 2;
  192859. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192860. *sp = (png_byte)((v >> 8) & 0xff);
  192861. *(sp + 1) = (png_byte)(v & 0xff);
  192862. sp += 2;
  192863. }
  192864. }
  192865. break;
  192866. }
  192867. case PNG_COLOR_TYPE_RGB_ALPHA:
  192868. {
  192869. if (row_info->bit_depth == 8)
  192870. {
  192871. sp = row;
  192872. for (i = 0; i < row_width; i++)
  192873. {
  192874. *sp = gamma_table[*sp];
  192875. sp++;
  192876. *sp = gamma_table[*sp];
  192877. sp++;
  192878. *sp = gamma_table[*sp];
  192879. sp++;
  192880. sp++;
  192881. }
  192882. }
  192883. else /* if (row_info->bit_depth == 16) */
  192884. {
  192885. sp = row;
  192886. for (i = 0; i < row_width; i++)
  192887. {
  192888. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192889. *sp = (png_byte)((v >> 8) & 0xff);
  192890. *(sp + 1) = (png_byte)(v & 0xff);
  192891. sp += 2;
  192892. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192893. *sp = (png_byte)((v >> 8) & 0xff);
  192894. *(sp + 1) = (png_byte)(v & 0xff);
  192895. sp += 2;
  192896. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192897. *sp = (png_byte)((v >> 8) & 0xff);
  192898. *(sp + 1) = (png_byte)(v & 0xff);
  192899. sp += 4;
  192900. }
  192901. }
  192902. break;
  192903. }
  192904. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192905. {
  192906. if (row_info->bit_depth == 8)
  192907. {
  192908. sp = row;
  192909. for (i = 0; i < row_width; i++)
  192910. {
  192911. *sp = gamma_table[*sp];
  192912. sp += 2;
  192913. }
  192914. }
  192915. else /* if (row_info->bit_depth == 16) */
  192916. {
  192917. sp = row;
  192918. for (i = 0; i < row_width; i++)
  192919. {
  192920. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192921. *sp = (png_byte)((v >> 8) & 0xff);
  192922. *(sp + 1) = (png_byte)(v & 0xff);
  192923. sp += 4;
  192924. }
  192925. }
  192926. break;
  192927. }
  192928. case PNG_COLOR_TYPE_GRAY:
  192929. {
  192930. if (row_info->bit_depth == 2)
  192931. {
  192932. sp = row;
  192933. for (i = 0; i < row_width; i += 4)
  192934. {
  192935. int a = *sp & 0xc0;
  192936. int b = *sp & 0x30;
  192937. int c = *sp & 0x0c;
  192938. int d = *sp & 0x03;
  192939. *sp = (png_byte)(
  192940. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192941. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192942. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192943. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192944. sp++;
  192945. }
  192946. }
  192947. if (row_info->bit_depth == 4)
  192948. {
  192949. sp = row;
  192950. for (i = 0; i < row_width; i += 2)
  192951. {
  192952. int msb = *sp & 0xf0;
  192953. int lsb = *sp & 0x0f;
  192954. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192955. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192956. sp++;
  192957. }
  192958. }
  192959. else if (row_info->bit_depth == 8)
  192960. {
  192961. sp = row;
  192962. for (i = 0; i < row_width; i++)
  192963. {
  192964. *sp = gamma_table[*sp];
  192965. sp++;
  192966. }
  192967. }
  192968. else if (row_info->bit_depth == 16)
  192969. {
  192970. sp = row;
  192971. for (i = 0; i < row_width; i++)
  192972. {
  192973. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192974. *sp = (png_byte)((v >> 8) & 0xff);
  192975. *(sp + 1) = (png_byte)(v & 0xff);
  192976. sp += 2;
  192977. }
  192978. }
  192979. break;
  192980. }
  192981. }
  192982. }
  192983. }
  192984. #endif
  192985. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192986. /* Expands a palette row to an RGB or RGBA row depending
  192987. * upon whether you supply trans and num_trans.
  192988. */
  192989. void /* PRIVATE */
  192990. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192991. png_colorp palette, png_bytep trans, int num_trans)
  192992. {
  192993. int shift, value;
  192994. png_bytep sp, dp;
  192995. png_uint_32 i;
  192996. png_uint_32 row_width=row_info->width;
  192997. png_debug(1, "in png_do_expand_palette\n");
  192998. if (
  192999. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193000. row != NULL && row_info != NULL &&
  193001. #endif
  193002. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193003. {
  193004. if (row_info->bit_depth < 8)
  193005. {
  193006. switch (row_info->bit_depth)
  193007. {
  193008. case 1:
  193009. {
  193010. sp = row + (png_size_t)((row_width - 1) >> 3);
  193011. dp = row + (png_size_t)row_width - 1;
  193012. shift = 7 - (int)((row_width + 7) & 0x07);
  193013. for (i = 0; i < row_width; i++)
  193014. {
  193015. if ((*sp >> shift) & 0x01)
  193016. *dp = 1;
  193017. else
  193018. *dp = 0;
  193019. if (shift == 7)
  193020. {
  193021. shift = 0;
  193022. sp--;
  193023. }
  193024. else
  193025. shift++;
  193026. dp--;
  193027. }
  193028. break;
  193029. }
  193030. case 2:
  193031. {
  193032. sp = row + (png_size_t)((row_width - 1) >> 2);
  193033. dp = row + (png_size_t)row_width - 1;
  193034. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193035. for (i = 0; i < row_width; i++)
  193036. {
  193037. value = (*sp >> shift) & 0x03;
  193038. *dp = (png_byte)value;
  193039. if (shift == 6)
  193040. {
  193041. shift = 0;
  193042. sp--;
  193043. }
  193044. else
  193045. shift += 2;
  193046. dp--;
  193047. }
  193048. break;
  193049. }
  193050. case 4:
  193051. {
  193052. sp = row + (png_size_t)((row_width - 1) >> 1);
  193053. dp = row + (png_size_t)row_width - 1;
  193054. shift = (int)((row_width & 0x01) << 2);
  193055. for (i = 0; i < row_width; i++)
  193056. {
  193057. value = (*sp >> shift) & 0x0f;
  193058. *dp = (png_byte)value;
  193059. if (shift == 4)
  193060. {
  193061. shift = 0;
  193062. sp--;
  193063. }
  193064. else
  193065. shift += 4;
  193066. dp--;
  193067. }
  193068. break;
  193069. }
  193070. }
  193071. row_info->bit_depth = 8;
  193072. row_info->pixel_depth = 8;
  193073. row_info->rowbytes = row_width;
  193074. }
  193075. switch (row_info->bit_depth)
  193076. {
  193077. case 8:
  193078. {
  193079. if (trans != NULL)
  193080. {
  193081. sp = row + (png_size_t)row_width - 1;
  193082. dp = row + (png_size_t)(row_width << 2) - 1;
  193083. for (i = 0; i < row_width; i++)
  193084. {
  193085. if ((int)(*sp) >= num_trans)
  193086. *dp-- = 0xff;
  193087. else
  193088. *dp-- = trans[*sp];
  193089. *dp-- = palette[*sp].blue;
  193090. *dp-- = palette[*sp].green;
  193091. *dp-- = palette[*sp].red;
  193092. sp--;
  193093. }
  193094. row_info->bit_depth = 8;
  193095. row_info->pixel_depth = 32;
  193096. row_info->rowbytes = row_width * 4;
  193097. row_info->color_type = 6;
  193098. row_info->channels = 4;
  193099. }
  193100. else
  193101. {
  193102. sp = row + (png_size_t)row_width - 1;
  193103. dp = row + (png_size_t)(row_width * 3) - 1;
  193104. for (i = 0; i < row_width; i++)
  193105. {
  193106. *dp-- = palette[*sp].blue;
  193107. *dp-- = palette[*sp].green;
  193108. *dp-- = palette[*sp].red;
  193109. sp--;
  193110. }
  193111. row_info->bit_depth = 8;
  193112. row_info->pixel_depth = 24;
  193113. row_info->rowbytes = row_width * 3;
  193114. row_info->color_type = 2;
  193115. row_info->channels = 3;
  193116. }
  193117. break;
  193118. }
  193119. }
  193120. }
  193121. }
  193122. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193123. * expanded transparency value is supplied, an alpha channel is built.
  193124. */
  193125. void /* PRIVATE */
  193126. png_do_expand(png_row_infop row_info, png_bytep row,
  193127. png_color_16p trans_value)
  193128. {
  193129. int shift, value;
  193130. png_bytep sp, dp;
  193131. png_uint_32 i;
  193132. png_uint_32 row_width=row_info->width;
  193133. png_debug(1, "in png_do_expand\n");
  193134. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193135. if (row != NULL && row_info != NULL)
  193136. #endif
  193137. {
  193138. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193139. {
  193140. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193141. if (row_info->bit_depth < 8)
  193142. {
  193143. switch (row_info->bit_depth)
  193144. {
  193145. case 1:
  193146. {
  193147. gray = (png_uint_16)((gray&0x01)*0xff);
  193148. sp = row + (png_size_t)((row_width - 1) >> 3);
  193149. dp = row + (png_size_t)row_width - 1;
  193150. shift = 7 - (int)((row_width + 7) & 0x07);
  193151. for (i = 0; i < row_width; i++)
  193152. {
  193153. if ((*sp >> shift) & 0x01)
  193154. *dp = 0xff;
  193155. else
  193156. *dp = 0;
  193157. if (shift == 7)
  193158. {
  193159. shift = 0;
  193160. sp--;
  193161. }
  193162. else
  193163. shift++;
  193164. dp--;
  193165. }
  193166. break;
  193167. }
  193168. case 2:
  193169. {
  193170. gray = (png_uint_16)((gray&0x03)*0x55);
  193171. sp = row + (png_size_t)((row_width - 1) >> 2);
  193172. dp = row + (png_size_t)row_width - 1;
  193173. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193174. for (i = 0; i < row_width; i++)
  193175. {
  193176. value = (*sp >> shift) & 0x03;
  193177. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193178. (value << 6));
  193179. if (shift == 6)
  193180. {
  193181. shift = 0;
  193182. sp--;
  193183. }
  193184. else
  193185. shift += 2;
  193186. dp--;
  193187. }
  193188. break;
  193189. }
  193190. case 4:
  193191. {
  193192. gray = (png_uint_16)((gray&0x0f)*0x11);
  193193. sp = row + (png_size_t)((row_width - 1) >> 1);
  193194. dp = row + (png_size_t)row_width - 1;
  193195. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193196. for (i = 0; i < row_width; i++)
  193197. {
  193198. value = (*sp >> shift) & 0x0f;
  193199. *dp = (png_byte)(value | (value << 4));
  193200. if (shift == 4)
  193201. {
  193202. shift = 0;
  193203. sp--;
  193204. }
  193205. else
  193206. shift = 4;
  193207. dp--;
  193208. }
  193209. break;
  193210. }
  193211. }
  193212. row_info->bit_depth = 8;
  193213. row_info->pixel_depth = 8;
  193214. row_info->rowbytes = row_width;
  193215. }
  193216. if (trans_value != NULL)
  193217. {
  193218. if (row_info->bit_depth == 8)
  193219. {
  193220. gray = gray & 0xff;
  193221. sp = row + (png_size_t)row_width - 1;
  193222. dp = row + (png_size_t)(row_width << 1) - 1;
  193223. for (i = 0; i < row_width; i++)
  193224. {
  193225. if (*sp == gray)
  193226. *dp-- = 0;
  193227. else
  193228. *dp-- = 0xff;
  193229. *dp-- = *sp--;
  193230. }
  193231. }
  193232. else if (row_info->bit_depth == 16)
  193233. {
  193234. png_byte gray_high = (gray >> 8) & 0xff;
  193235. png_byte gray_low = gray & 0xff;
  193236. sp = row + row_info->rowbytes - 1;
  193237. dp = row + (row_info->rowbytes << 1) - 1;
  193238. for (i = 0; i < row_width; i++)
  193239. {
  193240. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193241. {
  193242. *dp-- = 0;
  193243. *dp-- = 0;
  193244. }
  193245. else
  193246. {
  193247. *dp-- = 0xff;
  193248. *dp-- = 0xff;
  193249. }
  193250. *dp-- = *sp--;
  193251. *dp-- = *sp--;
  193252. }
  193253. }
  193254. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193255. row_info->channels = 2;
  193256. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193257. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193258. row_width);
  193259. }
  193260. }
  193261. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193262. {
  193263. if (row_info->bit_depth == 8)
  193264. {
  193265. png_byte red = trans_value->red & 0xff;
  193266. png_byte green = trans_value->green & 0xff;
  193267. png_byte blue = trans_value->blue & 0xff;
  193268. sp = row + (png_size_t)row_info->rowbytes - 1;
  193269. dp = row + (png_size_t)(row_width << 2) - 1;
  193270. for (i = 0; i < row_width; i++)
  193271. {
  193272. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193273. *dp-- = 0;
  193274. else
  193275. *dp-- = 0xff;
  193276. *dp-- = *sp--;
  193277. *dp-- = *sp--;
  193278. *dp-- = *sp--;
  193279. }
  193280. }
  193281. else if (row_info->bit_depth == 16)
  193282. {
  193283. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193284. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193285. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193286. png_byte red_low = trans_value->red & 0xff;
  193287. png_byte green_low = trans_value->green & 0xff;
  193288. png_byte blue_low = trans_value->blue & 0xff;
  193289. sp = row + row_info->rowbytes - 1;
  193290. dp = row + (png_size_t)(row_width << 3) - 1;
  193291. for (i = 0; i < row_width; i++)
  193292. {
  193293. if (*(sp - 5) == red_high &&
  193294. *(sp - 4) == red_low &&
  193295. *(sp - 3) == green_high &&
  193296. *(sp - 2) == green_low &&
  193297. *(sp - 1) == blue_high &&
  193298. *(sp ) == blue_low)
  193299. {
  193300. *dp-- = 0;
  193301. *dp-- = 0;
  193302. }
  193303. else
  193304. {
  193305. *dp-- = 0xff;
  193306. *dp-- = 0xff;
  193307. }
  193308. *dp-- = *sp--;
  193309. *dp-- = *sp--;
  193310. *dp-- = *sp--;
  193311. *dp-- = *sp--;
  193312. *dp-- = *sp--;
  193313. *dp-- = *sp--;
  193314. }
  193315. }
  193316. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193317. row_info->channels = 4;
  193318. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193319. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193320. }
  193321. }
  193322. }
  193323. #endif
  193324. #if defined(PNG_READ_DITHER_SUPPORTED)
  193325. void /* PRIVATE */
  193326. png_do_dither(png_row_infop row_info, png_bytep row,
  193327. png_bytep palette_lookup, png_bytep dither_lookup)
  193328. {
  193329. png_bytep sp, dp;
  193330. png_uint_32 i;
  193331. png_uint_32 row_width=row_info->width;
  193332. png_debug(1, "in png_do_dither\n");
  193333. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193334. if (row != NULL && row_info != NULL)
  193335. #endif
  193336. {
  193337. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193338. palette_lookup && row_info->bit_depth == 8)
  193339. {
  193340. int r, g, b, p;
  193341. sp = row;
  193342. dp = row;
  193343. for (i = 0; i < row_width; i++)
  193344. {
  193345. r = *sp++;
  193346. g = *sp++;
  193347. b = *sp++;
  193348. /* this looks real messy, but the compiler will reduce
  193349. it down to a reasonable formula. For example, with
  193350. 5 bits per color, we get:
  193351. p = (((r >> 3) & 0x1f) << 10) |
  193352. (((g >> 3) & 0x1f) << 5) |
  193353. ((b >> 3) & 0x1f);
  193354. */
  193355. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193356. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193357. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193358. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193359. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193360. (PNG_DITHER_BLUE_BITS)) |
  193361. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193362. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193363. *dp++ = palette_lookup[p];
  193364. }
  193365. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193366. row_info->channels = 1;
  193367. row_info->pixel_depth = row_info->bit_depth;
  193368. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193369. }
  193370. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193371. palette_lookup != NULL && row_info->bit_depth == 8)
  193372. {
  193373. int r, g, b, p;
  193374. sp = row;
  193375. dp = row;
  193376. for (i = 0; i < row_width; i++)
  193377. {
  193378. r = *sp++;
  193379. g = *sp++;
  193380. b = *sp++;
  193381. sp++;
  193382. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193383. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193384. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193385. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193386. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193387. (PNG_DITHER_BLUE_BITS)) |
  193388. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193389. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193390. *dp++ = palette_lookup[p];
  193391. }
  193392. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193393. row_info->channels = 1;
  193394. row_info->pixel_depth = row_info->bit_depth;
  193395. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193396. }
  193397. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193398. dither_lookup && row_info->bit_depth == 8)
  193399. {
  193400. sp = row;
  193401. for (i = 0; i < row_width; i++, sp++)
  193402. {
  193403. *sp = dither_lookup[*sp];
  193404. }
  193405. }
  193406. }
  193407. }
  193408. #endif
  193409. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193410. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193411. static PNG_CONST int png_gamma_shift[] =
  193412. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193413. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193414. * tables, we don't make a full table if we are reducing to 8-bit in
  193415. * the future. Note also how the gamma_16 tables are segmented so that
  193416. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193417. */
  193418. void /* PRIVATE */
  193419. png_build_gamma_table(png_structp png_ptr)
  193420. {
  193421. png_debug(1, "in png_build_gamma_table\n");
  193422. if (png_ptr->bit_depth <= 8)
  193423. {
  193424. int i;
  193425. double g;
  193426. if (png_ptr->screen_gamma > .000001)
  193427. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193428. else
  193429. g = 1.0;
  193430. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193431. (png_uint_32)256);
  193432. for (i = 0; i < 256; i++)
  193433. {
  193434. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193435. g) * 255.0 + .5);
  193436. }
  193437. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193438. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193439. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193440. {
  193441. g = 1.0 / (png_ptr->gamma);
  193442. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193443. (png_uint_32)256);
  193444. for (i = 0; i < 256; i++)
  193445. {
  193446. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193447. g) * 255.0 + .5);
  193448. }
  193449. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193450. (png_uint_32)256);
  193451. if(png_ptr->screen_gamma > 0.000001)
  193452. g = 1.0 / png_ptr->screen_gamma;
  193453. else
  193454. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193455. for (i = 0; i < 256; i++)
  193456. {
  193457. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193458. g) * 255.0 + .5);
  193459. }
  193460. }
  193461. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193462. }
  193463. else
  193464. {
  193465. double g;
  193466. int i, j, shift, num;
  193467. int sig_bit;
  193468. png_uint_32 ig;
  193469. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193470. {
  193471. sig_bit = (int)png_ptr->sig_bit.red;
  193472. if ((int)png_ptr->sig_bit.green > sig_bit)
  193473. sig_bit = png_ptr->sig_bit.green;
  193474. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193475. sig_bit = png_ptr->sig_bit.blue;
  193476. }
  193477. else
  193478. {
  193479. sig_bit = (int)png_ptr->sig_bit.gray;
  193480. }
  193481. if (sig_bit > 0)
  193482. shift = 16 - sig_bit;
  193483. else
  193484. shift = 0;
  193485. if (png_ptr->transformations & PNG_16_TO_8)
  193486. {
  193487. if (shift < (16 - PNG_MAX_GAMMA_8))
  193488. shift = (16 - PNG_MAX_GAMMA_8);
  193489. }
  193490. if (shift > 8)
  193491. shift = 8;
  193492. if (shift < 0)
  193493. shift = 0;
  193494. png_ptr->gamma_shift = (png_byte)shift;
  193495. num = (1 << (8 - shift));
  193496. if (png_ptr->screen_gamma > .000001)
  193497. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193498. else
  193499. g = 1.0;
  193500. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193501. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193502. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193503. {
  193504. double fin, fout;
  193505. png_uint_32 last, max;
  193506. for (i = 0; i < num; i++)
  193507. {
  193508. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193509. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193510. }
  193511. g = 1.0 / g;
  193512. last = 0;
  193513. for (i = 0; i < 256; i++)
  193514. {
  193515. fout = ((double)i + 0.5) / 256.0;
  193516. fin = pow(fout, g);
  193517. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193518. while (last <= max)
  193519. {
  193520. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193521. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193522. (png_uint_16)i | ((png_uint_16)i << 8));
  193523. last++;
  193524. }
  193525. }
  193526. while (last < ((png_uint_32)num << 8))
  193527. {
  193528. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193529. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193530. last++;
  193531. }
  193532. }
  193533. else
  193534. {
  193535. for (i = 0; i < num; i++)
  193536. {
  193537. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193538. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193539. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193540. for (j = 0; j < 256; j++)
  193541. {
  193542. png_ptr->gamma_16_table[i][j] =
  193543. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193544. 65535.0, g) * 65535.0 + .5);
  193545. }
  193546. }
  193547. }
  193548. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193549. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193550. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193551. {
  193552. g = 1.0 / (png_ptr->gamma);
  193553. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193554. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193555. for (i = 0; i < num; i++)
  193556. {
  193557. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193558. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193559. ig = (((png_uint_32)i *
  193560. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193561. for (j = 0; j < 256; j++)
  193562. {
  193563. png_ptr->gamma_16_to_1[i][j] =
  193564. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193565. 65535.0, g) * 65535.0 + .5);
  193566. }
  193567. }
  193568. if(png_ptr->screen_gamma > 0.000001)
  193569. g = 1.0 / png_ptr->screen_gamma;
  193570. else
  193571. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193572. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193573. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193574. for (i = 0; i < num; i++)
  193575. {
  193576. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193577. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193578. ig = (((png_uint_32)i *
  193579. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193580. for (j = 0; j < 256; j++)
  193581. {
  193582. png_ptr->gamma_16_from_1[i][j] =
  193583. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193584. 65535.0, g) * 65535.0 + .5);
  193585. }
  193586. }
  193587. }
  193588. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193589. }
  193590. }
  193591. #endif
  193592. /* To do: install integer version of png_build_gamma_table here */
  193593. #endif
  193594. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193595. /* undoes intrapixel differencing */
  193596. void /* PRIVATE */
  193597. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193598. {
  193599. png_debug(1, "in png_do_read_intrapixel\n");
  193600. if (
  193601. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193602. row != NULL && row_info != NULL &&
  193603. #endif
  193604. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193605. {
  193606. int bytes_per_pixel;
  193607. png_uint_32 row_width = row_info->width;
  193608. if (row_info->bit_depth == 8)
  193609. {
  193610. png_bytep rp;
  193611. png_uint_32 i;
  193612. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193613. bytes_per_pixel = 3;
  193614. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193615. bytes_per_pixel = 4;
  193616. else
  193617. return;
  193618. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193619. {
  193620. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193621. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193622. }
  193623. }
  193624. else if (row_info->bit_depth == 16)
  193625. {
  193626. png_bytep rp;
  193627. png_uint_32 i;
  193628. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193629. bytes_per_pixel = 6;
  193630. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193631. bytes_per_pixel = 8;
  193632. else
  193633. return;
  193634. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193635. {
  193636. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193637. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193638. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193639. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193640. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193641. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193642. *(rp+1) = (png_byte)(red & 0xff);
  193643. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193644. *(rp+5) = (png_byte)(blue & 0xff);
  193645. }
  193646. }
  193647. }
  193648. }
  193649. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193650. #endif /* PNG_READ_SUPPORTED */
  193651. /*** End of inlined file: pngrtran.c ***/
  193652. /*** Start of inlined file: pngrutil.c ***/
  193653. /* pngrutil.c - utilities to read a PNG file
  193654. *
  193655. * Last changed in libpng 1.2.21 [October 4, 2007]
  193656. * For conditions of distribution and use, see copyright notice in png.h
  193657. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193658. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193659. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193660. *
  193661. * This file contains routines that are only called from within
  193662. * libpng itself during the course of reading an image.
  193663. */
  193664. #define PNG_INTERNAL
  193665. #if defined(PNG_READ_SUPPORTED)
  193666. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193667. # define WIN32_WCE_OLD
  193668. #endif
  193669. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193670. # if defined(WIN32_WCE_OLD)
  193671. /* strtod() function is not supported on WindowsCE */
  193672. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193673. {
  193674. double result = 0;
  193675. int len;
  193676. wchar_t *str, *end;
  193677. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193678. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193679. if ( NULL != str )
  193680. {
  193681. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193682. result = wcstod(str, &end);
  193683. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193684. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193685. png_free(png_ptr, str);
  193686. }
  193687. return result;
  193688. }
  193689. # else
  193690. # define png_strtod(p,a,b) strtod(a,b)
  193691. # endif
  193692. #endif
  193693. png_uint_32 PNGAPI
  193694. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193695. {
  193696. png_uint_32 i = png_get_uint_32(buf);
  193697. if (i > PNG_UINT_31_MAX)
  193698. png_error(png_ptr, "PNG unsigned integer out of range.");
  193699. return (i);
  193700. }
  193701. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193702. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193703. png_uint_32 PNGAPI
  193704. png_get_uint_32(png_bytep buf)
  193705. {
  193706. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193707. ((png_uint_32)(*(buf + 1)) << 16) +
  193708. ((png_uint_32)(*(buf + 2)) << 8) +
  193709. (png_uint_32)(*(buf + 3));
  193710. return (i);
  193711. }
  193712. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193713. * data is stored in the PNG file in two's complement format, and it is
  193714. * assumed that the machine format for signed integers is the same. */
  193715. png_int_32 PNGAPI
  193716. png_get_int_32(png_bytep buf)
  193717. {
  193718. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193719. ((png_int_32)(*(buf + 1)) << 16) +
  193720. ((png_int_32)(*(buf + 2)) << 8) +
  193721. (png_int_32)(*(buf + 3));
  193722. return (i);
  193723. }
  193724. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193725. png_uint_16 PNGAPI
  193726. png_get_uint_16(png_bytep buf)
  193727. {
  193728. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193729. (png_uint_16)(*(buf + 1)));
  193730. return (i);
  193731. }
  193732. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193733. /* Read data, and (optionally) run it through the CRC. */
  193734. void /* PRIVATE */
  193735. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193736. {
  193737. if(png_ptr == NULL) return;
  193738. png_read_data(png_ptr, buf, length);
  193739. png_calculate_crc(png_ptr, buf, length);
  193740. }
  193741. /* Optionally skip data and then check the CRC. Depending on whether we
  193742. are reading a ancillary or critical chunk, and how the program has set
  193743. things up, we may calculate the CRC on the data and print a message.
  193744. Returns '1' if there was a CRC error, '0' otherwise. */
  193745. int /* PRIVATE */
  193746. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193747. {
  193748. png_size_t i;
  193749. png_size_t istop = png_ptr->zbuf_size;
  193750. for (i = (png_size_t)skip; i > istop; i -= istop)
  193751. {
  193752. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193753. }
  193754. if (i)
  193755. {
  193756. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193757. }
  193758. if (png_crc_error(png_ptr))
  193759. {
  193760. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193761. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193762. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193763. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193764. {
  193765. png_chunk_warning(png_ptr, "CRC error");
  193766. }
  193767. else
  193768. {
  193769. png_chunk_error(png_ptr, "CRC error");
  193770. }
  193771. return (1);
  193772. }
  193773. return (0);
  193774. }
  193775. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193776. the data it has read thus far. */
  193777. int /* PRIVATE */
  193778. png_crc_error(png_structp png_ptr)
  193779. {
  193780. png_byte crc_bytes[4];
  193781. png_uint_32 crc;
  193782. int need_crc = 1;
  193783. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193784. {
  193785. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193786. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193787. need_crc = 0;
  193788. }
  193789. else /* critical */
  193790. {
  193791. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193792. need_crc = 0;
  193793. }
  193794. png_read_data(png_ptr, crc_bytes, 4);
  193795. if (need_crc)
  193796. {
  193797. crc = png_get_uint_32(crc_bytes);
  193798. return ((int)(crc != png_ptr->crc));
  193799. }
  193800. else
  193801. return (0);
  193802. }
  193803. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193804. defined(PNG_READ_iCCP_SUPPORTED)
  193805. /*
  193806. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193807. * points at an allocated area holding the contents of a chunk with a
  193808. * trailing compressed part. What we get back is an allocated area
  193809. * holding the original prefix part and an uncompressed version of the
  193810. * trailing part (the malloc area passed in is freed).
  193811. */
  193812. png_charp /* PRIVATE */
  193813. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193814. png_charp chunkdata, png_size_t chunklength,
  193815. png_size_t prefix_size, png_size_t *newlength)
  193816. {
  193817. static PNG_CONST char msg[] = "Error decoding compressed text";
  193818. png_charp text;
  193819. png_size_t text_size;
  193820. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193821. {
  193822. int ret = Z_OK;
  193823. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193824. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193825. png_ptr->zstream.next_out = png_ptr->zbuf;
  193826. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193827. text_size = 0;
  193828. text = NULL;
  193829. while (png_ptr->zstream.avail_in)
  193830. {
  193831. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193832. if (ret != Z_OK && ret != Z_STREAM_END)
  193833. {
  193834. if (png_ptr->zstream.msg != NULL)
  193835. png_warning(png_ptr, png_ptr->zstream.msg);
  193836. else
  193837. png_warning(png_ptr, msg);
  193838. inflateReset(&png_ptr->zstream);
  193839. png_ptr->zstream.avail_in = 0;
  193840. if (text == NULL)
  193841. {
  193842. text_size = prefix_size + png_sizeof(msg) + 1;
  193843. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193844. if (text == NULL)
  193845. {
  193846. png_free(png_ptr,chunkdata);
  193847. png_error(png_ptr,"Not enough memory to decompress chunk");
  193848. }
  193849. png_memcpy(text, chunkdata, prefix_size);
  193850. }
  193851. text[text_size - 1] = 0x00;
  193852. /* Copy what we can of the error message into the text chunk */
  193853. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193854. text_size = png_sizeof(msg) > text_size ? text_size :
  193855. png_sizeof(msg);
  193856. png_memcpy(text + prefix_size, msg, text_size + 1);
  193857. break;
  193858. }
  193859. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193860. {
  193861. if (text == NULL)
  193862. {
  193863. text_size = prefix_size +
  193864. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193865. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193866. if (text == NULL)
  193867. {
  193868. png_free(png_ptr,chunkdata);
  193869. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193870. }
  193871. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193872. text_size - prefix_size);
  193873. png_memcpy(text, chunkdata, prefix_size);
  193874. *(text + text_size) = 0x00;
  193875. }
  193876. else
  193877. {
  193878. png_charp tmp;
  193879. tmp = text;
  193880. text = (png_charp)png_malloc_warn(png_ptr,
  193881. (png_uint_32)(text_size +
  193882. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193883. if (text == NULL)
  193884. {
  193885. png_free(png_ptr, tmp);
  193886. png_free(png_ptr, chunkdata);
  193887. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193888. }
  193889. png_memcpy(text, tmp, text_size);
  193890. png_free(png_ptr, tmp);
  193891. png_memcpy(text + text_size, png_ptr->zbuf,
  193892. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193893. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193894. *(text + text_size) = 0x00;
  193895. }
  193896. if (ret == Z_STREAM_END)
  193897. break;
  193898. else
  193899. {
  193900. png_ptr->zstream.next_out = png_ptr->zbuf;
  193901. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193902. }
  193903. }
  193904. }
  193905. if (ret != Z_STREAM_END)
  193906. {
  193907. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193908. char umsg[52];
  193909. if (ret == Z_BUF_ERROR)
  193910. png_snprintf(umsg, 52,
  193911. "Buffer error in compressed datastream in %s chunk",
  193912. png_ptr->chunk_name);
  193913. else if (ret == Z_DATA_ERROR)
  193914. png_snprintf(umsg, 52,
  193915. "Data error in compressed datastream in %s chunk",
  193916. png_ptr->chunk_name);
  193917. else
  193918. png_snprintf(umsg, 52,
  193919. "Incomplete compressed datastream in %s chunk",
  193920. png_ptr->chunk_name);
  193921. png_warning(png_ptr, umsg);
  193922. #else
  193923. png_warning(png_ptr,
  193924. "Incomplete compressed datastream in chunk other than IDAT");
  193925. #endif
  193926. text_size=prefix_size;
  193927. if (text == NULL)
  193928. {
  193929. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193930. if (text == NULL)
  193931. {
  193932. png_free(png_ptr, chunkdata);
  193933. png_error(png_ptr,"Not enough memory for text.");
  193934. }
  193935. png_memcpy(text, chunkdata, prefix_size);
  193936. }
  193937. *(text + text_size) = 0x00;
  193938. }
  193939. inflateReset(&png_ptr->zstream);
  193940. png_ptr->zstream.avail_in = 0;
  193941. png_free(png_ptr, chunkdata);
  193942. chunkdata = text;
  193943. *newlength=text_size;
  193944. }
  193945. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193946. {
  193947. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193948. char umsg[50];
  193949. png_snprintf(umsg, 50,
  193950. "Unknown zTXt compression type %d", comp_type);
  193951. png_warning(png_ptr, umsg);
  193952. #else
  193953. png_warning(png_ptr, "Unknown zTXt compression type");
  193954. #endif
  193955. *(chunkdata + prefix_size) = 0x00;
  193956. *newlength=prefix_size;
  193957. }
  193958. return chunkdata;
  193959. }
  193960. #endif
  193961. /* read and check the IDHR chunk */
  193962. void /* PRIVATE */
  193963. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193964. {
  193965. png_byte buf[13];
  193966. png_uint_32 width, height;
  193967. int bit_depth, color_type, compression_type, filter_type;
  193968. int interlace_type;
  193969. png_debug(1, "in png_handle_IHDR\n");
  193970. if (png_ptr->mode & PNG_HAVE_IHDR)
  193971. png_error(png_ptr, "Out of place IHDR");
  193972. /* check the length */
  193973. if (length != 13)
  193974. png_error(png_ptr, "Invalid IHDR chunk");
  193975. png_ptr->mode |= PNG_HAVE_IHDR;
  193976. png_crc_read(png_ptr, buf, 13);
  193977. png_crc_finish(png_ptr, 0);
  193978. width = png_get_uint_31(png_ptr, buf);
  193979. height = png_get_uint_31(png_ptr, buf + 4);
  193980. bit_depth = buf[8];
  193981. color_type = buf[9];
  193982. compression_type = buf[10];
  193983. filter_type = buf[11];
  193984. interlace_type = buf[12];
  193985. /* set internal variables */
  193986. png_ptr->width = width;
  193987. png_ptr->height = height;
  193988. png_ptr->bit_depth = (png_byte)bit_depth;
  193989. png_ptr->interlaced = (png_byte)interlace_type;
  193990. png_ptr->color_type = (png_byte)color_type;
  193991. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193992. png_ptr->filter_type = (png_byte)filter_type;
  193993. #endif
  193994. png_ptr->compression_type = (png_byte)compression_type;
  193995. /* find number of channels */
  193996. switch (png_ptr->color_type)
  193997. {
  193998. case PNG_COLOR_TYPE_GRAY:
  193999. case PNG_COLOR_TYPE_PALETTE:
  194000. png_ptr->channels = 1;
  194001. break;
  194002. case PNG_COLOR_TYPE_RGB:
  194003. png_ptr->channels = 3;
  194004. break;
  194005. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194006. png_ptr->channels = 2;
  194007. break;
  194008. case PNG_COLOR_TYPE_RGB_ALPHA:
  194009. png_ptr->channels = 4;
  194010. break;
  194011. }
  194012. /* set up other useful info */
  194013. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194014. png_ptr->channels);
  194015. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194016. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194017. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194018. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194019. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194020. color_type, interlace_type, compression_type, filter_type);
  194021. }
  194022. /* read and check the palette */
  194023. void /* PRIVATE */
  194024. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194025. {
  194026. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194027. int num, i;
  194028. #ifndef PNG_NO_POINTER_INDEXING
  194029. png_colorp pal_ptr;
  194030. #endif
  194031. png_debug(1, "in png_handle_PLTE\n");
  194032. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194033. png_error(png_ptr, "Missing IHDR before PLTE");
  194034. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194035. {
  194036. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194037. png_crc_finish(png_ptr, length);
  194038. return;
  194039. }
  194040. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194041. png_error(png_ptr, "Duplicate PLTE chunk");
  194042. png_ptr->mode |= PNG_HAVE_PLTE;
  194043. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194044. {
  194045. png_warning(png_ptr,
  194046. "Ignoring PLTE chunk in grayscale PNG");
  194047. png_crc_finish(png_ptr, length);
  194048. return;
  194049. }
  194050. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194051. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194052. {
  194053. png_crc_finish(png_ptr, length);
  194054. return;
  194055. }
  194056. #endif
  194057. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194058. {
  194059. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194060. {
  194061. png_warning(png_ptr, "Invalid palette chunk");
  194062. png_crc_finish(png_ptr, length);
  194063. return;
  194064. }
  194065. else
  194066. {
  194067. png_error(png_ptr, "Invalid palette chunk");
  194068. }
  194069. }
  194070. num = (int)length / 3;
  194071. #ifndef PNG_NO_POINTER_INDEXING
  194072. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194073. {
  194074. png_byte buf[3];
  194075. png_crc_read(png_ptr, buf, 3);
  194076. pal_ptr->red = buf[0];
  194077. pal_ptr->green = buf[1];
  194078. pal_ptr->blue = buf[2];
  194079. }
  194080. #else
  194081. for (i = 0; i < num; i++)
  194082. {
  194083. png_byte buf[3];
  194084. png_crc_read(png_ptr, buf, 3);
  194085. /* don't depend upon png_color being any order */
  194086. palette[i].red = buf[0];
  194087. palette[i].green = buf[1];
  194088. palette[i].blue = buf[2];
  194089. }
  194090. #endif
  194091. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194092. whatever the normal CRC configuration tells us. However, if we
  194093. have an RGB image, the PLTE can be considered ancillary, so
  194094. we will act as though it is. */
  194095. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194096. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194097. #endif
  194098. {
  194099. png_crc_finish(png_ptr, 0);
  194100. }
  194101. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194102. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194103. {
  194104. /* If we don't want to use the data from an ancillary chunk,
  194105. we have two options: an error abort, or a warning and we
  194106. ignore the data in this chunk (which should be OK, since
  194107. it's considered ancillary for a RGB or RGBA image). */
  194108. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194109. {
  194110. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194111. {
  194112. png_chunk_error(png_ptr, "CRC error");
  194113. }
  194114. else
  194115. {
  194116. png_chunk_warning(png_ptr, "CRC error");
  194117. return;
  194118. }
  194119. }
  194120. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194121. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194122. {
  194123. png_chunk_warning(png_ptr, "CRC error");
  194124. }
  194125. }
  194126. #endif
  194127. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194128. #if defined(PNG_READ_tRNS_SUPPORTED)
  194129. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194130. {
  194131. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194132. {
  194133. if (png_ptr->num_trans > (png_uint_16)num)
  194134. {
  194135. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194136. png_ptr->num_trans = (png_uint_16)num;
  194137. }
  194138. if (info_ptr->num_trans > (png_uint_16)num)
  194139. {
  194140. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194141. info_ptr->num_trans = (png_uint_16)num;
  194142. }
  194143. }
  194144. }
  194145. #endif
  194146. }
  194147. void /* PRIVATE */
  194148. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194149. {
  194150. png_debug(1, "in png_handle_IEND\n");
  194151. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194152. {
  194153. png_error(png_ptr, "No image in file");
  194154. }
  194155. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194156. if (length != 0)
  194157. {
  194158. png_warning(png_ptr, "Incorrect IEND chunk length");
  194159. }
  194160. png_crc_finish(png_ptr, length);
  194161. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194162. }
  194163. #if defined(PNG_READ_gAMA_SUPPORTED)
  194164. void /* PRIVATE */
  194165. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194166. {
  194167. png_fixed_point igamma;
  194168. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194169. float file_gamma;
  194170. #endif
  194171. png_byte buf[4];
  194172. png_debug(1, "in png_handle_gAMA\n");
  194173. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194174. png_error(png_ptr, "Missing IHDR before gAMA");
  194175. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194176. {
  194177. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194178. png_crc_finish(png_ptr, length);
  194179. return;
  194180. }
  194181. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194182. /* Should be an error, but we can cope with it */
  194183. png_warning(png_ptr, "Out of place gAMA chunk");
  194184. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194185. #if defined(PNG_READ_sRGB_SUPPORTED)
  194186. && !(info_ptr->valid & PNG_INFO_sRGB)
  194187. #endif
  194188. )
  194189. {
  194190. png_warning(png_ptr, "Duplicate gAMA chunk");
  194191. png_crc_finish(png_ptr, length);
  194192. return;
  194193. }
  194194. if (length != 4)
  194195. {
  194196. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194197. png_crc_finish(png_ptr, length);
  194198. return;
  194199. }
  194200. png_crc_read(png_ptr, buf, 4);
  194201. if (png_crc_finish(png_ptr, 0))
  194202. return;
  194203. igamma = (png_fixed_point)png_get_uint_32(buf);
  194204. /* check for zero gamma */
  194205. if (igamma == 0)
  194206. {
  194207. png_warning(png_ptr,
  194208. "Ignoring gAMA chunk with gamma=0");
  194209. return;
  194210. }
  194211. #if defined(PNG_READ_sRGB_SUPPORTED)
  194212. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194213. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194214. {
  194215. png_warning(png_ptr,
  194216. "Ignoring incorrect gAMA value when sRGB is also present");
  194217. #ifndef PNG_NO_CONSOLE_IO
  194218. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194219. #endif
  194220. return;
  194221. }
  194222. #endif /* PNG_READ_sRGB_SUPPORTED */
  194223. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194224. file_gamma = (float)igamma / (float)100000.0;
  194225. # ifdef PNG_READ_GAMMA_SUPPORTED
  194226. png_ptr->gamma = file_gamma;
  194227. # endif
  194228. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194229. #endif
  194230. #ifdef PNG_FIXED_POINT_SUPPORTED
  194231. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194232. #endif
  194233. }
  194234. #endif
  194235. #if defined(PNG_READ_sBIT_SUPPORTED)
  194236. void /* PRIVATE */
  194237. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194238. {
  194239. png_size_t truelen;
  194240. png_byte buf[4];
  194241. png_debug(1, "in png_handle_sBIT\n");
  194242. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194243. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194244. png_error(png_ptr, "Missing IHDR before sBIT");
  194245. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194246. {
  194247. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194248. png_crc_finish(png_ptr, length);
  194249. return;
  194250. }
  194251. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194252. {
  194253. /* Should be an error, but we can cope with it */
  194254. png_warning(png_ptr, "Out of place sBIT chunk");
  194255. }
  194256. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194257. {
  194258. png_warning(png_ptr, "Duplicate sBIT chunk");
  194259. png_crc_finish(png_ptr, length);
  194260. return;
  194261. }
  194262. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194263. truelen = 3;
  194264. else
  194265. truelen = (png_size_t)png_ptr->channels;
  194266. if (length != truelen || length > 4)
  194267. {
  194268. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194269. png_crc_finish(png_ptr, length);
  194270. return;
  194271. }
  194272. png_crc_read(png_ptr, buf, truelen);
  194273. if (png_crc_finish(png_ptr, 0))
  194274. return;
  194275. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194276. {
  194277. png_ptr->sig_bit.red = buf[0];
  194278. png_ptr->sig_bit.green = buf[1];
  194279. png_ptr->sig_bit.blue = buf[2];
  194280. png_ptr->sig_bit.alpha = buf[3];
  194281. }
  194282. else
  194283. {
  194284. png_ptr->sig_bit.gray = buf[0];
  194285. png_ptr->sig_bit.red = buf[0];
  194286. png_ptr->sig_bit.green = buf[0];
  194287. png_ptr->sig_bit.blue = buf[0];
  194288. png_ptr->sig_bit.alpha = buf[1];
  194289. }
  194290. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194291. }
  194292. #endif
  194293. #if defined(PNG_READ_cHRM_SUPPORTED)
  194294. void /* PRIVATE */
  194295. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194296. {
  194297. png_byte buf[4];
  194298. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194299. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194300. #endif
  194301. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194302. int_y_green, int_x_blue, int_y_blue;
  194303. png_uint_32 uint_x, uint_y;
  194304. png_debug(1, "in png_handle_cHRM\n");
  194305. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194306. png_error(png_ptr, "Missing IHDR before cHRM");
  194307. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194308. {
  194309. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194310. png_crc_finish(png_ptr, length);
  194311. return;
  194312. }
  194313. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194314. /* Should be an error, but we can cope with it */
  194315. png_warning(png_ptr, "Missing PLTE before cHRM");
  194316. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194317. #if defined(PNG_READ_sRGB_SUPPORTED)
  194318. && !(info_ptr->valid & PNG_INFO_sRGB)
  194319. #endif
  194320. )
  194321. {
  194322. png_warning(png_ptr, "Duplicate cHRM chunk");
  194323. png_crc_finish(png_ptr, length);
  194324. return;
  194325. }
  194326. if (length != 32)
  194327. {
  194328. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194329. png_crc_finish(png_ptr, length);
  194330. return;
  194331. }
  194332. png_crc_read(png_ptr, buf, 4);
  194333. uint_x = png_get_uint_32(buf);
  194334. png_crc_read(png_ptr, buf, 4);
  194335. uint_y = png_get_uint_32(buf);
  194336. if (uint_x > 80000L || uint_y > 80000L ||
  194337. uint_x + uint_y > 100000L)
  194338. {
  194339. png_warning(png_ptr, "Invalid cHRM white point");
  194340. png_crc_finish(png_ptr, 24);
  194341. return;
  194342. }
  194343. int_x_white = (png_fixed_point)uint_x;
  194344. int_y_white = (png_fixed_point)uint_y;
  194345. png_crc_read(png_ptr, buf, 4);
  194346. uint_x = png_get_uint_32(buf);
  194347. png_crc_read(png_ptr, buf, 4);
  194348. uint_y = png_get_uint_32(buf);
  194349. if (uint_x + uint_y > 100000L)
  194350. {
  194351. png_warning(png_ptr, "Invalid cHRM red point");
  194352. png_crc_finish(png_ptr, 16);
  194353. return;
  194354. }
  194355. int_x_red = (png_fixed_point)uint_x;
  194356. int_y_red = (png_fixed_point)uint_y;
  194357. png_crc_read(png_ptr, buf, 4);
  194358. uint_x = png_get_uint_32(buf);
  194359. png_crc_read(png_ptr, buf, 4);
  194360. uint_y = png_get_uint_32(buf);
  194361. if (uint_x + uint_y > 100000L)
  194362. {
  194363. png_warning(png_ptr, "Invalid cHRM green point");
  194364. png_crc_finish(png_ptr, 8);
  194365. return;
  194366. }
  194367. int_x_green = (png_fixed_point)uint_x;
  194368. int_y_green = (png_fixed_point)uint_y;
  194369. png_crc_read(png_ptr, buf, 4);
  194370. uint_x = png_get_uint_32(buf);
  194371. png_crc_read(png_ptr, buf, 4);
  194372. uint_y = png_get_uint_32(buf);
  194373. if (uint_x + uint_y > 100000L)
  194374. {
  194375. png_warning(png_ptr, "Invalid cHRM blue point");
  194376. png_crc_finish(png_ptr, 0);
  194377. return;
  194378. }
  194379. int_x_blue = (png_fixed_point)uint_x;
  194380. int_y_blue = (png_fixed_point)uint_y;
  194381. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194382. white_x = (float)int_x_white / (float)100000.0;
  194383. white_y = (float)int_y_white / (float)100000.0;
  194384. red_x = (float)int_x_red / (float)100000.0;
  194385. red_y = (float)int_y_red / (float)100000.0;
  194386. green_x = (float)int_x_green / (float)100000.0;
  194387. green_y = (float)int_y_green / (float)100000.0;
  194388. blue_x = (float)int_x_blue / (float)100000.0;
  194389. blue_y = (float)int_y_blue / (float)100000.0;
  194390. #endif
  194391. #if defined(PNG_READ_sRGB_SUPPORTED)
  194392. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194393. {
  194394. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194395. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194396. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194397. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194398. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194399. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194400. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194401. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194402. {
  194403. png_warning(png_ptr,
  194404. "Ignoring incorrect cHRM value when sRGB is also present");
  194405. #ifndef PNG_NO_CONSOLE_IO
  194406. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194407. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194408. white_x, white_y, red_x, red_y);
  194409. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194410. green_x, green_y, blue_x, blue_y);
  194411. #else
  194412. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194413. int_x_white, int_y_white, int_x_red, int_y_red);
  194414. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194415. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194416. #endif
  194417. #endif /* PNG_NO_CONSOLE_IO */
  194418. }
  194419. png_crc_finish(png_ptr, 0);
  194420. return;
  194421. }
  194422. #endif /* PNG_READ_sRGB_SUPPORTED */
  194423. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194424. png_set_cHRM(png_ptr, info_ptr,
  194425. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194426. #endif
  194427. #ifdef PNG_FIXED_POINT_SUPPORTED
  194428. png_set_cHRM_fixed(png_ptr, info_ptr,
  194429. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194430. int_y_green, int_x_blue, int_y_blue);
  194431. #endif
  194432. if (png_crc_finish(png_ptr, 0))
  194433. return;
  194434. }
  194435. #endif
  194436. #if defined(PNG_READ_sRGB_SUPPORTED)
  194437. void /* PRIVATE */
  194438. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194439. {
  194440. int intent;
  194441. png_byte buf[1];
  194442. png_debug(1, "in png_handle_sRGB\n");
  194443. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194444. png_error(png_ptr, "Missing IHDR before sRGB");
  194445. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194446. {
  194447. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194448. png_crc_finish(png_ptr, length);
  194449. return;
  194450. }
  194451. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194452. /* Should be an error, but we can cope with it */
  194453. png_warning(png_ptr, "Out of place sRGB chunk");
  194454. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194455. {
  194456. png_warning(png_ptr, "Duplicate sRGB chunk");
  194457. png_crc_finish(png_ptr, length);
  194458. return;
  194459. }
  194460. if (length != 1)
  194461. {
  194462. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194463. png_crc_finish(png_ptr, length);
  194464. return;
  194465. }
  194466. png_crc_read(png_ptr, buf, 1);
  194467. if (png_crc_finish(png_ptr, 0))
  194468. return;
  194469. intent = buf[0];
  194470. /* check for bad intent */
  194471. if (intent >= PNG_sRGB_INTENT_LAST)
  194472. {
  194473. png_warning(png_ptr, "Unknown sRGB intent");
  194474. return;
  194475. }
  194476. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194477. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194478. {
  194479. png_fixed_point igamma;
  194480. #ifdef PNG_FIXED_POINT_SUPPORTED
  194481. igamma=info_ptr->int_gamma;
  194482. #else
  194483. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194484. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194485. # endif
  194486. #endif
  194487. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194488. {
  194489. png_warning(png_ptr,
  194490. "Ignoring incorrect gAMA value when sRGB is also present");
  194491. #ifndef PNG_NO_CONSOLE_IO
  194492. # ifdef PNG_FIXED_POINT_SUPPORTED
  194493. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194494. # else
  194495. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194496. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194497. # endif
  194498. # endif
  194499. #endif
  194500. }
  194501. }
  194502. #endif /* PNG_READ_gAMA_SUPPORTED */
  194503. #ifdef PNG_READ_cHRM_SUPPORTED
  194504. #ifdef PNG_FIXED_POINT_SUPPORTED
  194505. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194506. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194507. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194508. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194509. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194510. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194511. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194512. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194513. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194514. {
  194515. png_warning(png_ptr,
  194516. "Ignoring incorrect cHRM value when sRGB is also present");
  194517. }
  194518. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194519. #endif /* PNG_READ_cHRM_SUPPORTED */
  194520. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194521. }
  194522. #endif /* PNG_READ_sRGB_SUPPORTED */
  194523. #if defined(PNG_READ_iCCP_SUPPORTED)
  194524. void /* PRIVATE */
  194525. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194526. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194527. {
  194528. png_charp chunkdata;
  194529. png_byte compression_type;
  194530. png_bytep pC;
  194531. png_charp profile;
  194532. png_uint_32 skip = 0;
  194533. png_uint_32 profile_size, profile_length;
  194534. png_size_t slength, prefix_length, data_length;
  194535. png_debug(1, "in png_handle_iCCP\n");
  194536. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194537. png_error(png_ptr, "Missing IHDR before iCCP");
  194538. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194539. {
  194540. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194541. png_crc_finish(png_ptr, length);
  194542. return;
  194543. }
  194544. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194545. /* Should be an error, but we can cope with it */
  194546. png_warning(png_ptr, "Out of place iCCP chunk");
  194547. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194548. {
  194549. png_warning(png_ptr, "Duplicate iCCP chunk");
  194550. png_crc_finish(png_ptr, length);
  194551. return;
  194552. }
  194553. #ifdef PNG_MAX_MALLOC_64K
  194554. if (length > (png_uint_32)65535L)
  194555. {
  194556. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194557. skip = length - (png_uint_32)65535L;
  194558. length = (png_uint_32)65535L;
  194559. }
  194560. #endif
  194561. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194562. slength = (png_size_t)length;
  194563. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194564. if (png_crc_finish(png_ptr, skip))
  194565. {
  194566. png_free(png_ptr, chunkdata);
  194567. return;
  194568. }
  194569. chunkdata[slength] = 0x00;
  194570. for (profile = chunkdata; *profile; profile++)
  194571. /* empty loop to find end of name */ ;
  194572. ++profile;
  194573. /* there should be at least one zero (the compression type byte)
  194574. following the separator, and we should be on it */
  194575. if ( profile >= chunkdata + slength - 1)
  194576. {
  194577. png_free(png_ptr, chunkdata);
  194578. png_warning(png_ptr, "Malformed iCCP chunk");
  194579. return;
  194580. }
  194581. /* compression_type should always be zero */
  194582. compression_type = *profile++;
  194583. if (compression_type)
  194584. {
  194585. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194586. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194587. wrote nonzero) */
  194588. }
  194589. prefix_length = profile - chunkdata;
  194590. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194591. slength, prefix_length, &data_length);
  194592. profile_length = data_length - prefix_length;
  194593. if ( prefix_length > data_length || profile_length < 4)
  194594. {
  194595. png_free(png_ptr, chunkdata);
  194596. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194597. return;
  194598. }
  194599. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194600. pC = (png_bytep)(chunkdata+prefix_length);
  194601. profile_size = ((*(pC ))<<24) |
  194602. ((*(pC+1))<<16) |
  194603. ((*(pC+2))<< 8) |
  194604. ((*(pC+3)) );
  194605. if(profile_size < profile_length)
  194606. profile_length = profile_size;
  194607. if(profile_size > profile_length)
  194608. {
  194609. png_free(png_ptr, chunkdata);
  194610. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194611. return;
  194612. }
  194613. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194614. chunkdata + prefix_length, profile_length);
  194615. png_free(png_ptr, chunkdata);
  194616. }
  194617. #endif /* PNG_READ_iCCP_SUPPORTED */
  194618. #if defined(PNG_READ_sPLT_SUPPORTED)
  194619. void /* PRIVATE */
  194620. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194621. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194622. {
  194623. png_bytep chunkdata;
  194624. png_bytep entry_start;
  194625. png_sPLT_t new_palette;
  194626. #ifdef PNG_NO_POINTER_INDEXING
  194627. png_sPLT_entryp pp;
  194628. #endif
  194629. int data_length, entry_size, i;
  194630. png_uint_32 skip = 0;
  194631. png_size_t slength;
  194632. png_debug(1, "in png_handle_sPLT\n");
  194633. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194634. png_error(png_ptr, "Missing IHDR before sPLT");
  194635. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194636. {
  194637. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194638. png_crc_finish(png_ptr, length);
  194639. return;
  194640. }
  194641. #ifdef PNG_MAX_MALLOC_64K
  194642. if (length > (png_uint_32)65535L)
  194643. {
  194644. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194645. skip = length - (png_uint_32)65535L;
  194646. length = (png_uint_32)65535L;
  194647. }
  194648. #endif
  194649. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194650. slength = (png_size_t)length;
  194651. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194652. if (png_crc_finish(png_ptr, skip))
  194653. {
  194654. png_free(png_ptr, chunkdata);
  194655. return;
  194656. }
  194657. chunkdata[slength] = 0x00;
  194658. for (entry_start = chunkdata; *entry_start; entry_start++)
  194659. /* empty loop to find end of name */ ;
  194660. ++entry_start;
  194661. /* a sample depth should follow the separator, and we should be on it */
  194662. if (entry_start > chunkdata + slength - 2)
  194663. {
  194664. png_free(png_ptr, chunkdata);
  194665. png_warning(png_ptr, "malformed sPLT chunk");
  194666. return;
  194667. }
  194668. new_palette.depth = *entry_start++;
  194669. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194670. data_length = (slength - (entry_start - chunkdata));
  194671. /* integrity-check the data length */
  194672. if (data_length % entry_size)
  194673. {
  194674. png_free(png_ptr, chunkdata);
  194675. png_warning(png_ptr, "sPLT chunk has bad length");
  194676. return;
  194677. }
  194678. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194679. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194680. png_sizeof(png_sPLT_entry)))
  194681. {
  194682. png_warning(png_ptr, "sPLT chunk too long");
  194683. return;
  194684. }
  194685. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194686. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194687. if (new_palette.entries == NULL)
  194688. {
  194689. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194690. return;
  194691. }
  194692. #ifndef PNG_NO_POINTER_INDEXING
  194693. for (i = 0; i < new_palette.nentries; i++)
  194694. {
  194695. png_sPLT_entryp pp = new_palette.entries + i;
  194696. if (new_palette.depth == 8)
  194697. {
  194698. pp->red = *entry_start++;
  194699. pp->green = *entry_start++;
  194700. pp->blue = *entry_start++;
  194701. pp->alpha = *entry_start++;
  194702. }
  194703. else
  194704. {
  194705. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194706. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194707. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194708. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194709. }
  194710. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194711. }
  194712. #else
  194713. pp = new_palette.entries;
  194714. for (i = 0; i < new_palette.nentries; i++)
  194715. {
  194716. if (new_palette.depth == 8)
  194717. {
  194718. pp[i].red = *entry_start++;
  194719. pp[i].green = *entry_start++;
  194720. pp[i].blue = *entry_start++;
  194721. pp[i].alpha = *entry_start++;
  194722. }
  194723. else
  194724. {
  194725. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194726. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194727. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194728. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194729. }
  194730. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194731. }
  194732. #endif
  194733. /* discard all chunk data except the name and stash that */
  194734. new_palette.name = (png_charp)chunkdata;
  194735. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194736. png_free(png_ptr, chunkdata);
  194737. png_free(png_ptr, new_palette.entries);
  194738. }
  194739. #endif /* PNG_READ_sPLT_SUPPORTED */
  194740. #if defined(PNG_READ_tRNS_SUPPORTED)
  194741. void /* PRIVATE */
  194742. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194743. {
  194744. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194745. int bit_mask;
  194746. png_debug(1, "in png_handle_tRNS\n");
  194747. /* For non-indexed color, mask off any bits in the tRNS value that
  194748. * exceed the bit depth. Some creators were writing extra bits there.
  194749. * This is not needed for indexed color. */
  194750. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194751. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194752. png_error(png_ptr, "Missing IHDR before tRNS");
  194753. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194754. {
  194755. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194756. png_crc_finish(png_ptr, length);
  194757. return;
  194758. }
  194759. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194760. {
  194761. png_warning(png_ptr, "Duplicate tRNS chunk");
  194762. png_crc_finish(png_ptr, length);
  194763. return;
  194764. }
  194765. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194766. {
  194767. png_byte buf[2];
  194768. if (length != 2)
  194769. {
  194770. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194771. png_crc_finish(png_ptr, length);
  194772. return;
  194773. }
  194774. png_crc_read(png_ptr, buf, 2);
  194775. png_ptr->num_trans = 1;
  194776. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194777. }
  194778. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194779. {
  194780. png_byte buf[6];
  194781. if (length != 6)
  194782. {
  194783. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194784. png_crc_finish(png_ptr, length);
  194785. return;
  194786. }
  194787. png_crc_read(png_ptr, buf, (png_size_t)length);
  194788. png_ptr->num_trans = 1;
  194789. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194790. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194791. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194792. }
  194793. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194794. {
  194795. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194796. {
  194797. /* Should be an error, but we can cope with it. */
  194798. png_warning(png_ptr, "Missing PLTE before tRNS");
  194799. }
  194800. if (length > (png_uint_32)png_ptr->num_palette ||
  194801. length > PNG_MAX_PALETTE_LENGTH)
  194802. {
  194803. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194804. png_crc_finish(png_ptr, length);
  194805. return;
  194806. }
  194807. if (length == 0)
  194808. {
  194809. png_warning(png_ptr, "Zero length tRNS chunk");
  194810. png_crc_finish(png_ptr, length);
  194811. return;
  194812. }
  194813. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194814. png_ptr->num_trans = (png_uint_16)length;
  194815. }
  194816. else
  194817. {
  194818. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194819. png_crc_finish(png_ptr, length);
  194820. return;
  194821. }
  194822. if (png_crc_finish(png_ptr, 0))
  194823. {
  194824. png_ptr->num_trans = 0;
  194825. return;
  194826. }
  194827. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194828. &(png_ptr->trans_values));
  194829. }
  194830. #endif
  194831. #if defined(PNG_READ_bKGD_SUPPORTED)
  194832. void /* PRIVATE */
  194833. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194834. {
  194835. png_size_t truelen;
  194836. png_byte buf[6];
  194837. png_debug(1, "in png_handle_bKGD\n");
  194838. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194839. png_error(png_ptr, "Missing IHDR before bKGD");
  194840. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194841. {
  194842. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194843. png_crc_finish(png_ptr, length);
  194844. return;
  194845. }
  194846. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194847. !(png_ptr->mode & PNG_HAVE_PLTE))
  194848. {
  194849. png_warning(png_ptr, "Missing PLTE before bKGD");
  194850. png_crc_finish(png_ptr, length);
  194851. return;
  194852. }
  194853. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194854. {
  194855. png_warning(png_ptr, "Duplicate bKGD chunk");
  194856. png_crc_finish(png_ptr, length);
  194857. return;
  194858. }
  194859. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194860. truelen = 1;
  194861. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194862. truelen = 6;
  194863. else
  194864. truelen = 2;
  194865. if (length != truelen)
  194866. {
  194867. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194868. png_crc_finish(png_ptr, length);
  194869. return;
  194870. }
  194871. png_crc_read(png_ptr, buf, truelen);
  194872. if (png_crc_finish(png_ptr, 0))
  194873. return;
  194874. /* We convert the index value into RGB components so that we can allow
  194875. * arbitrary RGB values for background when we have transparency, and
  194876. * so it is easy to determine the RGB values of the background color
  194877. * from the info_ptr struct. */
  194878. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194879. {
  194880. png_ptr->background.index = buf[0];
  194881. if(info_ptr->num_palette)
  194882. {
  194883. if(buf[0] > info_ptr->num_palette)
  194884. {
  194885. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194886. return;
  194887. }
  194888. png_ptr->background.red =
  194889. (png_uint_16)png_ptr->palette[buf[0]].red;
  194890. png_ptr->background.green =
  194891. (png_uint_16)png_ptr->palette[buf[0]].green;
  194892. png_ptr->background.blue =
  194893. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194894. }
  194895. }
  194896. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194897. {
  194898. png_ptr->background.red =
  194899. png_ptr->background.green =
  194900. png_ptr->background.blue =
  194901. png_ptr->background.gray = png_get_uint_16(buf);
  194902. }
  194903. else
  194904. {
  194905. png_ptr->background.red = png_get_uint_16(buf);
  194906. png_ptr->background.green = png_get_uint_16(buf + 2);
  194907. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194908. }
  194909. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194910. }
  194911. #endif
  194912. #if defined(PNG_READ_hIST_SUPPORTED)
  194913. void /* PRIVATE */
  194914. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194915. {
  194916. unsigned int num, i;
  194917. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194918. png_debug(1, "in png_handle_hIST\n");
  194919. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194920. png_error(png_ptr, "Missing IHDR before hIST");
  194921. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194922. {
  194923. png_warning(png_ptr, "Invalid hIST after IDAT");
  194924. png_crc_finish(png_ptr, length);
  194925. return;
  194926. }
  194927. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194928. {
  194929. png_warning(png_ptr, "Missing PLTE before hIST");
  194930. png_crc_finish(png_ptr, length);
  194931. return;
  194932. }
  194933. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194934. {
  194935. png_warning(png_ptr, "Duplicate hIST chunk");
  194936. png_crc_finish(png_ptr, length);
  194937. return;
  194938. }
  194939. num = length / 2 ;
  194940. if (num != (unsigned int) png_ptr->num_palette || num >
  194941. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194942. {
  194943. png_warning(png_ptr, "Incorrect hIST chunk length");
  194944. png_crc_finish(png_ptr, length);
  194945. return;
  194946. }
  194947. for (i = 0; i < num; i++)
  194948. {
  194949. png_byte buf[2];
  194950. png_crc_read(png_ptr, buf, 2);
  194951. readbuf[i] = png_get_uint_16(buf);
  194952. }
  194953. if (png_crc_finish(png_ptr, 0))
  194954. return;
  194955. png_set_hIST(png_ptr, info_ptr, readbuf);
  194956. }
  194957. #endif
  194958. #if defined(PNG_READ_pHYs_SUPPORTED)
  194959. void /* PRIVATE */
  194960. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194961. {
  194962. png_byte buf[9];
  194963. png_uint_32 res_x, res_y;
  194964. int unit_type;
  194965. png_debug(1, "in png_handle_pHYs\n");
  194966. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194967. png_error(png_ptr, "Missing IHDR before pHYs");
  194968. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194969. {
  194970. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194971. png_crc_finish(png_ptr, length);
  194972. return;
  194973. }
  194974. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194975. {
  194976. png_warning(png_ptr, "Duplicate pHYs chunk");
  194977. png_crc_finish(png_ptr, length);
  194978. return;
  194979. }
  194980. if (length != 9)
  194981. {
  194982. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194983. png_crc_finish(png_ptr, length);
  194984. return;
  194985. }
  194986. png_crc_read(png_ptr, buf, 9);
  194987. if (png_crc_finish(png_ptr, 0))
  194988. return;
  194989. res_x = png_get_uint_32(buf);
  194990. res_y = png_get_uint_32(buf + 4);
  194991. unit_type = buf[8];
  194992. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194993. }
  194994. #endif
  194995. #if defined(PNG_READ_oFFs_SUPPORTED)
  194996. void /* PRIVATE */
  194997. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194998. {
  194999. png_byte buf[9];
  195000. png_int_32 offset_x, offset_y;
  195001. int unit_type;
  195002. png_debug(1, "in png_handle_oFFs\n");
  195003. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195004. png_error(png_ptr, "Missing IHDR before oFFs");
  195005. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195006. {
  195007. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195008. png_crc_finish(png_ptr, length);
  195009. return;
  195010. }
  195011. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195012. {
  195013. png_warning(png_ptr, "Duplicate oFFs chunk");
  195014. png_crc_finish(png_ptr, length);
  195015. return;
  195016. }
  195017. if (length != 9)
  195018. {
  195019. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195020. png_crc_finish(png_ptr, length);
  195021. return;
  195022. }
  195023. png_crc_read(png_ptr, buf, 9);
  195024. if (png_crc_finish(png_ptr, 0))
  195025. return;
  195026. offset_x = png_get_int_32(buf);
  195027. offset_y = png_get_int_32(buf + 4);
  195028. unit_type = buf[8];
  195029. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195030. }
  195031. #endif
  195032. #if defined(PNG_READ_pCAL_SUPPORTED)
  195033. /* read the pCAL chunk (described in the PNG Extensions document) */
  195034. void /* PRIVATE */
  195035. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195036. {
  195037. png_charp purpose;
  195038. png_int_32 X0, X1;
  195039. png_byte type, nparams;
  195040. png_charp buf, units, endptr;
  195041. png_charpp params;
  195042. png_size_t slength;
  195043. int i;
  195044. png_debug(1, "in png_handle_pCAL\n");
  195045. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195046. png_error(png_ptr, "Missing IHDR before pCAL");
  195047. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195048. {
  195049. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195050. png_crc_finish(png_ptr, length);
  195051. return;
  195052. }
  195053. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195054. {
  195055. png_warning(png_ptr, "Duplicate pCAL chunk");
  195056. png_crc_finish(png_ptr, length);
  195057. return;
  195058. }
  195059. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195060. length + 1);
  195061. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195062. if (purpose == NULL)
  195063. {
  195064. png_warning(png_ptr, "No memory for pCAL purpose.");
  195065. return;
  195066. }
  195067. slength = (png_size_t)length;
  195068. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195069. if (png_crc_finish(png_ptr, 0))
  195070. {
  195071. png_free(png_ptr, purpose);
  195072. return;
  195073. }
  195074. purpose[slength] = 0x00; /* null terminate the last string */
  195075. png_debug(3, "Finding end of pCAL purpose string\n");
  195076. for (buf = purpose; *buf; buf++)
  195077. /* empty loop */ ;
  195078. endptr = purpose + slength;
  195079. /* We need to have at least 12 bytes after the purpose string
  195080. in order to get the parameter information. */
  195081. if (endptr <= buf + 12)
  195082. {
  195083. png_warning(png_ptr, "Invalid pCAL data");
  195084. png_free(png_ptr, purpose);
  195085. return;
  195086. }
  195087. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195088. X0 = png_get_int_32((png_bytep)buf+1);
  195089. X1 = png_get_int_32((png_bytep)buf+5);
  195090. type = buf[9];
  195091. nparams = buf[10];
  195092. units = buf + 11;
  195093. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195094. /* Check that we have the right number of parameters for known
  195095. equation types. */
  195096. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195097. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195098. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195099. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195100. {
  195101. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195102. png_free(png_ptr, purpose);
  195103. return;
  195104. }
  195105. else if (type >= PNG_EQUATION_LAST)
  195106. {
  195107. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195108. }
  195109. for (buf = units; *buf; buf++)
  195110. /* Empty loop to move past the units string. */ ;
  195111. png_debug(3, "Allocating pCAL parameters array\n");
  195112. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195113. *png_sizeof(png_charp))) ;
  195114. if (params == NULL)
  195115. {
  195116. png_free(png_ptr, purpose);
  195117. png_warning(png_ptr, "No memory for pCAL params.");
  195118. return;
  195119. }
  195120. /* Get pointers to the start of each parameter string. */
  195121. for (i = 0; i < (int)nparams; i++)
  195122. {
  195123. buf++; /* Skip the null string terminator from previous parameter. */
  195124. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195125. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195126. /* Empty loop to move past each parameter string */ ;
  195127. /* Make sure we haven't run out of data yet */
  195128. if (buf > endptr)
  195129. {
  195130. png_warning(png_ptr, "Invalid pCAL data");
  195131. png_free(png_ptr, purpose);
  195132. png_free(png_ptr, params);
  195133. return;
  195134. }
  195135. }
  195136. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195137. units, params);
  195138. png_free(png_ptr, purpose);
  195139. png_free(png_ptr, params);
  195140. }
  195141. #endif
  195142. #if defined(PNG_READ_sCAL_SUPPORTED)
  195143. /* read the sCAL chunk */
  195144. void /* PRIVATE */
  195145. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195146. {
  195147. png_charp buffer, ep;
  195148. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195149. double width, height;
  195150. png_charp vp;
  195151. #else
  195152. #ifdef PNG_FIXED_POINT_SUPPORTED
  195153. png_charp swidth, sheight;
  195154. #endif
  195155. #endif
  195156. png_size_t slength;
  195157. png_debug(1, "in png_handle_sCAL\n");
  195158. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195159. png_error(png_ptr, "Missing IHDR before sCAL");
  195160. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195161. {
  195162. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195163. png_crc_finish(png_ptr, length);
  195164. return;
  195165. }
  195166. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195167. {
  195168. png_warning(png_ptr, "Duplicate sCAL chunk");
  195169. png_crc_finish(png_ptr, length);
  195170. return;
  195171. }
  195172. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195173. length + 1);
  195174. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195175. if (buffer == NULL)
  195176. {
  195177. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195178. return;
  195179. }
  195180. slength = (png_size_t)length;
  195181. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195182. if (png_crc_finish(png_ptr, 0))
  195183. {
  195184. png_free(png_ptr, buffer);
  195185. return;
  195186. }
  195187. buffer[slength] = 0x00; /* null terminate the last string */
  195188. ep = buffer + 1; /* skip unit byte */
  195189. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195190. width = png_strtod(png_ptr, ep, &vp);
  195191. if (*vp)
  195192. {
  195193. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195194. return;
  195195. }
  195196. #else
  195197. #ifdef PNG_FIXED_POINT_SUPPORTED
  195198. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195199. if (swidth == NULL)
  195200. {
  195201. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195202. return;
  195203. }
  195204. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195205. #endif
  195206. #endif
  195207. for (ep = buffer; *ep; ep++)
  195208. /* empty loop */ ;
  195209. ep++;
  195210. if (buffer + slength < ep)
  195211. {
  195212. png_warning(png_ptr, "Truncated sCAL chunk");
  195213. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195214. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195215. png_free(png_ptr, swidth);
  195216. #endif
  195217. png_free(png_ptr, buffer);
  195218. return;
  195219. }
  195220. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195221. height = png_strtod(png_ptr, ep, &vp);
  195222. if (*vp)
  195223. {
  195224. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195225. return;
  195226. }
  195227. #else
  195228. #ifdef PNG_FIXED_POINT_SUPPORTED
  195229. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195230. if (swidth == NULL)
  195231. {
  195232. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195233. return;
  195234. }
  195235. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195236. #endif
  195237. #endif
  195238. if (buffer + slength < ep
  195239. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195240. || width <= 0. || height <= 0.
  195241. #endif
  195242. )
  195243. {
  195244. png_warning(png_ptr, "Invalid sCAL data");
  195245. png_free(png_ptr, buffer);
  195246. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195247. png_free(png_ptr, swidth);
  195248. png_free(png_ptr, sheight);
  195249. #endif
  195250. return;
  195251. }
  195252. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195253. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195254. #else
  195255. #ifdef PNG_FIXED_POINT_SUPPORTED
  195256. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195257. #endif
  195258. #endif
  195259. png_free(png_ptr, buffer);
  195260. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195261. png_free(png_ptr, swidth);
  195262. png_free(png_ptr, sheight);
  195263. #endif
  195264. }
  195265. #endif
  195266. #if defined(PNG_READ_tIME_SUPPORTED)
  195267. void /* PRIVATE */
  195268. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195269. {
  195270. png_byte buf[7];
  195271. png_time mod_time;
  195272. png_debug(1, "in png_handle_tIME\n");
  195273. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195274. png_error(png_ptr, "Out of place tIME chunk");
  195275. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195276. {
  195277. png_warning(png_ptr, "Duplicate tIME chunk");
  195278. png_crc_finish(png_ptr, length);
  195279. return;
  195280. }
  195281. if (png_ptr->mode & PNG_HAVE_IDAT)
  195282. png_ptr->mode |= PNG_AFTER_IDAT;
  195283. if (length != 7)
  195284. {
  195285. png_warning(png_ptr, "Incorrect tIME chunk length");
  195286. png_crc_finish(png_ptr, length);
  195287. return;
  195288. }
  195289. png_crc_read(png_ptr, buf, 7);
  195290. if (png_crc_finish(png_ptr, 0))
  195291. return;
  195292. mod_time.second = buf[6];
  195293. mod_time.minute = buf[5];
  195294. mod_time.hour = buf[4];
  195295. mod_time.day = buf[3];
  195296. mod_time.month = buf[2];
  195297. mod_time.year = png_get_uint_16(buf);
  195298. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195299. }
  195300. #endif
  195301. #if defined(PNG_READ_tEXt_SUPPORTED)
  195302. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195303. void /* PRIVATE */
  195304. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195305. {
  195306. png_textp text_ptr;
  195307. png_charp key;
  195308. png_charp text;
  195309. png_uint_32 skip = 0;
  195310. png_size_t slength;
  195311. int ret;
  195312. png_debug(1, "in png_handle_tEXt\n");
  195313. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195314. png_error(png_ptr, "Missing IHDR before tEXt");
  195315. if (png_ptr->mode & PNG_HAVE_IDAT)
  195316. png_ptr->mode |= PNG_AFTER_IDAT;
  195317. #ifdef PNG_MAX_MALLOC_64K
  195318. if (length > (png_uint_32)65535L)
  195319. {
  195320. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195321. skip = length - (png_uint_32)65535L;
  195322. length = (png_uint_32)65535L;
  195323. }
  195324. #endif
  195325. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195326. if (key == NULL)
  195327. {
  195328. png_warning(png_ptr, "No memory to process text chunk.");
  195329. return;
  195330. }
  195331. slength = (png_size_t)length;
  195332. png_crc_read(png_ptr, (png_bytep)key, slength);
  195333. if (png_crc_finish(png_ptr, skip))
  195334. {
  195335. png_free(png_ptr, key);
  195336. return;
  195337. }
  195338. key[slength] = 0x00;
  195339. for (text = key; *text; text++)
  195340. /* empty loop to find end of key */ ;
  195341. if (text != key + slength)
  195342. text++;
  195343. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195344. (png_uint_32)png_sizeof(png_text));
  195345. if (text_ptr == NULL)
  195346. {
  195347. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195348. png_free(png_ptr, key);
  195349. return;
  195350. }
  195351. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195352. text_ptr->key = key;
  195353. #ifdef PNG_iTXt_SUPPORTED
  195354. text_ptr->lang = NULL;
  195355. text_ptr->lang_key = NULL;
  195356. text_ptr->itxt_length = 0;
  195357. #endif
  195358. text_ptr->text = text;
  195359. text_ptr->text_length = png_strlen(text);
  195360. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195361. png_free(png_ptr, key);
  195362. png_free(png_ptr, text_ptr);
  195363. if (ret)
  195364. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195365. }
  195366. #endif
  195367. #if defined(PNG_READ_zTXt_SUPPORTED)
  195368. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195369. void /* PRIVATE */
  195370. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195371. {
  195372. png_textp text_ptr;
  195373. png_charp chunkdata;
  195374. png_charp text;
  195375. int comp_type;
  195376. int ret;
  195377. png_size_t slength, prefix_len, data_len;
  195378. png_debug(1, "in png_handle_zTXt\n");
  195379. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195380. png_error(png_ptr, "Missing IHDR before zTXt");
  195381. if (png_ptr->mode & PNG_HAVE_IDAT)
  195382. png_ptr->mode |= PNG_AFTER_IDAT;
  195383. #ifdef PNG_MAX_MALLOC_64K
  195384. /* We will no doubt have problems with chunks even half this size, but
  195385. there is no hard and fast rule to tell us where to stop. */
  195386. if (length > (png_uint_32)65535L)
  195387. {
  195388. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195389. png_crc_finish(png_ptr, length);
  195390. return;
  195391. }
  195392. #endif
  195393. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195394. if (chunkdata == NULL)
  195395. {
  195396. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195397. return;
  195398. }
  195399. slength = (png_size_t)length;
  195400. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195401. if (png_crc_finish(png_ptr, 0))
  195402. {
  195403. png_free(png_ptr, chunkdata);
  195404. return;
  195405. }
  195406. chunkdata[slength] = 0x00;
  195407. for (text = chunkdata; *text; text++)
  195408. /* empty loop */ ;
  195409. /* zTXt must have some text after the chunkdataword */
  195410. if (text >= chunkdata + slength - 2)
  195411. {
  195412. png_warning(png_ptr, "Truncated zTXt chunk");
  195413. png_free(png_ptr, chunkdata);
  195414. return;
  195415. }
  195416. else
  195417. {
  195418. comp_type = *(++text);
  195419. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195420. {
  195421. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195422. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195423. }
  195424. text++; /* skip the compression_method byte */
  195425. }
  195426. prefix_len = text - chunkdata;
  195427. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195428. (png_size_t)length, prefix_len, &data_len);
  195429. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195430. (png_uint_32)png_sizeof(png_text));
  195431. if (text_ptr == NULL)
  195432. {
  195433. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195434. png_free(png_ptr, chunkdata);
  195435. return;
  195436. }
  195437. text_ptr->compression = comp_type;
  195438. text_ptr->key = chunkdata;
  195439. #ifdef PNG_iTXt_SUPPORTED
  195440. text_ptr->lang = NULL;
  195441. text_ptr->lang_key = NULL;
  195442. text_ptr->itxt_length = 0;
  195443. #endif
  195444. text_ptr->text = chunkdata + prefix_len;
  195445. text_ptr->text_length = data_len;
  195446. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195447. png_free(png_ptr, text_ptr);
  195448. png_free(png_ptr, chunkdata);
  195449. if (ret)
  195450. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195451. }
  195452. #endif
  195453. #if defined(PNG_READ_iTXt_SUPPORTED)
  195454. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195455. void /* PRIVATE */
  195456. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195457. {
  195458. png_textp text_ptr;
  195459. png_charp chunkdata;
  195460. png_charp key, lang, text, lang_key;
  195461. int comp_flag;
  195462. int comp_type = 0;
  195463. int ret;
  195464. png_size_t slength, prefix_len, data_len;
  195465. png_debug(1, "in png_handle_iTXt\n");
  195466. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195467. png_error(png_ptr, "Missing IHDR before iTXt");
  195468. if (png_ptr->mode & PNG_HAVE_IDAT)
  195469. png_ptr->mode |= PNG_AFTER_IDAT;
  195470. #ifdef PNG_MAX_MALLOC_64K
  195471. /* We will no doubt have problems with chunks even half this size, but
  195472. there is no hard and fast rule to tell us where to stop. */
  195473. if (length > (png_uint_32)65535L)
  195474. {
  195475. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195476. png_crc_finish(png_ptr, length);
  195477. return;
  195478. }
  195479. #endif
  195480. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195481. if (chunkdata == NULL)
  195482. {
  195483. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195484. return;
  195485. }
  195486. slength = (png_size_t)length;
  195487. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195488. if (png_crc_finish(png_ptr, 0))
  195489. {
  195490. png_free(png_ptr, chunkdata);
  195491. return;
  195492. }
  195493. chunkdata[slength] = 0x00;
  195494. for (lang = chunkdata; *lang; lang++)
  195495. /* empty loop */ ;
  195496. lang++; /* skip NUL separator */
  195497. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195498. translated keyword (possibly empty), and possibly some text after the
  195499. keyword */
  195500. if (lang >= chunkdata + slength - 3)
  195501. {
  195502. png_warning(png_ptr, "Truncated iTXt chunk");
  195503. png_free(png_ptr, chunkdata);
  195504. return;
  195505. }
  195506. else
  195507. {
  195508. comp_flag = *lang++;
  195509. comp_type = *lang++;
  195510. }
  195511. for (lang_key = lang; *lang_key; lang_key++)
  195512. /* empty loop */ ;
  195513. lang_key++; /* skip NUL separator */
  195514. if (lang_key >= chunkdata + slength)
  195515. {
  195516. png_warning(png_ptr, "Truncated iTXt chunk");
  195517. png_free(png_ptr, chunkdata);
  195518. return;
  195519. }
  195520. for (text = lang_key; *text; text++)
  195521. /* empty loop */ ;
  195522. text++; /* skip NUL separator */
  195523. if (text >= chunkdata + slength)
  195524. {
  195525. png_warning(png_ptr, "Malformed iTXt chunk");
  195526. png_free(png_ptr, chunkdata);
  195527. return;
  195528. }
  195529. prefix_len = text - chunkdata;
  195530. key=chunkdata;
  195531. if (comp_flag)
  195532. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195533. (size_t)length, prefix_len, &data_len);
  195534. else
  195535. data_len=png_strlen(chunkdata + prefix_len);
  195536. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195537. (png_uint_32)png_sizeof(png_text));
  195538. if (text_ptr == NULL)
  195539. {
  195540. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195541. png_free(png_ptr, chunkdata);
  195542. return;
  195543. }
  195544. text_ptr->compression = (int)comp_flag + 1;
  195545. text_ptr->lang_key = chunkdata+(lang_key-key);
  195546. text_ptr->lang = chunkdata+(lang-key);
  195547. text_ptr->itxt_length = data_len;
  195548. text_ptr->text_length = 0;
  195549. text_ptr->key = chunkdata;
  195550. text_ptr->text = chunkdata + prefix_len;
  195551. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195552. png_free(png_ptr, text_ptr);
  195553. png_free(png_ptr, chunkdata);
  195554. if (ret)
  195555. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195556. }
  195557. #endif
  195558. /* This function is called when we haven't found a handler for a
  195559. chunk. If there isn't a problem with the chunk itself (ie bad
  195560. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195561. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195562. case it will be saved away to be written out later. */
  195563. void /* PRIVATE */
  195564. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195565. {
  195566. png_uint_32 skip = 0;
  195567. png_debug(1, "in png_handle_unknown\n");
  195568. if (png_ptr->mode & PNG_HAVE_IDAT)
  195569. {
  195570. #ifdef PNG_USE_LOCAL_ARRAYS
  195571. PNG_CONST PNG_IDAT;
  195572. #endif
  195573. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195574. png_ptr->mode |= PNG_AFTER_IDAT;
  195575. }
  195576. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195577. if (!(png_ptr->chunk_name[0] & 0x20))
  195578. {
  195579. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195580. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195581. PNG_HANDLE_CHUNK_ALWAYS
  195582. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195583. && png_ptr->read_user_chunk_fn == NULL
  195584. #endif
  195585. )
  195586. #endif
  195587. png_chunk_error(png_ptr, "unknown critical chunk");
  195588. }
  195589. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195590. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195591. (png_ptr->read_user_chunk_fn != NULL))
  195592. {
  195593. #ifdef PNG_MAX_MALLOC_64K
  195594. if (length > (png_uint_32)65535L)
  195595. {
  195596. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195597. skip = length - (png_uint_32)65535L;
  195598. length = (png_uint_32)65535L;
  195599. }
  195600. #endif
  195601. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195602. (png_charp)png_ptr->chunk_name, 5);
  195603. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195604. png_ptr->unknown_chunk.size = (png_size_t)length;
  195605. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195606. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195607. if(png_ptr->read_user_chunk_fn != NULL)
  195608. {
  195609. /* callback to user unknown chunk handler */
  195610. int ret;
  195611. ret = (*(png_ptr->read_user_chunk_fn))
  195612. (png_ptr, &png_ptr->unknown_chunk);
  195613. if (ret < 0)
  195614. png_chunk_error(png_ptr, "error in user chunk");
  195615. if (ret == 0)
  195616. {
  195617. if (!(png_ptr->chunk_name[0] & 0x20))
  195618. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195619. PNG_HANDLE_CHUNK_ALWAYS)
  195620. png_chunk_error(png_ptr, "unknown critical chunk");
  195621. png_set_unknown_chunks(png_ptr, info_ptr,
  195622. &png_ptr->unknown_chunk, 1);
  195623. }
  195624. }
  195625. #else
  195626. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195627. #endif
  195628. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195629. png_ptr->unknown_chunk.data = NULL;
  195630. }
  195631. else
  195632. #endif
  195633. skip = length;
  195634. png_crc_finish(png_ptr, skip);
  195635. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195636. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195637. #endif
  195638. }
  195639. /* This function is called to verify that a chunk name is valid.
  195640. This function can't have the "critical chunk check" incorporated
  195641. into it, since in the future we will need to be able to call user
  195642. functions to handle unknown critical chunks after we check that
  195643. the chunk name itself is valid. */
  195644. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195645. void /* PRIVATE */
  195646. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195647. {
  195648. png_debug(1, "in png_check_chunk_name\n");
  195649. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195650. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195651. {
  195652. png_chunk_error(png_ptr, "invalid chunk type");
  195653. }
  195654. }
  195655. /* Combines the row recently read in with the existing pixels in the
  195656. row. This routine takes care of alpha and transparency if requested.
  195657. This routine also handles the two methods of progressive display
  195658. of interlaced images, depending on the mask value.
  195659. The mask value describes which pixels are to be combined with
  195660. the row. The pattern always repeats every 8 pixels, so just 8
  195661. bits are needed. A one indicates the pixel is to be combined,
  195662. a zero indicates the pixel is to be skipped. This is in addition
  195663. to any alpha or transparency value associated with the pixel. If
  195664. you want all pixels to be combined, pass 0xff (255) in mask. */
  195665. void /* PRIVATE */
  195666. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195667. {
  195668. png_debug(1,"in png_combine_row\n");
  195669. if (mask == 0xff)
  195670. {
  195671. png_memcpy(row, png_ptr->row_buf + 1,
  195672. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195673. }
  195674. else
  195675. {
  195676. switch (png_ptr->row_info.pixel_depth)
  195677. {
  195678. case 1:
  195679. {
  195680. png_bytep sp = png_ptr->row_buf + 1;
  195681. png_bytep dp = row;
  195682. int s_inc, s_start, s_end;
  195683. int m = 0x80;
  195684. int shift;
  195685. png_uint_32 i;
  195686. png_uint_32 row_width = png_ptr->width;
  195687. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195688. if (png_ptr->transformations & PNG_PACKSWAP)
  195689. {
  195690. s_start = 0;
  195691. s_end = 7;
  195692. s_inc = 1;
  195693. }
  195694. else
  195695. #endif
  195696. {
  195697. s_start = 7;
  195698. s_end = 0;
  195699. s_inc = -1;
  195700. }
  195701. shift = s_start;
  195702. for (i = 0; i < row_width; i++)
  195703. {
  195704. if (m & mask)
  195705. {
  195706. int value;
  195707. value = (*sp >> shift) & 0x01;
  195708. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195709. *dp |= (png_byte)(value << shift);
  195710. }
  195711. if (shift == s_end)
  195712. {
  195713. shift = s_start;
  195714. sp++;
  195715. dp++;
  195716. }
  195717. else
  195718. shift += s_inc;
  195719. if (m == 1)
  195720. m = 0x80;
  195721. else
  195722. m >>= 1;
  195723. }
  195724. break;
  195725. }
  195726. case 2:
  195727. {
  195728. png_bytep sp = png_ptr->row_buf + 1;
  195729. png_bytep dp = row;
  195730. int s_start, s_end, s_inc;
  195731. int m = 0x80;
  195732. int shift;
  195733. png_uint_32 i;
  195734. png_uint_32 row_width = png_ptr->width;
  195735. int value;
  195736. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195737. if (png_ptr->transformations & PNG_PACKSWAP)
  195738. {
  195739. s_start = 0;
  195740. s_end = 6;
  195741. s_inc = 2;
  195742. }
  195743. else
  195744. #endif
  195745. {
  195746. s_start = 6;
  195747. s_end = 0;
  195748. s_inc = -2;
  195749. }
  195750. shift = s_start;
  195751. for (i = 0; i < row_width; i++)
  195752. {
  195753. if (m & mask)
  195754. {
  195755. value = (*sp >> shift) & 0x03;
  195756. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195757. *dp |= (png_byte)(value << shift);
  195758. }
  195759. if (shift == s_end)
  195760. {
  195761. shift = s_start;
  195762. sp++;
  195763. dp++;
  195764. }
  195765. else
  195766. shift += s_inc;
  195767. if (m == 1)
  195768. m = 0x80;
  195769. else
  195770. m >>= 1;
  195771. }
  195772. break;
  195773. }
  195774. case 4:
  195775. {
  195776. png_bytep sp = png_ptr->row_buf + 1;
  195777. png_bytep dp = row;
  195778. int s_start, s_end, s_inc;
  195779. int m = 0x80;
  195780. int shift;
  195781. png_uint_32 i;
  195782. png_uint_32 row_width = png_ptr->width;
  195783. int value;
  195784. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195785. if (png_ptr->transformations & PNG_PACKSWAP)
  195786. {
  195787. s_start = 0;
  195788. s_end = 4;
  195789. s_inc = 4;
  195790. }
  195791. else
  195792. #endif
  195793. {
  195794. s_start = 4;
  195795. s_end = 0;
  195796. s_inc = -4;
  195797. }
  195798. shift = s_start;
  195799. for (i = 0; i < row_width; i++)
  195800. {
  195801. if (m & mask)
  195802. {
  195803. value = (*sp >> shift) & 0xf;
  195804. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195805. *dp |= (png_byte)(value << shift);
  195806. }
  195807. if (shift == s_end)
  195808. {
  195809. shift = s_start;
  195810. sp++;
  195811. dp++;
  195812. }
  195813. else
  195814. shift += s_inc;
  195815. if (m == 1)
  195816. m = 0x80;
  195817. else
  195818. m >>= 1;
  195819. }
  195820. break;
  195821. }
  195822. default:
  195823. {
  195824. png_bytep sp = png_ptr->row_buf + 1;
  195825. png_bytep dp = row;
  195826. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195827. png_uint_32 i;
  195828. png_uint_32 row_width = png_ptr->width;
  195829. png_byte m = 0x80;
  195830. for (i = 0; i < row_width; i++)
  195831. {
  195832. if (m & mask)
  195833. {
  195834. png_memcpy(dp, sp, pixel_bytes);
  195835. }
  195836. sp += pixel_bytes;
  195837. dp += pixel_bytes;
  195838. if (m == 1)
  195839. m = 0x80;
  195840. else
  195841. m >>= 1;
  195842. }
  195843. break;
  195844. }
  195845. }
  195846. }
  195847. }
  195848. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195849. /* OLD pre-1.0.9 interface:
  195850. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195851. png_uint_32 transformations)
  195852. */
  195853. void /* PRIVATE */
  195854. png_do_read_interlace(png_structp png_ptr)
  195855. {
  195856. png_row_infop row_info = &(png_ptr->row_info);
  195857. png_bytep row = png_ptr->row_buf + 1;
  195858. int pass = png_ptr->pass;
  195859. png_uint_32 transformations = png_ptr->transformations;
  195860. #ifdef PNG_USE_LOCAL_ARRAYS
  195861. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195862. /* offset to next interlace block */
  195863. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195864. #endif
  195865. png_debug(1,"in png_do_read_interlace\n");
  195866. if (row != NULL && row_info != NULL)
  195867. {
  195868. png_uint_32 final_width;
  195869. final_width = row_info->width * png_pass_inc[pass];
  195870. switch (row_info->pixel_depth)
  195871. {
  195872. case 1:
  195873. {
  195874. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195875. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195876. int sshift, dshift;
  195877. int s_start, s_end, s_inc;
  195878. int jstop = png_pass_inc[pass];
  195879. png_byte v;
  195880. png_uint_32 i;
  195881. int j;
  195882. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195883. if (transformations & PNG_PACKSWAP)
  195884. {
  195885. sshift = (int)((row_info->width + 7) & 0x07);
  195886. dshift = (int)((final_width + 7) & 0x07);
  195887. s_start = 7;
  195888. s_end = 0;
  195889. s_inc = -1;
  195890. }
  195891. else
  195892. #endif
  195893. {
  195894. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195895. dshift = 7 - (int)((final_width + 7) & 0x07);
  195896. s_start = 0;
  195897. s_end = 7;
  195898. s_inc = 1;
  195899. }
  195900. for (i = 0; i < row_info->width; i++)
  195901. {
  195902. v = (png_byte)((*sp >> sshift) & 0x01);
  195903. for (j = 0; j < jstop; j++)
  195904. {
  195905. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195906. *dp |= (png_byte)(v << dshift);
  195907. if (dshift == s_end)
  195908. {
  195909. dshift = s_start;
  195910. dp--;
  195911. }
  195912. else
  195913. dshift += s_inc;
  195914. }
  195915. if (sshift == s_end)
  195916. {
  195917. sshift = s_start;
  195918. sp--;
  195919. }
  195920. else
  195921. sshift += s_inc;
  195922. }
  195923. break;
  195924. }
  195925. case 2:
  195926. {
  195927. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195928. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195929. int sshift, dshift;
  195930. int s_start, s_end, s_inc;
  195931. int jstop = png_pass_inc[pass];
  195932. png_uint_32 i;
  195933. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195934. if (transformations & PNG_PACKSWAP)
  195935. {
  195936. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195937. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195938. s_start = 6;
  195939. s_end = 0;
  195940. s_inc = -2;
  195941. }
  195942. else
  195943. #endif
  195944. {
  195945. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195946. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195947. s_start = 0;
  195948. s_end = 6;
  195949. s_inc = 2;
  195950. }
  195951. for (i = 0; i < row_info->width; i++)
  195952. {
  195953. png_byte v;
  195954. int j;
  195955. v = (png_byte)((*sp >> sshift) & 0x03);
  195956. for (j = 0; j < jstop; j++)
  195957. {
  195958. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195959. *dp |= (png_byte)(v << dshift);
  195960. if (dshift == s_end)
  195961. {
  195962. dshift = s_start;
  195963. dp--;
  195964. }
  195965. else
  195966. dshift += s_inc;
  195967. }
  195968. if (sshift == s_end)
  195969. {
  195970. sshift = s_start;
  195971. sp--;
  195972. }
  195973. else
  195974. sshift += s_inc;
  195975. }
  195976. break;
  195977. }
  195978. case 4:
  195979. {
  195980. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195981. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195982. int sshift, dshift;
  195983. int s_start, s_end, s_inc;
  195984. png_uint_32 i;
  195985. int jstop = png_pass_inc[pass];
  195986. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195987. if (transformations & PNG_PACKSWAP)
  195988. {
  195989. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195990. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195991. s_start = 4;
  195992. s_end = 0;
  195993. s_inc = -4;
  195994. }
  195995. else
  195996. #endif
  195997. {
  195998. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195999. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196000. s_start = 0;
  196001. s_end = 4;
  196002. s_inc = 4;
  196003. }
  196004. for (i = 0; i < row_info->width; i++)
  196005. {
  196006. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196007. int j;
  196008. for (j = 0; j < jstop; j++)
  196009. {
  196010. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196011. *dp |= (png_byte)(v << dshift);
  196012. if (dshift == s_end)
  196013. {
  196014. dshift = s_start;
  196015. dp--;
  196016. }
  196017. else
  196018. dshift += s_inc;
  196019. }
  196020. if (sshift == s_end)
  196021. {
  196022. sshift = s_start;
  196023. sp--;
  196024. }
  196025. else
  196026. sshift += s_inc;
  196027. }
  196028. break;
  196029. }
  196030. default:
  196031. {
  196032. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196033. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196034. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196035. int jstop = png_pass_inc[pass];
  196036. png_uint_32 i;
  196037. for (i = 0; i < row_info->width; i++)
  196038. {
  196039. png_byte v[8];
  196040. int j;
  196041. png_memcpy(v, sp, pixel_bytes);
  196042. for (j = 0; j < jstop; j++)
  196043. {
  196044. png_memcpy(dp, v, pixel_bytes);
  196045. dp -= pixel_bytes;
  196046. }
  196047. sp -= pixel_bytes;
  196048. }
  196049. break;
  196050. }
  196051. }
  196052. row_info->width = final_width;
  196053. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196054. }
  196055. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196056. transformations = transformations; /* silence compiler warning */
  196057. #endif
  196058. }
  196059. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196060. void /* PRIVATE */
  196061. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196062. png_bytep prev_row, int filter)
  196063. {
  196064. png_debug(1, "in png_read_filter_row\n");
  196065. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196066. switch (filter)
  196067. {
  196068. case PNG_FILTER_VALUE_NONE:
  196069. break;
  196070. case PNG_FILTER_VALUE_SUB:
  196071. {
  196072. png_uint_32 i;
  196073. png_uint_32 istop = row_info->rowbytes;
  196074. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196075. png_bytep rp = row + bpp;
  196076. png_bytep lp = row;
  196077. for (i = bpp; i < istop; i++)
  196078. {
  196079. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196080. rp++;
  196081. }
  196082. break;
  196083. }
  196084. case PNG_FILTER_VALUE_UP:
  196085. {
  196086. png_uint_32 i;
  196087. png_uint_32 istop = row_info->rowbytes;
  196088. png_bytep rp = row;
  196089. png_bytep pp = prev_row;
  196090. for (i = 0; i < istop; i++)
  196091. {
  196092. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196093. rp++;
  196094. }
  196095. break;
  196096. }
  196097. case PNG_FILTER_VALUE_AVG:
  196098. {
  196099. png_uint_32 i;
  196100. png_bytep rp = row;
  196101. png_bytep pp = prev_row;
  196102. png_bytep lp = row;
  196103. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196104. png_uint_32 istop = row_info->rowbytes - bpp;
  196105. for (i = 0; i < bpp; i++)
  196106. {
  196107. *rp = (png_byte)(((int)(*rp) +
  196108. ((int)(*pp++) / 2 )) & 0xff);
  196109. rp++;
  196110. }
  196111. for (i = 0; i < istop; i++)
  196112. {
  196113. *rp = (png_byte)(((int)(*rp) +
  196114. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196115. rp++;
  196116. }
  196117. break;
  196118. }
  196119. case PNG_FILTER_VALUE_PAETH:
  196120. {
  196121. png_uint_32 i;
  196122. png_bytep rp = row;
  196123. png_bytep pp = prev_row;
  196124. png_bytep lp = row;
  196125. png_bytep cp = prev_row;
  196126. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196127. png_uint_32 istop=row_info->rowbytes - bpp;
  196128. for (i = 0; i < bpp; i++)
  196129. {
  196130. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196131. rp++;
  196132. }
  196133. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196134. {
  196135. int a, b, c, pa, pb, pc, p;
  196136. a = *lp++;
  196137. b = *pp++;
  196138. c = *cp++;
  196139. p = b - c;
  196140. pc = a - c;
  196141. #ifdef PNG_USE_ABS
  196142. pa = abs(p);
  196143. pb = abs(pc);
  196144. pc = abs(p + pc);
  196145. #else
  196146. pa = p < 0 ? -p : p;
  196147. pb = pc < 0 ? -pc : pc;
  196148. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196149. #endif
  196150. /*
  196151. if (pa <= pb && pa <= pc)
  196152. p = a;
  196153. else if (pb <= pc)
  196154. p = b;
  196155. else
  196156. p = c;
  196157. */
  196158. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196159. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196160. rp++;
  196161. }
  196162. break;
  196163. }
  196164. default:
  196165. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196166. *row=0;
  196167. break;
  196168. }
  196169. }
  196170. void /* PRIVATE */
  196171. png_read_finish_row(png_structp png_ptr)
  196172. {
  196173. #ifdef PNG_USE_LOCAL_ARRAYS
  196174. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196175. /* start of interlace block */
  196176. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196177. /* offset to next interlace block */
  196178. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196179. /* start of interlace block in the y direction */
  196180. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196181. /* offset to next interlace block in the y direction */
  196182. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196183. #endif
  196184. png_debug(1, "in png_read_finish_row\n");
  196185. png_ptr->row_number++;
  196186. if (png_ptr->row_number < png_ptr->num_rows)
  196187. return;
  196188. if (png_ptr->interlaced)
  196189. {
  196190. png_ptr->row_number = 0;
  196191. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196192. png_ptr->rowbytes + 1);
  196193. do
  196194. {
  196195. png_ptr->pass++;
  196196. if (png_ptr->pass >= 7)
  196197. break;
  196198. png_ptr->iwidth = (png_ptr->width +
  196199. png_pass_inc[png_ptr->pass] - 1 -
  196200. png_pass_start[png_ptr->pass]) /
  196201. png_pass_inc[png_ptr->pass];
  196202. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196203. png_ptr->iwidth) + 1;
  196204. if (!(png_ptr->transformations & PNG_INTERLACE))
  196205. {
  196206. png_ptr->num_rows = (png_ptr->height +
  196207. png_pass_yinc[png_ptr->pass] - 1 -
  196208. png_pass_ystart[png_ptr->pass]) /
  196209. png_pass_yinc[png_ptr->pass];
  196210. if (!(png_ptr->num_rows))
  196211. continue;
  196212. }
  196213. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196214. break;
  196215. } while (png_ptr->iwidth == 0);
  196216. if (png_ptr->pass < 7)
  196217. return;
  196218. }
  196219. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196220. {
  196221. #ifdef PNG_USE_LOCAL_ARRAYS
  196222. PNG_CONST PNG_IDAT;
  196223. #endif
  196224. char extra;
  196225. int ret;
  196226. png_ptr->zstream.next_out = (Bytef *)&extra;
  196227. png_ptr->zstream.avail_out = (uInt)1;
  196228. for(;;)
  196229. {
  196230. if (!(png_ptr->zstream.avail_in))
  196231. {
  196232. while (!png_ptr->idat_size)
  196233. {
  196234. png_byte chunk_length[4];
  196235. png_crc_finish(png_ptr, 0);
  196236. png_read_data(png_ptr, chunk_length, 4);
  196237. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196238. png_reset_crc(png_ptr);
  196239. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196240. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196241. png_error(png_ptr, "Not enough image data");
  196242. }
  196243. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196244. png_ptr->zstream.next_in = png_ptr->zbuf;
  196245. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196246. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196247. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196248. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196249. }
  196250. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196251. if (ret == Z_STREAM_END)
  196252. {
  196253. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196254. png_ptr->idat_size)
  196255. png_warning(png_ptr, "Extra compressed data");
  196256. png_ptr->mode |= PNG_AFTER_IDAT;
  196257. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196258. break;
  196259. }
  196260. if (ret != Z_OK)
  196261. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196262. "Decompression Error");
  196263. if (!(png_ptr->zstream.avail_out))
  196264. {
  196265. png_warning(png_ptr, "Extra compressed data.");
  196266. png_ptr->mode |= PNG_AFTER_IDAT;
  196267. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196268. break;
  196269. }
  196270. }
  196271. png_ptr->zstream.avail_out = 0;
  196272. }
  196273. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196274. png_warning(png_ptr, "Extra compression data");
  196275. inflateReset(&png_ptr->zstream);
  196276. png_ptr->mode |= PNG_AFTER_IDAT;
  196277. }
  196278. void /* PRIVATE */
  196279. png_read_start_row(png_structp png_ptr)
  196280. {
  196281. #ifdef PNG_USE_LOCAL_ARRAYS
  196282. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196283. /* start of interlace block */
  196284. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196285. /* offset to next interlace block */
  196286. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196287. /* start of interlace block in the y direction */
  196288. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196289. /* offset to next interlace block in the y direction */
  196290. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196291. #endif
  196292. int max_pixel_depth;
  196293. png_uint_32 row_bytes;
  196294. png_debug(1, "in png_read_start_row\n");
  196295. png_ptr->zstream.avail_in = 0;
  196296. png_init_read_transformations(png_ptr);
  196297. if (png_ptr->interlaced)
  196298. {
  196299. if (!(png_ptr->transformations & PNG_INTERLACE))
  196300. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196301. png_pass_ystart[0]) / png_pass_yinc[0];
  196302. else
  196303. png_ptr->num_rows = png_ptr->height;
  196304. png_ptr->iwidth = (png_ptr->width +
  196305. png_pass_inc[png_ptr->pass] - 1 -
  196306. png_pass_start[png_ptr->pass]) /
  196307. png_pass_inc[png_ptr->pass];
  196308. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196309. png_ptr->irowbytes = (png_size_t)row_bytes;
  196310. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196311. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196312. }
  196313. else
  196314. {
  196315. png_ptr->num_rows = png_ptr->height;
  196316. png_ptr->iwidth = png_ptr->width;
  196317. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196318. }
  196319. max_pixel_depth = png_ptr->pixel_depth;
  196320. #if defined(PNG_READ_PACK_SUPPORTED)
  196321. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196322. max_pixel_depth = 8;
  196323. #endif
  196324. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196325. if (png_ptr->transformations & PNG_EXPAND)
  196326. {
  196327. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196328. {
  196329. if (png_ptr->num_trans)
  196330. max_pixel_depth = 32;
  196331. else
  196332. max_pixel_depth = 24;
  196333. }
  196334. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196335. {
  196336. if (max_pixel_depth < 8)
  196337. max_pixel_depth = 8;
  196338. if (png_ptr->num_trans)
  196339. max_pixel_depth *= 2;
  196340. }
  196341. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196342. {
  196343. if (png_ptr->num_trans)
  196344. {
  196345. max_pixel_depth *= 4;
  196346. max_pixel_depth /= 3;
  196347. }
  196348. }
  196349. }
  196350. #endif
  196351. #if defined(PNG_READ_FILLER_SUPPORTED)
  196352. if (png_ptr->transformations & (PNG_FILLER))
  196353. {
  196354. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196355. max_pixel_depth = 32;
  196356. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196357. {
  196358. if (max_pixel_depth <= 8)
  196359. max_pixel_depth = 16;
  196360. else
  196361. max_pixel_depth = 32;
  196362. }
  196363. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196364. {
  196365. if (max_pixel_depth <= 32)
  196366. max_pixel_depth = 32;
  196367. else
  196368. max_pixel_depth = 64;
  196369. }
  196370. }
  196371. #endif
  196372. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196373. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196374. {
  196375. if (
  196376. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196377. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196378. #endif
  196379. #if defined(PNG_READ_FILLER_SUPPORTED)
  196380. (png_ptr->transformations & (PNG_FILLER)) ||
  196381. #endif
  196382. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196383. {
  196384. if (max_pixel_depth <= 16)
  196385. max_pixel_depth = 32;
  196386. else
  196387. max_pixel_depth = 64;
  196388. }
  196389. else
  196390. {
  196391. if (max_pixel_depth <= 8)
  196392. {
  196393. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196394. max_pixel_depth = 32;
  196395. else
  196396. max_pixel_depth = 24;
  196397. }
  196398. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196399. max_pixel_depth = 64;
  196400. else
  196401. max_pixel_depth = 48;
  196402. }
  196403. }
  196404. #endif
  196405. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196406. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196407. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196408. {
  196409. int user_pixel_depth=png_ptr->user_transform_depth*
  196410. png_ptr->user_transform_channels;
  196411. if(user_pixel_depth > max_pixel_depth)
  196412. max_pixel_depth=user_pixel_depth;
  196413. }
  196414. #endif
  196415. /* align the width on the next larger 8 pixels. Mainly used
  196416. for interlacing */
  196417. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196418. /* calculate the maximum bytes needed, adding a byte and a pixel
  196419. for safety's sake */
  196420. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196421. 1 + ((max_pixel_depth + 7) >> 3);
  196422. #ifdef PNG_MAX_MALLOC_64K
  196423. if (row_bytes > (png_uint_32)65536L)
  196424. png_error(png_ptr, "This image requires a row greater than 64KB");
  196425. #endif
  196426. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196427. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196428. #ifdef PNG_MAX_MALLOC_64K
  196429. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196430. png_error(png_ptr, "This image requires a row greater than 64KB");
  196431. #endif
  196432. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196433. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196434. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196435. png_ptr->rowbytes + 1));
  196436. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196437. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196438. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196439. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196440. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196441. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196442. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196443. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196444. }
  196445. #endif /* PNG_READ_SUPPORTED */
  196446. /*** End of inlined file: pngrutil.c ***/
  196447. /*** Start of inlined file: pngset.c ***/
  196448. /* pngset.c - storage of image information into info struct
  196449. *
  196450. * Last changed in libpng 1.2.21 [October 4, 2007]
  196451. * For conditions of distribution and use, see copyright notice in png.h
  196452. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196453. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196454. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196455. *
  196456. * The functions here are used during reads to store data from the file
  196457. * into the info struct, and during writes to store application data
  196458. * into the info struct for writing into the file. This abstracts the
  196459. * info struct and allows us to change the structure in the future.
  196460. */
  196461. #define PNG_INTERNAL
  196462. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196463. #if defined(PNG_bKGD_SUPPORTED)
  196464. void PNGAPI
  196465. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196466. {
  196467. png_debug1(1, "in %s storage function\n", "bKGD");
  196468. if (png_ptr == NULL || info_ptr == NULL)
  196469. return;
  196470. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196471. info_ptr->valid |= PNG_INFO_bKGD;
  196472. }
  196473. #endif
  196474. #if defined(PNG_cHRM_SUPPORTED)
  196475. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196476. void PNGAPI
  196477. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196478. double white_x, double white_y, double red_x, double red_y,
  196479. double green_x, double green_y, double blue_x, double blue_y)
  196480. {
  196481. png_debug1(1, "in %s storage function\n", "cHRM");
  196482. if (png_ptr == NULL || info_ptr == NULL)
  196483. return;
  196484. if (white_x < 0.0 || white_y < 0.0 ||
  196485. red_x < 0.0 || red_y < 0.0 ||
  196486. green_x < 0.0 || green_y < 0.0 ||
  196487. blue_x < 0.0 || blue_y < 0.0)
  196488. {
  196489. png_warning(png_ptr,
  196490. "Ignoring attempt to set negative chromaticity value");
  196491. return;
  196492. }
  196493. if (white_x > 21474.83 || white_y > 21474.83 ||
  196494. red_x > 21474.83 || red_y > 21474.83 ||
  196495. green_x > 21474.83 || green_y > 21474.83 ||
  196496. blue_x > 21474.83 || blue_y > 21474.83)
  196497. {
  196498. png_warning(png_ptr,
  196499. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196500. return;
  196501. }
  196502. info_ptr->x_white = (float)white_x;
  196503. info_ptr->y_white = (float)white_y;
  196504. info_ptr->x_red = (float)red_x;
  196505. info_ptr->y_red = (float)red_y;
  196506. info_ptr->x_green = (float)green_x;
  196507. info_ptr->y_green = (float)green_y;
  196508. info_ptr->x_blue = (float)blue_x;
  196509. info_ptr->y_blue = (float)blue_y;
  196510. #ifdef PNG_FIXED_POINT_SUPPORTED
  196511. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196512. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196513. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196514. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196515. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196516. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196517. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196518. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196519. #endif
  196520. info_ptr->valid |= PNG_INFO_cHRM;
  196521. }
  196522. #endif
  196523. #ifdef PNG_FIXED_POINT_SUPPORTED
  196524. void PNGAPI
  196525. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196526. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196527. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196528. png_fixed_point blue_x, png_fixed_point blue_y)
  196529. {
  196530. png_debug1(1, "in %s storage function\n", "cHRM");
  196531. if (png_ptr == NULL || info_ptr == NULL)
  196532. return;
  196533. if (white_x < 0 || white_y < 0 ||
  196534. red_x < 0 || red_y < 0 ||
  196535. green_x < 0 || green_y < 0 ||
  196536. blue_x < 0 || blue_y < 0)
  196537. {
  196538. png_warning(png_ptr,
  196539. "Ignoring attempt to set negative chromaticity value");
  196540. return;
  196541. }
  196542. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196543. if (white_x > (double) PNG_UINT_31_MAX ||
  196544. white_y > (double) PNG_UINT_31_MAX ||
  196545. red_x > (double) PNG_UINT_31_MAX ||
  196546. red_y > (double) PNG_UINT_31_MAX ||
  196547. green_x > (double) PNG_UINT_31_MAX ||
  196548. green_y > (double) PNG_UINT_31_MAX ||
  196549. blue_x > (double) PNG_UINT_31_MAX ||
  196550. blue_y > (double) PNG_UINT_31_MAX)
  196551. #else
  196552. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196553. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196554. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196555. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196556. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196557. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196558. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196559. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196560. #endif
  196561. {
  196562. png_warning(png_ptr,
  196563. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196564. return;
  196565. }
  196566. info_ptr->int_x_white = white_x;
  196567. info_ptr->int_y_white = white_y;
  196568. info_ptr->int_x_red = red_x;
  196569. info_ptr->int_y_red = red_y;
  196570. info_ptr->int_x_green = green_x;
  196571. info_ptr->int_y_green = green_y;
  196572. info_ptr->int_x_blue = blue_x;
  196573. info_ptr->int_y_blue = blue_y;
  196574. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196575. info_ptr->x_white = (float)(white_x/100000.);
  196576. info_ptr->y_white = (float)(white_y/100000.);
  196577. info_ptr->x_red = (float)( red_x/100000.);
  196578. info_ptr->y_red = (float)( red_y/100000.);
  196579. info_ptr->x_green = (float)(green_x/100000.);
  196580. info_ptr->y_green = (float)(green_y/100000.);
  196581. info_ptr->x_blue = (float)( blue_x/100000.);
  196582. info_ptr->y_blue = (float)( blue_y/100000.);
  196583. #endif
  196584. info_ptr->valid |= PNG_INFO_cHRM;
  196585. }
  196586. #endif
  196587. #endif
  196588. #if defined(PNG_gAMA_SUPPORTED)
  196589. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196590. void PNGAPI
  196591. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196592. {
  196593. double gamma;
  196594. png_debug1(1, "in %s storage function\n", "gAMA");
  196595. if (png_ptr == NULL || info_ptr == NULL)
  196596. return;
  196597. /* Check for overflow */
  196598. if (file_gamma > 21474.83)
  196599. {
  196600. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196601. gamma=21474.83;
  196602. }
  196603. else
  196604. gamma=file_gamma;
  196605. info_ptr->gamma = (float)gamma;
  196606. #ifdef PNG_FIXED_POINT_SUPPORTED
  196607. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196608. #endif
  196609. info_ptr->valid |= PNG_INFO_gAMA;
  196610. if(gamma == 0.0)
  196611. png_warning(png_ptr, "Setting gamma=0");
  196612. }
  196613. #endif
  196614. void PNGAPI
  196615. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196616. int_gamma)
  196617. {
  196618. png_fixed_point gamma;
  196619. png_debug1(1, "in %s storage function\n", "gAMA");
  196620. if (png_ptr == NULL || info_ptr == NULL)
  196621. return;
  196622. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196623. {
  196624. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196625. gamma=PNG_UINT_31_MAX;
  196626. }
  196627. else
  196628. {
  196629. if (int_gamma < 0)
  196630. {
  196631. png_warning(png_ptr, "Setting negative gamma to zero");
  196632. gamma=0;
  196633. }
  196634. else
  196635. gamma=int_gamma;
  196636. }
  196637. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196638. info_ptr->gamma = (float)(gamma/100000.);
  196639. #endif
  196640. #ifdef PNG_FIXED_POINT_SUPPORTED
  196641. info_ptr->int_gamma = gamma;
  196642. #endif
  196643. info_ptr->valid |= PNG_INFO_gAMA;
  196644. if(gamma == 0)
  196645. png_warning(png_ptr, "Setting gamma=0");
  196646. }
  196647. #endif
  196648. #if defined(PNG_hIST_SUPPORTED)
  196649. void PNGAPI
  196650. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196651. {
  196652. int i;
  196653. png_debug1(1, "in %s storage function\n", "hIST");
  196654. if (png_ptr == NULL || info_ptr == NULL)
  196655. return;
  196656. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196657. > PNG_MAX_PALETTE_LENGTH)
  196658. {
  196659. png_warning(png_ptr,
  196660. "Invalid palette size, hIST allocation skipped.");
  196661. return;
  196662. }
  196663. #ifdef PNG_FREE_ME_SUPPORTED
  196664. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196665. #endif
  196666. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196667. 1.2.1 */
  196668. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196669. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196670. if (png_ptr->hist == NULL)
  196671. {
  196672. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196673. return;
  196674. }
  196675. for (i = 0; i < info_ptr->num_palette; i++)
  196676. png_ptr->hist[i] = hist[i];
  196677. info_ptr->hist = png_ptr->hist;
  196678. info_ptr->valid |= PNG_INFO_hIST;
  196679. #ifdef PNG_FREE_ME_SUPPORTED
  196680. info_ptr->free_me |= PNG_FREE_HIST;
  196681. #else
  196682. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196683. #endif
  196684. }
  196685. #endif
  196686. void PNGAPI
  196687. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196688. png_uint_32 width, png_uint_32 height, int bit_depth,
  196689. int color_type, int interlace_type, int compression_type,
  196690. int filter_type)
  196691. {
  196692. png_debug1(1, "in %s storage function\n", "IHDR");
  196693. if (png_ptr == NULL || info_ptr == NULL)
  196694. return;
  196695. /* check for width and height valid values */
  196696. if (width == 0 || height == 0)
  196697. png_error(png_ptr, "Image width or height is zero in IHDR");
  196698. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196699. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196700. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196701. #else
  196702. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196703. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196704. #endif
  196705. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196706. png_error(png_ptr, "Invalid image size in IHDR");
  196707. if ( width > (PNG_UINT_32_MAX
  196708. >> 3) /* 8-byte RGBA pixels */
  196709. - 64 /* bigrowbuf hack */
  196710. - 1 /* filter byte */
  196711. - 7*8 /* rounding of width to multiple of 8 pixels */
  196712. - 8) /* extra max_pixel_depth pad */
  196713. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196714. /* check other values */
  196715. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196716. bit_depth != 8 && bit_depth != 16)
  196717. png_error(png_ptr, "Invalid bit depth in IHDR");
  196718. if (color_type < 0 || color_type == 1 ||
  196719. color_type == 5 || color_type > 6)
  196720. png_error(png_ptr, "Invalid color type in IHDR");
  196721. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196722. ((color_type == PNG_COLOR_TYPE_RGB ||
  196723. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196724. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196725. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196726. if (interlace_type >= PNG_INTERLACE_LAST)
  196727. png_error(png_ptr, "Unknown interlace method in IHDR");
  196728. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196729. png_error(png_ptr, "Unknown compression method in IHDR");
  196730. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196731. /* Accept filter_method 64 (intrapixel differencing) only if
  196732. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196733. * 2. Libpng did not read a PNG signature (this filter_method is only
  196734. * used in PNG datastreams that are embedded in MNG datastreams) and
  196735. * 3. The application called png_permit_mng_features with a mask that
  196736. * included PNG_FLAG_MNG_FILTER_64 and
  196737. * 4. The filter_method is 64 and
  196738. * 5. The color_type is RGB or RGBA
  196739. */
  196740. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196741. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196742. if(filter_type != PNG_FILTER_TYPE_BASE)
  196743. {
  196744. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196745. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196746. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196747. (color_type == PNG_COLOR_TYPE_RGB ||
  196748. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196749. png_error(png_ptr, "Unknown filter method in IHDR");
  196750. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196751. png_warning(png_ptr, "Invalid filter method in IHDR");
  196752. }
  196753. #else
  196754. if(filter_type != PNG_FILTER_TYPE_BASE)
  196755. png_error(png_ptr, "Unknown filter method in IHDR");
  196756. #endif
  196757. info_ptr->width = width;
  196758. info_ptr->height = height;
  196759. info_ptr->bit_depth = (png_byte)bit_depth;
  196760. info_ptr->color_type =(png_byte) color_type;
  196761. info_ptr->compression_type = (png_byte)compression_type;
  196762. info_ptr->filter_type = (png_byte)filter_type;
  196763. info_ptr->interlace_type = (png_byte)interlace_type;
  196764. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196765. info_ptr->channels = 1;
  196766. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196767. info_ptr->channels = 3;
  196768. else
  196769. info_ptr->channels = 1;
  196770. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196771. info_ptr->channels++;
  196772. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196773. /* check for potential overflow */
  196774. if (width > (PNG_UINT_32_MAX
  196775. >> 3) /* 8-byte RGBA pixels */
  196776. - 64 /* bigrowbuf hack */
  196777. - 1 /* filter byte */
  196778. - 7*8 /* rounding of width to multiple of 8 pixels */
  196779. - 8) /* extra max_pixel_depth pad */
  196780. info_ptr->rowbytes = (png_size_t)0;
  196781. else
  196782. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196783. }
  196784. #if defined(PNG_oFFs_SUPPORTED)
  196785. void PNGAPI
  196786. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196787. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196788. {
  196789. png_debug1(1, "in %s storage function\n", "oFFs");
  196790. if (png_ptr == NULL || info_ptr == NULL)
  196791. return;
  196792. info_ptr->x_offset = offset_x;
  196793. info_ptr->y_offset = offset_y;
  196794. info_ptr->offset_unit_type = (png_byte)unit_type;
  196795. info_ptr->valid |= PNG_INFO_oFFs;
  196796. }
  196797. #endif
  196798. #if defined(PNG_pCAL_SUPPORTED)
  196799. void PNGAPI
  196800. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196801. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196802. png_charp units, png_charpp params)
  196803. {
  196804. png_uint_32 length;
  196805. int i;
  196806. png_debug1(1, "in %s storage function\n", "pCAL");
  196807. if (png_ptr == NULL || info_ptr == NULL)
  196808. return;
  196809. length = png_strlen(purpose) + 1;
  196810. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196811. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196812. if (info_ptr->pcal_purpose == NULL)
  196813. {
  196814. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196815. return;
  196816. }
  196817. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196818. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196819. info_ptr->pcal_X0 = X0;
  196820. info_ptr->pcal_X1 = X1;
  196821. info_ptr->pcal_type = (png_byte)type;
  196822. info_ptr->pcal_nparams = (png_byte)nparams;
  196823. length = png_strlen(units) + 1;
  196824. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196825. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196826. if (info_ptr->pcal_units == NULL)
  196827. {
  196828. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196829. return;
  196830. }
  196831. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196832. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196833. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196834. if (info_ptr->pcal_params == NULL)
  196835. {
  196836. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196837. return;
  196838. }
  196839. info_ptr->pcal_params[nparams] = NULL;
  196840. for (i = 0; i < nparams; i++)
  196841. {
  196842. length = png_strlen(params[i]) + 1;
  196843. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196844. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196845. if (info_ptr->pcal_params[i] == NULL)
  196846. {
  196847. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196848. return;
  196849. }
  196850. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196851. }
  196852. info_ptr->valid |= PNG_INFO_pCAL;
  196853. #ifdef PNG_FREE_ME_SUPPORTED
  196854. info_ptr->free_me |= PNG_FREE_PCAL;
  196855. #endif
  196856. }
  196857. #endif
  196858. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196859. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196860. void PNGAPI
  196861. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196862. int unit, double width, double height)
  196863. {
  196864. png_debug1(1, "in %s storage function\n", "sCAL");
  196865. if (png_ptr == NULL || info_ptr == NULL)
  196866. return;
  196867. info_ptr->scal_unit = (png_byte)unit;
  196868. info_ptr->scal_pixel_width = width;
  196869. info_ptr->scal_pixel_height = height;
  196870. info_ptr->valid |= PNG_INFO_sCAL;
  196871. }
  196872. #else
  196873. #ifdef PNG_FIXED_POINT_SUPPORTED
  196874. void PNGAPI
  196875. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196876. int unit, png_charp swidth, png_charp sheight)
  196877. {
  196878. png_uint_32 length;
  196879. png_debug1(1, "in %s storage function\n", "sCAL");
  196880. if (png_ptr == NULL || info_ptr == NULL)
  196881. return;
  196882. info_ptr->scal_unit = (png_byte)unit;
  196883. length = png_strlen(swidth) + 1;
  196884. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196885. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196886. if (info_ptr->scal_s_width == NULL)
  196887. {
  196888. png_warning(png_ptr,
  196889. "Memory allocation failed while processing sCAL.");
  196890. }
  196891. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196892. length = png_strlen(sheight) + 1;
  196893. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196894. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196895. if (info_ptr->scal_s_height == NULL)
  196896. {
  196897. png_free (png_ptr, info_ptr->scal_s_width);
  196898. png_warning(png_ptr,
  196899. "Memory allocation failed while processing sCAL.");
  196900. }
  196901. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196902. info_ptr->valid |= PNG_INFO_sCAL;
  196903. #ifdef PNG_FREE_ME_SUPPORTED
  196904. info_ptr->free_me |= PNG_FREE_SCAL;
  196905. #endif
  196906. }
  196907. #endif
  196908. #endif
  196909. #endif
  196910. #if defined(PNG_pHYs_SUPPORTED)
  196911. void PNGAPI
  196912. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196913. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196914. {
  196915. png_debug1(1, "in %s storage function\n", "pHYs");
  196916. if (png_ptr == NULL || info_ptr == NULL)
  196917. return;
  196918. info_ptr->x_pixels_per_unit = res_x;
  196919. info_ptr->y_pixels_per_unit = res_y;
  196920. info_ptr->phys_unit_type = (png_byte)unit_type;
  196921. info_ptr->valid |= PNG_INFO_pHYs;
  196922. }
  196923. #endif
  196924. void PNGAPI
  196925. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196926. png_colorp palette, int num_palette)
  196927. {
  196928. png_debug1(1, "in %s storage function\n", "PLTE");
  196929. if (png_ptr == NULL || info_ptr == NULL)
  196930. return;
  196931. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196932. {
  196933. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196934. png_error(png_ptr, "Invalid palette length");
  196935. else
  196936. {
  196937. png_warning(png_ptr, "Invalid palette length");
  196938. return;
  196939. }
  196940. }
  196941. /*
  196942. * It may not actually be necessary to set png_ptr->palette here;
  196943. * we do it for backward compatibility with the way the png_handle_tRNS
  196944. * function used to do the allocation.
  196945. */
  196946. #ifdef PNG_FREE_ME_SUPPORTED
  196947. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196948. #endif
  196949. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196950. of num_palette entries,
  196951. in case of an invalid PNG file that has too-large sample values. */
  196952. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196953. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196954. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196955. png_sizeof(png_color));
  196956. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196957. info_ptr->palette = png_ptr->palette;
  196958. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196959. #ifdef PNG_FREE_ME_SUPPORTED
  196960. info_ptr->free_me |= PNG_FREE_PLTE;
  196961. #else
  196962. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196963. #endif
  196964. info_ptr->valid |= PNG_INFO_PLTE;
  196965. }
  196966. #if defined(PNG_sBIT_SUPPORTED)
  196967. void PNGAPI
  196968. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196969. png_color_8p sig_bit)
  196970. {
  196971. png_debug1(1, "in %s storage function\n", "sBIT");
  196972. if (png_ptr == NULL || info_ptr == NULL)
  196973. return;
  196974. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196975. info_ptr->valid |= PNG_INFO_sBIT;
  196976. }
  196977. #endif
  196978. #if defined(PNG_sRGB_SUPPORTED)
  196979. void PNGAPI
  196980. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196981. {
  196982. png_debug1(1, "in %s storage function\n", "sRGB");
  196983. if (png_ptr == NULL || info_ptr == NULL)
  196984. return;
  196985. info_ptr->srgb_intent = (png_byte)intent;
  196986. info_ptr->valid |= PNG_INFO_sRGB;
  196987. }
  196988. void PNGAPI
  196989. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196990. int intent)
  196991. {
  196992. #if defined(PNG_gAMA_SUPPORTED)
  196993. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196994. float file_gamma;
  196995. #endif
  196996. #ifdef PNG_FIXED_POINT_SUPPORTED
  196997. png_fixed_point int_file_gamma;
  196998. #endif
  196999. #endif
  197000. #if defined(PNG_cHRM_SUPPORTED)
  197001. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197002. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197003. #endif
  197004. #ifdef PNG_FIXED_POINT_SUPPORTED
  197005. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197006. int_green_y, int_blue_x, int_blue_y;
  197007. #endif
  197008. #endif
  197009. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197010. if (png_ptr == NULL || info_ptr == NULL)
  197011. return;
  197012. png_set_sRGB(png_ptr, info_ptr, intent);
  197013. #if defined(PNG_gAMA_SUPPORTED)
  197014. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197015. file_gamma = (float).45455;
  197016. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197017. #endif
  197018. #ifdef PNG_FIXED_POINT_SUPPORTED
  197019. int_file_gamma = 45455L;
  197020. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197021. #endif
  197022. #endif
  197023. #if defined(PNG_cHRM_SUPPORTED)
  197024. #ifdef PNG_FIXED_POINT_SUPPORTED
  197025. int_white_x = 31270L;
  197026. int_white_y = 32900L;
  197027. int_red_x = 64000L;
  197028. int_red_y = 33000L;
  197029. int_green_x = 30000L;
  197030. int_green_y = 60000L;
  197031. int_blue_x = 15000L;
  197032. int_blue_y = 6000L;
  197033. png_set_cHRM_fixed(png_ptr, info_ptr,
  197034. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197035. int_blue_x, int_blue_y);
  197036. #endif
  197037. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197038. white_x = (float).3127;
  197039. white_y = (float).3290;
  197040. red_x = (float).64;
  197041. red_y = (float).33;
  197042. green_x = (float).30;
  197043. green_y = (float).60;
  197044. blue_x = (float).15;
  197045. blue_y = (float).06;
  197046. png_set_cHRM(png_ptr, info_ptr,
  197047. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197048. #endif
  197049. #endif
  197050. }
  197051. #endif
  197052. #if defined(PNG_iCCP_SUPPORTED)
  197053. void PNGAPI
  197054. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197055. png_charp name, int compression_type,
  197056. png_charp profile, png_uint_32 proflen)
  197057. {
  197058. png_charp new_iccp_name;
  197059. png_charp new_iccp_profile;
  197060. png_debug1(1, "in %s storage function\n", "iCCP");
  197061. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197062. return;
  197063. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197064. if (new_iccp_name == NULL)
  197065. {
  197066. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197067. return;
  197068. }
  197069. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197070. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197071. if (new_iccp_profile == NULL)
  197072. {
  197073. png_free (png_ptr, new_iccp_name);
  197074. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197075. return;
  197076. }
  197077. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197078. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197079. info_ptr->iccp_proflen = proflen;
  197080. info_ptr->iccp_name = new_iccp_name;
  197081. info_ptr->iccp_profile = new_iccp_profile;
  197082. /* Compression is always zero but is here so the API and info structure
  197083. * does not have to change if we introduce multiple compression types */
  197084. info_ptr->iccp_compression = (png_byte)compression_type;
  197085. #ifdef PNG_FREE_ME_SUPPORTED
  197086. info_ptr->free_me |= PNG_FREE_ICCP;
  197087. #endif
  197088. info_ptr->valid |= PNG_INFO_iCCP;
  197089. }
  197090. #endif
  197091. #if defined(PNG_TEXT_SUPPORTED)
  197092. void PNGAPI
  197093. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197094. int num_text)
  197095. {
  197096. int ret;
  197097. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197098. if (ret)
  197099. png_error(png_ptr, "Insufficient memory to store text");
  197100. }
  197101. int /* PRIVATE */
  197102. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197103. int num_text)
  197104. {
  197105. int i;
  197106. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197107. "text" : (png_const_charp)png_ptr->chunk_name));
  197108. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197109. return(0);
  197110. /* Make sure we have enough space in the "text" array in info_struct
  197111. * to hold all of the incoming text_ptr objects.
  197112. */
  197113. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197114. {
  197115. if (info_ptr->text != NULL)
  197116. {
  197117. png_textp old_text;
  197118. int old_max;
  197119. old_max = info_ptr->max_text;
  197120. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197121. old_text = info_ptr->text;
  197122. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197123. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197124. if (info_ptr->text == NULL)
  197125. {
  197126. png_free(png_ptr, old_text);
  197127. return(1);
  197128. }
  197129. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197130. png_sizeof(png_text)));
  197131. png_free(png_ptr, old_text);
  197132. }
  197133. else
  197134. {
  197135. info_ptr->max_text = num_text + 8;
  197136. info_ptr->num_text = 0;
  197137. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197138. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197139. if (info_ptr->text == NULL)
  197140. return(1);
  197141. #ifdef PNG_FREE_ME_SUPPORTED
  197142. info_ptr->free_me |= PNG_FREE_TEXT;
  197143. #endif
  197144. }
  197145. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197146. info_ptr->max_text);
  197147. }
  197148. for (i = 0; i < num_text; i++)
  197149. {
  197150. png_size_t text_length,key_len;
  197151. png_size_t lang_len,lang_key_len;
  197152. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197153. if (text_ptr[i].key == NULL)
  197154. continue;
  197155. key_len = png_strlen(text_ptr[i].key);
  197156. if(text_ptr[i].compression <= 0)
  197157. {
  197158. lang_len = 0;
  197159. lang_key_len = 0;
  197160. }
  197161. else
  197162. #ifdef PNG_iTXt_SUPPORTED
  197163. {
  197164. /* set iTXt data */
  197165. if (text_ptr[i].lang != NULL)
  197166. lang_len = png_strlen(text_ptr[i].lang);
  197167. else
  197168. lang_len = 0;
  197169. if (text_ptr[i].lang_key != NULL)
  197170. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197171. else
  197172. lang_key_len = 0;
  197173. }
  197174. #else
  197175. {
  197176. png_warning(png_ptr, "iTXt chunk not supported.");
  197177. continue;
  197178. }
  197179. #endif
  197180. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197181. {
  197182. text_length = 0;
  197183. #ifdef PNG_iTXt_SUPPORTED
  197184. if(text_ptr[i].compression > 0)
  197185. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197186. else
  197187. #endif
  197188. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197189. }
  197190. else
  197191. {
  197192. text_length = png_strlen(text_ptr[i].text);
  197193. textp->compression = text_ptr[i].compression;
  197194. }
  197195. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197196. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197197. if (textp->key == NULL)
  197198. return(1);
  197199. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197200. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197201. (int)textp->key);
  197202. png_memcpy(textp->key, text_ptr[i].key,
  197203. (png_size_t)(key_len));
  197204. *(textp->key+key_len) = '\0';
  197205. #ifdef PNG_iTXt_SUPPORTED
  197206. if (text_ptr[i].compression > 0)
  197207. {
  197208. textp->lang=textp->key + key_len + 1;
  197209. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197210. *(textp->lang+lang_len) = '\0';
  197211. textp->lang_key=textp->lang + lang_len + 1;
  197212. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197213. *(textp->lang_key+lang_key_len) = '\0';
  197214. textp->text=textp->lang_key + lang_key_len + 1;
  197215. }
  197216. else
  197217. #endif
  197218. {
  197219. #ifdef PNG_iTXt_SUPPORTED
  197220. textp->lang=NULL;
  197221. textp->lang_key=NULL;
  197222. #endif
  197223. textp->text=textp->key + key_len + 1;
  197224. }
  197225. if(text_length)
  197226. png_memcpy(textp->text, text_ptr[i].text,
  197227. (png_size_t)(text_length));
  197228. *(textp->text+text_length) = '\0';
  197229. #ifdef PNG_iTXt_SUPPORTED
  197230. if(textp->compression > 0)
  197231. {
  197232. textp->text_length = 0;
  197233. textp->itxt_length = text_length;
  197234. }
  197235. else
  197236. #endif
  197237. {
  197238. textp->text_length = text_length;
  197239. #ifdef PNG_iTXt_SUPPORTED
  197240. textp->itxt_length = 0;
  197241. #endif
  197242. }
  197243. info_ptr->num_text++;
  197244. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197245. }
  197246. return(0);
  197247. }
  197248. #endif
  197249. #if defined(PNG_tIME_SUPPORTED)
  197250. void PNGAPI
  197251. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197252. {
  197253. png_debug1(1, "in %s storage function\n", "tIME");
  197254. if (png_ptr == NULL || info_ptr == NULL ||
  197255. (png_ptr->mode & PNG_WROTE_tIME))
  197256. return;
  197257. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197258. info_ptr->valid |= PNG_INFO_tIME;
  197259. }
  197260. #endif
  197261. #if defined(PNG_tRNS_SUPPORTED)
  197262. void PNGAPI
  197263. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197264. png_bytep trans, int num_trans, png_color_16p trans_values)
  197265. {
  197266. png_debug1(1, "in %s storage function\n", "tRNS");
  197267. if (png_ptr == NULL || info_ptr == NULL)
  197268. return;
  197269. if (trans != NULL)
  197270. {
  197271. /*
  197272. * It may not actually be necessary to set png_ptr->trans here;
  197273. * we do it for backward compatibility with the way the png_handle_tRNS
  197274. * function used to do the allocation.
  197275. */
  197276. #ifdef PNG_FREE_ME_SUPPORTED
  197277. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197278. #endif
  197279. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197280. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197281. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197282. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197283. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197284. #ifdef PNG_FREE_ME_SUPPORTED
  197285. info_ptr->free_me |= PNG_FREE_TRNS;
  197286. #else
  197287. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197288. #endif
  197289. }
  197290. if (trans_values != NULL)
  197291. {
  197292. png_memcpy(&(info_ptr->trans_values), trans_values,
  197293. png_sizeof(png_color_16));
  197294. if (num_trans == 0)
  197295. num_trans = 1;
  197296. }
  197297. info_ptr->num_trans = (png_uint_16)num_trans;
  197298. info_ptr->valid |= PNG_INFO_tRNS;
  197299. }
  197300. #endif
  197301. #if defined(PNG_sPLT_SUPPORTED)
  197302. void PNGAPI
  197303. png_set_sPLT(png_structp png_ptr,
  197304. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197305. {
  197306. png_sPLT_tp np;
  197307. int i;
  197308. if (png_ptr == NULL || info_ptr == NULL)
  197309. return;
  197310. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197311. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197312. if (np == NULL)
  197313. {
  197314. png_warning(png_ptr, "No memory for sPLT palettes.");
  197315. return;
  197316. }
  197317. png_memcpy(np, info_ptr->splt_palettes,
  197318. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197319. png_free(png_ptr, info_ptr->splt_palettes);
  197320. info_ptr->splt_palettes=NULL;
  197321. for (i = 0; i < nentries; i++)
  197322. {
  197323. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197324. png_sPLT_tp from = entries + i;
  197325. to->name = (png_charp)png_malloc_warn(png_ptr,
  197326. png_strlen(from->name) + 1);
  197327. if (to->name == NULL)
  197328. {
  197329. png_warning(png_ptr,
  197330. "Out of memory while processing sPLT chunk");
  197331. }
  197332. /* TODO: use png_malloc_warn */
  197333. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197334. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197335. from->nentries * png_sizeof(png_sPLT_entry));
  197336. /* TODO: use png_malloc_warn */
  197337. png_memcpy(to->entries, from->entries,
  197338. from->nentries * png_sizeof(png_sPLT_entry));
  197339. if (to->entries == NULL)
  197340. {
  197341. png_warning(png_ptr,
  197342. "Out of memory while processing sPLT chunk");
  197343. png_free(png_ptr,to->name);
  197344. to->name = NULL;
  197345. }
  197346. to->nentries = from->nentries;
  197347. to->depth = from->depth;
  197348. }
  197349. info_ptr->splt_palettes = np;
  197350. info_ptr->splt_palettes_num += nentries;
  197351. info_ptr->valid |= PNG_INFO_sPLT;
  197352. #ifdef PNG_FREE_ME_SUPPORTED
  197353. info_ptr->free_me |= PNG_FREE_SPLT;
  197354. #endif
  197355. }
  197356. #endif /* PNG_sPLT_SUPPORTED */
  197357. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197358. void PNGAPI
  197359. png_set_unknown_chunks(png_structp png_ptr,
  197360. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197361. {
  197362. png_unknown_chunkp np;
  197363. int i;
  197364. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197365. return;
  197366. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197367. (info_ptr->unknown_chunks_num + num_unknowns) *
  197368. png_sizeof(png_unknown_chunk));
  197369. if (np == NULL)
  197370. {
  197371. png_warning(png_ptr,
  197372. "Out of memory while processing unknown chunk.");
  197373. return;
  197374. }
  197375. png_memcpy(np, info_ptr->unknown_chunks,
  197376. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197377. png_free(png_ptr, info_ptr->unknown_chunks);
  197378. info_ptr->unknown_chunks=NULL;
  197379. for (i = 0; i < num_unknowns; i++)
  197380. {
  197381. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197382. png_unknown_chunkp from = unknowns + i;
  197383. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197384. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197385. if (to->data == NULL)
  197386. {
  197387. png_warning(png_ptr,
  197388. "Out of memory while processing unknown chunk.");
  197389. }
  197390. else
  197391. {
  197392. png_memcpy(to->data, from->data, from->size);
  197393. to->size = from->size;
  197394. /* note our location in the read or write sequence */
  197395. to->location = (png_byte)(png_ptr->mode & 0xff);
  197396. }
  197397. }
  197398. info_ptr->unknown_chunks = np;
  197399. info_ptr->unknown_chunks_num += num_unknowns;
  197400. #ifdef PNG_FREE_ME_SUPPORTED
  197401. info_ptr->free_me |= PNG_FREE_UNKN;
  197402. #endif
  197403. }
  197404. void PNGAPI
  197405. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197406. int chunk, int location)
  197407. {
  197408. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197409. (int)info_ptr->unknown_chunks_num)
  197410. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197411. }
  197412. #endif
  197413. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197414. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197415. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197416. void PNGAPI
  197417. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197418. {
  197419. /* This function is deprecated in favor of png_permit_mng_features()
  197420. and will be removed from libpng-1.3.0 */
  197421. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197422. if (png_ptr == NULL)
  197423. return;
  197424. png_ptr->mng_features_permitted = (png_byte)
  197425. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197426. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197427. }
  197428. #endif
  197429. #endif
  197430. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197431. png_uint_32 PNGAPI
  197432. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197433. {
  197434. png_debug(1, "in png_permit_mng_features\n");
  197435. if (png_ptr == NULL)
  197436. return (png_uint_32)0;
  197437. png_ptr->mng_features_permitted =
  197438. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197439. return (png_uint_32)png_ptr->mng_features_permitted;
  197440. }
  197441. #endif
  197442. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197443. void PNGAPI
  197444. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197445. chunk_list, int num_chunks)
  197446. {
  197447. png_bytep new_list, p;
  197448. int i, old_num_chunks;
  197449. if (png_ptr == NULL)
  197450. return;
  197451. if (num_chunks == 0)
  197452. {
  197453. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197454. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197455. else
  197456. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197457. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197458. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197459. else
  197460. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197461. return;
  197462. }
  197463. if (chunk_list == NULL)
  197464. return;
  197465. old_num_chunks=png_ptr->num_chunk_list;
  197466. new_list=(png_bytep)png_malloc(png_ptr,
  197467. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197468. if(png_ptr->chunk_list != NULL)
  197469. {
  197470. png_memcpy(new_list, png_ptr->chunk_list,
  197471. (png_size_t)(5*old_num_chunks));
  197472. png_free(png_ptr, png_ptr->chunk_list);
  197473. png_ptr->chunk_list=NULL;
  197474. }
  197475. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197476. (png_size_t)(5*num_chunks));
  197477. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197478. *p=(png_byte)keep;
  197479. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197480. png_ptr->chunk_list=new_list;
  197481. #ifdef PNG_FREE_ME_SUPPORTED
  197482. png_ptr->free_me |= PNG_FREE_LIST;
  197483. #endif
  197484. }
  197485. #endif
  197486. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197487. void PNGAPI
  197488. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197489. png_user_chunk_ptr read_user_chunk_fn)
  197490. {
  197491. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197492. if (png_ptr == NULL)
  197493. return;
  197494. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197495. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197496. }
  197497. #endif
  197498. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197499. void PNGAPI
  197500. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197501. {
  197502. png_debug1(1, "in %s storage function\n", "rows");
  197503. if (png_ptr == NULL || info_ptr == NULL)
  197504. return;
  197505. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197506. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197507. info_ptr->row_pointers = row_pointers;
  197508. if(row_pointers)
  197509. info_ptr->valid |= PNG_INFO_IDAT;
  197510. }
  197511. #endif
  197512. #ifdef PNG_WRITE_SUPPORTED
  197513. void PNGAPI
  197514. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197515. {
  197516. if (png_ptr == NULL)
  197517. return;
  197518. if(png_ptr->zbuf)
  197519. png_free(png_ptr, png_ptr->zbuf);
  197520. png_ptr->zbuf_size = (png_size_t)size;
  197521. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197522. png_ptr->zstream.next_out = png_ptr->zbuf;
  197523. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197524. }
  197525. #endif
  197526. void PNGAPI
  197527. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197528. {
  197529. if (png_ptr && info_ptr)
  197530. info_ptr->valid &= ~(mask);
  197531. }
  197532. #ifndef PNG_1_0_X
  197533. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197534. /* function was added to libpng 1.2.0 and should always exist by default */
  197535. void PNGAPI
  197536. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197537. {
  197538. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197539. if (png_ptr != NULL)
  197540. png_ptr->asm_flags = 0;
  197541. }
  197542. /* this function was added to libpng 1.2.0 */
  197543. void PNGAPI
  197544. png_set_mmx_thresholds (png_structp png_ptr,
  197545. png_byte,
  197546. png_uint_32)
  197547. {
  197548. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197549. if (png_ptr == NULL)
  197550. return;
  197551. }
  197552. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197553. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197554. /* this function was added to libpng 1.2.6 */
  197555. void PNGAPI
  197556. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197557. png_uint_32 user_height_max)
  197558. {
  197559. /* Images with dimensions larger than these limits will be
  197560. * rejected by png_set_IHDR(). To accept any PNG datastream
  197561. * regardless of dimensions, set both limits to 0x7ffffffL.
  197562. */
  197563. if(png_ptr == NULL) return;
  197564. png_ptr->user_width_max = user_width_max;
  197565. png_ptr->user_height_max = user_height_max;
  197566. }
  197567. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197568. #endif /* ?PNG_1_0_X */
  197569. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197570. /*** End of inlined file: pngset.c ***/
  197571. /*** Start of inlined file: pngtrans.c ***/
  197572. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197573. *
  197574. * Last changed in libpng 1.2.17 May 15, 2007
  197575. * For conditions of distribution and use, see copyright notice in png.h
  197576. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197577. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197578. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197579. */
  197580. #define PNG_INTERNAL
  197581. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197582. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197583. /* turn on BGR-to-RGB mapping */
  197584. void PNGAPI
  197585. png_set_bgr(png_structp png_ptr)
  197586. {
  197587. png_debug(1, "in png_set_bgr\n");
  197588. if(png_ptr == NULL) return;
  197589. png_ptr->transformations |= PNG_BGR;
  197590. }
  197591. #endif
  197592. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197593. /* turn on 16 bit byte swapping */
  197594. void PNGAPI
  197595. png_set_swap(png_structp png_ptr)
  197596. {
  197597. png_debug(1, "in png_set_swap\n");
  197598. if(png_ptr == NULL) return;
  197599. if (png_ptr->bit_depth == 16)
  197600. png_ptr->transformations |= PNG_SWAP_BYTES;
  197601. }
  197602. #endif
  197603. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197604. /* turn on pixel packing */
  197605. void PNGAPI
  197606. png_set_packing(png_structp png_ptr)
  197607. {
  197608. png_debug(1, "in png_set_packing\n");
  197609. if(png_ptr == NULL) return;
  197610. if (png_ptr->bit_depth < 8)
  197611. {
  197612. png_ptr->transformations |= PNG_PACK;
  197613. png_ptr->usr_bit_depth = 8;
  197614. }
  197615. }
  197616. #endif
  197617. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197618. /* turn on packed pixel swapping */
  197619. void PNGAPI
  197620. png_set_packswap(png_structp png_ptr)
  197621. {
  197622. png_debug(1, "in png_set_packswap\n");
  197623. if(png_ptr == NULL) return;
  197624. if (png_ptr->bit_depth < 8)
  197625. png_ptr->transformations |= PNG_PACKSWAP;
  197626. }
  197627. #endif
  197628. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197629. void PNGAPI
  197630. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197631. {
  197632. png_debug(1, "in png_set_shift\n");
  197633. if(png_ptr == NULL) return;
  197634. png_ptr->transformations |= PNG_SHIFT;
  197635. png_ptr->shift = *true_bits;
  197636. }
  197637. #endif
  197638. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197639. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197640. int PNGAPI
  197641. png_set_interlace_handling(png_structp png_ptr)
  197642. {
  197643. png_debug(1, "in png_set_interlace handling\n");
  197644. if (png_ptr && png_ptr->interlaced)
  197645. {
  197646. png_ptr->transformations |= PNG_INTERLACE;
  197647. return (7);
  197648. }
  197649. return (1);
  197650. }
  197651. #endif
  197652. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197653. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197654. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197655. * for 48-bit input data, as well as to avoid problems with some compilers
  197656. * that don't like bytes as parameters.
  197657. */
  197658. void PNGAPI
  197659. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197660. {
  197661. png_debug(1, "in png_set_filler\n");
  197662. if(png_ptr == NULL) return;
  197663. png_ptr->transformations |= PNG_FILLER;
  197664. png_ptr->filler = (png_byte)filler;
  197665. if (filler_loc == PNG_FILLER_AFTER)
  197666. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197667. else
  197668. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197669. /* This should probably go in the "do_read_filler" routine.
  197670. * I attempted to do that in libpng-1.0.1a but that caused problems
  197671. * so I restored it in libpng-1.0.2a
  197672. */
  197673. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197674. {
  197675. png_ptr->usr_channels = 4;
  197676. }
  197677. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197678. * a less-than-8-bit grayscale to GA? */
  197679. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197680. {
  197681. png_ptr->usr_channels = 2;
  197682. }
  197683. }
  197684. #if !defined(PNG_1_0_X)
  197685. /* Added to libpng-1.2.7 */
  197686. void PNGAPI
  197687. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197688. {
  197689. png_debug(1, "in png_set_add_alpha\n");
  197690. if(png_ptr == NULL) return;
  197691. png_set_filler(png_ptr, filler, filler_loc);
  197692. png_ptr->transformations |= PNG_ADD_ALPHA;
  197693. }
  197694. #endif
  197695. #endif
  197696. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197697. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197698. void PNGAPI
  197699. png_set_swap_alpha(png_structp png_ptr)
  197700. {
  197701. png_debug(1, "in png_set_swap_alpha\n");
  197702. if(png_ptr == NULL) return;
  197703. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197704. }
  197705. #endif
  197706. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197707. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197708. void PNGAPI
  197709. png_set_invert_alpha(png_structp png_ptr)
  197710. {
  197711. png_debug(1, "in png_set_invert_alpha\n");
  197712. if(png_ptr == NULL) return;
  197713. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197714. }
  197715. #endif
  197716. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197717. void PNGAPI
  197718. png_set_invert_mono(png_structp png_ptr)
  197719. {
  197720. png_debug(1, "in png_set_invert_mono\n");
  197721. if(png_ptr == NULL) return;
  197722. png_ptr->transformations |= PNG_INVERT_MONO;
  197723. }
  197724. /* invert monochrome grayscale data */
  197725. void /* PRIVATE */
  197726. png_do_invert(png_row_infop row_info, png_bytep row)
  197727. {
  197728. png_debug(1, "in png_do_invert\n");
  197729. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197730. * if (row_info->bit_depth == 1 &&
  197731. */
  197732. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197733. if (row == NULL || row_info == NULL)
  197734. return;
  197735. #endif
  197736. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197737. {
  197738. png_bytep rp = row;
  197739. png_uint_32 i;
  197740. png_uint_32 istop = row_info->rowbytes;
  197741. for (i = 0; i < istop; i++)
  197742. {
  197743. *rp = (png_byte)(~(*rp));
  197744. rp++;
  197745. }
  197746. }
  197747. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197748. row_info->bit_depth == 8)
  197749. {
  197750. png_bytep rp = row;
  197751. png_uint_32 i;
  197752. png_uint_32 istop = row_info->rowbytes;
  197753. for (i = 0; i < istop; i+=2)
  197754. {
  197755. *rp = (png_byte)(~(*rp));
  197756. rp+=2;
  197757. }
  197758. }
  197759. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197760. row_info->bit_depth == 16)
  197761. {
  197762. png_bytep rp = row;
  197763. png_uint_32 i;
  197764. png_uint_32 istop = row_info->rowbytes;
  197765. for (i = 0; i < istop; i+=4)
  197766. {
  197767. *rp = (png_byte)(~(*rp));
  197768. *(rp+1) = (png_byte)(~(*(rp+1)));
  197769. rp+=4;
  197770. }
  197771. }
  197772. }
  197773. #endif
  197774. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197775. /* swaps byte order on 16 bit depth images */
  197776. void /* PRIVATE */
  197777. png_do_swap(png_row_infop row_info, png_bytep row)
  197778. {
  197779. png_debug(1, "in png_do_swap\n");
  197780. if (
  197781. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197782. row != NULL && row_info != NULL &&
  197783. #endif
  197784. row_info->bit_depth == 16)
  197785. {
  197786. png_bytep rp = row;
  197787. png_uint_32 i;
  197788. png_uint_32 istop= row_info->width * row_info->channels;
  197789. for (i = 0; i < istop; i++, rp += 2)
  197790. {
  197791. png_byte t = *rp;
  197792. *rp = *(rp + 1);
  197793. *(rp + 1) = t;
  197794. }
  197795. }
  197796. }
  197797. #endif
  197798. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197799. static PNG_CONST png_byte onebppswaptable[256] = {
  197800. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197801. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197802. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197803. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197804. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197805. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197806. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197807. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197808. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197809. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197810. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197811. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197812. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197813. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197814. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197815. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197816. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197817. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197818. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197819. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197820. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197821. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197822. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197823. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197824. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197825. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197826. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197827. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197828. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197829. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197830. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197831. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197832. };
  197833. static PNG_CONST png_byte twobppswaptable[256] = {
  197834. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197835. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197836. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197837. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197838. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197839. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197840. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197841. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197842. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197843. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197844. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197845. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197846. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197847. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197848. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197849. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197850. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197851. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197852. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197853. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197854. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197855. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197856. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197857. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197858. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197859. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197860. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197861. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197862. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197863. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197864. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197865. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197866. };
  197867. static PNG_CONST png_byte fourbppswaptable[256] = {
  197868. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197869. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197870. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197871. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197872. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197873. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197874. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197875. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197876. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197877. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197878. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197879. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197880. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197881. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197882. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197883. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197884. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197885. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197886. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197887. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197888. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197889. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197890. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197891. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197892. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197893. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197894. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197895. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197896. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197897. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197898. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197899. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197900. };
  197901. /* swaps pixel packing order within bytes */
  197902. void /* PRIVATE */
  197903. png_do_packswap(png_row_infop row_info, png_bytep row)
  197904. {
  197905. png_debug(1, "in png_do_packswap\n");
  197906. if (
  197907. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197908. row != NULL && row_info != NULL &&
  197909. #endif
  197910. row_info->bit_depth < 8)
  197911. {
  197912. png_bytep rp, end, table;
  197913. end = row + row_info->rowbytes;
  197914. if (row_info->bit_depth == 1)
  197915. table = (png_bytep)onebppswaptable;
  197916. else if (row_info->bit_depth == 2)
  197917. table = (png_bytep)twobppswaptable;
  197918. else if (row_info->bit_depth == 4)
  197919. table = (png_bytep)fourbppswaptable;
  197920. else
  197921. return;
  197922. for (rp = row; rp < end; rp++)
  197923. *rp = table[*rp];
  197924. }
  197925. }
  197926. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197927. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197928. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197929. /* remove filler or alpha byte(s) */
  197930. void /* PRIVATE */
  197931. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197932. {
  197933. png_debug(1, "in png_do_strip_filler\n");
  197934. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197935. if (row != NULL && row_info != NULL)
  197936. #endif
  197937. {
  197938. png_bytep sp=row;
  197939. png_bytep dp=row;
  197940. png_uint_32 row_width=row_info->width;
  197941. png_uint_32 i;
  197942. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197943. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197944. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197945. row_info->channels == 4)
  197946. {
  197947. if (row_info->bit_depth == 8)
  197948. {
  197949. /* This converts from RGBX or RGBA to RGB */
  197950. if (flags & PNG_FLAG_FILLER_AFTER)
  197951. {
  197952. dp+=3; sp+=4;
  197953. for (i = 1; i < row_width; i++)
  197954. {
  197955. *dp++ = *sp++;
  197956. *dp++ = *sp++;
  197957. *dp++ = *sp++;
  197958. sp++;
  197959. }
  197960. }
  197961. /* This converts from XRGB or ARGB to RGB */
  197962. else
  197963. {
  197964. for (i = 0; i < row_width; i++)
  197965. {
  197966. sp++;
  197967. *dp++ = *sp++;
  197968. *dp++ = *sp++;
  197969. *dp++ = *sp++;
  197970. }
  197971. }
  197972. row_info->pixel_depth = 24;
  197973. row_info->rowbytes = row_width * 3;
  197974. }
  197975. else /* if (row_info->bit_depth == 16) */
  197976. {
  197977. if (flags & PNG_FLAG_FILLER_AFTER)
  197978. {
  197979. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197980. sp += 8; dp += 6;
  197981. for (i = 1; i < row_width; i++)
  197982. {
  197983. /* This could be (although png_memcpy is probably slower):
  197984. png_memcpy(dp, sp, 6);
  197985. sp += 8;
  197986. dp += 6;
  197987. */
  197988. *dp++ = *sp++;
  197989. *dp++ = *sp++;
  197990. *dp++ = *sp++;
  197991. *dp++ = *sp++;
  197992. *dp++ = *sp++;
  197993. *dp++ = *sp++;
  197994. sp += 2;
  197995. }
  197996. }
  197997. else
  197998. {
  197999. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198000. for (i = 0; i < row_width; i++)
  198001. {
  198002. /* This could be (although png_memcpy is probably slower):
  198003. png_memcpy(dp, sp, 6);
  198004. sp += 8;
  198005. dp += 6;
  198006. */
  198007. sp+=2;
  198008. *dp++ = *sp++;
  198009. *dp++ = *sp++;
  198010. *dp++ = *sp++;
  198011. *dp++ = *sp++;
  198012. *dp++ = *sp++;
  198013. *dp++ = *sp++;
  198014. }
  198015. }
  198016. row_info->pixel_depth = 48;
  198017. row_info->rowbytes = row_width * 6;
  198018. }
  198019. row_info->channels = 3;
  198020. }
  198021. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198022. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198023. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198024. row_info->channels == 2)
  198025. {
  198026. if (row_info->bit_depth == 8)
  198027. {
  198028. /* This converts from GX or GA to G */
  198029. if (flags & PNG_FLAG_FILLER_AFTER)
  198030. {
  198031. for (i = 0; i < row_width; i++)
  198032. {
  198033. *dp++ = *sp++;
  198034. sp++;
  198035. }
  198036. }
  198037. /* This converts from XG or AG to G */
  198038. else
  198039. {
  198040. for (i = 0; i < row_width; i++)
  198041. {
  198042. sp++;
  198043. *dp++ = *sp++;
  198044. }
  198045. }
  198046. row_info->pixel_depth = 8;
  198047. row_info->rowbytes = row_width;
  198048. }
  198049. else /* if (row_info->bit_depth == 16) */
  198050. {
  198051. if (flags & PNG_FLAG_FILLER_AFTER)
  198052. {
  198053. /* This converts from GGXX or GGAA to GG */
  198054. sp += 4; dp += 2;
  198055. for (i = 1; i < row_width; i++)
  198056. {
  198057. *dp++ = *sp++;
  198058. *dp++ = *sp++;
  198059. sp += 2;
  198060. }
  198061. }
  198062. else
  198063. {
  198064. /* This converts from XXGG or AAGG to GG */
  198065. for (i = 0; i < row_width; i++)
  198066. {
  198067. sp += 2;
  198068. *dp++ = *sp++;
  198069. *dp++ = *sp++;
  198070. }
  198071. }
  198072. row_info->pixel_depth = 16;
  198073. row_info->rowbytes = row_width * 2;
  198074. }
  198075. row_info->channels = 1;
  198076. }
  198077. if (flags & PNG_FLAG_STRIP_ALPHA)
  198078. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198079. }
  198080. }
  198081. #endif
  198082. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198083. /* swaps red and blue bytes within a pixel */
  198084. void /* PRIVATE */
  198085. png_do_bgr(png_row_infop row_info, png_bytep row)
  198086. {
  198087. png_debug(1, "in png_do_bgr\n");
  198088. if (
  198089. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198090. row != NULL && row_info != NULL &&
  198091. #endif
  198092. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198093. {
  198094. png_uint_32 row_width = row_info->width;
  198095. if (row_info->bit_depth == 8)
  198096. {
  198097. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198098. {
  198099. png_bytep rp;
  198100. png_uint_32 i;
  198101. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198102. {
  198103. png_byte save = *rp;
  198104. *rp = *(rp + 2);
  198105. *(rp + 2) = save;
  198106. }
  198107. }
  198108. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198109. {
  198110. png_bytep rp;
  198111. png_uint_32 i;
  198112. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198113. {
  198114. png_byte save = *rp;
  198115. *rp = *(rp + 2);
  198116. *(rp + 2) = save;
  198117. }
  198118. }
  198119. }
  198120. else if (row_info->bit_depth == 16)
  198121. {
  198122. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198123. {
  198124. png_bytep rp;
  198125. png_uint_32 i;
  198126. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198127. {
  198128. png_byte save = *rp;
  198129. *rp = *(rp + 4);
  198130. *(rp + 4) = save;
  198131. save = *(rp + 1);
  198132. *(rp + 1) = *(rp + 5);
  198133. *(rp + 5) = save;
  198134. }
  198135. }
  198136. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198137. {
  198138. png_bytep rp;
  198139. png_uint_32 i;
  198140. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198141. {
  198142. png_byte save = *rp;
  198143. *rp = *(rp + 4);
  198144. *(rp + 4) = save;
  198145. save = *(rp + 1);
  198146. *(rp + 1) = *(rp + 5);
  198147. *(rp + 5) = save;
  198148. }
  198149. }
  198150. }
  198151. }
  198152. }
  198153. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198154. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198155. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198156. defined(PNG_LEGACY_SUPPORTED)
  198157. void PNGAPI
  198158. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198159. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198160. {
  198161. png_debug(1, "in png_set_user_transform_info\n");
  198162. if(png_ptr == NULL) return;
  198163. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198164. png_ptr->user_transform_ptr = user_transform_ptr;
  198165. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198166. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198167. #else
  198168. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198169. png_warning(png_ptr,
  198170. "This version of libpng does not support user transform info");
  198171. #endif
  198172. }
  198173. #endif
  198174. /* This function returns a pointer to the user_transform_ptr associated with
  198175. * the user transform functions. The application should free any memory
  198176. * associated with this pointer before png_write_destroy and png_read_destroy
  198177. * are called.
  198178. */
  198179. png_voidp PNGAPI
  198180. png_get_user_transform_ptr(png_structp png_ptr)
  198181. {
  198182. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198183. if (png_ptr == NULL) return (NULL);
  198184. return ((png_voidp)png_ptr->user_transform_ptr);
  198185. #else
  198186. return (NULL);
  198187. #endif
  198188. }
  198189. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198190. /*** End of inlined file: pngtrans.c ***/
  198191. /*** Start of inlined file: pngwio.c ***/
  198192. /* pngwio.c - functions for data output
  198193. *
  198194. * Last changed in libpng 1.2.13 November 13, 2006
  198195. * For conditions of distribution and use, see copyright notice in png.h
  198196. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198197. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198198. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198199. *
  198200. * This file provides a location for all output. Users who need
  198201. * special handling are expected to write functions that have the same
  198202. * arguments as these and perform similar functions, but that possibly
  198203. * use different output methods. Note that you shouldn't change these
  198204. * functions, but rather write replacement functions and then change
  198205. * them at run time with png_set_write_fn(...).
  198206. */
  198207. #define PNG_INTERNAL
  198208. #ifdef PNG_WRITE_SUPPORTED
  198209. /* Write the data to whatever output you are using. The default routine
  198210. writes to a file pointer. Note that this routine sometimes gets called
  198211. with very small lengths, so you should implement some kind of simple
  198212. buffering if you are using unbuffered writes. This should never be asked
  198213. to write more than 64K on a 16 bit machine. */
  198214. void /* PRIVATE */
  198215. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198216. {
  198217. if (png_ptr->write_data_fn != NULL )
  198218. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198219. else
  198220. png_error(png_ptr, "Call to NULL write function");
  198221. }
  198222. #if !defined(PNG_NO_STDIO)
  198223. /* This is the function that does the actual writing of data. If you are
  198224. not writing to a standard C stream, you should create a replacement
  198225. write_data function and use it at run time with png_set_write_fn(), rather
  198226. than changing the library. */
  198227. #ifndef USE_FAR_KEYWORD
  198228. void PNGAPI
  198229. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198230. {
  198231. png_uint_32 check;
  198232. if(png_ptr == NULL) return;
  198233. #if defined(_WIN32_WCE)
  198234. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198235. check = 0;
  198236. #else
  198237. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198238. #endif
  198239. if (check != length)
  198240. png_error(png_ptr, "Write Error");
  198241. }
  198242. #else
  198243. /* this is the model-independent version. Since the standard I/O library
  198244. can't handle far buffers in the medium and small models, we have to copy
  198245. the data.
  198246. */
  198247. #define NEAR_BUF_SIZE 1024
  198248. #define MIN(a,b) (a <= b ? a : b)
  198249. void PNGAPI
  198250. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198251. {
  198252. png_uint_32 check;
  198253. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198254. png_FILE_p io_ptr;
  198255. if(png_ptr == NULL) return;
  198256. /* Check if data really is near. If so, use usual code. */
  198257. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198258. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198259. if ((png_bytep)near_data == data)
  198260. {
  198261. #if defined(_WIN32_WCE)
  198262. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198263. check = 0;
  198264. #else
  198265. check = fwrite(near_data, 1, length, io_ptr);
  198266. #endif
  198267. }
  198268. else
  198269. {
  198270. png_byte buf[NEAR_BUF_SIZE];
  198271. png_size_t written, remaining, err;
  198272. check = 0;
  198273. remaining = length;
  198274. do
  198275. {
  198276. written = MIN(NEAR_BUF_SIZE, remaining);
  198277. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198278. #if defined(_WIN32_WCE)
  198279. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198280. err = 0;
  198281. #else
  198282. err = fwrite(buf, 1, written, io_ptr);
  198283. #endif
  198284. if (err != written)
  198285. break;
  198286. else
  198287. check += err;
  198288. data += written;
  198289. remaining -= written;
  198290. }
  198291. while (remaining != 0);
  198292. }
  198293. if (check != length)
  198294. png_error(png_ptr, "Write Error");
  198295. }
  198296. #endif
  198297. #endif
  198298. /* This function is called to output any data pending writing (normally
  198299. to disk). After png_flush is called, there should be no data pending
  198300. writing in any buffers. */
  198301. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198302. void /* PRIVATE */
  198303. png_flush(png_structp png_ptr)
  198304. {
  198305. if (png_ptr->output_flush_fn != NULL)
  198306. (*(png_ptr->output_flush_fn))(png_ptr);
  198307. }
  198308. #if !defined(PNG_NO_STDIO)
  198309. void PNGAPI
  198310. png_default_flush(png_structp png_ptr)
  198311. {
  198312. #if !defined(_WIN32_WCE)
  198313. png_FILE_p io_ptr;
  198314. #endif
  198315. if(png_ptr == NULL) return;
  198316. #if !defined(_WIN32_WCE)
  198317. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198318. if (io_ptr != NULL)
  198319. fflush(io_ptr);
  198320. #endif
  198321. }
  198322. #endif
  198323. #endif
  198324. /* This function allows the application to supply new output functions for
  198325. libpng if standard C streams aren't being used.
  198326. This function takes as its arguments:
  198327. png_ptr - pointer to a png output data structure
  198328. io_ptr - pointer to user supplied structure containing info about
  198329. the output functions. May be NULL.
  198330. write_data_fn - pointer to a new output function that takes as its
  198331. arguments a pointer to a png_struct, a pointer to
  198332. data to be written, and a 32-bit unsigned int that is
  198333. the number of bytes to be written. The new write
  198334. function should call png_error(png_ptr, "Error msg")
  198335. to exit and output any fatal error messages.
  198336. flush_data_fn - pointer to a new flush function that takes as its
  198337. arguments a pointer to a png_struct. After a call to
  198338. the flush function, there should be no data in any buffers
  198339. or pending transmission. If the output method doesn't do
  198340. any buffering of ouput, a function prototype must still be
  198341. supplied although it doesn't have to do anything. If
  198342. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198343. time, output_flush_fn will be ignored, although it must be
  198344. supplied for compatibility. */
  198345. void PNGAPI
  198346. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198347. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198348. {
  198349. if(png_ptr == NULL) return;
  198350. png_ptr->io_ptr = io_ptr;
  198351. #if !defined(PNG_NO_STDIO)
  198352. if (write_data_fn != NULL)
  198353. png_ptr->write_data_fn = write_data_fn;
  198354. else
  198355. png_ptr->write_data_fn = png_default_write_data;
  198356. #else
  198357. png_ptr->write_data_fn = write_data_fn;
  198358. #endif
  198359. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198360. #if !defined(PNG_NO_STDIO)
  198361. if (output_flush_fn != NULL)
  198362. png_ptr->output_flush_fn = output_flush_fn;
  198363. else
  198364. png_ptr->output_flush_fn = png_default_flush;
  198365. #else
  198366. png_ptr->output_flush_fn = output_flush_fn;
  198367. #endif
  198368. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198369. /* It is an error to read while writing a png file */
  198370. if (png_ptr->read_data_fn != NULL)
  198371. {
  198372. png_ptr->read_data_fn = NULL;
  198373. png_warning(png_ptr,
  198374. "Attempted to set both read_data_fn and write_data_fn in");
  198375. png_warning(png_ptr,
  198376. "the same structure. Resetting read_data_fn to NULL.");
  198377. }
  198378. }
  198379. #if defined(USE_FAR_KEYWORD)
  198380. #if defined(_MSC_VER)
  198381. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198382. {
  198383. void *near_ptr;
  198384. void FAR *far_ptr;
  198385. FP_OFF(near_ptr) = FP_OFF(ptr);
  198386. far_ptr = (void FAR *)near_ptr;
  198387. if(check != 0)
  198388. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198389. png_error(png_ptr,"segment lost in conversion");
  198390. return(near_ptr);
  198391. }
  198392. # else
  198393. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198394. {
  198395. void *near_ptr;
  198396. void FAR *far_ptr;
  198397. near_ptr = (void FAR *)ptr;
  198398. far_ptr = (void FAR *)near_ptr;
  198399. if(check != 0)
  198400. if(far_ptr != ptr)
  198401. png_error(png_ptr,"segment lost in conversion");
  198402. return(near_ptr);
  198403. }
  198404. # endif
  198405. # endif
  198406. #endif /* PNG_WRITE_SUPPORTED */
  198407. /*** End of inlined file: pngwio.c ***/
  198408. /*** Start of inlined file: pngwrite.c ***/
  198409. /* pngwrite.c - general routines to write a PNG file
  198410. *
  198411. * Last changed in libpng 1.2.15 January 5, 2007
  198412. * For conditions of distribution and use, see copyright notice in png.h
  198413. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198414. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198415. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198416. */
  198417. /* get internal access to png.h */
  198418. #define PNG_INTERNAL
  198419. #ifdef PNG_WRITE_SUPPORTED
  198420. /* Writes all the PNG information. This is the suggested way to use the
  198421. * library. If you have a new chunk to add, make a function to write it,
  198422. * and put it in the correct location here. If you want the chunk written
  198423. * after the image data, put it in png_write_end(). I strongly encourage
  198424. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198425. * the chunk, as that will keep the code from breaking if you want to just
  198426. * write a plain PNG file. If you have long comments, I suggest writing
  198427. * them in png_write_end(), and compressing them.
  198428. */
  198429. void PNGAPI
  198430. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198431. {
  198432. png_debug(1, "in png_write_info_before_PLTE\n");
  198433. if (png_ptr == NULL || info_ptr == NULL)
  198434. return;
  198435. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198436. {
  198437. png_write_sig(png_ptr); /* write PNG signature */
  198438. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198439. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198440. {
  198441. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198442. png_ptr->mng_features_permitted=0;
  198443. }
  198444. #endif
  198445. /* write IHDR information. */
  198446. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198447. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198448. info_ptr->filter_type,
  198449. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198450. info_ptr->interlace_type);
  198451. #else
  198452. 0);
  198453. #endif
  198454. /* the rest of these check to see if the valid field has the appropriate
  198455. flag set, and if it does, writes the chunk. */
  198456. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198457. if (info_ptr->valid & PNG_INFO_gAMA)
  198458. {
  198459. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198460. png_write_gAMA(png_ptr, info_ptr->gamma);
  198461. #else
  198462. #ifdef PNG_FIXED_POINT_SUPPORTED
  198463. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198464. # endif
  198465. #endif
  198466. }
  198467. #endif
  198468. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198469. if (info_ptr->valid & PNG_INFO_sRGB)
  198470. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198471. #endif
  198472. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198473. if (info_ptr->valid & PNG_INFO_iCCP)
  198474. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198475. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198476. #endif
  198477. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198478. if (info_ptr->valid & PNG_INFO_sBIT)
  198479. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198480. #endif
  198481. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198482. if (info_ptr->valid & PNG_INFO_cHRM)
  198483. {
  198484. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198485. png_write_cHRM(png_ptr,
  198486. info_ptr->x_white, info_ptr->y_white,
  198487. info_ptr->x_red, info_ptr->y_red,
  198488. info_ptr->x_green, info_ptr->y_green,
  198489. info_ptr->x_blue, info_ptr->y_blue);
  198490. #else
  198491. # ifdef PNG_FIXED_POINT_SUPPORTED
  198492. png_write_cHRM_fixed(png_ptr,
  198493. info_ptr->int_x_white, info_ptr->int_y_white,
  198494. info_ptr->int_x_red, info_ptr->int_y_red,
  198495. info_ptr->int_x_green, info_ptr->int_y_green,
  198496. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198497. # endif
  198498. #endif
  198499. }
  198500. #endif
  198501. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198502. if (info_ptr->unknown_chunks_num)
  198503. {
  198504. png_unknown_chunk *up;
  198505. png_debug(5, "writing extra chunks\n");
  198506. for (up = info_ptr->unknown_chunks;
  198507. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198508. up++)
  198509. {
  198510. int keep=png_handle_as_unknown(png_ptr, up->name);
  198511. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198512. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198513. !(up->location & PNG_HAVE_IDAT) &&
  198514. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198515. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198516. {
  198517. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198518. }
  198519. }
  198520. }
  198521. #endif
  198522. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198523. }
  198524. }
  198525. void PNGAPI
  198526. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198527. {
  198528. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198529. int i;
  198530. #endif
  198531. png_debug(1, "in png_write_info\n");
  198532. if (png_ptr == NULL || info_ptr == NULL)
  198533. return;
  198534. png_write_info_before_PLTE(png_ptr, info_ptr);
  198535. if (info_ptr->valid & PNG_INFO_PLTE)
  198536. png_write_PLTE(png_ptr, info_ptr->palette,
  198537. (png_uint_32)info_ptr->num_palette);
  198538. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198539. png_error(png_ptr, "Valid palette required for paletted images");
  198540. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198541. if (info_ptr->valid & PNG_INFO_tRNS)
  198542. {
  198543. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198544. /* invert the alpha channel (in tRNS) */
  198545. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198546. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198547. {
  198548. int j;
  198549. for (j=0; j<(int)info_ptr->num_trans; j++)
  198550. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198551. }
  198552. #endif
  198553. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198554. info_ptr->num_trans, info_ptr->color_type);
  198555. }
  198556. #endif
  198557. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198558. if (info_ptr->valid & PNG_INFO_bKGD)
  198559. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198560. #endif
  198561. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198562. if (info_ptr->valid & PNG_INFO_hIST)
  198563. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198564. #endif
  198565. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198566. if (info_ptr->valid & PNG_INFO_oFFs)
  198567. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198568. info_ptr->offset_unit_type);
  198569. #endif
  198570. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198571. if (info_ptr->valid & PNG_INFO_pCAL)
  198572. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198573. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198574. info_ptr->pcal_units, info_ptr->pcal_params);
  198575. #endif
  198576. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198577. if (info_ptr->valid & PNG_INFO_sCAL)
  198578. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198579. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198580. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198581. #else
  198582. #ifdef PNG_FIXED_POINT_SUPPORTED
  198583. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198584. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198585. #else
  198586. png_warning(png_ptr,
  198587. "png_write_sCAL not supported; sCAL chunk not written.");
  198588. #endif
  198589. #endif
  198590. #endif
  198591. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198592. if (info_ptr->valid & PNG_INFO_pHYs)
  198593. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198594. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198595. #endif
  198596. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198597. if (info_ptr->valid & PNG_INFO_tIME)
  198598. {
  198599. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198600. png_ptr->mode |= PNG_WROTE_tIME;
  198601. }
  198602. #endif
  198603. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198604. if (info_ptr->valid & PNG_INFO_sPLT)
  198605. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198606. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198607. #endif
  198608. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198609. /* Check to see if we need to write text chunks */
  198610. for (i = 0; i < info_ptr->num_text; i++)
  198611. {
  198612. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198613. info_ptr->text[i].compression);
  198614. /* an internationalized chunk? */
  198615. if (info_ptr->text[i].compression > 0)
  198616. {
  198617. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198618. /* write international chunk */
  198619. png_write_iTXt(png_ptr,
  198620. info_ptr->text[i].compression,
  198621. info_ptr->text[i].key,
  198622. info_ptr->text[i].lang,
  198623. info_ptr->text[i].lang_key,
  198624. info_ptr->text[i].text);
  198625. #else
  198626. png_warning(png_ptr, "Unable to write international text");
  198627. #endif
  198628. /* Mark this chunk as written */
  198629. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198630. }
  198631. /* If we want a compressed text chunk */
  198632. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198633. {
  198634. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198635. /* write compressed chunk */
  198636. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198637. info_ptr->text[i].text, 0,
  198638. info_ptr->text[i].compression);
  198639. #else
  198640. png_warning(png_ptr, "Unable to write compressed text");
  198641. #endif
  198642. /* Mark this chunk as written */
  198643. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198644. }
  198645. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198646. {
  198647. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198648. /* write uncompressed chunk */
  198649. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198650. info_ptr->text[i].text,
  198651. 0);
  198652. #else
  198653. png_warning(png_ptr, "Unable to write uncompressed text");
  198654. #endif
  198655. /* Mark this chunk as written */
  198656. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198657. }
  198658. }
  198659. #endif
  198660. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198661. if (info_ptr->unknown_chunks_num)
  198662. {
  198663. png_unknown_chunk *up;
  198664. png_debug(5, "writing extra chunks\n");
  198665. for (up = info_ptr->unknown_chunks;
  198666. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198667. up++)
  198668. {
  198669. int keep=png_handle_as_unknown(png_ptr, up->name);
  198670. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198671. up->location && (up->location & PNG_HAVE_PLTE) &&
  198672. !(up->location & PNG_HAVE_IDAT) &&
  198673. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198674. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198675. {
  198676. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198677. }
  198678. }
  198679. }
  198680. #endif
  198681. }
  198682. /* Writes the end of the PNG file. If you don't want to write comments or
  198683. * time information, you can pass NULL for info. If you already wrote these
  198684. * in png_write_info(), do not write them again here. If you have long
  198685. * comments, I suggest writing them here, and compressing them.
  198686. */
  198687. void PNGAPI
  198688. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198689. {
  198690. png_debug(1, "in png_write_end\n");
  198691. if (png_ptr == NULL)
  198692. return;
  198693. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198694. png_error(png_ptr, "No IDATs written into file");
  198695. /* see if user wants us to write information chunks */
  198696. if (info_ptr != NULL)
  198697. {
  198698. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198699. int i; /* local index variable */
  198700. #endif
  198701. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198702. /* check to see if user has supplied a time chunk */
  198703. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198704. !(png_ptr->mode & PNG_WROTE_tIME))
  198705. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198706. #endif
  198707. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198708. /* loop through comment chunks */
  198709. for (i = 0; i < info_ptr->num_text; i++)
  198710. {
  198711. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198712. info_ptr->text[i].compression);
  198713. /* an internationalized chunk? */
  198714. if (info_ptr->text[i].compression > 0)
  198715. {
  198716. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198717. /* write international chunk */
  198718. png_write_iTXt(png_ptr,
  198719. info_ptr->text[i].compression,
  198720. info_ptr->text[i].key,
  198721. info_ptr->text[i].lang,
  198722. info_ptr->text[i].lang_key,
  198723. info_ptr->text[i].text);
  198724. #else
  198725. png_warning(png_ptr, "Unable to write international text");
  198726. #endif
  198727. /* Mark this chunk as written */
  198728. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198729. }
  198730. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198731. {
  198732. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198733. /* write compressed chunk */
  198734. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198735. info_ptr->text[i].text, 0,
  198736. info_ptr->text[i].compression);
  198737. #else
  198738. png_warning(png_ptr, "Unable to write compressed text");
  198739. #endif
  198740. /* Mark this chunk as written */
  198741. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198742. }
  198743. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198744. {
  198745. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198746. /* write uncompressed chunk */
  198747. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198748. info_ptr->text[i].text, 0);
  198749. #else
  198750. png_warning(png_ptr, "Unable to write uncompressed text");
  198751. #endif
  198752. /* Mark this chunk as written */
  198753. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198754. }
  198755. }
  198756. #endif
  198757. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198758. if (info_ptr->unknown_chunks_num)
  198759. {
  198760. png_unknown_chunk *up;
  198761. png_debug(5, "writing extra chunks\n");
  198762. for (up = info_ptr->unknown_chunks;
  198763. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198764. up++)
  198765. {
  198766. int keep=png_handle_as_unknown(png_ptr, up->name);
  198767. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198768. up->location && (up->location & PNG_AFTER_IDAT) &&
  198769. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198770. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198771. {
  198772. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198773. }
  198774. }
  198775. }
  198776. #endif
  198777. }
  198778. png_ptr->mode |= PNG_AFTER_IDAT;
  198779. /* write end of PNG file */
  198780. png_write_IEND(png_ptr);
  198781. }
  198782. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198783. #if !defined(_WIN32_WCE)
  198784. /* "time.h" functions are not supported on WindowsCE */
  198785. void PNGAPI
  198786. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198787. {
  198788. png_debug(1, "in png_convert_from_struct_tm\n");
  198789. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198790. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198791. ptime->day = (png_byte)ttime->tm_mday;
  198792. ptime->hour = (png_byte)ttime->tm_hour;
  198793. ptime->minute = (png_byte)ttime->tm_min;
  198794. ptime->second = (png_byte)ttime->tm_sec;
  198795. }
  198796. void PNGAPI
  198797. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198798. {
  198799. struct tm *tbuf;
  198800. png_debug(1, "in png_convert_from_time_t\n");
  198801. tbuf = gmtime(&ttime);
  198802. png_convert_from_struct_tm(ptime, tbuf);
  198803. }
  198804. #endif
  198805. #endif
  198806. /* Initialize png_ptr structure, and allocate any memory needed */
  198807. png_structp PNGAPI
  198808. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198809. png_error_ptr error_fn, png_error_ptr warn_fn)
  198810. {
  198811. #ifdef PNG_USER_MEM_SUPPORTED
  198812. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198813. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198814. }
  198815. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198816. png_structp PNGAPI
  198817. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198818. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198819. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198820. {
  198821. #endif /* PNG_USER_MEM_SUPPORTED */
  198822. png_structp png_ptr;
  198823. #ifdef PNG_SETJMP_SUPPORTED
  198824. #ifdef USE_FAR_KEYWORD
  198825. jmp_buf jmpbuf;
  198826. #endif
  198827. #endif
  198828. int i;
  198829. png_debug(1, "in png_create_write_struct\n");
  198830. #ifdef PNG_USER_MEM_SUPPORTED
  198831. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198832. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198833. #else
  198834. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198835. #endif /* PNG_USER_MEM_SUPPORTED */
  198836. if (png_ptr == NULL)
  198837. return (NULL);
  198838. /* added at libpng-1.2.6 */
  198839. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198840. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198841. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198842. #endif
  198843. #ifdef PNG_SETJMP_SUPPORTED
  198844. #ifdef USE_FAR_KEYWORD
  198845. if (setjmp(jmpbuf))
  198846. #else
  198847. if (setjmp(png_ptr->jmpbuf))
  198848. #endif
  198849. {
  198850. png_free(png_ptr, png_ptr->zbuf);
  198851. png_ptr->zbuf=NULL;
  198852. png_destroy_struct(png_ptr);
  198853. return (NULL);
  198854. }
  198855. #ifdef USE_FAR_KEYWORD
  198856. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198857. #endif
  198858. #endif
  198859. #ifdef PNG_USER_MEM_SUPPORTED
  198860. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198861. #endif /* PNG_USER_MEM_SUPPORTED */
  198862. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198863. i=0;
  198864. do
  198865. {
  198866. if(user_png_ver[i] != png_libpng_ver[i])
  198867. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198868. } while (png_libpng_ver[i++]);
  198869. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198870. {
  198871. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198872. * we must recompile any applications that use any older library version.
  198873. * For versions after libpng 1.0, we will be compatible, so we need
  198874. * only check the first digit.
  198875. */
  198876. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198877. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198878. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198879. {
  198880. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198881. char msg[80];
  198882. if (user_png_ver)
  198883. {
  198884. png_snprintf(msg, 80,
  198885. "Application was compiled with png.h from libpng-%.20s",
  198886. user_png_ver);
  198887. png_warning(png_ptr, msg);
  198888. }
  198889. png_snprintf(msg, 80,
  198890. "Application is running with png.c from libpng-%.20s",
  198891. png_libpng_ver);
  198892. png_warning(png_ptr, msg);
  198893. #endif
  198894. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198895. png_ptr->flags=0;
  198896. #endif
  198897. png_error(png_ptr,
  198898. "Incompatible libpng version in application and library");
  198899. }
  198900. }
  198901. /* initialize zbuf - compression buffer */
  198902. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198903. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198904. (png_uint_32)png_ptr->zbuf_size);
  198905. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198906. png_flush_ptr_NULL);
  198907. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198908. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198909. 1, png_doublep_NULL, png_doublep_NULL);
  198910. #endif
  198911. #ifdef PNG_SETJMP_SUPPORTED
  198912. /* Applications that neglect to set up their own setjmp() and then encounter
  198913. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198914. abort instead of returning. */
  198915. #ifdef USE_FAR_KEYWORD
  198916. if (setjmp(jmpbuf))
  198917. PNG_ABORT();
  198918. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198919. #else
  198920. if (setjmp(png_ptr->jmpbuf))
  198921. PNG_ABORT();
  198922. #endif
  198923. #endif
  198924. return (png_ptr);
  198925. }
  198926. /* Initialize png_ptr structure, and allocate any memory needed */
  198927. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198928. /* Deprecated. */
  198929. #undef png_write_init
  198930. void PNGAPI
  198931. png_write_init(png_structp png_ptr)
  198932. {
  198933. /* We only come here via pre-1.0.7-compiled applications */
  198934. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198935. }
  198936. void PNGAPI
  198937. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198938. png_size_t png_struct_size, png_size_t png_info_size)
  198939. {
  198940. /* We only come here via pre-1.0.12-compiled applications */
  198941. if(png_ptr == NULL) return;
  198942. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198943. if(png_sizeof(png_struct) > png_struct_size ||
  198944. png_sizeof(png_info) > png_info_size)
  198945. {
  198946. char msg[80];
  198947. png_ptr->warning_fn=NULL;
  198948. if (user_png_ver)
  198949. {
  198950. png_snprintf(msg, 80,
  198951. "Application was compiled with png.h from libpng-%.20s",
  198952. user_png_ver);
  198953. png_warning(png_ptr, msg);
  198954. }
  198955. png_snprintf(msg, 80,
  198956. "Application is running with png.c from libpng-%.20s",
  198957. png_libpng_ver);
  198958. png_warning(png_ptr, msg);
  198959. }
  198960. #endif
  198961. if(png_sizeof(png_struct) > png_struct_size)
  198962. {
  198963. png_ptr->error_fn=NULL;
  198964. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198965. png_ptr->flags=0;
  198966. #endif
  198967. png_error(png_ptr,
  198968. "The png struct allocated by the application for writing is too small.");
  198969. }
  198970. if(png_sizeof(png_info) > png_info_size)
  198971. {
  198972. png_ptr->error_fn=NULL;
  198973. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198974. png_ptr->flags=0;
  198975. #endif
  198976. png_error(png_ptr,
  198977. "The info struct allocated by the application for writing is too small.");
  198978. }
  198979. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198980. }
  198981. #endif /* PNG_1_0_X || PNG_1_2_X */
  198982. void PNGAPI
  198983. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198984. png_size_t png_struct_size)
  198985. {
  198986. png_structp png_ptr=*ptr_ptr;
  198987. #ifdef PNG_SETJMP_SUPPORTED
  198988. jmp_buf tmp_jmp; /* to save current jump buffer */
  198989. #endif
  198990. int i = 0;
  198991. if (png_ptr == NULL)
  198992. return;
  198993. do
  198994. {
  198995. if (user_png_ver[i] != png_libpng_ver[i])
  198996. {
  198997. #ifdef PNG_LEGACY_SUPPORTED
  198998. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198999. #else
  199000. png_ptr->warning_fn=NULL;
  199001. png_warning(png_ptr,
  199002. "Application uses deprecated png_write_init() and should be recompiled.");
  199003. break;
  199004. #endif
  199005. }
  199006. } while (png_libpng_ver[i++]);
  199007. png_debug(1, "in png_write_init_3\n");
  199008. #ifdef PNG_SETJMP_SUPPORTED
  199009. /* save jump buffer and error functions */
  199010. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199011. #endif
  199012. if (png_sizeof(png_struct) > png_struct_size)
  199013. {
  199014. png_destroy_struct(png_ptr);
  199015. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199016. *ptr_ptr = png_ptr;
  199017. }
  199018. /* reset all variables to 0 */
  199019. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199020. /* added at libpng-1.2.6 */
  199021. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199022. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199023. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199024. #endif
  199025. #ifdef PNG_SETJMP_SUPPORTED
  199026. /* restore jump buffer */
  199027. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199028. #endif
  199029. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199030. png_flush_ptr_NULL);
  199031. /* initialize zbuf - compression buffer */
  199032. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199033. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199034. (png_uint_32)png_ptr->zbuf_size);
  199035. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199036. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199037. 1, png_doublep_NULL, png_doublep_NULL);
  199038. #endif
  199039. }
  199040. /* Write a few rows of image data. If the image is interlaced,
  199041. * either you will have to write the 7 sub images, or, if you
  199042. * have called png_set_interlace_handling(), you will have to
  199043. * "write" the image seven times.
  199044. */
  199045. void PNGAPI
  199046. png_write_rows(png_structp png_ptr, png_bytepp row,
  199047. png_uint_32 num_rows)
  199048. {
  199049. png_uint_32 i; /* row counter */
  199050. png_bytepp rp; /* row pointer */
  199051. png_debug(1, "in png_write_rows\n");
  199052. if (png_ptr == NULL)
  199053. return;
  199054. /* loop through the rows */
  199055. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199056. {
  199057. png_write_row(png_ptr, *rp);
  199058. }
  199059. }
  199060. /* Write the image. You only need to call this function once, even
  199061. * if you are writing an interlaced image.
  199062. */
  199063. void PNGAPI
  199064. png_write_image(png_structp png_ptr, png_bytepp image)
  199065. {
  199066. png_uint_32 i; /* row index */
  199067. int pass, num_pass; /* pass variables */
  199068. png_bytepp rp; /* points to current row */
  199069. if (png_ptr == NULL)
  199070. return;
  199071. png_debug(1, "in png_write_image\n");
  199072. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199073. /* intialize interlace handling. If image is not interlaced,
  199074. this will set pass to 1 */
  199075. num_pass = png_set_interlace_handling(png_ptr);
  199076. #else
  199077. num_pass = 1;
  199078. #endif
  199079. /* loop through passes */
  199080. for (pass = 0; pass < num_pass; pass++)
  199081. {
  199082. /* loop through image */
  199083. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199084. {
  199085. png_write_row(png_ptr, *rp);
  199086. }
  199087. }
  199088. }
  199089. /* called by user to write a row of image data */
  199090. void PNGAPI
  199091. png_write_row(png_structp png_ptr, png_bytep row)
  199092. {
  199093. if (png_ptr == NULL)
  199094. return;
  199095. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199096. png_ptr->row_number, png_ptr->pass);
  199097. /* initialize transformations and other stuff if first time */
  199098. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199099. {
  199100. /* make sure we wrote the header info */
  199101. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199102. png_error(png_ptr,
  199103. "png_write_info was never called before png_write_row.");
  199104. /* check for transforms that have been set but were defined out */
  199105. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199106. if (png_ptr->transformations & PNG_INVERT_MONO)
  199107. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199108. #endif
  199109. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199110. if (png_ptr->transformations & PNG_FILLER)
  199111. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199112. #endif
  199113. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199114. if (png_ptr->transformations & PNG_PACKSWAP)
  199115. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199116. #endif
  199117. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199118. if (png_ptr->transformations & PNG_PACK)
  199119. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199120. #endif
  199121. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199122. if (png_ptr->transformations & PNG_SHIFT)
  199123. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199124. #endif
  199125. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199126. if (png_ptr->transformations & PNG_BGR)
  199127. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199128. #endif
  199129. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199130. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199131. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199132. #endif
  199133. png_write_start_row(png_ptr);
  199134. }
  199135. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199136. /* if interlaced and not interested in row, return */
  199137. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199138. {
  199139. switch (png_ptr->pass)
  199140. {
  199141. case 0:
  199142. if (png_ptr->row_number & 0x07)
  199143. {
  199144. png_write_finish_row(png_ptr);
  199145. return;
  199146. }
  199147. break;
  199148. case 1:
  199149. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199150. {
  199151. png_write_finish_row(png_ptr);
  199152. return;
  199153. }
  199154. break;
  199155. case 2:
  199156. if ((png_ptr->row_number & 0x07) != 4)
  199157. {
  199158. png_write_finish_row(png_ptr);
  199159. return;
  199160. }
  199161. break;
  199162. case 3:
  199163. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199164. {
  199165. png_write_finish_row(png_ptr);
  199166. return;
  199167. }
  199168. break;
  199169. case 4:
  199170. if ((png_ptr->row_number & 0x03) != 2)
  199171. {
  199172. png_write_finish_row(png_ptr);
  199173. return;
  199174. }
  199175. break;
  199176. case 5:
  199177. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199178. {
  199179. png_write_finish_row(png_ptr);
  199180. return;
  199181. }
  199182. break;
  199183. case 6:
  199184. if (!(png_ptr->row_number & 0x01))
  199185. {
  199186. png_write_finish_row(png_ptr);
  199187. return;
  199188. }
  199189. break;
  199190. }
  199191. }
  199192. #endif
  199193. /* set up row info for transformations */
  199194. png_ptr->row_info.color_type = png_ptr->color_type;
  199195. png_ptr->row_info.width = png_ptr->usr_width;
  199196. png_ptr->row_info.channels = png_ptr->usr_channels;
  199197. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199198. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199199. png_ptr->row_info.channels);
  199200. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199201. png_ptr->row_info.width);
  199202. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199203. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199204. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199205. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199206. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199207. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199208. /* Copy user's row into buffer, leaving room for filter byte. */
  199209. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199210. png_ptr->row_info.rowbytes);
  199211. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199212. /* handle interlacing */
  199213. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199214. (png_ptr->transformations & PNG_INTERLACE))
  199215. {
  199216. png_do_write_interlace(&(png_ptr->row_info),
  199217. png_ptr->row_buf + 1, png_ptr->pass);
  199218. /* this should always get caught above, but still ... */
  199219. if (!(png_ptr->row_info.width))
  199220. {
  199221. png_write_finish_row(png_ptr);
  199222. return;
  199223. }
  199224. }
  199225. #endif
  199226. /* handle other transformations */
  199227. if (png_ptr->transformations)
  199228. png_do_write_transformations(png_ptr);
  199229. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199230. /* Write filter_method 64 (intrapixel differencing) only if
  199231. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199232. * 2. Libpng did not write a PNG signature (this filter_method is only
  199233. * used in PNG datastreams that are embedded in MNG datastreams) and
  199234. * 3. The application called png_permit_mng_features with a mask that
  199235. * included PNG_FLAG_MNG_FILTER_64 and
  199236. * 4. The filter_method is 64 and
  199237. * 5. The color_type is RGB or RGBA
  199238. */
  199239. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199240. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199241. {
  199242. /* Intrapixel differencing */
  199243. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199244. }
  199245. #endif
  199246. /* Find a filter if necessary, filter the row and write it out. */
  199247. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199248. if (png_ptr->write_row_fn != NULL)
  199249. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199250. }
  199251. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199252. /* Set the automatic flush interval or 0 to turn flushing off */
  199253. void PNGAPI
  199254. png_set_flush(png_structp png_ptr, int nrows)
  199255. {
  199256. png_debug(1, "in png_set_flush\n");
  199257. if (png_ptr == NULL)
  199258. return;
  199259. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199260. }
  199261. /* flush the current output buffers now */
  199262. void PNGAPI
  199263. png_write_flush(png_structp png_ptr)
  199264. {
  199265. int wrote_IDAT;
  199266. png_debug(1, "in png_write_flush\n");
  199267. if (png_ptr == NULL)
  199268. return;
  199269. /* We have already written out all of the data */
  199270. if (png_ptr->row_number >= png_ptr->num_rows)
  199271. return;
  199272. do
  199273. {
  199274. int ret;
  199275. /* compress the data */
  199276. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199277. wrote_IDAT = 0;
  199278. /* check for compression errors */
  199279. if (ret != Z_OK)
  199280. {
  199281. if (png_ptr->zstream.msg != NULL)
  199282. png_error(png_ptr, png_ptr->zstream.msg);
  199283. else
  199284. png_error(png_ptr, "zlib error");
  199285. }
  199286. if (!(png_ptr->zstream.avail_out))
  199287. {
  199288. /* write the IDAT and reset the zlib output buffer */
  199289. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199290. png_ptr->zbuf_size);
  199291. png_ptr->zstream.next_out = png_ptr->zbuf;
  199292. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199293. wrote_IDAT = 1;
  199294. }
  199295. } while(wrote_IDAT == 1);
  199296. /* If there is any data left to be output, write it into a new IDAT */
  199297. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199298. {
  199299. /* write the IDAT and reset the zlib output buffer */
  199300. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199301. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199302. png_ptr->zstream.next_out = png_ptr->zbuf;
  199303. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199304. }
  199305. png_ptr->flush_rows = 0;
  199306. png_flush(png_ptr);
  199307. }
  199308. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199309. /* free all memory used by the write */
  199310. void PNGAPI
  199311. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199312. {
  199313. png_structp png_ptr = NULL;
  199314. png_infop info_ptr = NULL;
  199315. #ifdef PNG_USER_MEM_SUPPORTED
  199316. png_free_ptr free_fn = NULL;
  199317. png_voidp mem_ptr = NULL;
  199318. #endif
  199319. png_debug(1, "in png_destroy_write_struct\n");
  199320. if (png_ptr_ptr != NULL)
  199321. {
  199322. png_ptr = *png_ptr_ptr;
  199323. #ifdef PNG_USER_MEM_SUPPORTED
  199324. free_fn = png_ptr->free_fn;
  199325. mem_ptr = png_ptr->mem_ptr;
  199326. #endif
  199327. }
  199328. if (info_ptr_ptr != NULL)
  199329. info_ptr = *info_ptr_ptr;
  199330. if (info_ptr != NULL)
  199331. {
  199332. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199333. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199334. if (png_ptr->num_chunk_list)
  199335. {
  199336. png_free(png_ptr, png_ptr->chunk_list);
  199337. png_ptr->chunk_list=NULL;
  199338. png_ptr->num_chunk_list=0;
  199339. }
  199340. #endif
  199341. #ifdef PNG_USER_MEM_SUPPORTED
  199342. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199343. (png_voidp)mem_ptr);
  199344. #else
  199345. png_destroy_struct((png_voidp)info_ptr);
  199346. #endif
  199347. *info_ptr_ptr = NULL;
  199348. }
  199349. if (png_ptr != NULL)
  199350. {
  199351. png_write_destroy(png_ptr);
  199352. #ifdef PNG_USER_MEM_SUPPORTED
  199353. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199354. (png_voidp)mem_ptr);
  199355. #else
  199356. png_destroy_struct((png_voidp)png_ptr);
  199357. #endif
  199358. *png_ptr_ptr = NULL;
  199359. }
  199360. }
  199361. /* Free any memory used in png_ptr struct (old method) */
  199362. void /* PRIVATE */
  199363. png_write_destroy(png_structp png_ptr)
  199364. {
  199365. #ifdef PNG_SETJMP_SUPPORTED
  199366. jmp_buf tmp_jmp; /* save jump buffer */
  199367. #endif
  199368. png_error_ptr error_fn;
  199369. png_error_ptr warning_fn;
  199370. png_voidp error_ptr;
  199371. #ifdef PNG_USER_MEM_SUPPORTED
  199372. png_free_ptr free_fn;
  199373. #endif
  199374. png_debug(1, "in png_write_destroy\n");
  199375. /* free any memory zlib uses */
  199376. deflateEnd(&png_ptr->zstream);
  199377. /* free our memory. png_free checks NULL for us. */
  199378. png_free(png_ptr, png_ptr->zbuf);
  199379. png_free(png_ptr, png_ptr->row_buf);
  199380. png_free(png_ptr, png_ptr->prev_row);
  199381. png_free(png_ptr, png_ptr->sub_row);
  199382. png_free(png_ptr, png_ptr->up_row);
  199383. png_free(png_ptr, png_ptr->avg_row);
  199384. png_free(png_ptr, png_ptr->paeth_row);
  199385. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199386. png_free(png_ptr, png_ptr->time_buffer);
  199387. #endif
  199388. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199389. png_free(png_ptr, png_ptr->prev_filters);
  199390. png_free(png_ptr, png_ptr->filter_weights);
  199391. png_free(png_ptr, png_ptr->inv_filter_weights);
  199392. png_free(png_ptr, png_ptr->filter_costs);
  199393. png_free(png_ptr, png_ptr->inv_filter_costs);
  199394. #endif
  199395. #ifdef PNG_SETJMP_SUPPORTED
  199396. /* reset structure */
  199397. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199398. #endif
  199399. error_fn = png_ptr->error_fn;
  199400. warning_fn = png_ptr->warning_fn;
  199401. error_ptr = png_ptr->error_ptr;
  199402. #ifdef PNG_USER_MEM_SUPPORTED
  199403. free_fn = png_ptr->free_fn;
  199404. #endif
  199405. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199406. png_ptr->error_fn = error_fn;
  199407. png_ptr->warning_fn = warning_fn;
  199408. png_ptr->error_ptr = error_ptr;
  199409. #ifdef PNG_USER_MEM_SUPPORTED
  199410. png_ptr->free_fn = free_fn;
  199411. #endif
  199412. #ifdef PNG_SETJMP_SUPPORTED
  199413. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199414. #endif
  199415. }
  199416. /* Allow the application to select one or more row filters to use. */
  199417. void PNGAPI
  199418. png_set_filter(png_structp png_ptr, int method, int filters)
  199419. {
  199420. png_debug(1, "in png_set_filter\n");
  199421. if (png_ptr == NULL)
  199422. return;
  199423. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199424. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199425. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199426. method = PNG_FILTER_TYPE_BASE;
  199427. #endif
  199428. if (method == PNG_FILTER_TYPE_BASE)
  199429. {
  199430. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199431. {
  199432. #ifndef PNG_NO_WRITE_FILTER
  199433. case 5:
  199434. case 6:
  199435. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199436. #endif /* PNG_NO_WRITE_FILTER */
  199437. case PNG_FILTER_VALUE_NONE:
  199438. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199439. #ifndef PNG_NO_WRITE_FILTER
  199440. case PNG_FILTER_VALUE_SUB:
  199441. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199442. case PNG_FILTER_VALUE_UP:
  199443. png_ptr->do_filter=PNG_FILTER_UP; break;
  199444. case PNG_FILTER_VALUE_AVG:
  199445. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199446. case PNG_FILTER_VALUE_PAETH:
  199447. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199448. default: png_ptr->do_filter = (png_byte)filters; break;
  199449. #else
  199450. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199451. #endif /* PNG_NO_WRITE_FILTER */
  199452. }
  199453. /* If we have allocated the row_buf, this means we have already started
  199454. * with the image and we should have allocated all of the filter buffers
  199455. * that have been selected. If prev_row isn't already allocated, then
  199456. * it is too late to start using the filters that need it, since we
  199457. * will be missing the data in the previous row. If an application
  199458. * wants to start and stop using particular filters during compression,
  199459. * it should start out with all of the filters, and then add and
  199460. * remove them after the start of compression.
  199461. */
  199462. if (png_ptr->row_buf != NULL)
  199463. {
  199464. #ifndef PNG_NO_WRITE_FILTER
  199465. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199466. {
  199467. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199468. (png_ptr->rowbytes + 1));
  199469. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199470. }
  199471. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199472. {
  199473. if (png_ptr->prev_row == NULL)
  199474. {
  199475. png_warning(png_ptr, "Can't add Up filter after starting");
  199476. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199477. }
  199478. else
  199479. {
  199480. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199481. (png_ptr->rowbytes + 1));
  199482. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199483. }
  199484. }
  199485. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199486. {
  199487. if (png_ptr->prev_row == NULL)
  199488. {
  199489. png_warning(png_ptr, "Can't add Average filter after starting");
  199490. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199491. }
  199492. else
  199493. {
  199494. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199495. (png_ptr->rowbytes + 1));
  199496. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199497. }
  199498. }
  199499. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199500. png_ptr->paeth_row == NULL)
  199501. {
  199502. if (png_ptr->prev_row == NULL)
  199503. {
  199504. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199505. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199506. }
  199507. else
  199508. {
  199509. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199510. (png_ptr->rowbytes + 1));
  199511. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199512. }
  199513. }
  199514. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199515. #endif /* PNG_NO_WRITE_FILTER */
  199516. png_ptr->do_filter = PNG_FILTER_NONE;
  199517. }
  199518. }
  199519. else
  199520. png_error(png_ptr, "Unknown custom filter method");
  199521. }
  199522. /* This allows us to influence the way in which libpng chooses the "best"
  199523. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199524. * differences metric is relatively fast and effective, there is some
  199525. * question as to whether it can be improved upon by trying to keep the
  199526. * filtered data going to zlib more consistent, hopefully resulting in
  199527. * better compression.
  199528. */
  199529. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199530. void PNGAPI
  199531. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199532. int num_weights, png_doublep filter_weights,
  199533. png_doublep filter_costs)
  199534. {
  199535. int i;
  199536. png_debug(1, "in png_set_filter_heuristics\n");
  199537. if (png_ptr == NULL)
  199538. return;
  199539. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199540. {
  199541. png_warning(png_ptr, "Unknown filter heuristic method");
  199542. return;
  199543. }
  199544. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199545. {
  199546. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199547. }
  199548. if (num_weights < 0 || filter_weights == NULL ||
  199549. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199550. {
  199551. num_weights = 0;
  199552. }
  199553. png_ptr->num_prev_filters = (png_byte)num_weights;
  199554. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199555. if (num_weights > 0)
  199556. {
  199557. if (png_ptr->prev_filters == NULL)
  199558. {
  199559. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199560. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199561. /* To make sure that the weighting starts out fairly */
  199562. for (i = 0; i < num_weights; i++)
  199563. {
  199564. png_ptr->prev_filters[i] = 255;
  199565. }
  199566. }
  199567. if (png_ptr->filter_weights == NULL)
  199568. {
  199569. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199570. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199571. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199572. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199573. for (i = 0; i < num_weights; i++)
  199574. {
  199575. png_ptr->inv_filter_weights[i] =
  199576. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199577. }
  199578. }
  199579. for (i = 0; i < num_weights; i++)
  199580. {
  199581. if (filter_weights[i] < 0.0)
  199582. {
  199583. png_ptr->inv_filter_weights[i] =
  199584. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199585. }
  199586. else
  199587. {
  199588. png_ptr->inv_filter_weights[i] =
  199589. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199590. png_ptr->filter_weights[i] =
  199591. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199592. }
  199593. }
  199594. }
  199595. /* If, in the future, there are other filter methods, this would
  199596. * need to be based on png_ptr->filter.
  199597. */
  199598. if (png_ptr->filter_costs == NULL)
  199599. {
  199600. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199601. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199602. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199603. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199604. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199605. {
  199606. png_ptr->inv_filter_costs[i] =
  199607. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199608. }
  199609. }
  199610. /* Here is where we set the relative costs of the different filters. We
  199611. * should take the desired compression level into account when setting
  199612. * the costs, so that Paeth, for instance, has a high relative cost at low
  199613. * compression levels, while it has a lower relative cost at higher
  199614. * compression settings. The filter types are in order of increasing
  199615. * relative cost, so it would be possible to do this with an algorithm.
  199616. */
  199617. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199618. {
  199619. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199620. {
  199621. png_ptr->inv_filter_costs[i] =
  199622. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199623. }
  199624. else if (filter_costs[i] >= 1.0)
  199625. {
  199626. png_ptr->inv_filter_costs[i] =
  199627. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199628. png_ptr->filter_costs[i] =
  199629. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199630. }
  199631. }
  199632. }
  199633. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199634. void PNGAPI
  199635. png_set_compression_level(png_structp png_ptr, int level)
  199636. {
  199637. png_debug(1, "in png_set_compression_level\n");
  199638. if (png_ptr == NULL)
  199639. return;
  199640. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199641. png_ptr->zlib_level = level;
  199642. }
  199643. void PNGAPI
  199644. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199645. {
  199646. png_debug(1, "in png_set_compression_mem_level\n");
  199647. if (png_ptr == NULL)
  199648. return;
  199649. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199650. png_ptr->zlib_mem_level = mem_level;
  199651. }
  199652. void PNGAPI
  199653. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199654. {
  199655. png_debug(1, "in png_set_compression_strategy\n");
  199656. if (png_ptr == NULL)
  199657. return;
  199658. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199659. png_ptr->zlib_strategy = strategy;
  199660. }
  199661. void PNGAPI
  199662. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199663. {
  199664. if (png_ptr == NULL)
  199665. return;
  199666. if (window_bits > 15)
  199667. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199668. else if (window_bits < 8)
  199669. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199670. #ifndef WBITS_8_OK
  199671. /* avoid libpng bug with 256-byte windows */
  199672. if (window_bits == 8)
  199673. {
  199674. png_warning(png_ptr, "Compression window is being reset to 512");
  199675. window_bits=9;
  199676. }
  199677. #endif
  199678. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199679. png_ptr->zlib_window_bits = window_bits;
  199680. }
  199681. void PNGAPI
  199682. png_set_compression_method(png_structp png_ptr, int method)
  199683. {
  199684. png_debug(1, "in png_set_compression_method\n");
  199685. if (png_ptr == NULL)
  199686. return;
  199687. if (method != 8)
  199688. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199689. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199690. png_ptr->zlib_method = method;
  199691. }
  199692. void PNGAPI
  199693. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199694. {
  199695. if (png_ptr == NULL)
  199696. return;
  199697. png_ptr->write_row_fn = write_row_fn;
  199698. }
  199699. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199700. void PNGAPI
  199701. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199702. write_user_transform_fn)
  199703. {
  199704. png_debug(1, "in png_set_write_user_transform_fn\n");
  199705. if (png_ptr == NULL)
  199706. return;
  199707. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199708. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199709. }
  199710. #endif
  199711. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199712. void PNGAPI
  199713. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199714. int transforms, voidp params)
  199715. {
  199716. if (png_ptr == NULL || info_ptr == NULL)
  199717. return;
  199718. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199719. /* invert the alpha channel from opacity to transparency */
  199720. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199721. png_set_invert_alpha(png_ptr);
  199722. #endif
  199723. /* Write the file header information. */
  199724. png_write_info(png_ptr, info_ptr);
  199725. /* ------ these transformations don't touch the info structure ------- */
  199726. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199727. /* invert monochrome pixels */
  199728. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199729. png_set_invert_mono(png_ptr);
  199730. #endif
  199731. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199732. /* Shift the pixels up to a legal bit depth and fill in
  199733. * as appropriate to correctly scale the image.
  199734. */
  199735. if ((transforms & PNG_TRANSFORM_SHIFT)
  199736. && (info_ptr->valid & PNG_INFO_sBIT))
  199737. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199738. #endif
  199739. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199740. /* pack pixels into bytes */
  199741. if (transforms & PNG_TRANSFORM_PACKING)
  199742. png_set_packing(png_ptr);
  199743. #endif
  199744. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199745. /* swap location of alpha bytes from ARGB to RGBA */
  199746. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199747. png_set_swap_alpha(png_ptr);
  199748. #endif
  199749. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199750. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199751. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199752. */
  199753. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199754. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199755. #endif
  199756. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199757. /* flip BGR pixels to RGB */
  199758. if (transforms & PNG_TRANSFORM_BGR)
  199759. png_set_bgr(png_ptr);
  199760. #endif
  199761. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199762. /* swap bytes of 16-bit files to most significant byte first */
  199763. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199764. png_set_swap(png_ptr);
  199765. #endif
  199766. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199767. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199768. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199769. png_set_packswap(png_ptr);
  199770. #endif
  199771. /* ----------------------- end of transformations ------------------- */
  199772. /* write the bits */
  199773. if (info_ptr->valid & PNG_INFO_IDAT)
  199774. png_write_image(png_ptr, info_ptr->row_pointers);
  199775. /* It is REQUIRED to call this to finish writing the rest of the file */
  199776. png_write_end(png_ptr, info_ptr);
  199777. transforms = transforms; /* quiet compiler warnings */
  199778. params = params;
  199779. }
  199780. #endif
  199781. #endif /* PNG_WRITE_SUPPORTED */
  199782. /*** End of inlined file: pngwrite.c ***/
  199783. /*** Start of inlined file: pngwtran.c ***/
  199784. /* pngwtran.c - transforms the data in a row for PNG writers
  199785. *
  199786. * Last changed in libpng 1.2.9 April 14, 2006
  199787. * For conditions of distribution and use, see copyright notice in png.h
  199788. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199789. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199790. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199791. */
  199792. #define PNG_INTERNAL
  199793. #ifdef PNG_WRITE_SUPPORTED
  199794. /* Transform the data according to the user's wishes. The order of
  199795. * transformations is significant.
  199796. */
  199797. void /* PRIVATE */
  199798. png_do_write_transformations(png_structp png_ptr)
  199799. {
  199800. png_debug(1, "in png_do_write_transformations\n");
  199801. if (png_ptr == NULL)
  199802. return;
  199803. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199804. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199805. if(png_ptr->write_user_transform_fn != NULL)
  199806. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199807. (png_ptr, /* png_ptr */
  199808. &(png_ptr->row_info), /* row_info: */
  199809. /* png_uint_32 width; width of row */
  199810. /* png_uint_32 rowbytes; number of bytes in row */
  199811. /* png_byte color_type; color type of pixels */
  199812. /* png_byte bit_depth; bit depth of samples */
  199813. /* png_byte channels; number of channels (1-4) */
  199814. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199815. png_ptr->row_buf + 1); /* start of pixel data for row */
  199816. #endif
  199817. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199818. if (png_ptr->transformations & PNG_FILLER)
  199819. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199820. png_ptr->flags);
  199821. #endif
  199822. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199823. if (png_ptr->transformations & PNG_PACKSWAP)
  199824. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199825. #endif
  199826. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199827. if (png_ptr->transformations & PNG_PACK)
  199828. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199829. (png_uint_32)png_ptr->bit_depth);
  199830. #endif
  199831. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199832. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199833. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199834. #endif
  199835. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199836. if (png_ptr->transformations & PNG_SHIFT)
  199837. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199838. &(png_ptr->shift));
  199839. #endif
  199840. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199841. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199842. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199843. #endif
  199844. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199845. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199846. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199847. #endif
  199848. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199849. if (png_ptr->transformations & PNG_BGR)
  199850. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199851. #endif
  199852. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199853. if (png_ptr->transformations & PNG_INVERT_MONO)
  199854. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199855. #endif
  199856. }
  199857. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199858. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199859. * row_info bit depth should be 8 (one pixel per byte). The channels
  199860. * should be 1 (this only happens on grayscale and paletted images).
  199861. */
  199862. void /* PRIVATE */
  199863. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199864. {
  199865. png_debug(1, "in png_do_pack\n");
  199866. if (row_info->bit_depth == 8 &&
  199867. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199868. row != NULL && row_info != NULL &&
  199869. #endif
  199870. row_info->channels == 1)
  199871. {
  199872. switch ((int)bit_depth)
  199873. {
  199874. case 1:
  199875. {
  199876. png_bytep sp, dp;
  199877. int mask, v;
  199878. png_uint_32 i;
  199879. png_uint_32 row_width = row_info->width;
  199880. sp = row;
  199881. dp = row;
  199882. mask = 0x80;
  199883. v = 0;
  199884. for (i = 0; i < row_width; i++)
  199885. {
  199886. if (*sp != 0)
  199887. v |= mask;
  199888. sp++;
  199889. if (mask > 1)
  199890. mask >>= 1;
  199891. else
  199892. {
  199893. mask = 0x80;
  199894. *dp = (png_byte)v;
  199895. dp++;
  199896. v = 0;
  199897. }
  199898. }
  199899. if (mask != 0x80)
  199900. *dp = (png_byte)v;
  199901. break;
  199902. }
  199903. case 2:
  199904. {
  199905. png_bytep sp, dp;
  199906. int shift, v;
  199907. png_uint_32 i;
  199908. png_uint_32 row_width = row_info->width;
  199909. sp = row;
  199910. dp = row;
  199911. shift = 6;
  199912. v = 0;
  199913. for (i = 0; i < row_width; i++)
  199914. {
  199915. png_byte value;
  199916. value = (png_byte)(*sp & 0x03);
  199917. v |= (value << shift);
  199918. if (shift == 0)
  199919. {
  199920. shift = 6;
  199921. *dp = (png_byte)v;
  199922. dp++;
  199923. v = 0;
  199924. }
  199925. else
  199926. shift -= 2;
  199927. sp++;
  199928. }
  199929. if (shift != 6)
  199930. *dp = (png_byte)v;
  199931. break;
  199932. }
  199933. case 4:
  199934. {
  199935. png_bytep sp, dp;
  199936. int shift, v;
  199937. png_uint_32 i;
  199938. png_uint_32 row_width = row_info->width;
  199939. sp = row;
  199940. dp = row;
  199941. shift = 4;
  199942. v = 0;
  199943. for (i = 0; i < row_width; i++)
  199944. {
  199945. png_byte value;
  199946. value = (png_byte)(*sp & 0x0f);
  199947. v |= (value << shift);
  199948. if (shift == 0)
  199949. {
  199950. shift = 4;
  199951. *dp = (png_byte)v;
  199952. dp++;
  199953. v = 0;
  199954. }
  199955. else
  199956. shift -= 4;
  199957. sp++;
  199958. }
  199959. if (shift != 4)
  199960. *dp = (png_byte)v;
  199961. break;
  199962. }
  199963. }
  199964. row_info->bit_depth = (png_byte)bit_depth;
  199965. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199966. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199967. row_info->width);
  199968. }
  199969. }
  199970. #endif
  199971. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199972. /* Shift pixel values to take advantage of whole range. Pass the
  199973. * true number of bits in bit_depth. The row should be packed
  199974. * according to row_info->bit_depth. Thus, if you had a row of
  199975. * bit depth 4, but the pixels only had values from 0 to 7, you
  199976. * would pass 3 as bit_depth, and this routine would translate the
  199977. * data to 0 to 15.
  199978. */
  199979. void /* PRIVATE */
  199980. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199981. {
  199982. png_debug(1, "in png_do_shift\n");
  199983. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199984. if (row != NULL && row_info != NULL &&
  199985. #else
  199986. if (
  199987. #endif
  199988. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199989. {
  199990. int shift_start[4], shift_dec[4];
  199991. int channels = 0;
  199992. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199993. {
  199994. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199995. shift_dec[channels] = bit_depth->red;
  199996. channels++;
  199997. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199998. shift_dec[channels] = bit_depth->green;
  199999. channels++;
  200000. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200001. shift_dec[channels] = bit_depth->blue;
  200002. channels++;
  200003. }
  200004. else
  200005. {
  200006. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200007. shift_dec[channels] = bit_depth->gray;
  200008. channels++;
  200009. }
  200010. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200011. {
  200012. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200013. shift_dec[channels] = bit_depth->alpha;
  200014. channels++;
  200015. }
  200016. /* with low row depths, could only be grayscale, so one channel */
  200017. if (row_info->bit_depth < 8)
  200018. {
  200019. png_bytep bp = row;
  200020. png_uint_32 i;
  200021. png_byte mask;
  200022. png_uint_32 row_bytes = row_info->rowbytes;
  200023. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200024. mask = 0x55;
  200025. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200026. mask = 0x11;
  200027. else
  200028. mask = 0xff;
  200029. for (i = 0; i < row_bytes; i++, bp++)
  200030. {
  200031. png_uint_16 v;
  200032. int j;
  200033. v = *bp;
  200034. *bp = 0;
  200035. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200036. {
  200037. if (j > 0)
  200038. *bp |= (png_byte)((v << j) & 0xff);
  200039. else
  200040. *bp |= (png_byte)((v >> (-j)) & mask);
  200041. }
  200042. }
  200043. }
  200044. else if (row_info->bit_depth == 8)
  200045. {
  200046. png_bytep bp = row;
  200047. png_uint_32 i;
  200048. png_uint_32 istop = channels * row_info->width;
  200049. for (i = 0; i < istop; i++, bp++)
  200050. {
  200051. png_uint_16 v;
  200052. int j;
  200053. int c = (int)(i%channels);
  200054. v = *bp;
  200055. *bp = 0;
  200056. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200057. {
  200058. if (j > 0)
  200059. *bp |= (png_byte)((v << j) & 0xff);
  200060. else
  200061. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200062. }
  200063. }
  200064. }
  200065. else
  200066. {
  200067. png_bytep bp;
  200068. png_uint_32 i;
  200069. png_uint_32 istop = channels * row_info->width;
  200070. for (bp = row, i = 0; i < istop; i++)
  200071. {
  200072. int c = (int)(i%channels);
  200073. png_uint_16 value, v;
  200074. int j;
  200075. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200076. value = 0;
  200077. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200078. {
  200079. if (j > 0)
  200080. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200081. else
  200082. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200083. }
  200084. *bp++ = (png_byte)(value >> 8);
  200085. *bp++ = (png_byte)(value & 0xff);
  200086. }
  200087. }
  200088. }
  200089. }
  200090. #endif
  200091. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200092. void /* PRIVATE */
  200093. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200094. {
  200095. png_debug(1, "in png_do_write_swap_alpha\n");
  200096. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200097. if (row != NULL && row_info != NULL)
  200098. #endif
  200099. {
  200100. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200101. {
  200102. /* This converts from ARGB to RGBA */
  200103. if (row_info->bit_depth == 8)
  200104. {
  200105. png_bytep sp, dp;
  200106. png_uint_32 i;
  200107. png_uint_32 row_width = row_info->width;
  200108. for (i = 0, sp = dp = row; i < row_width; i++)
  200109. {
  200110. png_byte save = *(sp++);
  200111. *(dp++) = *(sp++);
  200112. *(dp++) = *(sp++);
  200113. *(dp++) = *(sp++);
  200114. *(dp++) = save;
  200115. }
  200116. }
  200117. /* This converts from AARRGGBB to RRGGBBAA */
  200118. else
  200119. {
  200120. png_bytep sp, dp;
  200121. png_uint_32 i;
  200122. png_uint_32 row_width = row_info->width;
  200123. for (i = 0, sp = dp = row; i < row_width; i++)
  200124. {
  200125. png_byte save[2];
  200126. save[0] = *(sp++);
  200127. save[1] = *(sp++);
  200128. *(dp++) = *(sp++);
  200129. *(dp++) = *(sp++);
  200130. *(dp++) = *(sp++);
  200131. *(dp++) = *(sp++);
  200132. *(dp++) = *(sp++);
  200133. *(dp++) = *(sp++);
  200134. *(dp++) = save[0];
  200135. *(dp++) = save[1];
  200136. }
  200137. }
  200138. }
  200139. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200140. {
  200141. /* This converts from AG to GA */
  200142. if (row_info->bit_depth == 8)
  200143. {
  200144. png_bytep sp, dp;
  200145. png_uint_32 i;
  200146. png_uint_32 row_width = row_info->width;
  200147. for (i = 0, sp = dp = row; i < row_width; i++)
  200148. {
  200149. png_byte save = *(sp++);
  200150. *(dp++) = *(sp++);
  200151. *(dp++) = save;
  200152. }
  200153. }
  200154. /* This converts from AAGG to GGAA */
  200155. else
  200156. {
  200157. png_bytep sp, dp;
  200158. png_uint_32 i;
  200159. png_uint_32 row_width = row_info->width;
  200160. for (i = 0, sp = dp = row; i < row_width; i++)
  200161. {
  200162. png_byte save[2];
  200163. save[0] = *(sp++);
  200164. save[1] = *(sp++);
  200165. *(dp++) = *(sp++);
  200166. *(dp++) = *(sp++);
  200167. *(dp++) = save[0];
  200168. *(dp++) = save[1];
  200169. }
  200170. }
  200171. }
  200172. }
  200173. }
  200174. #endif
  200175. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200176. void /* PRIVATE */
  200177. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200178. {
  200179. png_debug(1, "in png_do_write_invert_alpha\n");
  200180. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200181. if (row != NULL && row_info != NULL)
  200182. #endif
  200183. {
  200184. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200185. {
  200186. /* This inverts the alpha channel in RGBA */
  200187. if (row_info->bit_depth == 8)
  200188. {
  200189. png_bytep sp, dp;
  200190. png_uint_32 i;
  200191. png_uint_32 row_width = row_info->width;
  200192. for (i = 0, sp = dp = row; i < row_width; i++)
  200193. {
  200194. /* does nothing
  200195. *(dp++) = *(sp++);
  200196. *(dp++) = *(sp++);
  200197. *(dp++) = *(sp++);
  200198. */
  200199. sp+=3; dp = sp;
  200200. *(dp++) = (png_byte)(255 - *(sp++));
  200201. }
  200202. }
  200203. /* This inverts the alpha channel in RRGGBBAA */
  200204. else
  200205. {
  200206. png_bytep sp, dp;
  200207. png_uint_32 i;
  200208. png_uint_32 row_width = row_info->width;
  200209. for (i = 0, sp = dp = row; i < row_width; i++)
  200210. {
  200211. /* does nothing
  200212. *(dp++) = *(sp++);
  200213. *(dp++) = *(sp++);
  200214. *(dp++) = *(sp++);
  200215. *(dp++) = *(sp++);
  200216. *(dp++) = *(sp++);
  200217. *(dp++) = *(sp++);
  200218. */
  200219. sp+=6; dp = sp;
  200220. *(dp++) = (png_byte)(255 - *(sp++));
  200221. *(dp++) = (png_byte)(255 - *(sp++));
  200222. }
  200223. }
  200224. }
  200225. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200226. {
  200227. /* This inverts the alpha channel in GA */
  200228. if (row_info->bit_depth == 8)
  200229. {
  200230. png_bytep sp, dp;
  200231. png_uint_32 i;
  200232. png_uint_32 row_width = row_info->width;
  200233. for (i = 0, sp = dp = row; i < row_width; i++)
  200234. {
  200235. *(dp++) = *(sp++);
  200236. *(dp++) = (png_byte)(255 - *(sp++));
  200237. }
  200238. }
  200239. /* This inverts the alpha channel in GGAA */
  200240. else
  200241. {
  200242. png_bytep sp, dp;
  200243. png_uint_32 i;
  200244. png_uint_32 row_width = row_info->width;
  200245. for (i = 0, sp = dp = row; i < row_width; i++)
  200246. {
  200247. /* does nothing
  200248. *(dp++) = *(sp++);
  200249. *(dp++) = *(sp++);
  200250. */
  200251. sp+=2; dp = sp;
  200252. *(dp++) = (png_byte)(255 - *(sp++));
  200253. *(dp++) = (png_byte)(255 - *(sp++));
  200254. }
  200255. }
  200256. }
  200257. }
  200258. }
  200259. #endif
  200260. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200261. /* undoes intrapixel differencing */
  200262. void /* PRIVATE */
  200263. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200264. {
  200265. png_debug(1, "in png_do_write_intrapixel\n");
  200266. if (
  200267. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200268. row != NULL && row_info != NULL &&
  200269. #endif
  200270. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200271. {
  200272. int bytes_per_pixel;
  200273. png_uint_32 row_width = row_info->width;
  200274. if (row_info->bit_depth == 8)
  200275. {
  200276. png_bytep rp;
  200277. png_uint_32 i;
  200278. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200279. bytes_per_pixel = 3;
  200280. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200281. bytes_per_pixel = 4;
  200282. else
  200283. return;
  200284. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200285. {
  200286. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200287. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200288. }
  200289. }
  200290. else if (row_info->bit_depth == 16)
  200291. {
  200292. png_bytep rp;
  200293. png_uint_32 i;
  200294. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200295. bytes_per_pixel = 6;
  200296. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200297. bytes_per_pixel = 8;
  200298. else
  200299. return;
  200300. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200301. {
  200302. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200303. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200304. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200305. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200306. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200307. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200308. *(rp+1) = (png_byte)(red & 0xff);
  200309. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200310. *(rp+5) = (png_byte)(blue & 0xff);
  200311. }
  200312. }
  200313. }
  200314. }
  200315. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200316. #endif /* PNG_WRITE_SUPPORTED */
  200317. /*** End of inlined file: pngwtran.c ***/
  200318. /*** Start of inlined file: pngwutil.c ***/
  200319. /* pngwutil.c - utilities to write a PNG file
  200320. *
  200321. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200322. * For conditions of distribution and use, see copyright notice in png.h
  200323. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200324. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200325. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200326. */
  200327. #define PNG_INTERNAL
  200328. #ifdef PNG_WRITE_SUPPORTED
  200329. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200330. * with unsigned numbers for convenience, although one supported
  200331. * ancillary chunk uses signed (two's complement) numbers.
  200332. */
  200333. void PNGAPI
  200334. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200335. {
  200336. buf[0] = (png_byte)((i >> 24) & 0xff);
  200337. buf[1] = (png_byte)((i >> 16) & 0xff);
  200338. buf[2] = (png_byte)((i >> 8) & 0xff);
  200339. buf[3] = (png_byte)(i & 0xff);
  200340. }
  200341. /* The png_save_int_32 function assumes integers are stored in two's
  200342. * complement format. If this isn't the case, then this routine needs to
  200343. * be modified to write data in two's complement format.
  200344. */
  200345. void PNGAPI
  200346. png_save_int_32(png_bytep buf, png_int_32 i)
  200347. {
  200348. buf[0] = (png_byte)((i >> 24) & 0xff);
  200349. buf[1] = (png_byte)((i >> 16) & 0xff);
  200350. buf[2] = (png_byte)((i >> 8) & 0xff);
  200351. buf[3] = (png_byte)(i & 0xff);
  200352. }
  200353. /* Place a 16-bit number into a buffer in PNG byte order.
  200354. * The parameter is declared unsigned int, not png_uint_16,
  200355. * just to avoid potential problems on pre-ANSI C compilers.
  200356. */
  200357. void PNGAPI
  200358. png_save_uint_16(png_bytep buf, unsigned int i)
  200359. {
  200360. buf[0] = (png_byte)((i >> 8) & 0xff);
  200361. buf[1] = (png_byte)(i & 0xff);
  200362. }
  200363. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200364. * representing the chunk name. The array must be at least 4 bytes in
  200365. * length, and does not need to be null terminated. To be safe, pass the
  200366. * pre-defined chunk names here, and if you need a new one, define it
  200367. * where the others are defined. The length is the length of the data.
  200368. * All the data must be present. If that is not possible, use the
  200369. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200370. * functions instead.
  200371. */
  200372. void PNGAPI
  200373. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200374. png_bytep data, png_size_t length)
  200375. {
  200376. if(png_ptr == NULL) return;
  200377. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200378. png_write_chunk_data(png_ptr, data, length);
  200379. png_write_chunk_end(png_ptr);
  200380. }
  200381. /* Write the start of a PNG chunk. The type is the chunk type.
  200382. * The total_length is the sum of the lengths of all the data you will be
  200383. * passing in png_write_chunk_data().
  200384. */
  200385. void PNGAPI
  200386. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200387. png_uint_32 length)
  200388. {
  200389. png_byte buf[4];
  200390. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200391. if(png_ptr == NULL) return;
  200392. /* write the length */
  200393. png_save_uint_32(buf, length);
  200394. png_write_data(png_ptr, buf, (png_size_t)4);
  200395. /* write the chunk name */
  200396. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200397. /* reset the crc and run it over the chunk name */
  200398. png_reset_crc(png_ptr);
  200399. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200400. }
  200401. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200402. * Note that multiple calls to this function are allowed, and that the
  200403. * sum of the lengths from these calls *must* add up to the total_length
  200404. * given to png_write_chunk_start().
  200405. */
  200406. void PNGAPI
  200407. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200408. {
  200409. /* write the data, and run the CRC over it */
  200410. if(png_ptr == NULL) return;
  200411. if (data != NULL && length > 0)
  200412. {
  200413. png_calculate_crc(png_ptr, data, length);
  200414. png_write_data(png_ptr, data, length);
  200415. }
  200416. }
  200417. /* Finish a chunk started with png_write_chunk_start(). */
  200418. void PNGAPI
  200419. png_write_chunk_end(png_structp png_ptr)
  200420. {
  200421. png_byte buf[4];
  200422. if(png_ptr == NULL) return;
  200423. /* write the crc */
  200424. png_save_uint_32(buf, png_ptr->crc);
  200425. png_write_data(png_ptr, buf, (png_size_t)4);
  200426. }
  200427. /* Simple function to write the signature. If we have already written
  200428. * the magic bytes of the signature, or more likely, the PNG stream is
  200429. * being embedded into another stream and doesn't need its own signature,
  200430. * we should call png_set_sig_bytes() to tell libpng how many of the
  200431. * bytes have already been written.
  200432. */
  200433. void /* PRIVATE */
  200434. png_write_sig(png_structp png_ptr)
  200435. {
  200436. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200437. /* write the rest of the 8 byte signature */
  200438. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200439. (png_size_t)8 - png_ptr->sig_bytes);
  200440. if(png_ptr->sig_bytes < 3)
  200441. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200442. }
  200443. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200444. /*
  200445. * This pair of functions encapsulates the operation of (a) compressing a
  200446. * text string, and (b) issuing it later as a series of chunk data writes.
  200447. * The compression_state structure is shared context for these functions
  200448. * set up by the caller in order to make the whole mess thread-safe.
  200449. */
  200450. typedef struct
  200451. {
  200452. char *input; /* the uncompressed input data */
  200453. int input_len; /* its length */
  200454. int num_output_ptr; /* number of output pointers used */
  200455. int max_output_ptr; /* size of output_ptr */
  200456. png_charpp output_ptr; /* array of pointers to output */
  200457. } compression_state;
  200458. /* compress given text into storage in the png_ptr structure */
  200459. static int /* PRIVATE */
  200460. png_text_compress(png_structp png_ptr,
  200461. png_charp text, png_size_t text_len, int compression,
  200462. compression_state *comp)
  200463. {
  200464. int ret;
  200465. comp->num_output_ptr = 0;
  200466. comp->max_output_ptr = 0;
  200467. comp->output_ptr = NULL;
  200468. comp->input = NULL;
  200469. comp->input_len = 0;
  200470. /* we may just want to pass the text right through */
  200471. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200472. {
  200473. comp->input = text;
  200474. comp->input_len = text_len;
  200475. return((int)text_len);
  200476. }
  200477. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200478. {
  200479. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200480. char msg[50];
  200481. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200482. png_warning(png_ptr, msg);
  200483. #else
  200484. png_warning(png_ptr, "Unknown compression type");
  200485. #endif
  200486. }
  200487. /* We can't write the chunk until we find out how much data we have,
  200488. * which means we need to run the compressor first and save the
  200489. * output. This shouldn't be a problem, as the vast majority of
  200490. * comments should be reasonable, but we will set up an array of
  200491. * malloc'd pointers to be sure.
  200492. *
  200493. * If we knew the application was well behaved, we could simplify this
  200494. * greatly by assuming we can always malloc an output buffer large
  200495. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200496. * and malloc this directly. The only time this would be a bad idea is
  200497. * if we can't malloc more than 64K and we have 64K of random input
  200498. * data, or if the input string is incredibly large (although this
  200499. * wouldn't cause a failure, just a slowdown due to swapping).
  200500. */
  200501. /* set up the compression buffers */
  200502. png_ptr->zstream.avail_in = (uInt)text_len;
  200503. png_ptr->zstream.next_in = (Bytef *)text;
  200504. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200505. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200506. /* this is the same compression loop as in png_write_row() */
  200507. do
  200508. {
  200509. /* compress the data */
  200510. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200511. if (ret != Z_OK)
  200512. {
  200513. /* error */
  200514. if (png_ptr->zstream.msg != NULL)
  200515. png_error(png_ptr, png_ptr->zstream.msg);
  200516. else
  200517. png_error(png_ptr, "zlib error");
  200518. }
  200519. /* check to see if we need more room */
  200520. if (!(png_ptr->zstream.avail_out))
  200521. {
  200522. /* make sure the output array has room */
  200523. if (comp->num_output_ptr >= comp->max_output_ptr)
  200524. {
  200525. int old_max;
  200526. old_max = comp->max_output_ptr;
  200527. comp->max_output_ptr = comp->num_output_ptr + 4;
  200528. if (comp->output_ptr != NULL)
  200529. {
  200530. png_charpp old_ptr;
  200531. old_ptr = comp->output_ptr;
  200532. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200533. (png_uint_32)(comp->max_output_ptr *
  200534. png_sizeof (png_charpp)));
  200535. png_memcpy(comp->output_ptr, old_ptr, old_max
  200536. * png_sizeof (png_charp));
  200537. png_free(png_ptr, old_ptr);
  200538. }
  200539. else
  200540. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200541. (png_uint_32)(comp->max_output_ptr *
  200542. png_sizeof (png_charp)));
  200543. }
  200544. /* save the data */
  200545. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200546. (png_uint_32)png_ptr->zbuf_size);
  200547. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200548. png_ptr->zbuf_size);
  200549. comp->num_output_ptr++;
  200550. /* and reset the buffer */
  200551. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200552. png_ptr->zstream.next_out = png_ptr->zbuf;
  200553. }
  200554. /* continue until we don't have any more to compress */
  200555. } while (png_ptr->zstream.avail_in);
  200556. /* finish the compression */
  200557. do
  200558. {
  200559. /* tell zlib we are finished */
  200560. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200561. if (ret == Z_OK)
  200562. {
  200563. /* check to see if we need more room */
  200564. if (!(png_ptr->zstream.avail_out))
  200565. {
  200566. /* check to make sure our output array has room */
  200567. if (comp->num_output_ptr >= comp->max_output_ptr)
  200568. {
  200569. int old_max;
  200570. old_max = comp->max_output_ptr;
  200571. comp->max_output_ptr = comp->num_output_ptr + 4;
  200572. if (comp->output_ptr != NULL)
  200573. {
  200574. png_charpp old_ptr;
  200575. old_ptr = comp->output_ptr;
  200576. /* This could be optimized to realloc() */
  200577. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200578. (png_uint_32)(comp->max_output_ptr *
  200579. png_sizeof (png_charpp)));
  200580. png_memcpy(comp->output_ptr, old_ptr,
  200581. old_max * png_sizeof (png_charp));
  200582. png_free(png_ptr, old_ptr);
  200583. }
  200584. else
  200585. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200586. (png_uint_32)(comp->max_output_ptr *
  200587. png_sizeof (png_charp)));
  200588. }
  200589. /* save off the data */
  200590. comp->output_ptr[comp->num_output_ptr] =
  200591. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200592. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200593. png_ptr->zbuf_size);
  200594. comp->num_output_ptr++;
  200595. /* and reset the buffer pointers */
  200596. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200597. png_ptr->zstream.next_out = png_ptr->zbuf;
  200598. }
  200599. }
  200600. else if (ret != Z_STREAM_END)
  200601. {
  200602. /* we got an error */
  200603. if (png_ptr->zstream.msg != NULL)
  200604. png_error(png_ptr, png_ptr->zstream.msg);
  200605. else
  200606. png_error(png_ptr, "zlib error");
  200607. }
  200608. } while (ret != Z_STREAM_END);
  200609. /* text length is number of buffers plus last buffer */
  200610. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200611. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200612. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200613. return((int)text_len);
  200614. }
  200615. /* ship the compressed text out via chunk writes */
  200616. static void /* PRIVATE */
  200617. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200618. {
  200619. int i;
  200620. /* handle the no-compression case */
  200621. if (comp->input)
  200622. {
  200623. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200624. (png_size_t)comp->input_len);
  200625. return;
  200626. }
  200627. /* write saved output buffers, if any */
  200628. for (i = 0; i < comp->num_output_ptr; i++)
  200629. {
  200630. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200631. png_ptr->zbuf_size);
  200632. png_free(png_ptr, comp->output_ptr[i]);
  200633. comp->output_ptr[i]=NULL;
  200634. }
  200635. if (comp->max_output_ptr != 0)
  200636. png_free(png_ptr, comp->output_ptr);
  200637. comp->output_ptr=NULL;
  200638. /* write anything left in zbuf */
  200639. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200640. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200641. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200642. /* reset zlib for another zTXt/iTXt or image data */
  200643. deflateReset(&png_ptr->zstream);
  200644. png_ptr->zstream.data_type = Z_BINARY;
  200645. }
  200646. #endif
  200647. /* Write the IHDR chunk, and update the png_struct with the necessary
  200648. * information. Note that the rest of this code depends upon this
  200649. * information being correct.
  200650. */
  200651. void /* PRIVATE */
  200652. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200653. int bit_depth, int color_type, int compression_type, int filter_type,
  200654. int interlace_type)
  200655. {
  200656. #ifdef PNG_USE_LOCAL_ARRAYS
  200657. PNG_IHDR;
  200658. #endif
  200659. png_byte buf[13]; /* buffer to store the IHDR info */
  200660. png_debug(1, "in png_write_IHDR\n");
  200661. /* Check that we have valid input data from the application info */
  200662. switch (color_type)
  200663. {
  200664. case PNG_COLOR_TYPE_GRAY:
  200665. switch (bit_depth)
  200666. {
  200667. case 1:
  200668. case 2:
  200669. case 4:
  200670. case 8:
  200671. case 16: png_ptr->channels = 1; break;
  200672. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200673. }
  200674. break;
  200675. case PNG_COLOR_TYPE_RGB:
  200676. if (bit_depth != 8 && bit_depth != 16)
  200677. png_error(png_ptr, "Invalid bit depth for RGB image");
  200678. png_ptr->channels = 3;
  200679. break;
  200680. case PNG_COLOR_TYPE_PALETTE:
  200681. switch (bit_depth)
  200682. {
  200683. case 1:
  200684. case 2:
  200685. case 4:
  200686. case 8: png_ptr->channels = 1; break;
  200687. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200688. }
  200689. break;
  200690. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200691. if (bit_depth != 8 && bit_depth != 16)
  200692. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200693. png_ptr->channels = 2;
  200694. break;
  200695. case PNG_COLOR_TYPE_RGB_ALPHA:
  200696. if (bit_depth != 8 && bit_depth != 16)
  200697. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200698. png_ptr->channels = 4;
  200699. break;
  200700. default:
  200701. png_error(png_ptr, "Invalid image color type specified");
  200702. }
  200703. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200704. {
  200705. png_warning(png_ptr, "Invalid compression type specified");
  200706. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200707. }
  200708. /* Write filter_method 64 (intrapixel differencing) only if
  200709. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200710. * 2. Libpng did not write a PNG signature (this filter_method is only
  200711. * used in PNG datastreams that are embedded in MNG datastreams) and
  200712. * 3. The application called png_permit_mng_features with a mask that
  200713. * included PNG_FLAG_MNG_FILTER_64 and
  200714. * 4. The filter_method is 64 and
  200715. * 5. The color_type is RGB or RGBA
  200716. */
  200717. if (
  200718. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200719. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200720. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200721. (color_type == PNG_COLOR_TYPE_RGB ||
  200722. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200723. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200724. #endif
  200725. filter_type != PNG_FILTER_TYPE_BASE)
  200726. {
  200727. png_warning(png_ptr, "Invalid filter type specified");
  200728. filter_type = PNG_FILTER_TYPE_BASE;
  200729. }
  200730. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200731. if (interlace_type != PNG_INTERLACE_NONE &&
  200732. interlace_type != PNG_INTERLACE_ADAM7)
  200733. {
  200734. png_warning(png_ptr, "Invalid interlace type specified");
  200735. interlace_type = PNG_INTERLACE_ADAM7;
  200736. }
  200737. #else
  200738. interlace_type=PNG_INTERLACE_NONE;
  200739. #endif
  200740. /* save off the relevent information */
  200741. png_ptr->bit_depth = (png_byte)bit_depth;
  200742. png_ptr->color_type = (png_byte)color_type;
  200743. png_ptr->interlaced = (png_byte)interlace_type;
  200744. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200745. png_ptr->filter_type = (png_byte)filter_type;
  200746. #endif
  200747. png_ptr->compression_type = (png_byte)compression_type;
  200748. png_ptr->width = width;
  200749. png_ptr->height = height;
  200750. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200751. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200752. /* set the usr info, so any transformations can modify it */
  200753. png_ptr->usr_width = png_ptr->width;
  200754. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200755. png_ptr->usr_channels = png_ptr->channels;
  200756. /* pack the header information into the buffer */
  200757. png_save_uint_32(buf, width);
  200758. png_save_uint_32(buf + 4, height);
  200759. buf[8] = (png_byte)bit_depth;
  200760. buf[9] = (png_byte)color_type;
  200761. buf[10] = (png_byte)compression_type;
  200762. buf[11] = (png_byte)filter_type;
  200763. buf[12] = (png_byte)interlace_type;
  200764. /* write the chunk */
  200765. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200766. /* initialize zlib with PNG info */
  200767. png_ptr->zstream.zalloc = png_zalloc;
  200768. png_ptr->zstream.zfree = png_zfree;
  200769. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200770. if (!(png_ptr->do_filter))
  200771. {
  200772. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200773. png_ptr->bit_depth < 8)
  200774. png_ptr->do_filter = PNG_FILTER_NONE;
  200775. else
  200776. png_ptr->do_filter = PNG_ALL_FILTERS;
  200777. }
  200778. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200779. {
  200780. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200781. png_ptr->zlib_strategy = Z_FILTERED;
  200782. else
  200783. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200784. }
  200785. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200786. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200787. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200788. png_ptr->zlib_mem_level = 8;
  200789. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200790. png_ptr->zlib_window_bits = 15;
  200791. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200792. png_ptr->zlib_method = 8;
  200793. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200794. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200795. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200796. png_error(png_ptr, "zlib failed to initialize compressor");
  200797. png_ptr->zstream.next_out = png_ptr->zbuf;
  200798. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200799. /* libpng is not interested in zstream.data_type */
  200800. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200801. png_ptr->zstream.data_type = Z_BINARY;
  200802. png_ptr->mode = PNG_HAVE_IHDR;
  200803. }
  200804. /* write the palette. We are careful not to trust png_color to be in the
  200805. * correct order for PNG, so people can redefine it to any convenient
  200806. * structure.
  200807. */
  200808. void /* PRIVATE */
  200809. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200810. {
  200811. #ifdef PNG_USE_LOCAL_ARRAYS
  200812. PNG_PLTE;
  200813. #endif
  200814. png_uint_32 i;
  200815. png_colorp pal_ptr;
  200816. png_byte buf[3];
  200817. png_debug(1, "in png_write_PLTE\n");
  200818. if ((
  200819. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200820. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200821. #endif
  200822. num_pal == 0) || num_pal > 256)
  200823. {
  200824. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200825. {
  200826. png_error(png_ptr, "Invalid number of colors in palette");
  200827. }
  200828. else
  200829. {
  200830. png_warning(png_ptr, "Invalid number of colors in palette");
  200831. return;
  200832. }
  200833. }
  200834. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200835. {
  200836. png_warning(png_ptr,
  200837. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200838. return;
  200839. }
  200840. png_ptr->num_palette = (png_uint_16)num_pal;
  200841. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200842. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200843. #ifndef PNG_NO_POINTER_INDEXING
  200844. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200845. {
  200846. buf[0] = pal_ptr->red;
  200847. buf[1] = pal_ptr->green;
  200848. buf[2] = pal_ptr->blue;
  200849. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200850. }
  200851. #else
  200852. /* This is a little slower but some buggy compilers need to do this instead */
  200853. pal_ptr=palette;
  200854. for (i = 0; i < num_pal; i++)
  200855. {
  200856. buf[0] = pal_ptr[i].red;
  200857. buf[1] = pal_ptr[i].green;
  200858. buf[2] = pal_ptr[i].blue;
  200859. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200860. }
  200861. #endif
  200862. png_write_chunk_end(png_ptr);
  200863. png_ptr->mode |= PNG_HAVE_PLTE;
  200864. }
  200865. /* write an IDAT chunk */
  200866. void /* PRIVATE */
  200867. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200868. {
  200869. #ifdef PNG_USE_LOCAL_ARRAYS
  200870. PNG_IDAT;
  200871. #endif
  200872. png_debug(1, "in png_write_IDAT\n");
  200873. /* Optimize the CMF field in the zlib stream. */
  200874. /* This hack of the zlib stream is compliant to the stream specification. */
  200875. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200876. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200877. {
  200878. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200879. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200880. {
  200881. /* Avoid memory underflows and multiplication overflows. */
  200882. /* The conditions below are practically always satisfied;
  200883. however, they still must be checked. */
  200884. if (length >= 2 &&
  200885. png_ptr->height < 16384 && png_ptr->width < 16384)
  200886. {
  200887. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200888. ((png_ptr->width *
  200889. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200890. unsigned int z_cinfo = z_cmf >> 4;
  200891. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200892. while (uncompressed_idat_size <= half_z_window_size &&
  200893. half_z_window_size >= 256)
  200894. {
  200895. z_cinfo--;
  200896. half_z_window_size >>= 1;
  200897. }
  200898. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200899. if (data[0] != (png_byte)z_cmf)
  200900. {
  200901. data[0] = (png_byte)z_cmf;
  200902. data[1] &= 0xe0;
  200903. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200904. }
  200905. }
  200906. }
  200907. else
  200908. png_error(png_ptr,
  200909. "Invalid zlib compression method or flags in IDAT");
  200910. }
  200911. png_write_chunk(png_ptr, png_IDAT, data, length);
  200912. png_ptr->mode |= PNG_HAVE_IDAT;
  200913. }
  200914. /* write an IEND chunk */
  200915. void /* PRIVATE */
  200916. png_write_IEND(png_structp png_ptr)
  200917. {
  200918. #ifdef PNG_USE_LOCAL_ARRAYS
  200919. PNG_IEND;
  200920. #endif
  200921. png_debug(1, "in png_write_IEND\n");
  200922. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200923. (png_size_t)0);
  200924. png_ptr->mode |= PNG_HAVE_IEND;
  200925. }
  200926. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200927. /* write a gAMA chunk */
  200928. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200929. void /* PRIVATE */
  200930. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200931. {
  200932. #ifdef PNG_USE_LOCAL_ARRAYS
  200933. PNG_gAMA;
  200934. #endif
  200935. png_uint_32 igamma;
  200936. png_byte buf[4];
  200937. png_debug(1, "in png_write_gAMA\n");
  200938. /* file_gamma is saved in 1/100,000ths */
  200939. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200940. png_save_uint_32(buf, igamma);
  200941. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200942. }
  200943. #endif
  200944. #ifdef PNG_FIXED_POINT_SUPPORTED
  200945. void /* PRIVATE */
  200946. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200947. {
  200948. #ifdef PNG_USE_LOCAL_ARRAYS
  200949. PNG_gAMA;
  200950. #endif
  200951. png_byte buf[4];
  200952. png_debug(1, "in png_write_gAMA\n");
  200953. /* file_gamma is saved in 1/100,000ths */
  200954. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200955. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200956. }
  200957. #endif
  200958. #endif
  200959. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200960. /* write a sRGB chunk */
  200961. void /* PRIVATE */
  200962. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200963. {
  200964. #ifdef PNG_USE_LOCAL_ARRAYS
  200965. PNG_sRGB;
  200966. #endif
  200967. png_byte buf[1];
  200968. png_debug(1, "in png_write_sRGB\n");
  200969. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200970. png_warning(png_ptr,
  200971. "Invalid sRGB rendering intent specified");
  200972. buf[0]=(png_byte)srgb_intent;
  200973. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200974. }
  200975. #endif
  200976. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200977. /* write an iCCP chunk */
  200978. void /* PRIVATE */
  200979. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200980. png_charp profile, int profile_len)
  200981. {
  200982. #ifdef PNG_USE_LOCAL_ARRAYS
  200983. PNG_iCCP;
  200984. #endif
  200985. png_size_t name_len;
  200986. png_charp new_name;
  200987. compression_state comp;
  200988. int embedded_profile_len = 0;
  200989. png_debug(1, "in png_write_iCCP\n");
  200990. comp.num_output_ptr = 0;
  200991. comp.max_output_ptr = 0;
  200992. comp.output_ptr = NULL;
  200993. comp.input = NULL;
  200994. comp.input_len = 0;
  200995. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200996. &new_name)) == 0)
  200997. {
  200998. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200999. return;
  201000. }
  201001. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201002. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201003. if (profile == NULL)
  201004. profile_len = 0;
  201005. if (profile_len > 3)
  201006. embedded_profile_len =
  201007. ((*( (png_bytep)profile ))<<24) |
  201008. ((*( (png_bytep)profile+1))<<16) |
  201009. ((*( (png_bytep)profile+2))<< 8) |
  201010. ((*( (png_bytep)profile+3)) );
  201011. if (profile_len < embedded_profile_len)
  201012. {
  201013. png_warning(png_ptr,
  201014. "Embedded profile length too large in iCCP chunk");
  201015. return;
  201016. }
  201017. if (profile_len > embedded_profile_len)
  201018. {
  201019. png_warning(png_ptr,
  201020. "Truncating profile to actual length in iCCP chunk");
  201021. profile_len = embedded_profile_len;
  201022. }
  201023. if (profile_len)
  201024. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201025. PNG_COMPRESSION_TYPE_BASE, &comp);
  201026. /* make sure we include the NULL after the name and the compression type */
  201027. png_write_chunk_start(png_ptr, png_iCCP,
  201028. (png_uint_32)name_len+profile_len+2);
  201029. new_name[name_len+1]=0x00;
  201030. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201031. if (profile_len)
  201032. png_write_compressed_data_out(png_ptr, &comp);
  201033. png_write_chunk_end(png_ptr);
  201034. png_free(png_ptr, new_name);
  201035. }
  201036. #endif
  201037. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201038. /* write a sPLT chunk */
  201039. void /* PRIVATE */
  201040. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201041. {
  201042. #ifdef PNG_USE_LOCAL_ARRAYS
  201043. PNG_sPLT;
  201044. #endif
  201045. png_size_t name_len;
  201046. png_charp new_name;
  201047. png_byte entrybuf[10];
  201048. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201049. int palette_size = entry_size * spalette->nentries;
  201050. png_sPLT_entryp ep;
  201051. #ifdef PNG_NO_POINTER_INDEXING
  201052. int i;
  201053. #endif
  201054. png_debug(1, "in png_write_sPLT\n");
  201055. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201056. spalette->name, &new_name))==0)
  201057. {
  201058. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201059. return;
  201060. }
  201061. /* make sure we include the NULL after the name */
  201062. png_write_chunk_start(png_ptr, png_sPLT,
  201063. (png_uint_32)(name_len + 2 + palette_size));
  201064. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201065. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201066. /* loop through each palette entry, writing appropriately */
  201067. #ifndef PNG_NO_POINTER_INDEXING
  201068. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201069. {
  201070. if (spalette->depth == 8)
  201071. {
  201072. entrybuf[0] = (png_byte)ep->red;
  201073. entrybuf[1] = (png_byte)ep->green;
  201074. entrybuf[2] = (png_byte)ep->blue;
  201075. entrybuf[3] = (png_byte)ep->alpha;
  201076. png_save_uint_16(entrybuf + 4, ep->frequency);
  201077. }
  201078. else
  201079. {
  201080. png_save_uint_16(entrybuf + 0, ep->red);
  201081. png_save_uint_16(entrybuf + 2, ep->green);
  201082. png_save_uint_16(entrybuf + 4, ep->blue);
  201083. png_save_uint_16(entrybuf + 6, ep->alpha);
  201084. png_save_uint_16(entrybuf + 8, ep->frequency);
  201085. }
  201086. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201087. }
  201088. #else
  201089. ep=spalette->entries;
  201090. for (i=0; i>spalette->nentries; i++)
  201091. {
  201092. if (spalette->depth == 8)
  201093. {
  201094. entrybuf[0] = (png_byte)ep[i].red;
  201095. entrybuf[1] = (png_byte)ep[i].green;
  201096. entrybuf[2] = (png_byte)ep[i].blue;
  201097. entrybuf[3] = (png_byte)ep[i].alpha;
  201098. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201099. }
  201100. else
  201101. {
  201102. png_save_uint_16(entrybuf + 0, ep[i].red);
  201103. png_save_uint_16(entrybuf + 2, ep[i].green);
  201104. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201105. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201106. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201107. }
  201108. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201109. }
  201110. #endif
  201111. png_write_chunk_end(png_ptr);
  201112. png_free(png_ptr, new_name);
  201113. }
  201114. #endif
  201115. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201116. /* write the sBIT chunk */
  201117. void /* PRIVATE */
  201118. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201119. {
  201120. #ifdef PNG_USE_LOCAL_ARRAYS
  201121. PNG_sBIT;
  201122. #endif
  201123. png_byte buf[4];
  201124. png_size_t size;
  201125. png_debug(1, "in png_write_sBIT\n");
  201126. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201127. if (color_type & PNG_COLOR_MASK_COLOR)
  201128. {
  201129. png_byte maxbits;
  201130. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201131. png_ptr->usr_bit_depth);
  201132. if (sbit->red == 0 || sbit->red > maxbits ||
  201133. sbit->green == 0 || sbit->green > maxbits ||
  201134. sbit->blue == 0 || sbit->blue > maxbits)
  201135. {
  201136. png_warning(png_ptr, "Invalid sBIT depth specified");
  201137. return;
  201138. }
  201139. buf[0] = sbit->red;
  201140. buf[1] = sbit->green;
  201141. buf[2] = sbit->blue;
  201142. size = 3;
  201143. }
  201144. else
  201145. {
  201146. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201147. {
  201148. png_warning(png_ptr, "Invalid sBIT depth specified");
  201149. return;
  201150. }
  201151. buf[0] = sbit->gray;
  201152. size = 1;
  201153. }
  201154. if (color_type & PNG_COLOR_MASK_ALPHA)
  201155. {
  201156. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201157. {
  201158. png_warning(png_ptr, "Invalid sBIT depth specified");
  201159. return;
  201160. }
  201161. buf[size++] = sbit->alpha;
  201162. }
  201163. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201164. }
  201165. #endif
  201166. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201167. /* write the cHRM chunk */
  201168. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201169. void /* PRIVATE */
  201170. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201171. double red_x, double red_y, double green_x, double green_y,
  201172. double blue_x, double blue_y)
  201173. {
  201174. #ifdef PNG_USE_LOCAL_ARRAYS
  201175. PNG_cHRM;
  201176. #endif
  201177. png_byte buf[32];
  201178. png_uint_32 itemp;
  201179. png_debug(1, "in png_write_cHRM\n");
  201180. /* each value is saved in 1/100,000ths */
  201181. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201182. white_x + white_y > 1.0)
  201183. {
  201184. png_warning(png_ptr, "Invalid cHRM white point specified");
  201185. #if !defined(PNG_NO_CONSOLE_IO)
  201186. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201187. #endif
  201188. return;
  201189. }
  201190. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201191. png_save_uint_32(buf, itemp);
  201192. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201193. png_save_uint_32(buf + 4, itemp);
  201194. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201195. {
  201196. png_warning(png_ptr, "Invalid cHRM red point specified");
  201197. return;
  201198. }
  201199. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201200. png_save_uint_32(buf + 8, itemp);
  201201. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201202. png_save_uint_32(buf + 12, itemp);
  201203. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201204. {
  201205. png_warning(png_ptr, "Invalid cHRM green point specified");
  201206. return;
  201207. }
  201208. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201209. png_save_uint_32(buf + 16, itemp);
  201210. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201211. png_save_uint_32(buf + 20, itemp);
  201212. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201213. {
  201214. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201215. return;
  201216. }
  201217. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201218. png_save_uint_32(buf + 24, itemp);
  201219. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201220. png_save_uint_32(buf + 28, itemp);
  201221. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201222. }
  201223. #endif
  201224. #ifdef PNG_FIXED_POINT_SUPPORTED
  201225. void /* PRIVATE */
  201226. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201227. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201228. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201229. png_fixed_point blue_y)
  201230. {
  201231. #ifdef PNG_USE_LOCAL_ARRAYS
  201232. PNG_cHRM;
  201233. #endif
  201234. png_byte buf[32];
  201235. png_debug(1, "in png_write_cHRM\n");
  201236. /* each value is saved in 1/100,000ths */
  201237. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201238. {
  201239. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201240. #if !defined(PNG_NO_CONSOLE_IO)
  201241. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201242. #endif
  201243. return;
  201244. }
  201245. png_save_uint_32(buf, (png_uint_32)white_x);
  201246. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201247. if (red_x + red_y > 100000L)
  201248. {
  201249. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201250. return;
  201251. }
  201252. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201253. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201254. if (green_x + green_y > 100000L)
  201255. {
  201256. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201257. return;
  201258. }
  201259. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201260. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201261. if (blue_x + blue_y > 100000L)
  201262. {
  201263. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201264. return;
  201265. }
  201266. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201267. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201268. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201269. }
  201270. #endif
  201271. #endif
  201272. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201273. /* write the tRNS chunk */
  201274. void /* PRIVATE */
  201275. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201276. int num_trans, int color_type)
  201277. {
  201278. #ifdef PNG_USE_LOCAL_ARRAYS
  201279. PNG_tRNS;
  201280. #endif
  201281. png_byte buf[6];
  201282. png_debug(1, "in png_write_tRNS\n");
  201283. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201284. {
  201285. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201286. {
  201287. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201288. return;
  201289. }
  201290. /* write the chunk out as it is */
  201291. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201292. }
  201293. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201294. {
  201295. /* one 16 bit value */
  201296. if(tran->gray >= (1 << png_ptr->bit_depth))
  201297. {
  201298. png_warning(png_ptr,
  201299. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201300. return;
  201301. }
  201302. png_save_uint_16(buf, tran->gray);
  201303. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201304. }
  201305. else if (color_type == PNG_COLOR_TYPE_RGB)
  201306. {
  201307. /* three 16 bit values */
  201308. png_save_uint_16(buf, tran->red);
  201309. png_save_uint_16(buf + 2, tran->green);
  201310. png_save_uint_16(buf + 4, tran->blue);
  201311. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201312. {
  201313. png_warning(png_ptr,
  201314. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201315. return;
  201316. }
  201317. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201318. }
  201319. else
  201320. {
  201321. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201322. }
  201323. }
  201324. #endif
  201325. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201326. /* write the background chunk */
  201327. void /* PRIVATE */
  201328. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201329. {
  201330. #ifdef PNG_USE_LOCAL_ARRAYS
  201331. PNG_bKGD;
  201332. #endif
  201333. png_byte buf[6];
  201334. png_debug(1, "in png_write_bKGD\n");
  201335. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201336. {
  201337. if (
  201338. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201339. (png_ptr->num_palette ||
  201340. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201341. #endif
  201342. back->index > png_ptr->num_palette)
  201343. {
  201344. png_warning(png_ptr, "Invalid background palette index");
  201345. return;
  201346. }
  201347. buf[0] = back->index;
  201348. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201349. }
  201350. else if (color_type & PNG_COLOR_MASK_COLOR)
  201351. {
  201352. png_save_uint_16(buf, back->red);
  201353. png_save_uint_16(buf + 2, back->green);
  201354. png_save_uint_16(buf + 4, back->blue);
  201355. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201356. {
  201357. png_warning(png_ptr,
  201358. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201359. return;
  201360. }
  201361. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201362. }
  201363. else
  201364. {
  201365. if(back->gray >= (1 << png_ptr->bit_depth))
  201366. {
  201367. png_warning(png_ptr,
  201368. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201369. return;
  201370. }
  201371. png_save_uint_16(buf, back->gray);
  201372. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201373. }
  201374. }
  201375. #endif
  201376. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201377. /* write the histogram */
  201378. void /* PRIVATE */
  201379. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201380. {
  201381. #ifdef PNG_USE_LOCAL_ARRAYS
  201382. PNG_hIST;
  201383. #endif
  201384. int i;
  201385. png_byte buf[3];
  201386. png_debug(1, "in png_write_hIST\n");
  201387. if (num_hist > (int)png_ptr->num_palette)
  201388. {
  201389. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201390. png_ptr->num_palette);
  201391. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201392. return;
  201393. }
  201394. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201395. for (i = 0; i < num_hist; i++)
  201396. {
  201397. png_save_uint_16(buf, hist[i]);
  201398. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201399. }
  201400. png_write_chunk_end(png_ptr);
  201401. }
  201402. #endif
  201403. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201404. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201405. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201406. * and if invalid, correct the keyword rather than discarding the entire
  201407. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201408. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201409. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201410. *
  201411. * The new_key is allocated to hold the corrected keyword and must be freed
  201412. * by the calling routine. This avoids problems with trying to write to
  201413. * static keywords without having to have duplicate copies of the strings.
  201414. */
  201415. png_size_t /* PRIVATE */
  201416. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201417. {
  201418. png_size_t key_len;
  201419. png_charp kp, dp;
  201420. int kflag;
  201421. int kwarn=0;
  201422. png_debug(1, "in png_check_keyword\n");
  201423. *new_key = NULL;
  201424. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201425. {
  201426. png_warning(png_ptr, "zero length keyword");
  201427. return ((png_size_t)0);
  201428. }
  201429. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201430. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201431. if (*new_key == NULL)
  201432. {
  201433. png_warning(png_ptr, "Out of memory while procesing keyword");
  201434. return ((png_size_t)0);
  201435. }
  201436. /* Replace non-printing characters with a blank and print a warning */
  201437. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201438. {
  201439. if ((png_byte)*kp < 0x20 ||
  201440. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201441. {
  201442. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201443. char msg[40];
  201444. png_snprintf(msg, 40,
  201445. "invalid keyword character 0x%02X", (png_byte)*kp);
  201446. png_warning(png_ptr, msg);
  201447. #else
  201448. png_warning(png_ptr, "invalid character in keyword");
  201449. #endif
  201450. *dp = ' ';
  201451. }
  201452. else
  201453. {
  201454. *dp = *kp;
  201455. }
  201456. }
  201457. *dp = '\0';
  201458. /* Remove any trailing white space. */
  201459. kp = *new_key + key_len - 1;
  201460. if (*kp == ' ')
  201461. {
  201462. png_warning(png_ptr, "trailing spaces removed from keyword");
  201463. while (*kp == ' ')
  201464. {
  201465. *(kp--) = '\0';
  201466. key_len--;
  201467. }
  201468. }
  201469. /* Remove any leading white space. */
  201470. kp = *new_key;
  201471. if (*kp == ' ')
  201472. {
  201473. png_warning(png_ptr, "leading spaces removed from keyword");
  201474. while (*kp == ' ')
  201475. {
  201476. kp++;
  201477. key_len--;
  201478. }
  201479. }
  201480. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201481. /* Remove multiple internal spaces. */
  201482. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201483. {
  201484. if (*kp == ' ' && kflag == 0)
  201485. {
  201486. *(dp++) = *kp;
  201487. kflag = 1;
  201488. }
  201489. else if (*kp == ' ')
  201490. {
  201491. key_len--;
  201492. kwarn=1;
  201493. }
  201494. else
  201495. {
  201496. *(dp++) = *kp;
  201497. kflag = 0;
  201498. }
  201499. }
  201500. *dp = '\0';
  201501. if(kwarn)
  201502. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201503. if (key_len == 0)
  201504. {
  201505. png_free(png_ptr, *new_key);
  201506. *new_key=NULL;
  201507. png_warning(png_ptr, "Zero length keyword");
  201508. }
  201509. if (key_len > 79)
  201510. {
  201511. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201512. new_key[79] = '\0';
  201513. key_len = 79;
  201514. }
  201515. return (key_len);
  201516. }
  201517. #endif
  201518. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201519. /* write a tEXt chunk */
  201520. void /* PRIVATE */
  201521. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201522. png_size_t text_len)
  201523. {
  201524. #ifdef PNG_USE_LOCAL_ARRAYS
  201525. PNG_tEXt;
  201526. #endif
  201527. png_size_t key_len;
  201528. png_charp new_key;
  201529. png_debug(1, "in png_write_tEXt\n");
  201530. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201531. {
  201532. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201533. return;
  201534. }
  201535. if (text == NULL || *text == '\0')
  201536. text_len = 0;
  201537. else
  201538. text_len = png_strlen(text);
  201539. /* make sure we include the 0 after the key */
  201540. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201541. /*
  201542. * We leave it to the application to meet PNG-1.0 requirements on the
  201543. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201544. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201545. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201546. */
  201547. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201548. if (text_len)
  201549. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201550. png_write_chunk_end(png_ptr);
  201551. png_free(png_ptr, new_key);
  201552. }
  201553. #endif
  201554. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201555. /* write a compressed text chunk */
  201556. void /* PRIVATE */
  201557. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201558. png_size_t text_len, int compression)
  201559. {
  201560. #ifdef PNG_USE_LOCAL_ARRAYS
  201561. PNG_zTXt;
  201562. #endif
  201563. png_size_t key_len;
  201564. char buf[1];
  201565. png_charp new_key;
  201566. compression_state comp;
  201567. png_debug(1, "in png_write_zTXt\n");
  201568. comp.num_output_ptr = 0;
  201569. comp.max_output_ptr = 0;
  201570. comp.output_ptr = NULL;
  201571. comp.input = NULL;
  201572. comp.input_len = 0;
  201573. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201574. {
  201575. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201576. return;
  201577. }
  201578. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201579. {
  201580. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201581. png_free(png_ptr, new_key);
  201582. return;
  201583. }
  201584. text_len = png_strlen(text);
  201585. /* compute the compressed data; do it now for the length */
  201586. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201587. &comp);
  201588. /* write start of chunk */
  201589. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201590. (key_len+text_len+2));
  201591. /* write key */
  201592. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201593. png_free(png_ptr, new_key);
  201594. buf[0] = (png_byte)compression;
  201595. /* write compression */
  201596. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201597. /* write the compressed data */
  201598. png_write_compressed_data_out(png_ptr, &comp);
  201599. /* close the chunk */
  201600. png_write_chunk_end(png_ptr);
  201601. }
  201602. #endif
  201603. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201604. /* write an iTXt chunk */
  201605. void /* PRIVATE */
  201606. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201607. png_charp lang, png_charp lang_key, png_charp text)
  201608. {
  201609. #ifdef PNG_USE_LOCAL_ARRAYS
  201610. PNG_iTXt;
  201611. #endif
  201612. png_size_t lang_len, key_len, lang_key_len, text_len;
  201613. png_charp new_lang, new_key;
  201614. png_byte cbuf[2];
  201615. compression_state comp;
  201616. png_debug(1, "in png_write_iTXt\n");
  201617. comp.num_output_ptr = 0;
  201618. comp.max_output_ptr = 0;
  201619. comp.output_ptr = NULL;
  201620. comp.input = NULL;
  201621. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201622. {
  201623. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201624. return;
  201625. }
  201626. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201627. {
  201628. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201629. new_lang = NULL;
  201630. lang_len = 0;
  201631. }
  201632. if (lang_key == NULL)
  201633. lang_key_len = 0;
  201634. else
  201635. lang_key_len = png_strlen(lang_key);
  201636. if (text == NULL)
  201637. text_len = 0;
  201638. else
  201639. text_len = png_strlen(text);
  201640. /* compute the compressed data; do it now for the length */
  201641. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201642. &comp);
  201643. /* make sure we include the compression flag, the compression byte,
  201644. * and the NULs after the key, lang, and lang_key parts */
  201645. png_write_chunk_start(png_ptr, png_iTXt,
  201646. (png_uint_32)(
  201647. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201648. + key_len
  201649. + lang_len
  201650. + lang_key_len
  201651. + text_len));
  201652. /*
  201653. * We leave it to the application to meet PNG-1.0 requirements on the
  201654. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201655. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201656. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201657. */
  201658. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201659. /* set the compression flag */
  201660. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201661. compression == PNG_TEXT_COMPRESSION_NONE)
  201662. cbuf[0] = 0;
  201663. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201664. cbuf[0] = 1;
  201665. /* set the compression method */
  201666. cbuf[1] = 0;
  201667. png_write_chunk_data(png_ptr, cbuf, 2);
  201668. cbuf[0] = 0;
  201669. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201670. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201671. png_write_compressed_data_out(png_ptr, &comp);
  201672. png_write_chunk_end(png_ptr);
  201673. png_free(png_ptr, new_key);
  201674. if (new_lang)
  201675. png_free(png_ptr, new_lang);
  201676. }
  201677. #endif
  201678. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201679. /* write the oFFs chunk */
  201680. void /* PRIVATE */
  201681. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201682. int unit_type)
  201683. {
  201684. #ifdef PNG_USE_LOCAL_ARRAYS
  201685. PNG_oFFs;
  201686. #endif
  201687. png_byte buf[9];
  201688. png_debug(1, "in png_write_oFFs\n");
  201689. if (unit_type >= PNG_OFFSET_LAST)
  201690. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201691. png_save_int_32(buf, x_offset);
  201692. png_save_int_32(buf + 4, y_offset);
  201693. buf[8] = (png_byte)unit_type;
  201694. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201695. }
  201696. #endif
  201697. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201698. /* write the pCAL chunk (described in the PNG extensions document) */
  201699. void /* PRIVATE */
  201700. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201701. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201702. {
  201703. #ifdef PNG_USE_LOCAL_ARRAYS
  201704. PNG_pCAL;
  201705. #endif
  201706. png_size_t purpose_len, units_len, total_len;
  201707. png_uint_32p params_len;
  201708. png_byte buf[10];
  201709. png_charp new_purpose;
  201710. int i;
  201711. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201712. if (type >= PNG_EQUATION_LAST)
  201713. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201714. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201715. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201716. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201717. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201718. total_len = purpose_len + units_len + 10;
  201719. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201720. *png_sizeof(png_uint_32)));
  201721. /* Find the length of each parameter, making sure we don't count the
  201722. null terminator for the last parameter. */
  201723. for (i = 0; i < nparams; i++)
  201724. {
  201725. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201726. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201727. total_len += (png_size_t)params_len[i];
  201728. }
  201729. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201730. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201731. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201732. png_save_int_32(buf, X0);
  201733. png_save_int_32(buf + 4, X1);
  201734. buf[8] = (png_byte)type;
  201735. buf[9] = (png_byte)nparams;
  201736. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201737. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201738. png_free(png_ptr, new_purpose);
  201739. for (i = 0; i < nparams; i++)
  201740. {
  201741. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201742. (png_size_t)params_len[i]);
  201743. }
  201744. png_free(png_ptr, params_len);
  201745. png_write_chunk_end(png_ptr);
  201746. }
  201747. #endif
  201748. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201749. /* write the sCAL chunk */
  201750. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201751. void /* PRIVATE */
  201752. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201753. {
  201754. #ifdef PNG_USE_LOCAL_ARRAYS
  201755. PNG_sCAL;
  201756. #endif
  201757. char buf[64];
  201758. png_size_t total_len;
  201759. png_debug(1, "in png_write_sCAL\n");
  201760. buf[0] = (char)unit;
  201761. #if defined(_WIN32_WCE)
  201762. /* sprintf() function is not supported on WindowsCE */
  201763. {
  201764. wchar_t wc_buf[32];
  201765. size_t wc_len;
  201766. swprintf(wc_buf, TEXT("%12.12e"), width);
  201767. wc_len = wcslen(wc_buf);
  201768. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201769. total_len = wc_len + 2;
  201770. swprintf(wc_buf, TEXT("%12.12e"), height);
  201771. wc_len = wcslen(wc_buf);
  201772. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201773. NULL, NULL);
  201774. total_len += wc_len;
  201775. }
  201776. #else
  201777. png_snprintf(buf + 1, 63, "%12.12e", width);
  201778. total_len = 1 + png_strlen(buf + 1) + 1;
  201779. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201780. total_len += png_strlen(buf + total_len);
  201781. #endif
  201782. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201783. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201784. }
  201785. #else
  201786. #ifdef PNG_FIXED_POINT_SUPPORTED
  201787. void /* PRIVATE */
  201788. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201789. png_charp height)
  201790. {
  201791. #ifdef PNG_USE_LOCAL_ARRAYS
  201792. PNG_sCAL;
  201793. #endif
  201794. png_byte buf[64];
  201795. png_size_t wlen, hlen, total_len;
  201796. png_debug(1, "in png_write_sCAL_s\n");
  201797. wlen = png_strlen(width);
  201798. hlen = png_strlen(height);
  201799. total_len = wlen + hlen + 2;
  201800. if (total_len > 64)
  201801. {
  201802. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201803. return;
  201804. }
  201805. buf[0] = (png_byte)unit;
  201806. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201807. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201808. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201809. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201810. }
  201811. #endif
  201812. #endif
  201813. #endif
  201814. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201815. /* write the pHYs chunk */
  201816. void /* PRIVATE */
  201817. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201818. png_uint_32 y_pixels_per_unit,
  201819. int unit_type)
  201820. {
  201821. #ifdef PNG_USE_LOCAL_ARRAYS
  201822. PNG_pHYs;
  201823. #endif
  201824. png_byte buf[9];
  201825. png_debug(1, "in png_write_pHYs\n");
  201826. if (unit_type >= PNG_RESOLUTION_LAST)
  201827. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201828. png_save_uint_32(buf, x_pixels_per_unit);
  201829. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201830. buf[8] = (png_byte)unit_type;
  201831. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201832. }
  201833. #endif
  201834. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201835. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201836. * or png_convert_from_time_t(), or fill in the structure yourself.
  201837. */
  201838. void /* PRIVATE */
  201839. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201840. {
  201841. #ifdef PNG_USE_LOCAL_ARRAYS
  201842. PNG_tIME;
  201843. #endif
  201844. png_byte buf[7];
  201845. png_debug(1, "in png_write_tIME\n");
  201846. if (mod_time->month > 12 || mod_time->month < 1 ||
  201847. mod_time->day > 31 || mod_time->day < 1 ||
  201848. mod_time->hour > 23 || mod_time->second > 60)
  201849. {
  201850. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201851. return;
  201852. }
  201853. png_save_uint_16(buf, mod_time->year);
  201854. buf[2] = mod_time->month;
  201855. buf[3] = mod_time->day;
  201856. buf[4] = mod_time->hour;
  201857. buf[5] = mod_time->minute;
  201858. buf[6] = mod_time->second;
  201859. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201860. }
  201861. #endif
  201862. /* initializes the row writing capability of libpng */
  201863. void /* PRIVATE */
  201864. png_write_start_row(png_structp png_ptr)
  201865. {
  201866. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201867. #ifdef PNG_USE_LOCAL_ARRAYS
  201868. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201869. /* start of interlace block */
  201870. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201871. /* offset to next interlace block */
  201872. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201873. /* start of interlace block in the y direction */
  201874. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201875. /* offset to next interlace block in the y direction */
  201876. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201877. #endif
  201878. #endif
  201879. png_size_t buf_size;
  201880. png_debug(1, "in png_write_start_row\n");
  201881. buf_size = (png_size_t)(PNG_ROWBYTES(
  201882. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201883. /* set up row buffer */
  201884. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201885. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201886. #ifndef PNG_NO_WRITE_FILTERING
  201887. /* set up filtering buffer, if using this filter */
  201888. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201889. {
  201890. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201891. (png_ptr->rowbytes + 1));
  201892. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201893. }
  201894. /* We only need to keep the previous row if we are using one of these. */
  201895. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201896. {
  201897. /* set up previous row buffer */
  201898. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201899. png_memset(png_ptr->prev_row, 0, buf_size);
  201900. if (png_ptr->do_filter & PNG_FILTER_UP)
  201901. {
  201902. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201903. (png_ptr->rowbytes + 1));
  201904. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201905. }
  201906. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201907. {
  201908. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201909. (png_ptr->rowbytes + 1));
  201910. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201911. }
  201912. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201913. {
  201914. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201915. (png_ptr->rowbytes + 1));
  201916. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201917. }
  201918. #endif /* PNG_NO_WRITE_FILTERING */
  201919. }
  201920. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201921. /* if interlaced, we need to set up width and height of pass */
  201922. if (png_ptr->interlaced)
  201923. {
  201924. if (!(png_ptr->transformations & PNG_INTERLACE))
  201925. {
  201926. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201927. png_pass_ystart[0]) / png_pass_yinc[0];
  201928. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201929. png_pass_start[0]) / png_pass_inc[0];
  201930. }
  201931. else
  201932. {
  201933. png_ptr->num_rows = png_ptr->height;
  201934. png_ptr->usr_width = png_ptr->width;
  201935. }
  201936. }
  201937. else
  201938. #endif
  201939. {
  201940. png_ptr->num_rows = png_ptr->height;
  201941. png_ptr->usr_width = png_ptr->width;
  201942. }
  201943. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201944. png_ptr->zstream.next_out = png_ptr->zbuf;
  201945. }
  201946. /* Internal use only. Called when finished processing a row of data. */
  201947. void /* PRIVATE */
  201948. png_write_finish_row(png_structp png_ptr)
  201949. {
  201950. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201951. #ifdef PNG_USE_LOCAL_ARRAYS
  201952. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201953. /* start of interlace block */
  201954. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201955. /* offset to next interlace block */
  201956. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201957. /* start of interlace block in the y direction */
  201958. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201959. /* offset to next interlace block in the y direction */
  201960. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201961. #endif
  201962. #endif
  201963. int ret;
  201964. png_debug(1, "in png_write_finish_row\n");
  201965. /* next row */
  201966. png_ptr->row_number++;
  201967. /* see if we are done */
  201968. if (png_ptr->row_number < png_ptr->num_rows)
  201969. return;
  201970. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201971. /* if interlaced, go to next pass */
  201972. if (png_ptr->interlaced)
  201973. {
  201974. png_ptr->row_number = 0;
  201975. if (png_ptr->transformations & PNG_INTERLACE)
  201976. {
  201977. png_ptr->pass++;
  201978. }
  201979. else
  201980. {
  201981. /* loop until we find a non-zero width or height pass */
  201982. do
  201983. {
  201984. png_ptr->pass++;
  201985. if (png_ptr->pass >= 7)
  201986. break;
  201987. png_ptr->usr_width = (png_ptr->width +
  201988. png_pass_inc[png_ptr->pass] - 1 -
  201989. png_pass_start[png_ptr->pass]) /
  201990. png_pass_inc[png_ptr->pass];
  201991. png_ptr->num_rows = (png_ptr->height +
  201992. png_pass_yinc[png_ptr->pass] - 1 -
  201993. png_pass_ystart[png_ptr->pass]) /
  201994. png_pass_yinc[png_ptr->pass];
  201995. if (png_ptr->transformations & PNG_INTERLACE)
  201996. break;
  201997. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201998. }
  201999. /* reset the row above the image for the next pass */
  202000. if (png_ptr->pass < 7)
  202001. {
  202002. if (png_ptr->prev_row != NULL)
  202003. png_memset(png_ptr->prev_row, 0,
  202004. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202005. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202006. return;
  202007. }
  202008. }
  202009. #endif
  202010. /* if we get here, we've just written the last row, so we need
  202011. to flush the compressor */
  202012. do
  202013. {
  202014. /* tell the compressor we are done */
  202015. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202016. /* check for an error */
  202017. if (ret == Z_OK)
  202018. {
  202019. /* check to see if we need more room */
  202020. if (!(png_ptr->zstream.avail_out))
  202021. {
  202022. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202023. png_ptr->zstream.next_out = png_ptr->zbuf;
  202024. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202025. }
  202026. }
  202027. else if (ret != Z_STREAM_END)
  202028. {
  202029. if (png_ptr->zstream.msg != NULL)
  202030. png_error(png_ptr, png_ptr->zstream.msg);
  202031. else
  202032. png_error(png_ptr, "zlib error");
  202033. }
  202034. } while (ret != Z_STREAM_END);
  202035. /* write any extra space */
  202036. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202037. {
  202038. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202039. png_ptr->zstream.avail_out);
  202040. }
  202041. deflateReset(&png_ptr->zstream);
  202042. png_ptr->zstream.data_type = Z_BINARY;
  202043. }
  202044. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202045. /* Pick out the correct pixels for the interlace pass.
  202046. * The basic idea here is to go through the row with a source
  202047. * pointer and a destination pointer (sp and dp), and copy the
  202048. * correct pixels for the pass. As the row gets compacted,
  202049. * sp will always be >= dp, so we should never overwrite anything.
  202050. * See the default: case for the easiest code to understand.
  202051. */
  202052. void /* PRIVATE */
  202053. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202054. {
  202055. #ifdef PNG_USE_LOCAL_ARRAYS
  202056. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202057. /* start of interlace block */
  202058. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202059. /* offset to next interlace block */
  202060. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202061. #endif
  202062. png_debug(1, "in png_do_write_interlace\n");
  202063. /* we don't have to do anything on the last pass (6) */
  202064. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202065. if (row != NULL && row_info != NULL && pass < 6)
  202066. #else
  202067. if (pass < 6)
  202068. #endif
  202069. {
  202070. /* each pixel depth is handled separately */
  202071. switch (row_info->pixel_depth)
  202072. {
  202073. case 1:
  202074. {
  202075. png_bytep sp;
  202076. png_bytep dp;
  202077. int shift;
  202078. int d;
  202079. int value;
  202080. png_uint_32 i;
  202081. png_uint_32 row_width = row_info->width;
  202082. dp = row;
  202083. d = 0;
  202084. shift = 7;
  202085. for (i = png_pass_start[pass]; i < row_width;
  202086. i += png_pass_inc[pass])
  202087. {
  202088. sp = row + (png_size_t)(i >> 3);
  202089. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202090. d |= (value << shift);
  202091. if (shift == 0)
  202092. {
  202093. shift = 7;
  202094. *dp++ = (png_byte)d;
  202095. d = 0;
  202096. }
  202097. else
  202098. shift--;
  202099. }
  202100. if (shift != 7)
  202101. *dp = (png_byte)d;
  202102. break;
  202103. }
  202104. case 2:
  202105. {
  202106. png_bytep sp;
  202107. png_bytep dp;
  202108. int shift;
  202109. int d;
  202110. int value;
  202111. png_uint_32 i;
  202112. png_uint_32 row_width = row_info->width;
  202113. dp = row;
  202114. shift = 6;
  202115. d = 0;
  202116. for (i = png_pass_start[pass]; i < row_width;
  202117. i += png_pass_inc[pass])
  202118. {
  202119. sp = row + (png_size_t)(i >> 2);
  202120. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202121. d |= (value << shift);
  202122. if (shift == 0)
  202123. {
  202124. shift = 6;
  202125. *dp++ = (png_byte)d;
  202126. d = 0;
  202127. }
  202128. else
  202129. shift -= 2;
  202130. }
  202131. if (shift != 6)
  202132. *dp = (png_byte)d;
  202133. break;
  202134. }
  202135. case 4:
  202136. {
  202137. png_bytep sp;
  202138. png_bytep dp;
  202139. int shift;
  202140. int d;
  202141. int value;
  202142. png_uint_32 i;
  202143. png_uint_32 row_width = row_info->width;
  202144. dp = row;
  202145. shift = 4;
  202146. d = 0;
  202147. for (i = png_pass_start[pass]; i < row_width;
  202148. i += png_pass_inc[pass])
  202149. {
  202150. sp = row + (png_size_t)(i >> 1);
  202151. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202152. d |= (value << shift);
  202153. if (shift == 0)
  202154. {
  202155. shift = 4;
  202156. *dp++ = (png_byte)d;
  202157. d = 0;
  202158. }
  202159. else
  202160. shift -= 4;
  202161. }
  202162. if (shift != 4)
  202163. *dp = (png_byte)d;
  202164. break;
  202165. }
  202166. default:
  202167. {
  202168. png_bytep sp;
  202169. png_bytep dp;
  202170. png_uint_32 i;
  202171. png_uint_32 row_width = row_info->width;
  202172. png_size_t pixel_bytes;
  202173. /* start at the beginning */
  202174. dp = row;
  202175. /* find out how many bytes each pixel takes up */
  202176. pixel_bytes = (row_info->pixel_depth >> 3);
  202177. /* loop through the row, only looking at the pixels that
  202178. matter */
  202179. for (i = png_pass_start[pass]; i < row_width;
  202180. i += png_pass_inc[pass])
  202181. {
  202182. /* find out where the original pixel is */
  202183. sp = row + (png_size_t)i * pixel_bytes;
  202184. /* move the pixel */
  202185. if (dp != sp)
  202186. png_memcpy(dp, sp, pixel_bytes);
  202187. /* next pixel */
  202188. dp += pixel_bytes;
  202189. }
  202190. break;
  202191. }
  202192. }
  202193. /* set new row width */
  202194. row_info->width = (row_info->width +
  202195. png_pass_inc[pass] - 1 -
  202196. png_pass_start[pass]) /
  202197. png_pass_inc[pass];
  202198. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202199. row_info->width);
  202200. }
  202201. }
  202202. #endif
  202203. /* This filters the row, chooses which filter to use, if it has not already
  202204. * been specified by the application, and then writes the row out with the
  202205. * chosen filter.
  202206. */
  202207. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202208. #define PNG_HISHIFT 10
  202209. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202210. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202211. void /* PRIVATE */
  202212. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202213. {
  202214. png_bytep best_row;
  202215. #ifndef PNG_NO_WRITE_FILTER
  202216. png_bytep prev_row, row_buf;
  202217. png_uint_32 mins, bpp;
  202218. png_byte filter_to_do = png_ptr->do_filter;
  202219. png_uint_32 row_bytes = row_info->rowbytes;
  202220. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202221. int num_p_filters = (int)png_ptr->num_prev_filters;
  202222. #endif
  202223. png_debug(1, "in png_write_find_filter\n");
  202224. /* find out how many bytes offset each pixel is */
  202225. bpp = (row_info->pixel_depth + 7) >> 3;
  202226. prev_row = png_ptr->prev_row;
  202227. #endif
  202228. best_row = png_ptr->row_buf;
  202229. #ifndef PNG_NO_WRITE_FILTER
  202230. row_buf = best_row;
  202231. mins = PNG_MAXSUM;
  202232. /* The prediction method we use is to find which method provides the
  202233. * smallest value when summing the absolute values of the distances
  202234. * from zero, using anything >= 128 as negative numbers. This is known
  202235. * as the "minimum sum of absolute differences" heuristic. Other
  202236. * heuristics are the "weighted minimum sum of absolute differences"
  202237. * (experimental and can in theory improve compression), and the "zlib
  202238. * predictive" method (not implemented yet), which does test compressions
  202239. * of lines using different filter methods, and then chooses the
  202240. * (series of) filter(s) that give minimum compressed data size (VERY
  202241. * computationally expensive).
  202242. *
  202243. * GRR 980525: consider also
  202244. * (1) minimum sum of absolute differences from running average (i.e.,
  202245. * keep running sum of non-absolute differences & count of bytes)
  202246. * [track dispersion, too? restart average if dispersion too large?]
  202247. * (1b) minimum sum of absolute differences from sliding average, probably
  202248. * with window size <= deflate window (usually 32K)
  202249. * (2) minimum sum of squared differences from zero or running average
  202250. * (i.e., ~ root-mean-square approach)
  202251. */
  202252. /* We don't need to test the 'no filter' case if this is the only filter
  202253. * that has been chosen, as it doesn't actually do anything to the data.
  202254. */
  202255. if ((filter_to_do & PNG_FILTER_NONE) &&
  202256. filter_to_do != PNG_FILTER_NONE)
  202257. {
  202258. png_bytep rp;
  202259. png_uint_32 sum = 0;
  202260. png_uint_32 i;
  202261. int v;
  202262. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202263. {
  202264. v = *rp;
  202265. sum += (v < 128) ? v : 256 - v;
  202266. }
  202267. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202268. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202269. {
  202270. png_uint_32 sumhi, sumlo;
  202271. int j;
  202272. sumlo = sum & PNG_LOMASK;
  202273. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202274. /* Reduce the sum if we match any of the previous rows */
  202275. for (j = 0; j < num_p_filters; j++)
  202276. {
  202277. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202278. {
  202279. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202280. PNG_WEIGHT_SHIFT;
  202281. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202282. PNG_WEIGHT_SHIFT;
  202283. }
  202284. }
  202285. /* Factor in the cost of this filter (this is here for completeness,
  202286. * but it makes no sense to have a "cost" for the NONE filter, as
  202287. * it has the minimum possible computational cost - none).
  202288. */
  202289. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202290. PNG_COST_SHIFT;
  202291. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202292. PNG_COST_SHIFT;
  202293. if (sumhi > PNG_HIMASK)
  202294. sum = PNG_MAXSUM;
  202295. else
  202296. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202297. }
  202298. #endif
  202299. mins = sum;
  202300. }
  202301. /* sub filter */
  202302. if (filter_to_do == PNG_FILTER_SUB)
  202303. /* it's the only filter so no testing is needed */
  202304. {
  202305. png_bytep rp, lp, dp;
  202306. png_uint_32 i;
  202307. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202308. i++, rp++, dp++)
  202309. {
  202310. *dp = *rp;
  202311. }
  202312. for (lp = row_buf + 1; i < row_bytes;
  202313. i++, rp++, lp++, dp++)
  202314. {
  202315. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202316. }
  202317. best_row = png_ptr->sub_row;
  202318. }
  202319. else if (filter_to_do & PNG_FILTER_SUB)
  202320. {
  202321. png_bytep rp, dp, lp;
  202322. png_uint_32 sum = 0, lmins = mins;
  202323. png_uint_32 i;
  202324. int v;
  202325. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202326. /* We temporarily increase the "minimum sum" by the factor we
  202327. * would reduce the sum of this filter, so that we can do the
  202328. * early exit comparison without scaling the sum each time.
  202329. */
  202330. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202331. {
  202332. int j;
  202333. png_uint_32 lmhi, lmlo;
  202334. lmlo = lmins & PNG_LOMASK;
  202335. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202336. for (j = 0; j < num_p_filters; j++)
  202337. {
  202338. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202339. {
  202340. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202341. PNG_WEIGHT_SHIFT;
  202342. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202343. PNG_WEIGHT_SHIFT;
  202344. }
  202345. }
  202346. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202347. PNG_COST_SHIFT;
  202348. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202349. PNG_COST_SHIFT;
  202350. if (lmhi > PNG_HIMASK)
  202351. lmins = PNG_MAXSUM;
  202352. else
  202353. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202354. }
  202355. #endif
  202356. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202357. i++, rp++, dp++)
  202358. {
  202359. v = *dp = *rp;
  202360. sum += (v < 128) ? v : 256 - v;
  202361. }
  202362. for (lp = row_buf + 1; i < row_bytes;
  202363. i++, rp++, lp++, dp++)
  202364. {
  202365. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202366. sum += (v < 128) ? v : 256 - v;
  202367. if (sum > lmins) /* We are already worse, don't continue. */
  202368. break;
  202369. }
  202370. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202371. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202372. {
  202373. int j;
  202374. png_uint_32 sumhi, sumlo;
  202375. sumlo = sum & PNG_LOMASK;
  202376. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202377. for (j = 0; j < num_p_filters; j++)
  202378. {
  202379. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202380. {
  202381. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202382. PNG_WEIGHT_SHIFT;
  202383. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202384. PNG_WEIGHT_SHIFT;
  202385. }
  202386. }
  202387. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202388. PNG_COST_SHIFT;
  202389. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202390. PNG_COST_SHIFT;
  202391. if (sumhi > PNG_HIMASK)
  202392. sum = PNG_MAXSUM;
  202393. else
  202394. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202395. }
  202396. #endif
  202397. if (sum < mins)
  202398. {
  202399. mins = sum;
  202400. best_row = png_ptr->sub_row;
  202401. }
  202402. }
  202403. /* up filter */
  202404. if (filter_to_do == PNG_FILTER_UP)
  202405. {
  202406. png_bytep rp, dp, pp;
  202407. png_uint_32 i;
  202408. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202409. pp = prev_row + 1; i < row_bytes;
  202410. i++, rp++, pp++, dp++)
  202411. {
  202412. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202413. }
  202414. best_row = png_ptr->up_row;
  202415. }
  202416. else if (filter_to_do & PNG_FILTER_UP)
  202417. {
  202418. png_bytep rp, dp, pp;
  202419. png_uint_32 sum = 0, lmins = mins;
  202420. png_uint_32 i;
  202421. int v;
  202422. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202423. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202424. {
  202425. int j;
  202426. png_uint_32 lmhi, lmlo;
  202427. lmlo = lmins & PNG_LOMASK;
  202428. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202429. for (j = 0; j < num_p_filters; j++)
  202430. {
  202431. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202432. {
  202433. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202434. PNG_WEIGHT_SHIFT;
  202435. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202436. PNG_WEIGHT_SHIFT;
  202437. }
  202438. }
  202439. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202440. PNG_COST_SHIFT;
  202441. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202442. PNG_COST_SHIFT;
  202443. if (lmhi > PNG_HIMASK)
  202444. lmins = PNG_MAXSUM;
  202445. else
  202446. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202447. }
  202448. #endif
  202449. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202450. pp = prev_row + 1; i < row_bytes; i++)
  202451. {
  202452. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202453. sum += (v < 128) ? v : 256 - v;
  202454. if (sum > lmins) /* We are already worse, don't continue. */
  202455. break;
  202456. }
  202457. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202458. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202459. {
  202460. int j;
  202461. png_uint_32 sumhi, sumlo;
  202462. sumlo = sum & PNG_LOMASK;
  202463. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202464. for (j = 0; j < num_p_filters; j++)
  202465. {
  202466. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202467. {
  202468. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202469. PNG_WEIGHT_SHIFT;
  202470. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202471. PNG_WEIGHT_SHIFT;
  202472. }
  202473. }
  202474. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202475. PNG_COST_SHIFT;
  202476. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202477. PNG_COST_SHIFT;
  202478. if (sumhi > PNG_HIMASK)
  202479. sum = PNG_MAXSUM;
  202480. else
  202481. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202482. }
  202483. #endif
  202484. if (sum < mins)
  202485. {
  202486. mins = sum;
  202487. best_row = png_ptr->up_row;
  202488. }
  202489. }
  202490. /* avg filter */
  202491. if (filter_to_do == PNG_FILTER_AVG)
  202492. {
  202493. png_bytep rp, dp, pp, lp;
  202494. png_uint_32 i;
  202495. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202496. pp = prev_row + 1; i < bpp; i++)
  202497. {
  202498. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202499. }
  202500. for (lp = row_buf + 1; i < row_bytes; i++)
  202501. {
  202502. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202503. & 0xff);
  202504. }
  202505. best_row = png_ptr->avg_row;
  202506. }
  202507. else if (filter_to_do & PNG_FILTER_AVG)
  202508. {
  202509. png_bytep rp, dp, pp, lp;
  202510. png_uint_32 sum = 0, lmins = mins;
  202511. png_uint_32 i;
  202512. int v;
  202513. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202514. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202515. {
  202516. int j;
  202517. png_uint_32 lmhi, lmlo;
  202518. lmlo = lmins & PNG_LOMASK;
  202519. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202520. for (j = 0; j < num_p_filters; j++)
  202521. {
  202522. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202523. {
  202524. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202525. PNG_WEIGHT_SHIFT;
  202526. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202527. PNG_WEIGHT_SHIFT;
  202528. }
  202529. }
  202530. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202531. PNG_COST_SHIFT;
  202532. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202533. PNG_COST_SHIFT;
  202534. if (lmhi > PNG_HIMASK)
  202535. lmins = PNG_MAXSUM;
  202536. else
  202537. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202538. }
  202539. #endif
  202540. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202541. pp = prev_row + 1; i < bpp; i++)
  202542. {
  202543. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202544. sum += (v < 128) ? v : 256 - v;
  202545. }
  202546. for (lp = row_buf + 1; i < row_bytes; i++)
  202547. {
  202548. v = *dp++ =
  202549. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202550. sum += (v < 128) ? v : 256 - v;
  202551. if (sum > lmins) /* We are already worse, don't continue. */
  202552. break;
  202553. }
  202554. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202555. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202556. {
  202557. int j;
  202558. png_uint_32 sumhi, sumlo;
  202559. sumlo = sum & PNG_LOMASK;
  202560. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202561. for (j = 0; j < num_p_filters; j++)
  202562. {
  202563. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202564. {
  202565. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202566. PNG_WEIGHT_SHIFT;
  202567. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202568. PNG_WEIGHT_SHIFT;
  202569. }
  202570. }
  202571. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202572. PNG_COST_SHIFT;
  202573. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202574. PNG_COST_SHIFT;
  202575. if (sumhi > PNG_HIMASK)
  202576. sum = PNG_MAXSUM;
  202577. else
  202578. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202579. }
  202580. #endif
  202581. if (sum < mins)
  202582. {
  202583. mins = sum;
  202584. best_row = png_ptr->avg_row;
  202585. }
  202586. }
  202587. /* Paeth filter */
  202588. if (filter_to_do == PNG_FILTER_PAETH)
  202589. {
  202590. png_bytep rp, dp, pp, cp, lp;
  202591. png_uint_32 i;
  202592. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202593. pp = prev_row + 1; i < bpp; i++)
  202594. {
  202595. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202596. }
  202597. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202598. {
  202599. int a, b, c, pa, pb, pc, p;
  202600. b = *pp++;
  202601. c = *cp++;
  202602. a = *lp++;
  202603. p = b - c;
  202604. pc = a - c;
  202605. #ifdef PNG_USE_ABS
  202606. pa = abs(p);
  202607. pb = abs(pc);
  202608. pc = abs(p + pc);
  202609. #else
  202610. pa = p < 0 ? -p : p;
  202611. pb = pc < 0 ? -pc : pc;
  202612. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202613. #endif
  202614. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202615. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202616. }
  202617. best_row = png_ptr->paeth_row;
  202618. }
  202619. else if (filter_to_do & PNG_FILTER_PAETH)
  202620. {
  202621. png_bytep rp, dp, pp, cp, lp;
  202622. png_uint_32 sum = 0, lmins = mins;
  202623. png_uint_32 i;
  202624. int v;
  202625. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202626. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202627. {
  202628. int j;
  202629. png_uint_32 lmhi, lmlo;
  202630. lmlo = lmins & PNG_LOMASK;
  202631. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202632. for (j = 0; j < num_p_filters; j++)
  202633. {
  202634. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202635. {
  202636. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202637. PNG_WEIGHT_SHIFT;
  202638. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202639. PNG_WEIGHT_SHIFT;
  202640. }
  202641. }
  202642. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202643. PNG_COST_SHIFT;
  202644. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202645. PNG_COST_SHIFT;
  202646. if (lmhi > PNG_HIMASK)
  202647. lmins = PNG_MAXSUM;
  202648. else
  202649. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202650. }
  202651. #endif
  202652. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202653. pp = prev_row + 1; i < bpp; i++)
  202654. {
  202655. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202656. sum += (v < 128) ? v : 256 - v;
  202657. }
  202658. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202659. {
  202660. int a, b, c, pa, pb, pc, p;
  202661. b = *pp++;
  202662. c = *cp++;
  202663. a = *lp++;
  202664. #ifndef PNG_SLOW_PAETH
  202665. p = b - c;
  202666. pc = a - c;
  202667. #ifdef PNG_USE_ABS
  202668. pa = abs(p);
  202669. pb = abs(pc);
  202670. pc = abs(p + pc);
  202671. #else
  202672. pa = p < 0 ? -p : p;
  202673. pb = pc < 0 ? -pc : pc;
  202674. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202675. #endif
  202676. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202677. #else /* PNG_SLOW_PAETH */
  202678. p = a + b - c;
  202679. pa = abs(p - a);
  202680. pb = abs(p - b);
  202681. pc = abs(p - c);
  202682. if (pa <= pb && pa <= pc)
  202683. p = a;
  202684. else if (pb <= pc)
  202685. p = b;
  202686. else
  202687. p = c;
  202688. #endif /* PNG_SLOW_PAETH */
  202689. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202690. sum += (v < 128) ? v : 256 - v;
  202691. if (sum > lmins) /* We are already worse, don't continue. */
  202692. break;
  202693. }
  202694. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202695. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202696. {
  202697. int j;
  202698. png_uint_32 sumhi, sumlo;
  202699. sumlo = sum & PNG_LOMASK;
  202700. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202701. for (j = 0; j < num_p_filters; j++)
  202702. {
  202703. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202704. {
  202705. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202706. PNG_WEIGHT_SHIFT;
  202707. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202708. PNG_WEIGHT_SHIFT;
  202709. }
  202710. }
  202711. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202712. PNG_COST_SHIFT;
  202713. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202714. PNG_COST_SHIFT;
  202715. if (sumhi > PNG_HIMASK)
  202716. sum = PNG_MAXSUM;
  202717. else
  202718. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202719. }
  202720. #endif
  202721. if (sum < mins)
  202722. {
  202723. best_row = png_ptr->paeth_row;
  202724. }
  202725. }
  202726. #endif /* PNG_NO_WRITE_FILTER */
  202727. /* Do the actual writing of the filtered row data from the chosen filter. */
  202728. png_write_filtered_row(png_ptr, best_row);
  202729. #ifndef PNG_NO_WRITE_FILTER
  202730. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202731. /* Save the type of filter we picked this time for future calculations */
  202732. if (png_ptr->num_prev_filters > 0)
  202733. {
  202734. int j;
  202735. for (j = 1; j < num_p_filters; j++)
  202736. {
  202737. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202738. }
  202739. png_ptr->prev_filters[j] = best_row[0];
  202740. }
  202741. #endif
  202742. #endif /* PNG_NO_WRITE_FILTER */
  202743. }
  202744. /* Do the actual writing of a previously filtered row. */
  202745. void /* PRIVATE */
  202746. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202747. {
  202748. png_debug(1, "in png_write_filtered_row\n");
  202749. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202750. /* set up the zlib input buffer */
  202751. png_ptr->zstream.next_in = filtered_row;
  202752. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202753. /* repeat until we have compressed all the data */
  202754. do
  202755. {
  202756. int ret; /* return of zlib */
  202757. /* compress the data */
  202758. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202759. /* check for compression errors */
  202760. if (ret != Z_OK)
  202761. {
  202762. if (png_ptr->zstream.msg != NULL)
  202763. png_error(png_ptr, png_ptr->zstream.msg);
  202764. else
  202765. png_error(png_ptr, "zlib error");
  202766. }
  202767. /* see if it is time to write another IDAT */
  202768. if (!(png_ptr->zstream.avail_out))
  202769. {
  202770. /* write the IDAT and reset the zlib output buffer */
  202771. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202772. png_ptr->zstream.next_out = png_ptr->zbuf;
  202773. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202774. }
  202775. /* repeat until all data has been compressed */
  202776. } while (png_ptr->zstream.avail_in);
  202777. /* swap the current and previous rows */
  202778. if (png_ptr->prev_row != NULL)
  202779. {
  202780. png_bytep tptr;
  202781. tptr = png_ptr->prev_row;
  202782. png_ptr->prev_row = png_ptr->row_buf;
  202783. png_ptr->row_buf = tptr;
  202784. }
  202785. /* finish row - updates counters and flushes zlib if last row */
  202786. png_write_finish_row(png_ptr);
  202787. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202788. png_ptr->flush_rows++;
  202789. if (png_ptr->flush_dist > 0 &&
  202790. png_ptr->flush_rows >= png_ptr->flush_dist)
  202791. {
  202792. png_write_flush(png_ptr);
  202793. }
  202794. #endif
  202795. }
  202796. #endif /* PNG_WRITE_SUPPORTED */
  202797. /*** End of inlined file: pngwutil.c ***/
  202798. #else
  202799. extern "C"
  202800. {
  202801. #include <png.h>
  202802. #include <pngconf.h>
  202803. }
  202804. #endif
  202805. }
  202806. #undef max
  202807. #undef min
  202808. #if JUCE_MSVC
  202809. #pragma warning (pop)
  202810. #endif
  202811. BEGIN_JUCE_NAMESPACE
  202812. using ::calloc;
  202813. using ::malloc;
  202814. using ::free;
  202815. namespace PNGHelpers
  202816. {
  202817. using namespace pnglibNamespace;
  202818. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  202819. {
  202820. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202821. }
  202822. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202823. {
  202824. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202825. }
  202826. struct PNGErrorStruct {};
  202827. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  202828. {
  202829. throw PNGErrorStruct();
  202830. }
  202831. }
  202832. PNGImageFormat::PNGImageFormat() {}
  202833. PNGImageFormat::~PNGImageFormat() {}
  202834. const String PNGImageFormat::getFormatName()
  202835. {
  202836. return "PNG";
  202837. }
  202838. bool PNGImageFormat::canUnderstand (InputStream& in)
  202839. {
  202840. const int bytesNeeded = 4;
  202841. char header [bytesNeeded];
  202842. return in.read (header, bytesNeeded) == bytesNeeded
  202843. && header[1] == 'P'
  202844. && header[2] == 'N'
  202845. && header[3] == 'G';
  202846. }
  202847. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202848. const Image juce_loadWithCoreImage (InputStream& input);
  202849. #endif
  202850. const Image PNGImageFormat::decodeImage (InputStream& in)
  202851. {
  202852. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202853. return juce_loadWithCoreImage (in);
  202854. #else
  202855. using namespace pnglibNamespace;
  202856. Image image;
  202857. png_structp pngReadStruct;
  202858. png_infop pngInfoStruct;
  202859. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202860. if (pngReadStruct != 0)
  202861. {
  202862. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202863. if (pngInfoStruct == 0)
  202864. {
  202865. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202866. return Image::null;
  202867. }
  202868. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202869. // read the header..
  202870. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202871. png_uint_32 width, height;
  202872. int bitDepth, colorType, interlaceType;
  202873. png_read_info (pngReadStruct, pngInfoStruct);
  202874. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202875. &width, &height,
  202876. &bitDepth, &colorType,
  202877. &interlaceType, 0, 0);
  202878. if (bitDepth == 16)
  202879. png_set_strip_16 (pngReadStruct);
  202880. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202881. png_set_expand (pngReadStruct);
  202882. if (bitDepth < 8)
  202883. png_set_expand (pngReadStruct);
  202884. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202885. png_set_expand (pngReadStruct);
  202886. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202887. png_set_gray_to_rgb (pngReadStruct);
  202888. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202889. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202890. || pngInfoStruct->num_trans > 0;
  202891. // Load the image into a temp buffer in the pnglib format..
  202892. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202893. {
  202894. HeapBlock <png_bytep> rows (height);
  202895. for (int y = (int) height; --y >= 0;)
  202896. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202897. png_read_image (pngReadStruct, rows);
  202898. png_read_end (pngReadStruct, pngInfoStruct);
  202899. }
  202900. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202901. // now convert the data to a juce image format..
  202902. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202903. (int) width, (int) height, hasAlphaChan);
  202904. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  202905. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202906. const Image::BitmapData destData (image, true);
  202907. uint8* srcRow = tempBuffer;
  202908. uint8* destRow = destData.data;
  202909. for (int y = 0; y < (int) height; ++y)
  202910. {
  202911. const uint8* src = srcRow;
  202912. srcRow += (width << 2);
  202913. uint8* dest = destRow;
  202914. destRow += destData.lineStride;
  202915. if (hasAlphaChan)
  202916. {
  202917. for (int i = (int) width; --i >= 0;)
  202918. {
  202919. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202920. ((PixelARGB*) dest)->premultiply();
  202921. dest += destData.pixelStride;
  202922. src += 4;
  202923. }
  202924. }
  202925. else
  202926. {
  202927. for (int i = (int) width; --i >= 0;)
  202928. {
  202929. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202930. dest += destData.pixelStride;
  202931. src += 4;
  202932. }
  202933. }
  202934. }
  202935. }
  202936. return image;
  202937. #endif
  202938. }
  202939. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202940. {
  202941. using namespace pnglibNamespace;
  202942. const int width = image.getWidth();
  202943. const int height = image.getHeight();
  202944. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202945. if (pngWriteStruct == 0)
  202946. return false;
  202947. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202948. if (pngInfoStruct == 0)
  202949. {
  202950. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202951. return false;
  202952. }
  202953. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202954. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202955. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202956. : PNG_COLOR_TYPE_RGB,
  202957. PNG_INTERLACE_NONE,
  202958. PNG_COMPRESSION_TYPE_BASE,
  202959. PNG_FILTER_TYPE_BASE);
  202960. HeapBlock <uint8> rowData (width * 4);
  202961. png_color_8 sig_bit;
  202962. sig_bit.red = 8;
  202963. sig_bit.green = 8;
  202964. sig_bit.blue = 8;
  202965. sig_bit.alpha = 8;
  202966. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202967. png_write_info (pngWriteStruct, pngInfoStruct);
  202968. png_set_shift (pngWriteStruct, &sig_bit);
  202969. png_set_packing (pngWriteStruct);
  202970. const Image::BitmapData srcData (image, false);
  202971. for (int y = 0; y < height; ++y)
  202972. {
  202973. uint8* dst = rowData;
  202974. const uint8* src = srcData.getLinePointer (y);
  202975. if (image.hasAlphaChannel())
  202976. {
  202977. for (int i = width; --i >= 0;)
  202978. {
  202979. PixelARGB p (*(const PixelARGB*) src);
  202980. p.unpremultiply();
  202981. *dst++ = p.getRed();
  202982. *dst++ = p.getGreen();
  202983. *dst++ = p.getBlue();
  202984. *dst++ = p.getAlpha();
  202985. src += srcData.pixelStride;
  202986. }
  202987. }
  202988. else
  202989. {
  202990. for (int i = width; --i >= 0;)
  202991. {
  202992. *dst++ = ((const PixelRGB*) src)->getRed();
  202993. *dst++ = ((const PixelRGB*) src)->getGreen();
  202994. *dst++ = ((const PixelRGB*) src)->getBlue();
  202995. src += srcData.pixelStride;
  202996. }
  202997. }
  202998. png_bytep rowPtr = rowData;
  202999. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203000. }
  203001. png_write_end (pngWriteStruct, pngInfoStruct);
  203002. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203003. out.flush();
  203004. return true;
  203005. }
  203006. END_JUCE_NAMESPACE
  203007. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203008. #endif
  203009. //==============================================================================
  203010. #if JUCE_BUILD_NATIVE
  203011. // Non-public headers that are needed by more than one platform must be included
  203012. // before the platform-specific sections..
  203013. BEGIN_JUCE_NAMESPACE
  203014. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203015. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203016. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203017. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203018. /**
  203019. Helper class that takes chunks of incoming midi bytes, packages them into
  203020. messages, and dispatches them to a midi callback.
  203021. */
  203022. class MidiDataConcatenator
  203023. {
  203024. public:
  203025. MidiDataConcatenator (const int initialBufferSize)
  203026. : pendingData (initialBufferSize),
  203027. pendingBytes (0), pendingDataTime (0)
  203028. {
  203029. }
  203030. void reset()
  203031. {
  203032. pendingBytes = 0;
  203033. pendingDataTime = 0;
  203034. }
  203035. void pushMidiData (const void* data, int numBytes, double time,
  203036. MidiInput* input, MidiInputCallback& callback)
  203037. {
  203038. const uint8* d = static_cast <const uint8*> (data);
  203039. while (numBytes > 0)
  203040. {
  203041. if (pendingBytes > 0 || d[0] == 0xf0)
  203042. {
  203043. processSysex (d, numBytes, time, input, callback);
  203044. }
  203045. else
  203046. {
  203047. int used = 0;
  203048. const MidiMessage m (d, numBytes, used, 0, time);
  203049. if (used <= 0)
  203050. break; // malformed message..
  203051. callback.handleIncomingMidiMessage (input, m);
  203052. numBytes -= used;
  203053. d += used;
  203054. }
  203055. }
  203056. }
  203057. private:
  203058. void processSysex (const uint8*& d, int& numBytes, double time,
  203059. MidiInput* input, MidiInputCallback& callback)
  203060. {
  203061. if (*d == 0xf0)
  203062. {
  203063. pendingBytes = 0;
  203064. pendingDataTime = time;
  203065. }
  203066. pendingData.ensureSize (pendingBytes + numBytes, false);
  203067. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203068. uint8* dest = totalMessage + pendingBytes;
  203069. do
  203070. {
  203071. if (pendingBytes > 0 && *d >= 0x80)
  203072. {
  203073. if (*d >= 0xfa || *d == 0xf8)
  203074. {
  203075. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203076. ++d;
  203077. --numBytes;
  203078. }
  203079. else
  203080. {
  203081. if (*d == 0xf7)
  203082. {
  203083. *dest++ = *d++;
  203084. pendingBytes++;
  203085. --numBytes;
  203086. }
  203087. break;
  203088. }
  203089. }
  203090. else
  203091. {
  203092. *dest++ = *d++;
  203093. pendingBytes++;
  203094. --numBytes;
  203095. }
  203096. }
  203097. while (numBytes > 0);
  203098. if (pendingBytes > 0)
  203099. {
  203100. if (totalMessage [pendingBytes - 1] == 0xf7)
  203101. {
  203102. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203103. pendingBytes = 0;
  203104. }
  203105. else
  203106. {
  203107. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203108. }
  203109. }
  203110. }
  203111. MemoryBlock pendingData;
  203112. int pendingBytes;
  203113. double pendingDataTime;
  203114. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203115. };
  203116. #endif
  203117. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203118. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203119. END_JUCE_NAMESPACE
  203120. #if JUCE_WINDOWS
  203121. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203122. /*
  203123. This file wraps together all the win32-specific code, so that
  203124. we can include all the native headers just once, and compile all our
  203125. platform-specific stuff in one big lump, keeping it out of the way of
  203126. the rest of the codebase.
  203127. */
  203128. #if JUCE_WINDOWS
  203129. #undef JUCE_BUILD_NATIVE
  203130. #define JUCE_BUILD_NATIVE 1
  203131. BEGIN_JUCE_NAMESPACE
  203132. #define JUCE_INCLUDED_FILE 1
  203133. // Now include the actual code files..
  203134. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203135. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203136. // compiled on its own).
  203137. #if JUCE_INCLUDED_FILE
  203138. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203139. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203140. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203141. #ifndef DOXYGEN
  203142. // use with DynamicLibraryLoader to simplify importing functions
  203143. //
  203144. // functionName: function to import
  203145. // localFunctionName: name you want to use to actually call it (must be different)
  203146. // returnType: the return type
  203147. // object: the DynamicLibraryLoader to use
  203148. // params: list of params (bracketed)
  203149. //
  203150. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203151. typedef returnType (WINAPI *type##localFunctionName) params; \
  203152. type##localFunctionName localFunctionName \
  203153. = (type##localFunctionName)object.findProcAddress (#functionName);
  203154. // loads and unloads a DLL automatically
  203155. class JUCE_API DynamicLibraryLoader
  203156. {
  203157. public:
  203158. DynamicLibraryLoader (const String& name = String::empty);
  203159. ~DynamicLibraryLoader();
  203160. bool load (const String& libraryName);
  203161. void* findProcAddress (const String& functionName);
  203162. private:
  203163. void* libHandle;
  203164. };
  203165. #endif
  203166. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203167. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203168. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203169. : libHandle (0)
  203170. {
  203171. load (name);
  203172. }
  203173. DynamicLibraryLoader::~DynamicLibraryLoader()
  203174. {
  203175. load (String::empty);
  203176. }
  203177. bool DynamicLibraryLoader::load (const String& name)
  203178. {
  203179. FreeLibrary ((HMODULE) libHandle);
  203180. libHandle = name.isNotEmpty() ? LoadLibrary (name.toUTF16()) : 0;
  203181. return libHandle != 0;
  203182. }
  203183. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203184. {
  203185. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toUTF8()); // (void* cast is required for mingw)
  203186. }
  203187. #endif
  203188. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203189. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203190. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203191. // compiled on its own).
  203192. #if JUCE_INCLUDED_FILE
  203193. void Logger::outputDebugString (const String& text)
  203194. {
  203195. OutputDebugString ((text + "\n").toUTF16());
  203196. }
  203197. static int64 hiResTicksPerSecond;
  203198. static double hiResTicksScaleFactor;
  203199. #if JUCE_USE_INTRINSICS
  203200. // CPU info functions using intrinsics...
  203201. #pragma intrinsic (__cpuid)
  203202. #pragma intrinsic (__rdtsc)
  203203. const String SystemStats::getCpuVendor()
  203204. {
  203205. int info [4];
  203206. __cpuid (info, 0);
  203207. char v [12];
  203208. memcpy (v, info + 1, 4);
  203209. memcpy (v + 4, info + 3, 4);
  203210. memcpy (v + 8, info + 2, 4);
  203211. return String (v, 12);
  203212. }
  203213. #else
  203214. // CPU info functions using old fashioned inline asm...
  203215. static void juce_getCpuVendor (char* const v)
  203216. {
  203217. int vendor[4];
  203218. zeromem (vendor, 16);
  203219. #ifdef JUCE_64BIT
  203220. #else
  203221. #ifndef __MINGW32__
  203222. __try
  203223. #endif
  203224. {
  203225. #if JUCE_GCC
  203226. unsigned int dummy = 0;
  203227. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203228. #else
  203229. __asm
  203230. {
  203231. mov eax, 0
  203232. cpuid
  203233. mov [vendor], ebx
  203234. mov [vendor + 4], edx
  203235. mov [vendor + 8], ecx
  203236. }
  203237. #endif
  203238. }
  203239. #ifndef __MINGW32__
  203240. __except (EXCEPTION_EXECUTE_HANDLER)
  203241. {
  203242. *v = 0;
  203243. }
  203244. #endif
  203245. #endif
  203246. memcpy (v, vendor, 16);
  203247. }
  203248. const String SystemStats::getCpuVendor()
  203249. {
  203250. char v [16];
  203251. juce_getCpuVendor (v);
  203252. return String (v, 16);
  203253. }
  203254. #endif
  203255. void SystemStats::initialiseStats()
  203256. {
  203257. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203258. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203259. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203260. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203261. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203262. #else
  203263. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203264. #endif
  203265. {
  203266. SYSTEM_INFO systemInfo;
  203267. GetSystemInfo (&systemInfo);
  203268. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203269. }
  203270. LARGE_INTEGER f;
  203271. QueryPerformanceFrequency (&f);
  203272. hiResTicksPerSecond = f.QuadPart;
  203273. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203274. String s (SystemStats::getJUCEVersion());
  203275. const MMRESULT res = timeBeginPeriod (1);
  203276. (void) res;
  203277. jassert (res == TIMERR_NOERROR);
  203278. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203279. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203280. #endif
  203281. }
  203282. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203283. {
  203284. OSVERSIONINFO info;
  203285. info.dwOSVersionInfoSize = sizeof (info);
  203286. GetVersionEx (&info);
  203287. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203288. {
  203289. switch (info.dwMajorVersion)
  203290. {
  203291. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203292. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203293. default: jassertfalse; break; // !! not a supported OS!
  203294. }
  203295. }
  203296. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203297. {
  203298. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203299. return Win98;
  203300. }
  203301. return UnknownOS;
  203302. }
  203303. const String SystemStats::getOperatingSystemName()
  203304. {
  203305. const char* name = "Unknown OS";
  203306. switch (getOperatingSystemType())
  203307. {
  203308. case Windows7: name = "Windows 7"; break;
  203309. case WinVista: name = "Windows Vista"; break;
  203310. case WinXP: name = "Windows XP"; break;
  203311. case Win2000: name = "Windows 2000"; break;
  203312. case Win98: name = "Windows 98"; break;
  203313. default: jassertfalse; break; // !! new type of OS?
  203314. }
  203315. return name;
  203316. }
  203317. bool SystemStats::isOperatingSystem64Bit()
  203318. {
  203319. #ifdef _WIN64
  203320. return true;
  203321. #else
  203322. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203323. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203324. BOOL isWow64 = FALSE;
  203325. return (fnIsWow64Process != 0)
  203326. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203327. && (isWow64 != FALSE);
  203328. #endif
  203329. }
  203330. int SystemStats::getMemorySizeInMegabytes()
  203331. {
  203332. MEMORYSTATUSEX mem;
  203333. mem.dwLength = sizeof (mem);
  203334. GlobalMemoryStatusEx (&mem);
  203335. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203336. }
  203337. uint32 juce_millisecondsSinceStartup() throw()
  203338. {
  203339. return (uint32) timeGetTime();
  203340. }
  203341. int64 Time::getHighResolutionTicks() throw()
  203342. {
  203343. LARGE_INTEGER ticks;
  203344. QueryPerformanceCounter (&ticks);
  203345. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203346. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203347. // fix for a very obscure PCI hardware bug that can make the counter
  203348. // sometimes jump forwards by a few seconds..
  203349. static int64 hiResTicksOffset = 0;
  203350. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203351. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203352. hiResTicksOffset = newOffset;
  203353. return ticks.QuadPart + hiResTicksOffset;
  203354. }
  203355. double Time::getMillisecondCounterHiRes() throw()
  203356. {
  203357. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203358. }
  203359. int64 Time::getHighResolutionTicksPerSecond() throw()
  203360. {
  203361. return hiResTicksPerSecond;
  203362. }
  203363. static int64 juce_getClockCycleCounter() throw()
  203364. {
  203365. #if JUCE_USE_INTRINSICS
  203366. // MS intrinsics version...
  203367. return __rdtsc();
  203368. #elif JUCE_GCC
  203369. // GNU inline asm version...
  203370. unsigned int hi = 0, lo = 0;
  203371. __asm__ __volatile__ (
  203372. "xor %%eax, %%eax \n\
  203373. xor %%edx, %%edx \n\
  203374. rdtsc \n\
  203375. movl %%eax, %[lo] \n\
  203376. movl %%edx, %[hi]"
  203377. :
  203378. : [hi] "m" (hi),
  203379. [lo] "m" (lo)
  203380. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203381. return (int64) ((((uint64) hi) << 32) | lo);
  203382. #else
  203383. // MSVC inline asm version...
  203384. unsigned int hi = 0, lo = 0;
  203385. __asm
  203386. {
  203387. xor eax, eax
  203388. xor edx, edx
  203389. rdtsc
  203390. mov lo, eax
  203391. mov hi, edx
  203392. }
  203393. return (int64) ((((uint64) hi) << 32) | lo);
  203394. #endif
  203395. }
  203396. int SystemStats::getCpuSpeedInMegaherz()
  203397. {
  203398. const int64 cycles = juce_getClockCycleCounter();
  203399. const uint32 millis = Time::getMillisecondCounter();
  203400. int lastResult = 0;
  203401. for (;;)
  203402. {
  203403. int n = 1000000;
  203404. while (--n > 0) {}
  203405. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203406. const int64 cyclesNow = juce_getClockCycleCounter();
  203407. if (millisElapsed > 80)
  203408. {
  203409. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203410. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203411. return newResult;
  203412. lastResult = newResult;
  203413. }
  203414. }
  203415. }
  203416. bool Time::setSystemTimeToThisTime() const
  203417. {
  203418. SYSTEMTIME st;
  203419. st.wDayOfWeek = 0;
  203420. st.wYear = (WORD) getYear();
  203421. st.wMonth = (WORD) (getMonth() + 1);
  203422. st.wDay = (WORD) getDayOfMonth();
  203423. st.wHour = (WORD) getHours();
  203424. st.wMinute = (WORD) getMinutes();
  203425. st.wSecond = (WORD) getSeconds();
  203426. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203427. // do this twice because of daylight saving conversion problems - the
  203428. // first one sets it up, the second one kicks it in.
  203429. return SetLocalTime (&st) != 0
  203430. && SetLocalTime (&st) != 0;
  203431. }
  203432. int SystemStats::getPageSize()
  203433. {
  203434. SYSTEM_INFO systemInfo;
  203435. GetSystemInfo (&systemInfo);
  203436. return systemInfo.dwPageSize;
  203437. }
  203438. const String SystemStats::getLogonName()
  203439. {
  203440. TCHAR text [256];
  203441. DWORD len = numElementsInArray (text) - 2;
  203442. zerostruct (text);
  203443. GetUserName (text, &len);
  203444. return String (text, len);
  203445. }
  203446. const String SystemStats::getFullUserName()
  203447. {
  203448. return getLogonName();
  203449. }
  203450. #endif
  203451. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203452. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203453. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203454. // compiled on its own).
  203455. #if JUCE_INCLUDED_FILE
  203456. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203457. extern HWND juce_messageWindowHandle;
  203458. #endif
  203459. #if ! JUCE_USE_INTRINSICS
  203460. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203461. // older ones we have to actually call the ops as win32 functions..
  203462. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203463. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203464. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203465. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203466. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203467. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203468. {
  203469. jassertfalse; // This operation isn't available in old MS compiler versions!
  203470. __int64 oldValue = *value;
  203471. if (oldValue == valueToCompare)
  203472. *value = newValue;
  203473. return oldValue;
  203474. }
  203475. #endif
  203476. CriticalSection::CriticalSection() throw()
  203477. {
  203478. // (just to check the MS haven't changed this structure and broken things...)
  203479. #if JUCE_VC7_OR_EARLIER
  203480. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203481. #else
  203482. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203483. #endif
  203484. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203485. }
  203486. CriticalSection::~CriticalSection() throw()
  203487. {
  203488. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203489. }
  203490. void CriticalSection::enter() const throw()
  203491. {
  203492. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203493. }
  203494. bool CriticalSection::tryEnter() const throw()
  203495. {
  203496. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203497. }
  203498. void CriticalSection::exit() const throw()
  203499. {
  203500. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203501. }
  203502. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203503. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203504. {
  203505. }
  203506. WaitableEvent::~WaitableEvent() throw()
  203507. {
  203508. CloseHandle (internal);
  203509. }
  203510. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203511. {
  203512. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203513. }
  203514. void WaitableEvent::signal() const throw()
  203515. {
  203516. SetEvent (internal);
  203517. }
  203518. void WaitableEvent::reset() const throw()
  203519. {
  203520. ResetEvent (internal);
  203521. }
  203522. void JUCE_API juce_threadEntryPoint (void*);
  203523. static unsigned int __stdcall threadEntryProc (void* userData)
  203524. {
  203525. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203526. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203527. GetCurrentThreadId(), TRUE);
  203528. #endif
  203529. juce_threadEntryPoint (userData);
  203530. _endthreadex (0);
  203531. return 0;
  203532. }
  203533. void Thread::launchThread()
  203534. {
  203535. unsigned int newThreadId;
  203536. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  203537. threadId_ = (ThreadID) newThreadId;
  203538. }
  203539. void Thread::closeThreadHandle()
  203540. {
  203541. CloseHandle ((HANDLE) threadHandle_);
  203542. threadId_ = 0;
  203543. threadHandle_ = 0;
  203544. }
  203545. void Thread::killThread()
  203546. {
  203547. if (threadHandle_ != 0)
  203548. {
  203549. #if JUCE_DEBUG
  203550. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203551. #endif
  203552. TerminateThread (threadHandle_, 0);
  203553. }
  203554. }
  203555. void Thread::setCurrentThreadName (const String& name)
  203556. {
  203557. #if JUCE_DEBUG && JUCE_MSVC
  203558. struct
  203559. {
  203560. DWORD dwType;
  203561. LPCSTR szName;
  203562. DWORD dwThreadID;
  203563. DWORD dwFlags;
  203564. } info;
  203565. info.dwType = 0x1000;
  203566. info.szName = name.toCString();
  203567. info.dwThreadID = GetCurrentThreadId();
  203568. info.dwFlags = 0;
  203569. __try
  203570. {
  203571. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203572. }
  203573. __except (EXCEPTION_CONTINUE_EXECUTION)
  203574. {}
  203575. #else
  203576. (void) name;
  203577. #endif
  203578. }
  203579. Thread::ThreadID Thread::getCurrentThreadId()
  203580. {
  203581. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203582. }
  203583. bool Thread::setThreadPriority (void* handle, int priority)
  203584. {
  203585. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203586. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203587. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203588. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203589. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203590. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203591. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203592. if (handle == 0)
  203593. handle = GetCurrentThread();
  203594. return SetThreadPriority (handle, pri) != FALSE;
  203595. }
  203596. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203597. {
  203598. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203599. }
  203600. struct SleepEvent
  203601. {
  203602. SleepEvent()
  203603. : handle (CreateEvent (0, 0, 0,
  203604. #if JUCE_DEBUG
  203605. _T("Juce Sleep Event")))
  203606. #else
  203607. 0))
  203608. #endif
  203609. {
  203610. }
  203611. HANDLE handle;
  203612. };
  203613. static SleepEvent sleepEvent;
  203614. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203615. {
  203616. if (millisecs >= 10)
  203617. {
  203618. Sleep (millisecs);
  203619. }
  203620. else
  203621. {
  203622. // unlike Sleep() this is guaranteed to return to the current thread after
  203623. // the time expires, so we'll use this for short waits, which are more likely
  203624. // to need to be accurate
  203625. WaitForSingleObject (sleepEvent.handle, millisecs);
  203626. }
  203627. }
  203628. void Thread::yield()
  203629. {
  203630. Sleep (0);
  203631. }
  203632. static int lastProcessPriority = -1;
  203633. // called by WindowDriver because Windows does wierd things to process priority
  203634. // when you swap apps, and this forces an update when the app is brought to the front.
  203635. void juce_repeatLastProcessPriority()
  203636. {
  203637. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203638. {
  203639. DWORD p;
  203640. switch (lastProcessPriority)
  203641. {
  203642. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203643. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203644. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203645. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203646. default: jassertfalse; return; // bad priority value
  203647. }
  203648. SetPriorityClass (GetCurrentProcess(), p);
  203649. }
  203650. }
  203651. void Process::setPriority (ProcessPriority prior)
  203652. {
  203653. if (lastProcessPriority != (int) prior)
  203654. {
  203655. lastProcessPriority = (int) prior;
  203656. juce_repeatLastProcessPriority();
  203657. }
  203658. }
  203659. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203660. {
  203661. return IsDebuggerPresent() != FALSE;
  203662. }
  203663. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203664. {
  203665. return juce_isRunningUnderDebugger();
  203666. }
  203667. void Process::raisePrivilege()
  203668. {
  203669. jassertfalse; // xxx not implemented
  203670. }
  203671. void Process::lowerPrivilege()
  203672. {
  203673. jassertfalse; // xxx not implemented
  203674. }
  203675. void Process::terminate()
  203676. {
  203677. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203678. _CrtDumpMemoryLeaks();
  203679. #endif
  203680. // bullet in the head in case there's a problem shutting down..
  203681. ExitProcess (0);
  203682. }
  203683. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203684. {
  203685. void* result = 0;
  203686. JUCE_TRY
  203687. {
  203688. result = LoadLibrary (name.toUTF16());
  203689. }
  203690. JUCE_CATCH_ALL
  203691. return result;
  203692. }
  203693. void PlatformUtilities::freeDynamicLibrary (void* h)
  203694. {
  203695. JUCE_TRY
  203696. {
  203697. if (h != 0)
  203698. FreeLibrary ((HMODULE) h);
  203699. }
  203700. JUCE_CATCH_ALL
  203701. }
  203702. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203703. {
  203704. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203705. }
  203706. class InterProcessLock::Pimpl
  203707. {
  203708. public:
  203709. Pimpl (const String& name, const int timeOutMillisecs)
  203710. : handle (0), refCount (1)
  203711. {
  203712. handle = CreateMutex (0, TRUE, ("Global\\" + name.replaceCharacter ('\\','/')).toUTF16());
  203713. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203714. {
  203715. if (timeOutMillisecs == 0)
  203716. {
  203717. close();
  203718. return;
  203719. }
  203720. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203721. {
  203722. case WAIT_OBJECT_0:
  203723. case WAIT_ABANDONED:
  203724. break;
  203725. case WAIT_TIMEOUT:
  203726. default:
  203727. close();
  203728. break;
  203729. }
  203730. }
  203731. }
  203732. ~Pimpl()
  203733. {
  203734. close();
  203735. }
  203736. void close()
  203737. {
  203738. if (handle != 0)
  203739. {
  203740. ReleaseMutex (handle);
  203741. CloseHandle (handle);
  203742. handle = 0;
  203743. }
  203744. }
  203745. HANDLE handle;
  203746. int refCount;
  203747. };
  203748. InterProcessLock::InterProcessLock (const String& name_)
  203749. : name (name_)
  203750. {
  203751. }
  203752. InterProcessLock::~InterProcessLock()
  203753. {
  203754. }
  203755. bool InterProcessLock::enter (const int timeOutMillisecs)
  203756. {
  203757. const ScopedLock sl (lock);
  203758. if (pimpl == 0)
  203759. {
  203760. pimpl = new Pimpl (name, timeOutMillisecs);
  203761. if (pimpl->handle == 0)
  203762. pimpl = 0;
  203763. }
  203764. else
  203765. {
  203766. pimpl->refCount++;
  203767. }
  203768. return pimpl != 0;
  203769. }
  203770. void InterProcessLock::exit()
  203771. {
  203772. const ScopedLock sl (lock);
  203773. // Trying to release the lock too many times!
  203774. jassert (pimpl != 0);
  203775. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203776. pimpl = 0;
  203777. }
  203778. #endif
  203779. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203780. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203781. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203782. // compiled on its own).
  203783. #if JUCE_INCLUDED_FILE
  203784. #ifndef CSIDL_MYMUSIC
  203785. #define CSIDL_MYMUSIC 0x000d
  203786. #endif
  203787. #ifndef CSIDL_MYVIDEO
  203788. #define CSIDL_MYVIDEO 0x000e
  203789. #endif
  203790. #ifndef INVALID_FILE_ATTRIBUTES
  203791. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203792. #endif
  203793. namespace WindowsFileHelpers
  203794. {
  203795. int64 fileTimeToTime (const FILETIME* const ft)
  203796. {
  203797. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203798. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203799. }
  203800. void timeToFileTime (const int64 time, FILETIME* const ft)
  203801. {
  203802. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203803. }
  203804. const String getDriveFromPath (String path)
  203805. {
  203806. WCHAR* p = const_cast <WCHAR*> (path.toUTF16().getAddress());
  203807. if (PathStripToRoot (p))
  203808. return String ((const WCHAR*) p);
  203809. return path;
  203810. }
  203811. int64 getDiskSpaceInfo (const String& path, const bool total)
  203812. {
  203813. ULARGE_INTEGER spc, tot, totFree;
  203814. if (GetDiskFreeSpaceEx (getDriveFromPath (path).toUTF16(), &spc, &tot, &totFree))
  203815. return total ? (int64) tot.QuadPart
  203816. : (int64) spc.QuadPart;
  203817. return 0;
  203818. }
  203819. unsigned int getWindowsDriveType (const String& path)
  203820. {
  203821. return GetDriveType (getDriveFromPath (path).toUTF16());
  203822. }
  203823. const File getSpecialFolderPath (int type)
  203824. {
  203825. WCHAR path [MAX_PATH + 256];
  203826. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203827. return File (String (path));
  203828. return File::nonexistent;
  203829. }
  203830. }
  203831. const juce_wchar File::separator = '\\';
  203832. const String File::separatorString ("\\");
  203833. bool File::exists() const
  203834. {
  203835. return fullPath.isNotEmpty()
  203836. && GetFileAttributes (fullPath.toUTF16()) != INVALID_FILE_ATTRIBUTES;
  203837. }
  203838. bool File::existsAsFile() const
  203839. {
  203840. return fullPath.isNotEmpty()
  203841. && (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203842. }
  203843. bool File::isDirectory() const
  203844. {
  203845. const DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203846. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203847. }
  203848. bool File::hasWriteAccess() const
  203849. {
  203850. if (exists())
  203851. return (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_READONLY) == 0;
  203852. // on windows, it seems that even read-only directories can still be written into,
  203853. // so checking the parent directory's permissions would return the wrong result..
  203854. return true;
  203855. }
  203856. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203857. {
  203858. DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203859. if (attr == INVALID_FILE_ATTRIBUTES)
  203860. return false;
  203861. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203862. return true;
  203863. if (shouldBeReadOnly)
  203864. attr |= FILE_ATTRIBUTE_READONLY;
  203865. else
  203866. attr &= ~FILE_ATTRIBUTE_READONLY;
  203867. return SetFileAttributes (fullPath.toUTF16(), attr) != FALSE;
  203868. }
  203869. bool File::isHidden() const
  203870. {
  203871. return (GetFileAttributes (getFullPathName().toUTF16()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203872. }
  203873. bool File::deleteFile() const
  203874. {
  203875. if (! exists())
  203876. return true;
  203877. else if (isDirectory())
  203878. return RemoveDirectory (fullPath.toUTF16()) != 0;
  203879. else
  203880. return DeleteFile (fullPath.toUTF16()) != 0;
  203881. }
  203882. bool File::moveToTrash() const
  203883. {
  203884. if (! exists())
  203885. return true;
  203886. SHFILEOPSTRUCT fos;
  203887. zerostruct (fos);
  203888. // The string we pass in must be double null terminated..
  203889. String doubleNullTermPath (getFullPathName() + " ");
  203890. WCHAR* const p = const_cast <WCHAR*> (doubleNullTermPath.toUTF16().getAddress());
  203891. p [getFullPathName().length()] = 0;
  203892. fos.wFunc = FO_DELETE;
  203893. fos.pFrom = p;
  203894. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203895. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203896. return SHFileOperation (&fos) == 0;
  203897. }
  203898. bool File::copyInternal (const File& dest) const
  203899. {
  203900. return CopyFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16(), false) != 0;
  203901. }
  203902. bool File::moveInternal (const File& dest) const
  203903. {
  203904. return MoveFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16()) != 0;
  203905. }
  203906. void File::createDirectoryInternal (const String& fileName) const
  203907. {
  203908. CreateDirectory (fileName.toUTF16(), 0);
  203909. }
  203910. int64 juce_fileSetPosition (void* handle, int64 pos)
  203911. {
  203912. LARGE_INTEGER li;
  203913. li.QuadPart = pos;
  203914. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203915. return li.QuadPart;
  203916. }
  203917. void FileInputStream::openHandle()
  203918. {
  203919. totalSize = file.getSize();
  203920. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203921. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203922. if (h != INVALID_HANDLE_VALUE)
  203923. fileHandle = (void*) h;
  203924. }
  203925. void FileInputStream::closeHandle()
  203926. {
  203927. CloseHandle ((HANDLE) fileHandle);
  203928. }
  203929. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  203930. {
  203931. if (fileHandle != 0)
  203932. {
  203933. DWORD actualNum = 0;
  203934. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203935. return (size_t) actualNum;
  203936. }
  203937. return 0;
  203938. }
  203939. void FileOutputStream::openHandle()
  203940. {
  203941. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203942. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203943. if (h != INVALID_HANDLE_VALUE)
  203944. {
  203945. LARGE_INTEGER li;
  203946. li.QuadPart = 0;
  203947. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  203948. if (li.LowPart != INVALID_SET_FILE_POINTER)
  203949. {
  203950. fileHandle = (void*) h;
  203951. currentPosition = li.QuadPart;
  203952. }
  203953. }
  203954. }
  203955. void FileOutputStream::closeHandle()
  203956. {
  203957. CloseHandle ((HANDLE) fileHandle);
  203958. }
  203959. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  203960. {
  203961. if (fileHandle != 0)
  203962. {
  203963. DWORD actualNum = 0;
  203964. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203965. return (int) actualNum;
  203966. }
  203967. return 0;
  203968. }
  203969. void FileOutputStream::flushInternal()
  203970. {
  203971. if (fileHandle != 0)
  203972. FlushFileBuffers ((HANDLE) fileHandle);
  203973. }
  203974. int64 File::getSize() const
  203975. {
  203976. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203977. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203978. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203979. return 0;
  203980. }
  203981. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203982. {
  203983. using namespace WindowsFileHelpers;
  203984. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203985. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203986. {
  203987. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203988. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203989. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203990. }
  203991. else
  203992. {
  203993. creationTime = accessTime = modificationTime = 0;
  203994. }
  203995. }
  203996. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203997. {
  203998. using namespace WindowsFileHelpers;
  203999. bool ok = false;
  204000. HANDLE h = CreateFile (fullPath.toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204001. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204002. if (h != INVALID_HANDLE_VALUE)
  204003. {
  204004. FILETIME m, a, c;
  204005. timeToFileTime (modificationTime, &m);
  204006. timeToFileTime (accessTime, &a);
  204007. timeToFileTime (creationTime, &c);
  204008. ok = SetFileTime (h,
  204009. creationTime > 0 ? &c : 0,
  204010. accessTime > 0 ? &a : 0,
  204011. modificationTime > 0 ? &m : 0) != 0;
  204012. CloseHandle (h);
  204013. }
  204014. return ok;
  204015. }
  204016. void File::findFileSystemRoots (Array<File>& destArray)
  204017. {
  204018. TCHAR buffer [2048];
  204019. buffer[0] = 0;
  204020. buffer[1] = 0;
  204021. GetLogicalDriveStrings (2048, buffer);
  204022. const TCHAR* n = buffer;
  204023. StringArray roots;
  204024. while (*n != 0)
  204025. {
  204026. roots.add (String (n));
  204027. while (*n++ != 0)
  204028. {}
  204029. }
  204030. roots.sort (true);
  204031. for (int i = 0; i < roots.size(); ++i)
  204032. destArray.add (roots [i]);
  204033. }
  204034. const String File::getVolumeLabel() const
  204035. {
  204036. TCHAR dest[64];
  204037. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204038. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204039. dest[0] = 0;
  204040. return dest;
  204041. }
  204042. int File::getVolumeSerialNumber() const
  204043. {
  204044. TCHAR dest[64];
  204045. DWORD serialNum;
  204046. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204047. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204048. return 0;
  204049. return (int) serialNum;
  204050. }
  204051. int64 File::getBytesFreeOnVolume() const
  204052. {
  204053. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204054. }
  204055. int64 File::getVolumeTotalSize() const
  204056. {
  204057. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204058. }
  204059. bool File::isOnCDRomDrive() const
  204060. {
  204061. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204062. }
  204063. bool File::isOnHardDisk() const
  204064. {
  204065. if (fullPath.isEmpty())
  204066. return false;
  204067. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204068. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204069. return n != DRIVE_REMOVABLE;
  204070. else
  204071. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204072. }
  204073. bool File::isOnRemovableDrive() const
  204074. {
  204075. if (fullPath.isEmpty())
  204076. return false;
  204077. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204078. return n == DRIVE_CDROM
  204079. || n == DRIVE_REMOTE
  204080. || n == DRIVE_REMOVABLE
  204081. || n == DRIVE_RAMDISK;
  204082. }
  204083. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204084. {
  204085. int csidlType = 0;
  204086. switch (type)
  204087. {
  204088. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204089. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204090. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204091. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204092. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204093. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204094. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204095. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204096. case tempDirectory:
  204097. {
  204098. WCHAR dest [2048];
  204099. dest[0] = 0;
  204100. GetTempPath (numElementsInArray (dest), dest);
  204101. return File (String (dest));
  204102. }
  204103. case invokedExecutableFile:
  204104. case currentExecutableFile:
  204105. case currentApplicationFile:
  204106. {
  204107. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204108. WCHAR dest [MAX_PATH + 256];
  204109. dest[0] = 0;
  204110. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204111. return File (String (dest));
  204112. }
  204113. case hostApplicationPath:
  204114. {
  204115. WCHAR dest [MAX_PATH + 256];
  204116. dest[0] = 0;
  204117. GetModuleFileName (0, dest, numElementsInArray (dest));
  204118. return File (String (dest));
  204119. }
  204120. default:
  204121. jassertfalse; // unknown type?
  204122. return File::nonexistent;
  204123. }
  204124. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204125. }
  204126. const File File::getCurrentWorkingDirectory()
  204127. {
  204128. WCHAR dest [MAX_PATH + 256];
  204129. dest[0] = 0;
  204130. GetCurrentDirectory (numElementsInArray (dest), dest);
  204131. return File (String (dest));
  204132. }
  204133. bool File::setAsCurrentWorkingDirectory() const
  204134. {
  204135. return SetCurrentDirectory (getFullPathName().toUTF16()) != FALSE;
  204136. }
  204137. const String File::getVersion() const
  204138. {
  204139. String result;
  204140. DWORD handle = 0;
  204141. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName().toUTF16(), &handle);
  204142. HeapBlock<char> buffer;
  204143. buffer.calloc (bufferSize);
  204144. if (GetFileVersionInfo (getFullPathName().toUTF16(), 0, bufferSize, buffer))
  204145. {
  204146. VS_FIXEDFILEINFO* vffi;
  204147. UINT len = 0;
  204148. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204149. {
  204150. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204151. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204152. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204153. << (int) LOWORD (vffi->dwFileVersionLS);
  204154. }
  204155. }
  204156. return result;
  204157. }
  204158. const File File::getLinkedTarget() const
  204159. {
  204160. File result (*this);
  204161. String p (getFullPathName());
  204162. if (! exists())
  204163. p += ".lnk";
  204164. else if (getFileExtension() != ".lnk")
  204165. return result;
  204166. ComSmartPtr <IShellLink> shellLink;
  204167. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204168. {
  204169. ComSmartPtr <IPersistFile> persistFile;
  204170. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204171. {
  204172. if (SUCCEEDED (persistFile->Load (p.toUTF16(), STGM_READ))
  204173. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204174. {
  204175. WIN32_FIND_DATA winFindData;
  204176. WCHAR resolvedPath [MAX_PATH];
  204177. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204178. result = File (resolvedPath);
  204179. }
  204180. }
  204181. }
  204182. return result;
  204183. }
  204184. class DirectoryIterator::NativeIterator::Pimpl
  204185. {
  204186. public:
  204187. Pimpl (const File& directory, const String& wildCard)
  204188. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204189. handle (INVALID_HANDLE_VALUE)
  204190. {
  204191. }
  204192. ~Pimpl()
  204193. {
  204194. if (handle != INVALID_HANDLE_VALUE)
  204195. FindClose (handle);
  204196. }
  204197. bool next (String& filenameFound,
  204198. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204199. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204200. {
  204201. using namespace WindowsFileHelpers;
  204202. WIN32_FIND_DATA findData;
  204203. if (handle == INVALID_HANDLE_VALUE)
  204204. {
  204205. handle = FindFirstFile (directoryWithWildCard.toUTF16(), &findData);
  204206. if (handle == INVALID_HANDLE_VALUE)
  204207. return false;
  204208. }
  204209. else
  204210. {
  204211. if (FindNextFile (handle, &findData) == 0)
  204212. return false;
  204213. }
  204214. filenameFound = findData.cFileName;
  204215. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204216. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204217. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204218. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204219. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204220. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204221. return true;
  204222. }
  204223. private:
  204224. const String directoryWithWildCard;
  204225. HANDLE handle;
  204226. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204227. };
  204228. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204229. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204230. {
  204231. }
  204232. DirectoryIterator::NativeIterator::~NativeIterator()
  204233. {
  204234. }
  204235. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204236. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204237. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204238. {
  204239. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204240. }
  204241. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204242. {
  204243. HINSTANCE hInstance = 0;
  204244. JUCE_TRY
  204245. {
  204246. hInstance = ShellExecute (0, 0, fileName.toUTF16(), parameters.toUTF16(), 0, SW_SHOWDEFAULT);
  204247. }
  204248. JUCE_CATCH_ALL
  204249. return hInstance > (HINSTANCE) 32;
  204250. }
  204251. void File::revealToUser() const
  204252. {
  204253. if (isDirectory())
  204254. startAsProcess();
  204255. else if (getParentDirectory().exists())
  204256. getParentDirectory().startAsProcess();
  204257. }
  204258. class NamedPipeInternal
  204259. {
  204260. public:
  204261. NamedPipeInternal (const String& file, const bool isPipe_)
  204262. : pipeH (0),
  204263. cancelEvent (0),
  204264. connected (false),
  204265. isPipe (isPipe_)
  204266. {
  204267. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204268. pipeH = isPipe ? CreateNamedPipe (file.toUTF16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204269. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204270. : CreateFile (file.toUTF16(), GENERIC_READ | GENERIC_WRITE, 0, 0,
  204271. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204272. }
  204273. ~NamedPipeInternal()
  204274. {
  204275. disconnectPipe();
  204276. if (pipeH != 0)
  204277. CloseHandle (pipeH);
  204278. CloseHandle (cancelEvent);
  204279. }
  204280. bool connect (const int timeOutMs)
  204281. {
  204282. if (! isPipe)
  204283. return true;
  204284. if (! connected)
  204285. {
  204286. OVERLAPPED over;
  204287. zerostruct (over);
  204288. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204289. if (ConnectNamedPipe (pipeH, &over))
  204290. {
  204291. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204292. }
  204293. else
  204294. {
  204295. const int err = GetLastError();
  204296. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204297. {
  204298. HANDLE handles[] = { over.hEvent, cancelEvent };
  204299. if (WaitForMultipleObjects (2, handles, FALSE,
  204300. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204301. connected = true;
  204302. }
  204303. else if (err == ERROR_PIPE_CONNECTED)
  204304. {
  204305. connected = true;
  204306. }
  204307. }
  204308. CloseHandle (over.hEvent);
  204309. }
  204310. return connected;
  204311. }
  204312. void disconnectPipe()
  204313. {
  204314. if (connected)
  204315. {
  204316. DisconnectNamedPipe (pipeH);
  204317. connected = false;
  204318. }
  204319. }
  204320. HANDLE pipeH;
  204321. HANDLE cancelEvent;
  204322. bool connected, isPipe;
  204323. };
  204324. void NamedPipe::close()
  204325. {
  204326. cancelPendingReads();
  204327. const ScopedLock sl (lock);
  204328. delete static_cast<NamedPipeInternal*> (internal);
  204329. internal = 0;
  204330. }
  204331. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204332. {
  204333. close();
  204334. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204335. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204336. {
  204337. internal = intern.release();
  204338. return true;
  204339. }
  204340. return false;
  204341. }
  204342. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204343. {
  204344. const ScopedLock sl (lock);
  204345. int bytesRead = -1;
  204346. bool waitAgain = true;
  204347. while (waitAgain && internal != 0)
  204348. {
  204349. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204350. waitAgain = false;
  204351. if (! intern->connect (timeOutMilliseconds))
  204352. break;
  204353. if (maxBytesToRead <= 0)
  204354. return 0;
  204355. OVERLAPPED over;
  204356. zerostruct (over);
  204357. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204358. unsigned long numRead;
  204359. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204360. {
  204361. bytesRead = (int) numRead;
  204362. }
  204363. else if (GetLastError() == ERROR_IO_PENDING)
  204364. {
  204365. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204366. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204367. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204368. : INFINITE);
  204369. if (waitResult != WAIT_OBJECT_0)
  204370. {
  204371. // if the operation timed out, let's cancel it...
  204372. CancelIo (intern->pipeH);
  204373. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204374. }
  204375. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204376. {
  204377. bytesRead = (int) numRead;
  204378. }
  204379. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204380. {
  204381. intern->disconnectPipe();
  204382. waitAgain = true;
  204383. }
  204384. }
  204385. else
  204386. {
  204387. waitAgain = internal != 0;
  204388. Sleep (5);
  204389. }
  204390. CloseHandle (over.hEvent);
  204391. }
  204392. return bytesRead;
  204393. }
  204394. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204395. {
  204396. int bytesWritten = -1;
  204397. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204398. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204399. {
  204400. if (numBytesToWrite <= 0)
  204401. return 0;
  204402. OVERLAPPED over;
  204403. zerostruct (over);
  204404. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204405. unsigned long numWritten;
  204406. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204407. {
  204408. bytesWritten = (int) numWritten;
  204409. }
  204410. else if (GetLastError() == ERROR_IO_PENDING)
  204411. {
  204412. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204413. DWORD waitResult;
  204414. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204415. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204416. : INFINITE);
  204417. if (waitResult != WAIT_OBJECT_0)
  204418. {
  204419. CancelIo (intern->pipeH);
  204420. WaitForSingleObject (over.hEvent, INFINITE);
  204421. }
  204422. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204423. {
  204424. bytesWritten = (int) numWritten;
  204425. }
  204426. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204427. {
  204428. intern->disconnectPipe();
  204429. }
  204430. }
  204431. CloseHandle (over.hEvent);
  204432. }
  204433. return bytesWritten;
  204434. }
  204435. void NamedPipe::cancelPendingReads()
  204436. {
  204437. if (internal != 0)
  204438. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204439. }
  204440. #endif
  204441. /*** End of inlined file: juce_win32_Files.cpp ***/
  204442. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204443. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204444. // compiled on its own).
  204445. #if JUCE_INCLUDED_FILE
  204446. #ifndef INTERNET_FLAG_NEED_FILE
  204447. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204448. #endif
  204449. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204450. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204451. #endif
  204452. #ifndef WORKAROUND_TIMEOUT_BUG
  204453. //#define WORKAROUND_TIMEOUT_BUG 1
  204454. #endif
  204455. #if WORKAROUND_TIMEOUT_BUG
  204456. // Required because of a Microsoft bug in setting a timeout
  204457. class InternetConnectThread : public Thread
  204458. {
  204459. public:
  204460. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET sessionHandle_, HINTERNET& connection_, const bool isFtp_)
  204461. : Thread ("Internet"), uc (uc_), sessionHandle (sessionHandle_), connection (connection_), isFtp (isFtp_)
  204462. {
  204463. startThread();
  204464. }
  204465. ~InternetConnectThread()
  204466. {
  204467. stopThread (60000);
  204468. }
  204469. void run()
  204470. {
  204471. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204472. uc.nPort, _T(""), _T(""),
  204473. isFtp ? INTERNET_SERVICE_FTP
  204474. : INTERNET_SERVICE_HTTP,
  204475. 0, 0);
  204476. notify();
  204477. }
  204478. private:
  204479. URL_COMPONENTS& uc;
  204480. HINTERNET sessionHandle;
  204481. HINTERNET& connection;
  204482. const bool isFtp;
  204483. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204484. };
  204485. #endif
  204486. class WebInputStream : public InputStream
  204487. {
  204488. public:
  204489. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204490. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204491. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204492. : connection (0), request (0),
  204493. address (address_), headers (headers_), postData (postData_), position (0),
  204494. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204495. {
  204496. createConnection (progressCallback, progressCallbackContext);
  204497. if (responseHeaders != 0 && ! isError())
  204498. {
  204499. DWORD bufferSizeBytes = 4096;
  204500. for (;;)
  204501. {
  204502. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204503. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204504. {
  204505. StringArray headersArray;
  204506. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204507. for (int i = 0; i < headersArray.size(); ++i)
  204508. {
  204509. const String& header = headersArray[i];
  204510. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204511. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204512. const String previousValue ((*responseHeaders) [key]);
  204513. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204514. }
  204515. break;
  204516. }
  204517. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204518. break;
  204519. }
  204520. }
  204521. }
  204522. ~WebInputStream()
  204523. {
  204524. close();
  204525. }
  204526. bool isError() const { return request == 0; }
  204527. bool isExhausted() { return finished; }
  204528. int64 getPosition() { return position; }
  204529. int64 getTotalLength()
  204530. {
  204531. if (! isError())
  204532. {
  204533. DWORD index = 0, result = 0, size = sizeof (result);
  204534. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204535. return (int64) result;
  204536. }
  204537. return -1;
  204538. }
  204539. int read (void* buffer, int bytesToRead)
  204540. {
  204541. DWORD bytesRead = 0;
  204542. if (! (finished || isError()))
  204543. {
  204544. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  204545. position += bytesRead;
  204546. if (bytesRead == 0)
  204547. finished = true;
  204548. }
  204549. return (int) bytesRead;
  204550. }
  204551. bool setPosition (int64 wantedPos)
  204552. {
  204553. if (isError())
  204554. return false;
  204555. if (wantedPos != position)
  204556. {
  204557. finished = false;
  204558. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  204559. if (position == wantedPos)
  204560. return true;
  204561. if (wantedPos < position)
  204562. {
  204563. close();
  204564. position = 0;
  204565. createConnection (0, 0);
  204566. }
  204567. skipNextBytes (wantedPos - position);
  204568. }
  204569. return true;
  204570. }
  204571. private:
  204572. HINTERNET connection, request;
  204573. String address, headers;
  204574. MemoryBlock postData;
  204575. int64 position;
  204576. bool finished;
  204577. const bool isPost;
  204578. int timeOutMs;
  204579. void close()
  204580. {
  204581. if (request != 0)
  204582. {
  204583. InternetCloseHandle (request);
  204584. request = 0;
  204585. }
  204586. if (connection != 0)
  204587. {
  204588. InternetCloseHandle (connection);
  204589. connection = 0;
  204590. }
  204591. }
  204592. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  204593. void* progressCallbackContext)
  204594. {
  204595. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  204596. close();
  204597. if (sessionHandle != 0)
  204598. {
  204599. // break up the url..
  204600. TCHAR file[1024], server[1024];
  204601. URL_COMPONENTS uc;
  204602. zerostruct (uc);
  204603. uc.dwStructSize = sizeof (uc);
  204604. uc.dwUrlPathLength = sizeof (file);
  204605. uc.dwHostNameLength = sizeof (server);
  204606. uc.lpszUrlPath = file;
  204607. uc.lpszHostName = server;
  204608. if (InternetCrackUrl (address.toUTF16(), 0, 0, &uc))
  204609. {
  204610. int disable = 1;
  204611. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204612. if (timeOutMs == 0)
  204613. timeOutMs = 30000;
  204614. else if (timeOutMs < 0)
  204615. timeOutMs = -1;
  204616. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204617. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  204618. #if WORKAROUND_TIMEOUT_BUG
  204619. connection = 0;
  204620. {
  204621. InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp);
  204622. connectThread.wait (timeOutMs);
  204623. if (connection == 0)
  204624. {
  204625. InternetCloseHandle (sessionHandle);
  204626. sessionHandle = 0;
  204627. }
  204628. }
  204629. #else
  204630. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  204631. _T(""), _T(""),
  204632. isFtp ? INTERNET_SERVICE_FTP
  204633. : INTERNET_SERVICE_HTTP,
  204634. 0, 0);
  204635. #endif
  204636. if (connection != 0)
  204637. {
  204638. if (isFtp)
  204639. {
  204640. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  204641. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  204642. }
  204643. else
  204644. {
  204645. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204646. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204647. if (address.startsWithIgnoreCase ("https:"))
  204648. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204649. // IE7 seems to automatically work out when it's https)
  204650. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  204651. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  204652. if (request != 0)
  204653. {
  204654. INTERNET_BUFFERS buffers;
  204655. zerostruct (buffers);
  204656. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204657. buffers.lpcszHeader = headers.toUTF16();
  204658. buffers.dwHeadersLength = headers.length();
  204659. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204660. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204661. {
  204662. int bytesSent = 0;
  204663. for (;;)
  204664. {
  204665. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204666. DWORD bytesDone = 0;
  204667. if (bytesToDo > 0
  204668. && ! InternetWriteFile (request,
  204669. static_cast <const char*> (postData.getData()) + bytesSent,
  204670. bytesToDo, &bytesDone))
  204671. {
  204672. break;
  204673. }
  204674. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204675. {
  204676. if (HttpEndRequest (request, 0, 0, 0))
  204677. return;
  204678. break;
  204679. }
  204680. bytesSent += bytesDone;
  204681. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  204682. break;
  204683. }
  204684. }
  204685. }
  204686. close();
  204687. }
  204688. }
  204689. }
  204690. }
  204691. }
  204692. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  204693. };
  204694. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  204695. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204696. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  204697. {
  204698. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  204699. progressCallback, progressCallbackContext,
  204700. headers, timeOutMs, responseHeaders));
  204701. return wi->isError() ? 0 : wi.release();
  204702. }
  204703. namespace MACAddressHelpers
  204704. {
  204705. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204706. {
  204707. DynamicLibraryLoader dll ("iphlpapi.dll");
  204708. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204709. if (getAdaptersInfo != 0)
  204710. {
  204711. ULONG len = sizeof (IP_ADAPTER_INFO);
  204712. MemoryBlock mb;
  204713. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204714. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204715. {
  204716. mb.setSize (len);
  204717. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204718. }
  204719. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204720. {
  204721. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204722. {
  204723. if (adapter->AddressLength >= 6)
  204724. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  204725. }
  204726. }
  204727. }
  204728. }
  204729. void getViaNetBios (Array<MACAddress>& result)
  204730. {
  204731. DynamicLibraryLoader dll ("netapi32.dll");
  204732. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204733. if (NetbiosCall != 0)
  204734. {
  204735. NCB ncb;
  204736. zerostruct (ncb);
  204737. struct ASTAT
  204738. {
  204739. ADAPTER_STATUS adapt;
  204740. NAME_BUFFER NameBuff [30];
  204741. };
  204742. ASTAT astat;
  204743. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204744. LANA_ENUM enums;
  204745. zerostruct (enums);
  204746. ncb.ncb_command = NCBENUM;
  204747. ncb.ncb_buffer = (unsigned char*) &enums;
  204748. ncb.ncb_length = sizeof (LANA_ENUM);
  204749. NetbiosCall (&ncb);
  204750. for (int i = 0; i < enums.length; ++i)
  204751. {
  204752. zerostruct (ncb);
  204753. ncb.ncb_command = NCBRESET;
  204754. ncb.ncb_lana_num = enums.lana[i];
  204755. if (NetbiosCall (&ncb) == 0)
  204756. {
  204757. zerostruct (ncb);
  204758. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204759. ncb.ncb_command = NCBASTAT;
  204760. ncb.ncb_lana_num = enums.lana[i];
  204761. ncb.ncb_buffer = (unsigned char*) &astat;
  204762. ncb.ncb_length = sizeof (ASTAT);
  204763. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  204764. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  204765. }
  204766. }
  204767. }
  204768. }
  204769. }
  204770. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  204771. {
  204772. MACAddressHelpers::getViaGetAdaptersInfo (result);
  204773. MACAddressHelpers::getViaNetBios (result);
  204774. }
  204775. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204776. const String& emailSubject,
  204777. const String& bodyText,
  204778. const StringArray& filesToAttach)
  204779. {
  204780. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204781. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204782. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204783. bool ok = false;
  204784. if (mapiSendMail != 0)
  204785. {
  204786. MapiMessage message;
  204787. zerostruct (message);
  204788. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204789. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204790. MapiRecipDesc recip;
  204791. zerostruct (recip);
  204792. recip.ulRecipClass = MAPI_TO;
  204793. String targetEmailAddress_ (targetEmailAddress);
  204794. if (targetEmailAddress_.isEmpty())
  204795. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204796. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204797. message.nRecipCount = 1;
  204798. message.lpRecips = &recip;
  204799. HeapBlock <MapiFileDesc> files;
  204800. files.calloc (filesToAttach.size());
  204801. message.nFileCount = filesToAttach.size();
  204802. message.lpFiles = files;
  204803. for (int i = 0; i < filesToAttach.size(); ++i)
  204804. {
  204805. files[i].nPosition = (ULONG) -1;
  204806. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204807. }
  204808. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204809. }
  204810. FreeLibrary (h);
  204811. return ok;
  204812. }
  204813. #endif
  204814. /*** End of inlined file: juce_win32_Network.cpp ***/
  204815. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204816. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204817. // compiled on its own).
  204818. #if JUCE_INCLUDED_FILE
  204819. namespace
  204820. {
  204821. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  204822. {
  204823. HKEY rootKey = 0;
  204824. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204825. rootKey = HKEY_CURRENT_USER;
  204826. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204827. rootKey = HKEY_LOCAL_MACHINE;
  204828. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204829. rootKey = HKEY_CLASSES_ROOT;
  204830. if (rootKey != 0)
  204831. {
  204832. name = name.substring (name.indexOfChar ('\\') + 1);
  204833. const int lastSlash = name.lastIndexOfChar ('\\');
  204834. valueName = name.substring (lastSlash + 1);
  204835. name = name.substring (0, lastSlash);
  204836. HKEY key;
  204837. DWORD result;
  204838. if (createForWriting)
  204839. {
  204840. if (RegCreateKeyEx (rootKey, name.toUTF16(), 0, 0, REG_OPTION_NON_VOLATILE,
  204841. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204842. return key;
  204843. }
  204844. else
  204845. {
  204846. if (RegOpenKeyEx (rootKey, name.toUTF16(), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204847. return key;
  204848. }
  204849. }
  204850. return 0;
  204851. }
  204852. }
  204853. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204854. const String& defaultValue)
  204855. {
  204856. String valueName, result (defaultValue);
  204857. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204858. if (k != 0)
  204859. {
  204860. WCHAR buffer [2048];
  204861. unsigned long bufferSize = sizeof (buffer);
  204862. DWORD type = REG_SZ;
  204863. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204864. {
  204865. if (type == REG_SZ)
  204866. result = buffer;
  204867. else if (type == REG_DWORD)
  204868. result = String ((int) *(DWORD*) buffer);
  204869. }
  204870. RegCloseKey (k);
  204871. }
  204872. return result;
  204873. }
  204874. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204875. const String& value)
  204876. {
  204877. String valueName;
  204878. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204879. if (k != 0)
  204880. {
  204881. RegSetValueEx (k, valueName.toUTF16(), 0, REG_SZ,
  204882. (const BYTE*) value.toUTF16().getAddress(),
  204883. CharPointer_UTF16::getBytesRequiredFor (value.getCharPointer()));
  204884. RegCloseKey (k);
  204885. }
  204886. }
  204887. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204888. {
  204889. bool exists = false;
  204890. String valueName;
  204891. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204892. if (k != 0)
  204893. {
  204894. unsigned char buffer [2048];
  204895. unsigned long bufferSize = sizeof (buffer);
  204896. DWORD type = 0;
  204897. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204898. exists = true;
  204899. RegCloseKey (k);
  204900. }
  204901. return exists;
  204902. }
  204903. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204904. {
  204905. String valueName;
  204906. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204907. if (k != 0)
  204908. {
  204909. RegDeleteValue (k, valueName.toUTF16());
  204910. RegCloseKey (k);
  204911. }
  204912. }
  204913. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204914. {
  204915. String valueName;
  204916. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204917. if (k != 0)
  204918. {
  204919. RegDeleteKey (k, valueName.toUTF16());
  204920. RegCloseKey (k);
  204921. }
  204922. }
  204923. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204924. const String& symbolicDescription,
  204925. const String& fullDescription,
  204926. const File& targetExecutable,
  204927. int iconResourceNumber)
  204928. {
  204929. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204930. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204931. if (iconResourceNumber != 0)
  204932. setRegistryValue (key + "\\DefaultIcon\\",
  204933. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204934. setRegistryValue (key + "\\", fullDescription);
  204935. setRegistryValue (key + "\\shell\\open\\command\\",
  204936. targetExecutable.getFullPathName() + " %1");
  204937. }
  204938. bool juce_IsRunningInWine()
  204939. {
  204940. HKEY key;
  204941. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204942. {
  204943. RegCloseKey (key);
  204944. return true;
  204945. }
  204946. return false;
  204947. }
  204948. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204949. {
  204950. String s (::GetCommandLineW());
  204951. StringArray tokens;
  204952. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204953. return tokens.joinIntoString (" ", 1);
  204954. }
  204955. static void* currentModuleHandle = 0;
  204956. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204957. {
  204958. if (currentModuleHandle == 0)
  204959. currentModuleHandle = GetModuleHandle (0);
  204960. return currentModuleHandle;
  204961. }
  204962. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204963. {
  204964. currentModuleHandle = newHandle;
  204965. }
  204966. void PlatformUtilities::fpuReset()
  204967. {
  204968. #if JUCE_MSVC
  204969. _clearfp();
  204970. #endif
  204971. }
  204972. void PlatformUtilities::beep()
  204973. {
  204974. MessageBeep (MB_OK);
  204975. }
  204976. #endif
  204977. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204978. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204979. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204980. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204981. // compiled on its own).
  204982. #if JUCE_INCLUDED_FILE
  204983. static const unsigned int specialId = WM_APP + 0x4400;
  204984. static const unsigned int broadcastId = WM_APP + 0x4403;
  204985. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204986. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204987. HWND juce_messageWindowHandle = 0;
  204988. extern long improbableWindowNumber; // defined in windowing.cpp
  204989. #ifndef WM_APPCOMMAND
  204990. #define WM_APPCOMMAND 0x0319
  204991. #endif
  204992. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204993. const UINT message,
  204994. const WPARAM wParam,
  204995. const LPARAM lParam) throw()
  204996. {
  204997. JUCE_TRY
  204998. {
  204999. if (h == juce_messageWindowHandle)
  205000. {
  205001. if (message == specialCallbackId)
  205002. {
  205003. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205004. return (LRESULT) (*func) ((void*) lParam);
  205005. }
  205006. else if (message == specialId)
  205007. {
  205008. // these are trapped early in the dispatch call, but must also be checked
  205009. // here in case there are windows modal dialog boxes doing their own
  205010. // dispatch loop and not calling our version
  205011. Message* const message = reinterpret_cast <Message*> (lParam);
  205012. MessageManager::getInstance()->deliverMessage (message);
  205013. message->decReferenceCount();
  205014. return 0;
  205015. }
  205016. else if (message == broadcastId)
  205017. {
  205018. const ScopedPointer <String> messageString ((String*) lParam);
  205019. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205020. return 0;
  205021. }
  205022. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205023. {
  205024. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205025. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205026. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205027. return 0;
  205028. }
  205029. }
  205030. }
  205031. JUCE_CATCH_EXCEPTION
  205032. return DefWindowProc (h, message, wParam, lParam);
  205033. }
  205034. static bool isEventBlockedByModalComps (MSG& m)
  205035. {
  205036. if (Component::getNumCurrentlyModalComponents() == 0
  205037. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205038. return false;
  205039. switch (m.message)
  205040. {
  205041. case WM_MOUSEMOVE:
  205042. case WM_NCMOUSEMOVE:
  205043. case 0x020A: /* WM_MOUSEWHEEL */
  205044. case 0x020E: /* WM_MOUSEHWHEEL */
  205045. case WM_KEYUP:
  205046. case WM_SYSKEYUP:
  205047. case WM_CHAR:
  205048. case WM_APPCOMMAND:
  205049. case WM_LBUTTONUP:
  205050. case WM_MBUTTONUP:
  205051. case WM_RBUTTONUP:
  205052. case WM_MOUSEACTIVATE:
  205053. case WM_NCMOUSEHOVER:
  205054. case WM_MOUSEHOVER:
  205055. return true;
  205056. case WM_NCLBUTTONDOWN:
  205057. case WM_NCLBUTTONDBLCLK:
  205058. case WM_NCRBUTTONDOWN:
  205059. case WM_NCRBUTTONDBLCLK:
  205060. case WM_NCMBUTTONDOWN:
  205061. case WM_NCMBUTTONDBLCLK:
  205062. case WM_LBUTTONDOWN:
  205063. case WM_LBUTTONDBLCLK:
  205064. case WM_MBUTTONDOWN:
  205065. case WM_MBUTTONDBLCLK:
  205066. case WM_RBUTTONDOWN:
  205067. case WM_RBUTTONDBLCLK:
  205068. case WM_KEYDOWN:
  205069. case WM_SYSKEYDOWN:
  205070. {
  205071. Component* const modal = Component::getCurrentlyModalComponent (0);
  205072. if (modal != 0)
  205073. modal->inputAttemptWhenModal();
  205074. return true;
  205075. }
  205076. default:
  205077. break;
  205078. }
  205079. return false;
  205080. }
  205081. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205082. {
  205083. MSG m;
  205084. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205085. return false;
  205086. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205087. {
  205088. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205089. {
  205090. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205091. MessageManager::getInstance()->deliverMessage (message);
  205092. message->decReferenceCount();
  205093. }
  205094. else if (m.message == WM_QUIT)
  205095. {
  205096. if (JUCEApplication::getInstance() != 0)
  205097. JUCEApplication::getInstance()->systemRequestedQuit();
  205098. }
  205099. else if (! isEventBlockedByModalComps (m))
  205100. {
  205101. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205102. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205103. {
  205104. // if it's someone else's window being clicked on, and the focus is
  205105. // currently on a juce window, pass the kb focus over..
  205106. HWND currentFocus = GetFocus();
  205107. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205108. SetFocus (m.hwnd);
  205109. }
  205110. TranslateMessage (&m);
  205111. DispatchMessage (&m);
  205112. }
  205113. }
  205114. return true;
  205115. }
  205116. bool juce_postMessageToSystemQueue (Message* message)
  205117. {
  205118. message->incReferenceCount();
  205119. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205120. }
  205121. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205122. void* userData)
  205123. {
  205124. if (MessageManager::getInstance()->isThisTheMessageThread())
  205125. {
  205126. return (*callback) (userData);
  205127. }
  205128. else
  205129. {
  205130. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205131. // deadlock because the message manager is blocked from running, and can't
  205132. // call your function..
  205133. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205134. return (void*) SendMessage (juce_messageWindowHandle,
  205135. specialCallbackId,
  205136. (WPARAM) callback,
  205137. (LPARAM) userData);
  205138. }
  205139. }
  205140. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205141. {
  205142. if (hwnd != juce_messageWindowHandle)
  205143. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205144. return TRUE;
  205145. }
  205146. void MessageManager::broadcastMessage (const String& value)
  205147. {
  205148. Array<void*> windows;
  205149. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205150. const String localCopy (value);
  205151. COPYDATASTRUCT data;
  205152. data.dwData = broadcastId;
  205153. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205154. data.lpData = (void*) localCopy.toUTF16().getAddress();
  205155. for (int i = windows.size(); --i >= 0;)
  205156. {
  205157. HWND hwnd = (HWND) windows.getUnchecked(i);
  205158. TCHAR windowName [64]; // no need to read longer strings than this
  205159. GetWindowText (hwnd, windowName, 64);
  205160. windowName [63] = 0;
  205161. if (String (windowName) == messageWindowName)
  205162. {
  205163. DWORD_PTR result;
  205164. SendMessageTimeout (hwnd, WM_COPYDATA,
  205165. (WPARAM) juce_messageWindowHandle,
  205166. (LPARAM) &data,
  205167. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205168. 8000,
  205169. &result);
  205170. }
  205171. }
  205172. }
  205173. static const String getMessageWindowClassName()
  205174. {
  205175. // this name has to be different for each app/dll instance because otherwise
  205176. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205177. // window class).
  205178. static int number = 0;
  205179. if (number == 0)
  205180. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205181. return "JUCEcs_" + String (number);
  205182. }
  205183. void MessageManager::doPlatformSpecificInitialisation()
  205184. {
  205185. OleInitialize (0);
  205186. const String className (getMessageWindowClassName());
  205187. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205188. WNDCLASSEX wc;
  205189. zerostruct (wc);
  205190. wc.cbSize = sizeof (wc);
  205191. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205192. wc.cbWndExtra = 4;
  205193. wc.hInstance = hmod;
  205194. wc.lpszClassName = className.toUTF16();
  205195. RegisterClassEx (&wc);
  205196. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205197. messageWindowName,
  205198. 0, 0, 0, 0, 0, 0, 0,
  205199. hmod, 0);
  205200. }
  205201. void MessageManager::doPlatformSpecificShutdown()
  205202. {
  205203. DestroyWindow (juce_messageWindowHandle);
  205204. UnregisterClass (getMessageWindowClassName().toUTF16(), 0);
  205205. OleUninitialize();
  205206. }
  205207. #endif
  205208. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205209. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205210. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205211. // compiled on its own).
  205212. #if JUCE_INCLUDED_FILE
  205213. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205214. NEWTEXTMETRICEXW*,
  205215. int type,
  205216. LPARAM lParam)
  205217. {
  205218. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205219. {
  205220. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205221. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205222. }
  205223. return 1;
  205224. }
  205225. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205226. NEWTEXTMETRICEXW*,
  205227. int type,
  205228. LPARAM lParam)
  205229. {
  205230. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205231. {
  205232. LOGFONTW lf;
  205233. zerostruct (lf);
  205234. lf.lfWeight = FW_DONTCARE;
  205235. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205236. lf.lfQuality = DEFAULT_QUALITY;
  205237. lf.lfCharSet = DEFAULT_CHARSET;
  205238. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205239. lf.lfPitchAndFamily = FF_DONTCARE;
  205240. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205241. fontName.copyToUTF16 (lf.lfFaceName, LF_FACESIZE - 1);
  205242. HDC dc = CreateCompatibleDC (0);
  205243. EnumFontFamiliesEx (dc, &lf,
  205244. (FONTENUMPROCW) &wfontEnum2,
  205245. lParam, 0);
  205246. DeleteDC (dc);
  205247. }
  205248. return 1;
  205249. }
  205250. const StringArray Font::findAllTypefaceNames()
  205251. {
  205252. StringArray results;
  205253. HDC dc = CreateCompatibleDC (0);
  205254. {
  205255. LOGFONTW lf;
  205256. zerostruct (lf);
  205257. lf.lfWeight = FW_DONTCARE;
  205258. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205259. lf.lfQuality = DEFAULT_QUALITY;
  205260. lf.lfCharSet = DEFAULT_CHARSET;
  205261. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205262. lf.lfPitchAndFamily = FF_DONTCARE;
  205263. lf.lfFaceName[0] = 0;
  205264. EnumFontFamiliesEx (dc, &lf,
  205265. (FONTENUMPROCW) &wfontEnum1,
  205266. (LPARAM) &results, 0);
  205267. }
  205268. DeleteDC (dc);
  205269. results.sort (true);
  205270. return results;
  205271. }
  205272. extern bool juce_IsRunningInWine();
  205273. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205274. {
  205275. if (juce_IsRunningInWine())
  205276. {
  205277. // If we're running in Wine, then use fonts that might be available on Linux..
  205278. defaultSans = "Bitstream Vera Sans";
  205279. defaultSerif = "Bitstream Vera Serif";
  205280. defaultFixed = "Bitstream Vera Sans Mono";
  205281. }
  205282. else
  205283. {
  205284. defaultSans = "Verdana";
  205285. defaultSerif = "Times";
  205286. defaultFixed = "Lucida Console";
  205287. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205288. }
  205289. }
  205290. class FontDCHolder : private DeletedAtShutdown
  205291. {
  205292. public:
  205293. FontDCHolder()
  205294. : fontH (0), previousFontH (0), dc (0), numKPs (0), size (0),
  205295. bold (false), italic (false)
  205296. {
  205297. }
  205298. ~FontDCHolder()
  205299. {
  205300. deleteDCAndFont();
  205301. clearSingletonInstance();
  205302. }
  205303. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205304. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205305. {
  205306. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205307. {
  205308. fontName = fontName_;
  205309. bold = bold_;
  205310. italic = italic_;
  205311. size = size_;
  205312. deleteDCAndFont();
  205313. dc = CreateCompatibleDC (0);
  205314. SetMapperFlags (dc, 0);
  205315. SetMapMode (dc, MM_TEXT);
  205316. LOGFONTW lfw;
  205317. zerostruct (lfw);
  205318. lfw.lfCharSet = DEFAULT_CHARSET;
  205319. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205320. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205321. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205322. lfw.lfQuality = PROOF_QUALITY;
  205323. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205324. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205325. fontName.copyToUTF16 (lfw.lfFaceName, LF_FACESIZE - 1);
  205326. lfw.lfHeight = size > 0 ? size : -256;
  205327. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205328. if (standardSizedFont != 0)
  205329. {
  205330. if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
  205331. {
  205332. fontH = standardSizedFont;
  205333. if (size == 0)
  205334. {
  205335. OUTLINETEXTMETRIC otm;
  205336. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205337. {
  205338. lfw.lfHeight = -(int) otm.otmEMSquare;
  205339. fontH = CreateFontIndirect (&lfw);
  205340. SelectObject (dc, fontH);
  205341. DeleteObject (standardSizedFont);
  205342. }
  205343. }
  205344. }
  205345. }
  205346. }
  205347. return dc;
  205348. }
  205349. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205350. {
  205351. if (kps == 0)
  205352. {
  205353. numKPs = GetKerningPairs (dc, 0, 0);
  205354. kps.calloc (numKPs);
  205355. GetKerningPairs (dc, numKPs, kps);
  205356. }
  205357. numKPs_ = numKPs;
  205358. return kps;
  205359. }
  205360. private:
  205361. HFONT fontH;
  205362. HGDIOBJ previousFontH;
  205363. HDC dc;
  205364. String fontName;
  205365. HeapBlock <KERNINGPAIR> kps;
  205366. int numKPs, size;
  205367. bool bold, italic;
  205368. void deleteDCAndFont()
  205369. {
  205370. if (dc != 0)
  205371. {
  205372. SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
  205373. DeleteDC (dc);
  205374. dc = 0;
  205375. }
  205376. if (fontH != 0)
  205377. {
  205378. DeleteObject (fontH);
  205379. fontH = 0;
  205380. }
  205381. kps.free();
  205382. }
  205383. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205384. };
  205385. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205386. class WindowsTypeface : public CustomTypeface
  205387. {
  205388. public:
  205389. WindowsTypeface (const Font& font)
  205390. {
  205391. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205392. font.isBold(), font.isItalic(), 0);
  205393. TEXTMETRIC tm;
  205394. tm.tmAscent = tm.tmHeight = 1;
  205395. tm.tmDefaultChar = 0;
  205396. GetTextMetrics (dc, &tm);
  205397. setCharacteristics (font.getTypefaceName(),
  205398. tm.tmAscent / (float) tm.tmHeight,
  205399. font.isBold(), font.isItalic(),
  205400. tm.tmDefaultChar);
  205401. }
  205402. bool loadGlyphIfPossible (juce_wchar character)
  205403. {
  205404. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205405. GLYPHMETRICS gm;
  205406. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205407. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205408. // gets correctly created later on.
  205409. if (! isFallbackFont)
  205410. {
  205411. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205412. WORD index = 0;
  205413. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205414. && index == 0xffff)
  205415. {
  205416. return false;
  205417. }
  205418. }
  205419. Path glyphPath;
  205420. TEXTMETRIC tm;
  205421. if (! GetTextMetrics (dc, &tm))
  205422. {
  205423. addGlyph (character, glyphPath, 0);
  205424. return true;
  205425. }
  205426. const float height = (float) tm.tmHeight;
  205427. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205428. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205429. &gm, 0, 0, &identityMatrix);
  205430. if (bufSize > 0)
  205431. {
  205432. HeapBlock<char> data (bufSize);
  205433. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205434. bufSize, data, &identityMatrix);
  205435. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205436. const float scaleX = 1.0f / height;
  205437. const float scaleY = -1.0f / height;
  205438. while ((char*) pheader < data + bufSize)
  205439. {
  205440. float x = scaleX * pheader->pfxStart.x.value;
  205441. float y = scaleY * pheader->pfxStart.y.value;
  205442. glyphPath.startNewSubPath (x, y);
  205443. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205444. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205445. while ((const char*) curve < curveEnd)
  205446. {
  205447. if (curve->wType == TT_PRIM_LINE)
  205448. {
  205449. for (int i = 0; i < curve->cpfx; ++i)
  205450. {
  205451. x = scaleX * curve->apfx[i].x.value;
  205452. y = scaleY * curve->apfx[i].y.value;
  205453. glyphPath.lineTo (x, y);
  205454. }
  205455. }
  205456. else if (curve->wType == TT_PRIM_QSPLINE)
  205457. {
  205458. for (int i = 0; i < curve->cpfx - 1; ++i)
  205459. {
  205460. const float x2 = scaleX * curve->apfx[i].x.value;
  205461. const float y2 = scaleY * curve->apfx[i].y.value;
  205462. float x3, y3;
  205463. if (i < curve->cpfx - 2)
  205464. {
  205465. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205466. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205467. }
  205468. else
  205469. {
  205470. x3 = scaleX * curve->apfx[i + 1].x.value;
  205471. y3 = scaleY * curve->apfx[i + 1].y.value;
  205472. }
  205473. glyphPath.quadraticTo (x2, y2, x3, y3);
  205474. x = x3;
  205475. y = y3;
  205476. }
  205477. }
  205478. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205479. }
  205480. pheader = (const TTPOLYGONHEADER*) curve;
  205481. glyphPath.closeSubPath();
  205482. }
  205483. }
  205484. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205485. int numKPs;
  205486. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205487. for (int i = 0; i < numKPs; ++i)
  205488. {
  205489. if (kps[i].wFirst == character)
  205490. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205491. kps[i].iKernAmount / height);
  205492. }
  205493. return true;
  205494. }
  205495. private:
  205496. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205497. };
  205498. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205499. {
  205500. return new WindowsTypeface (font);
  205501. }
  205502. #endif
  205503. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205504. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205505. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205506. // compiled on its own).
  205507. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205508. class SharedD2DFactory : public DeletedAtShutdown
  205509. {
  205510. public:
  205511. SharedD2DFactory()
  205512. {
  205513. jassertfalse; //xxx Direct2D support isn't ready for use yet!
  205514. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, d2dFactory.resetAndGetPointerAddress());
  205515. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) directWriteFactory.resetAndGetPointerAddress());
  205516. if (directWriteFactory != 0)
  205517. directWriteFactory->GetSystemFontCollection (systemFonts.resetAndGetPointerAddress());
  205518. }
  205519. ~SharedD2DFactory()
  205520. {
  205521. clearSingletonInstance();
  205522. }
  205523. juce_DeclareSingleton (SharedD2DFactory, false);
  205524. ComSmartPtr <ID2D1Factory> d2dFactory;
  205525. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205526. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205527. };
  205528. juce_ImplementSingleton (SharedD2DFactory)
  205529. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205530. {
  205531. public:
  205532. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205533. : hwnd (hwnd_),
  205534. currentState (0)
  205535. {
  205536. RECT windowRect;
  205537. GetClientRect (hwnd, &windowRect);
  205538. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205539. bounds.setSize (size.width, size.height);
  205540. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205541. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205542. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, renderingTarget.resetAndGetPointerAddress());
  205543. // xxx check for error
  205544. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), colourBrush.resetAndGetPointerAddress());
  205545. }
  205546. ~Direct2DLowLevelGraphicsContext()
  205547. {
  205548. states.clear();
  205549. }
  205550. void resized()
  205551. {
  205552. RECT windowRect;
  205553. GetClientRect (hwnd, &windowRect);
  205554. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205555. renderingTarget->Resize (size);
  205556. bounds.setSize (size.width, size.height);
  205557. }
  205558. void clear()
  205559. {
  205560. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205561. }
  205562. void start()
  205563. {
  205564. renderingTarget->BeginDraw();
  205565. saveState();
  205566. }
  205567. void end()
  205568. {
  205569. states.clear();
  205570. currentState = 0;
  205571. renderingTarget->EndDraw();
  205572. renderingTarget->CheckWindowState();
  205573. }
  205574. bool isVectorDevice() const { return false; }
  205575. void setOrigin (int x, int y)
  205576. {
  205577. currentState->origin.addXY (x, y);
  205578. }
  205579. void addTransform (const AffineTransform& transform)
  205580. {
  205581. //xxx todo
  205582. jassertfalse;
  205583. }
  205584. float getScaleFactor()
  205585. {
  205586. jassertfalse; //xxx
  205587. return 1.0f;
  205588. }
  205589. bool clipToRectangle (const Rectangle<int>& r)
  205590. {
  205591. currentState->clipToRectangle (r);
  205592. return ! isClipEmpty();
  205593. }
  205594. bool clipToRectangleList (const RectangleList& clipRegion)
  205595. {
  205596. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205597. return ! isClipEmpty();
  205598. }
  205599. void excludeClipRectangle (const Rectangle<int>&)
  205600. {
  205601. //xxx
  205602. }
  205603. void clipToPath (const Path& path, const AffineTransform& transform)
  205604. {
  205605. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205606. }
  205607. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205608. {
  205609. currentState->clipToImage (sourceImage,transform);
  205610. }
  205611. bool clipRegionIntersects (const Rectangle<int>& r)
  205612. {
  205613. const Rectangle<int> r2 (r + currentState->origin);
  205614. return currentState->clipRect.intersects (r2);
  205615. }
  205616. const Rectangle<int> getClipBounds() const
  205617. {
  205618. // xxx could this take into account complex clip regions?
  205619. return currentState->clipRect - currentState->origin;
  205620. }
  205621. bool isClipEmpty() const
  205622. {
  205623. return currentState->clipRect.isEmpty();
  205624. }
  205625. void saveState()
  205626. {
  205627. states.add (new SavedState (*this));
  205628. currentState = states.getLast();
  205629. }
  205630. void restoreState()
  205631. {
  205632. jassert (states.size() > 1) //you should never pop the last state!
  205633. states.removeLast (1);
  205634. currentState = states.getLast();
  205635. }
  205636. void beginTransparencyLayer (float opacity)
  205637. {
  205638. jassertfalse; //xxx todo
  205639. }
  205640. void endTransparencyLayer()
  205641. {
  205642. jassertfalse; //xxx todo
  205643. }
  205644. void setFill (const FillType& fillType)
  205645. {
  205646. currentState->setFill (fillType);
  205647. }
  205648. void setOpacity (float newOpacity)
  205649. {
  205650. currentState->setOpacity (newOpacity);
  205651. }
  205652. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205653. {
  205654. }
  205655. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205656. {
  205657. currentState->createBrush();
  205658. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205659. }
  205660. void fillPath (const Path& p, const AffineTransform& transform)
  205661. {
  205662. currentState->createBrush();
  205663. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205664. if (renderingTarget != 0)
  205665. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205666. }
  205667. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205668. {
  205669. const int x = currentState->origin.getX();
  205670. const int y = currentState->origin.getY();
  205671. renderingTarget->SetTransform (transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205672. D2D1_SIZE_U size;
  205673. size.width = image.getWidth();
  205674. size.height = image.getHeight();
  205675. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205676. Image img (image.convertedToFormat (Image::ARGB));
  205677. Image::BitmapData bd (img, false);
  205678. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205679. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205680. {
  205681. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205682. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, tempBitmap.resetAndGetPointerAddress());
  205683. if (tempBitmap != 0)
  205684. renderingTarget->DrawBitmap (tempBitmap);
  205685. }
  205686. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205687. }
  205688. void drawLine (const Line <float>& line)
  205689. {
  205690. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205691. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205692. line.getEnd() + currentState->origin.toFloat());
  205693. currentState->createBrush();
  205694. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205695. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205696. currentState->currentBrush);
  205697. }
  205698. void drawVerticalLine (int x, float top, float bottom)
  205699. {
  205700. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205701. currentState->createBrush();
  205702. x += currentState->origin.getX();
  205703. const int y = currentState->origin.getY();
  205704. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205705. D2D1::Point2F (x, y + bottom),
  205706. currentState->currentBrush);
  205707. }
  205708. void drawHorizontalLine (int y, float left, float right)
  205709. {
  205710. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205711. currentState->createBrush();
  205712. y += currentState->origin.getY();
  205713. const int x = currentState->origin.getX();
  205714. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205715. D2D1::Point2F (x + right, y),
  205716. currentState->currentBrush);
  205717. }
  205718. void setFont (const Font& newFont)
  205719. {
  205720. currentState->setFont (newFont);
  205721. }
  205722. const Font getFont()
  205723. {
  205724. return currentState->font;
  205725. }
  205726. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205727. {
  205728. const float x = currentState->origin.getX();
  205729. const float y = currentState->origin.getY();
  205730. currentState->createBrush();
  205731. currentState->createFont();
  205732. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205733. float hScale = currentState->font.getHorizontalScale();
  205734. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205735. float dpiX = 0, dpiY = 0;
  205736. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205737. UINT32 glyphNum = glyphNumber;
  205738. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205739. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205740. DWRITE_GLYPH_OFFSET offset;
  205741. offset.advanceOffset = 0;
  205742. offset.ascenderOffset = 0;
  205743. float glyphAdvances = 0;
  205744. DWRITE_GLYPH_RUN glyph;
  205745. glyph.fontFace = currentState->currentFontFace;
  205746. glyph.glyphCount = 1;
  205747. glyph.glyphIndices = &glyphNum1;
  205748. glyph.isSideways = FALSE;
  205749. glyph.glyphAdvances = &glyphAdvances;
  205750. glyph.glyphOffsets = &offset;
  205751. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205752. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205753. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205754. }
  205755. class SavedState
  205756. {
  205757. public:
  205758. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205759. : owner (owner_), currentBrush (0),
  205760. fontScaling (1.0f), currentFontFace (0),
  205761. clipsRect (false), shouldClipRect (false),
  205762. clipsRectList (false), shouldClipRectList (false),
  205763. clipsComplex (false), shouldClipComplex (false),
  205764. clipsBitmap (false), shouldClipBitmap (false)
  205765. {
  205766. if (owner.currentState != 0)
  205767. {
  205768. // xxx seems like a very slow way to create one of these, and this is a performance
  205769. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205770. setFill (owner.currentState->fillType);
  205771. currentBrush = owner.currentState->currentBrush;
  205772. origin = owner.currentState->origin;
  205773. clipRect = owner.currentState->clipRect;
  205774. font = owner.currentState->font;
  205775. currentFontFace = owner.currentState->currentFontFace;
  205776. }
  205777. else
  205778. {
  205779. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205780. clipRect.setSize (size.width, size.height);
  205781. setFill (FillType (Colours::black));
  205782. }
  205783. }
  205784. ~SavedState()
  205785. {
  205786. clearClip();
  205787. clearFont();
  205788. clearFill();
  205789. clearPathClip();
  205790. clearImageClip();
  205791. complexClipLayer = 0;
  205792. bitmapMaskLayer = 0;
  205793. }
  205794. void clearClip()
  205795. {
  205796. popClips();
  205797. shouldClipRect = false;
  205798. }
  205799. void clipToRectangle (const Rectangle<int>& r)
  205800. {
  205801. clearClip();
  205802. clipRect = r + origin;
  205803. shouldClipRect = true;
  205804. pushClips();
  205805. }
  205806. void clearPathClip()
  205807. {
  205808. popClips();
  205809. if (shouldClipComplex)
  205810. {
  205811. complexClipGeometry = 0;
  205812. shouldClipComplex = false;
  205813. }
  205814. }
  205815. void clipToPath (ID2D1Geometry* geometry)
  205816. {
  205817. clearPathClip();
  205818. if (complexClipLayer == 0)
  205819. owner.renderingTarget->CreateLayer (complexClipLayer.resetAndGetPointerAddress());
  205820. complexClipGeometry = geometry;
  205821. shouldClipComplex = true;
  205822. pushClips();
  205823. }
  205824. void clearRectListClip()
  205825. {
  205826. popClips();
  205827. if (shouldClipRectList)
  205828. {
  205829. rectListGeometry = 0;
  205830. shouldClipRectList = false;
  205831. }
  205832. }
  205833. void clipToRectList (ID2D1Geometry* geometry)
  205834. {
  205835. clearRectListClip();
  205836. if (rectListLayer == 0)
  205837. owner.renderingTarget->CreateLayer (rectListLayer.resetAndGetPointerAddress());
  205838. rectListGeometry = geometry;
  205839. shouldClipRectList = true;
  205840. pushClips();
  205841. }
  205842. void clearImageClip()
  205843. {
  205844. popClips();
  205845. if (shouldClipBitmap)
  205846. {
  205847. maskBitmap = 0;
  205848. bitmapMaskBrush = 0;
  205849. shouldClipBitmap = false;
  205850. }
  205851. }
  205852. void clipToImage (const Image& image, const AffineTransform& transform)
  205853. {
  205854. clearImageClip();
  205855. if (bitmapMaskLayer == 0)
  205856. owner.renderingTarget->CreateLayer (bitmapMaskLayer.resetAndGetPointerAddress());
  205857. D2D1_BRUSH_PROPERTIES brushProps;
  205858. brushProps.opacity = 1;
  205859. brushProps.transform = transformToMatrix (transform);
  205860. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205861. D2D1_SIZE_U size;
  205862. size.width = image.getWidth();
  205863. size.height = image.getHeight();
  205864. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205865. maskImage = image.convertedToFormat (Image::ARGB);
  205866. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  205867. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205868. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205869. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, maskBitmap.resetAndGetPointerAddress());
  205870. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, bitmapMaskBrush.resetAndGetPointerAddress());
  205871. imageMaskLayerParams = D2D1::LayerParameters();
  205872. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  205873. shouldClipBitmap = true;
  205874. pushClips();
  205875. }
  205876. void popClips()
  205877. {
  205878. if (clipsBitmap)
  205879. {
  205880. owner.renderingTarget->PopLayer();
  205881. clipsBitmap = false;
  205882. }
  205883. if (clipsComplex)
  205884. {
  205885. owner.renderingTarget->PopLayer();
  205886. clipsComplex = false;
  205887. }
  205888. if (clipsRectList)
  205889. {
  205890. owner.renderingTarget->PopLayer();
  205891. clipsRectList = false;
  205892. }
  205893. if (clipsRect)
  205894. {
  205895. owner.renderingTarget->PopAxisAlignedClip();
  205896. clipsRect = false;
  205897. }
  205898. }
  205899. void pushClips()
  205900. {
  205901. if (shouldClipRect && ! clipsRect)
  205902. {
  205903. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  205904. clipsRect = true;
  205905. }
  205906. if (shouldClipRectList && ! clipsRectList)
  205907. {
  205908. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205909. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205910. layerParams.geometricMask = rectListGeometry;
  205911. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  205912. clipsRectList = true;
  205913. }
  205914. if (shouldClipComplex && ! clipsComplex)
  205915. {
  205916. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205917. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205918. layerParams.geometricMask = complexClipGeometry;
  205919. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  205920. clipsComplex = true;
  205921. }
  205922. if (shouldClipBitmap && ! clipsBitmap)
  205923. {
  205924. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  205925. clipsBitmap = true;
  205926. }
  205927. }
  205928. void setFill (const FillType& newFillType)
  205929. {
  205930. if (fillType != newFillType)
  205931. {
  205932. fillType = newFillType;
  205933. clearFill();
  205934. }
  205935. }
  205936. void clearFont()
  205937. {
  205938. currentFontFace = localFontFace = 0;
  205939. }
  205940. void setFont (const Font& newFont)
  205941. {
  205942. if (font != newFont)
  205943. {
  205944. font = newFont;
  205945. clearFont();
  205946. }
  205947. }
  205948. void createFont()
  205949. {
  205950. // xxx The font shouldn't be managed by the graphics context.
  205951. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  205952. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  205953. // WindowsTypeface class.
  205954. if (currentFontFace == 0)
  205955. {
  205956. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  205957. fontScaling = systemType->getAscent();
  205958. BOOL fontFound;
  205959. uint32 fontIndex;
  205960. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  205961. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  205962. if (! fontFound)
  205963. fontIndex = 0;
  205964. ComSmartPtr <IDWriteFontFamily> fontFam;
  205965. fonts->GetFontFamily (fontIndex, fontFam.resetAndGetPointerAddress());
  205966. ComSmartPtr <IDWriteFont> font;
  205967. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  205968. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  205969. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, font.resetAndGetPointerAddress());
  205970. font->CreateFontFace (localFontFace.resetAndGetPointerAddress());
  205971. currentFontFace = localFontFace;
  205972. }
  205973. }
  205974. void setOpacity (float newOpacity)
  205975. {
  205976. fillType.setOpacity (newOpacity);
  205977. if (currentBrush != 0)
  205978. currentBrush->SetOpacity (newOpacity);
  205979. }
  205980. void clearFill()
  205981. {
  205982. gradientStops = 0;
  205983. linearGradient = 0;
  205984. radialGradient = 0;
  205985. bitmap = 0;
  205986. bitmapBrush = 0;
  205987. currentBrush = 0;
  205988. }
  205989. void createBrush()
  205990. {
  205991. if (currentBrush == 0)
  205992. {
  205993. const int x = origin.getX();
  205994. const int y = origin.getY();
  205995. if (fillType.isColour())
  205996. {
  205997. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  205998. owner.colourBrush->SetColor (colour);
  205999. currentBrush = owner.colourBrush;
  206000. }
  206001. else if (fillType.isTiledImage())
  206002. {
  206003. D2D1_BRUSH_PROPERTIES brushProps;
  206004. brushProps.opacity = fillType.getOpacity();
  206005. brushProps.transform = transformToMatrix (fillType.transform);
  206006. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206007. image = fillType.image;
  206008. D2D1_SIZE_U size;
  206009. size.width = image.getWidth();
  206010. size.height = image.getHeight();
  206011. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206012. this->image = image.convertedToFormat (Image::ARGB);
  206013. Image::BitmapData bd (this->image, false);
  206014. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206015. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206016. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, bitmap.resetAndGetPointerAddress());
  206017. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, bitmapBrush.resetAndGetPointerAddress());
  206018. currentBrush = bitmapBrush;
  206019. }
  206020. else if (fillType.isGradient())
  206021. {
  206022. gradientStops = 0;
  206023. D2D1_BRUSH_PROPERTIES brushProps;
  206024. brushProps.opacity = fillType.getOpacity();
  206025. brushProps.transform = transformToMatrix (fillType.transform);
  206026. const int numColors = fillType.gradient->getNumColours();
  206027. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206028. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206029. {
  206030. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206031. stops[i].position = fillType.gradient->getColourPosition(i);
  206032. }
  206033. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, gradientStops.resetAndGetPointerAddress());
  206034. if (fillType.gradient->isRadial)
  206035. {
  206036. radialGradient = 0;
  206037. const Point<float>& p1 = fillType.gradient->point1;
  206038. const Point<float>& p2 = fillType.gradient->point2;
  206039. float r = p1.getDistanceFrom (p2);
  206040. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206041. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206042. D2D1::Point2F (0, 0),
  206043. r, r);
  206044. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, radialGradient.resetAndGetPointerAddress());
  206045. currentBrush = radialGradient;
  206046. }
  206047. else
  206048. {
  206049. linearGradient = 0;
  206050. const Point<float>& p1 = fillType.gradient->point1;
  206051. const Point<float>& p2 = fillType.gradient->point2;
  206052. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206053. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206054. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206055. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, linearGradient.resetAndGetPointerAddress());
  206056. currentBrush = linearGradient;
  206057. }
  206058. }
  206059. }
  206060. }
  206061. //xxx most of these members should probably be private...
  206062. Direct2DLowLevelGraphicsContext& owner;
  206063. Point<int> origin;
  206064. Font font;
  206065. float fontScaling;
  206066. IDWriteFontFace* currentFontFace;
  206067. ComSmartPtr <IDWriteFontFace> localFontFace;
  206068. FillType fillType;
  206069. Image image;
  206070. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206071. Rectangle<int> clipRect;
  206072. bool clipsRect, shouldClipRect;
  206073. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206074. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206075. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206076. bool clipsComplex, shouldClipComplex;
  206077. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206078. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206079. ComSmartPtr <ID2D1Layer> rectListLayer;
  206080. bool clipsRectList, shouldClipRectList;
  206081. Image maskImage;
  206082. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206083. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206084. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206085. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206086. bool clipsBitmap, shouldClipBitmap;
  206087. ID2D1Brush* currentBrush;
  206088. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206089. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206090. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206091. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206092. private:
  206093. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206094. };
  206095. private:
  206096. HWND hwnd;
  206097. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206098. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206099. Rectangle<int> bounds;
  206100. SavedState* currentState;
  206101. OwnedArray<SavedState> states;
  206102. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206103. {
  206104. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206105. }
  206106. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206107. {
  206108. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206109. }
  206110. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206111. {
  206112. transform.transformPoint (x, y);
  206113. return D2D1::Point2F (x, y);
  206114. }
  206115. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206116. {
  206117. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206118. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206119. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206120. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206121. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206122. }
  206123. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206124. {
  206125. ID2D1PathGeometry* p = 0;
  206126. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206127. ComSmartPtr <ID2D1GeometrySink> sink;
  206128. HRESULT hr = p->Open (sink.resetAndGetPointerAddress()); // xxx handle error
  206129. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206130. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206131. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206132. hr = sink->Close();
  206133. return p;
  206134. }
  206135. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206136. {
  206137. Path::Iterator it (path);
  206138. while (it.next())
  206139. {
  206140. switch (it.elementType)
  206141. {
  206142. case Path::Iterator::cubicTo:
  206143. {
  206144. D2D1_BEZIER_SEGMENT seg;
  206145. transform.transformPoint (it.x1, it.y1);
  206146. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206147. transform.transformPoint (it.x2, it.y2);
  206148. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206149. transform.transformPoint(it.x3, it.y3);
  206150. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206151. sink->AddBezier (seg);
  206152. break;
  206153. }
  206154. case Path::Iterator::lineTo:
  206155. {
  206156. transform.transformPoint (it.x1, it.y1);
  206157. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206158. break;
  206159. }
  206160. case Path::Iterator::quadraticTo:
  206161. {
  206162. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206163. transform.transformPoint (it.x1, it.y1);
  206164. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206165. transform.transformPoint (it.x2, it.y2);
  206166. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206167. sink->AddQuadraticBezier (seg);
  206168. break;
  206169. }
  206170. case Path::Iterator::closePath:
  206171. {
  206172. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206173. break;
  206174. }
  206175. case Path::Iterator::startNewSubPath:
  206176. {
  206177. transform.transformPoint (it.x1, it.y1);
  206178. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206179. break;
  206180. }
  206181. }
  206182. }
  206183. }
  206184. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206185. {
  206186. ID2D1PathGeometry* p = 0;
  206187. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206188. ComSmartPtr <ID2D1GeometrySink> sink;
  206189. HRESULT hr = p->Open (sink.resetAndGetPointerAddress());
  206190. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206191. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206192. hr = sink->Close();
  206193. return p;
  206194. }
  206195. static const D2D1::Matrix3x2F transformToMatrix (const AffineTransform& transform)
  206196. {
  206197. D2D1::Matrix3x2F matrix;
  206198. matrix._11 = transform.mat00;
  206199. matrix._12 = transform.mat10;
  206200. matrix._21 = transform.mat01;
  206201. matrix._22 = transform.mat11;
  206202. matrix._31 = transform.mat02;
  206203. matrix._32 = transform.mat12;
  206204. return matrix;
  206205. }
  206206. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206207. };
  206208. #endif
  206209. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206210. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206211. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206212. // compiled on its own).
  206213. #if JUCE_INCLUDED_FILE
  206214. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206215. // these are in the windows SDK, but need to be repeated here for GCC..
  206216. #ifndef GET_APPCOMMAND_LPARAM
  206217. #define FAPPCOMMAND_MASK 0xF000
  206218. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206219. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206220. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206221. #define APPCOMMAND_MEDIA_STOP 13
  206222. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206223. #define WM_APPCOMMAND 0x0319
  206224. #endif
  206225. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206226. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206227. extern bool juce_IsRunningInWine();
  206228. #ifndef ULW_ALPHA
  206229. #define ULW_ALPHA 0x00000002
  206230. #endif
  206231. #ifndef AC_SRC_ALPHA
  206232. #define AC_SRC_ALPHA 0x01
  206233. #endif
  206234. static bool shouldDeactivateTitleBar = true;
  206235. #define WM_TRAYNOTIFY WM_USER + 100
  206236. using ::abs;
  206237. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206238. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206239. bool Desktop::canUseSemiTransparentWindows() throw()
  206240. {
  206241. if (updateLayeredWindow == 0)
  206242. {
  206243. if (! juce_IsRunningInWine())
  206244. {
  206245. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206246. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206247. }
  206248. }
  206249. return updateLayeredWindow != 0;
  206250. }
  206251. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206252. {
  206253. return upright;
  206254. }
  206255. const int extendedKeyModifier = 0x10000;
  206256. const int KeyPress::spaceKey = VK_SPACE;
  206257. const int KeyPress::returnKey = VK_RETURN;
  206258. const int KeyPress::escapeKey = VK_ESCAPE;
  206259. const int KeyPress::backspaceKey = VK_BACK;
  206260. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206261. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206262. const int KeyPress::tabKey = VK_TAB;
  206263. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206264. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206265. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206266. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206267. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206268. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206269. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206270. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206271. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206272. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206273. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206274. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206275. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206276. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206277. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206278. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206279. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206280. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206281. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206282. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206283. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206284. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206285. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206286. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206287. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206288. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206289. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206290. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206291. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206292. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206293. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206294. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206295. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206296. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206297. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206298. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206299. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206300. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206301. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206302. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206303. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206304. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206305. const int KeyPress::playKey = 0x30000;
  206306. const int KeyPress::stopKey = 0x30001;
  206307. const int KeyPress::fastForwardKey = 0x30002;
  206308. const int KeyPress::rewindKey = 0x30003;
  206309. class WindowsBitmapImage : public Image::SharedImage
  206310. {
  206311. public:
  206312. HBITMAP hBitmap;
  206313. HGDIOBJ previousBitmap;
  206314. BITMAPV4HEADER bitmapInfo;
  206315. HDC hdc;
  206316. unsigned char* bitmapData;
  206317. WindowsBitmapImage (const Image::PixelFormat format_,
  206318. const int w, const int h, const bool clearImage)
  206319. : Image::SharedImage (format_, w, h)
  206320. {
  206321. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206322. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206323. zerostruct (bitmapInfo);
  206324. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206325. bitmapInfo.bV4Width = w;
  206326. bitmapInfo.bV4Height = h;
  206327. bitmapInfo.bV4Planes = 1;
  206328. bitmapInfo.bV4CSType = 1;
  206329. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206330. if (format_ == Image::ARGB)
  206331. {
  206332. bitmapInfo.bV4AlphaMask = 0xff000000;
  206333. bitmapInfo.bV4RedMask = 0xff0000;
  206334. bitmapInfo.bV4GreenMask = 0xff00;
  206335. bitmapInfo.bV4BlueMask = 0xff;
  206336. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206337. }
  206338. else
  206339. {
  206340. bitmapInfo.bV4V4Compression = BI_RGB;
  206341. }
  206342. lineStride = -((w * pixelStride + 3) & ~3);
  206343. HDC dc = GetDC (0);
  206344. hdc = CreateCompatibleDC (dc);
  206345. ReleaseDC (0, dc);
  206346. SetMapMode (hdc, MM_TEXT);
  206347. hBitmap = CreateDIBSection (hdc,
  206348. (BITMAPINFO*) &(bitmapInfo),
  206349. DIB_RGB_COLORS,
  206350. (void**) &bitmapData,
  206351. 0, 0);
  206352. previousBitmap = SelectObject (hdc, hBitmap);
  206353. if (format_ == Image::ARGB && clearImage)
  206354. zeromem (bitmapData, abs (h * lineStride));
  206355. imageData = bitmapData - (lineStride * (h - 1));
  206356. }
  206357. ~WindowsBitmapImage()
  206358. {
  206359. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  206360. DeleteDC (hdc);
  206361. DeleteObject (hBitmap);
  206362. }
  206363. Image::ImageType getType() const { return Image::NativeImage; }
  206364. LowLevelGraphicsContext* createLowLevelContext()
  206365. {
  206366. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206367. }
  206368. Image::SharedImage* clone()
  206369. {
  206370. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206371. for (int i = 0; i < height; ++i)
  206372. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206373. return im;
  206374. }
  206375. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206376. const int x, const int y,
  206377. const RectangleList& maskedRegion,
  206378. const uint8 updateLayeredWindowAlpha) throw()
  206379. {
  206380. static HDRAWDIB hdd = 0;
  206381. static bool needToCreateDrawDib = true;
  206382. if (needToCreateDrawDib)
  206383. {
  206384. needToCreateDrawDib = false;
  206385. HDC dc = GetDC (0);
  206386. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206387. ReleaseDC (0, dc);
  206388. // only open if we're not palettised
  206389. if (n > 8)
  206390. hdd = DrawDibOpen();
  206391. }
  206392. SetMapMode (dc, MM_TEXT);
  206393. if (transparent)
  206394. {
  206395. POINT p, pos;
  206396. SIZE size;
  206397. RECT windowBounds;
  206398. GetWindowRect (hwnd, &windowBounds);
  206399. p.x = -x;
  206400. p.y = -y;
  206401. pos.x = windowBounds.left;
  206402. pos.y = windowBounds.top;
  206403. size.cx = windowBounds.right - windowBounds.left;
  206404. size.cy = windowBounds.bottom - windowBounds.top;
  206405. BLENDFUNCTION bf;
  206406. bf.AlphaFormat = AC_SRC_ALPHA;
  206407. bf.BlendFlags = 0;
  206408. bf.BlendOp = AC_SRC_OVER;
  206409. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206410. if (! maskedRegion.isEmpty())
  206411. {
  206412. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206413. {
  206414. const Rectangle<int>& r = *i.getRectangle();
  206415. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206416. }
  206417. }
  206418. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206419. }
  206420. else
  206421. {
  206422. int savedDC = 0;
  206423. if (! maskedRegion.isEmpty())
  206424. {
  206425. savedDC = SaveDC (dc);
  206426. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206427. {
  206428. const Rectangle<int>& r = *i.getRectangle();
  206429. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206430. }
  206431. }
  206432. if (hdd == 0)
  206433. {
  206434. StretchDIBits (dc,
  206435. x, y, width, height,
  206436. 0, 0, width, height,
  206437. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206438. DIB_RGB_COLORS, SRCCOPY);
  206439. }
  206440. else
  206441. {
  206442. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206443. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206444. 0, 0, width, height, 0);
  206445. }
  206446. if (! maskedRegion.isEmpty())
  206447. RestoreDC (dc, savedDC);
  206448. }
  206449. }
  206450. private:
  206451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206452. };
  206453. namespace IconConverters
  206454. {
  206455. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206456. {
  206457. Image im;
  206458. if (bitmap != 0)
  206459. {
  206460. BITMAP bm;
  206461. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206462. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206463. {
  206464. HDC tempDC = GetDC (0);
  206465. HDC dc = CreateCompatibleDC (tempDC);
  206466. ReleaseDC (0, tempDC);
  206467. SelectObject (dc, bitmap);
  206468. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206469. Image::BitmapData imageData (im, true);
  206470. for (int y = bm.bmHeight; --y >= 0;)
  206471. {
  206472. for (int x = bm.bmWidth; --x >= 0;)
  206473. {
  206474. COLORREF col = GetPixel (dc, x, y);
  206475. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206476. (uint8) GetGValue (col),
  206477. (uint8) GetBValue (col)));
  206478. }
  206479. }
  206480. DeleteDC (dc);
  206481. }
  206482. }
  206483. return im;
  206484. }
  206485. const Image createImageFromHICON (HICON icon)
  206486. {
  206487. ICONINFO info;
  206488. if (GetIconInfo (icon, &info))
  206489. {
  206490. Image mask (createImageFromHBITMAP (info.hbmMask));
  206491. Image image (createImageFromHBITMAP (info.hbmColor));
  206492. if (mask.isValid() && image.isValid())
  206493. {
  206494. for (int y = image.getHeight(); --y >= 0;)
  206495. {
  206496. for (int x = image.getWidth(); --x >= 0;)
  206497. {
  206498. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206499. if (brightness > 0.0f)
  206500. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206501. }
  206502. }
  206503. return image;
  206504. }
  206505. }
  206506. return Image::null;
  206507. }
  206508. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206509. {
  206510. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206511. Image bitmap (nativeBitmap);
  206512. {
  206513. Graphics g (bitmap);
  206514. g.drawImageAt (image, 0, 0);
  206515. }
  206516. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206517. ICONINFO info;
  206518. info.fIcon = isIcon;
  206519. info.xHotspot = hotspotX;
  206520. info.yHotspot = hotspotY;
  206521. info.hbmMask = mask;
  206522. info.hbmColor = nativeBitmap->hBitmap;
  206523. HICON hi = CreateIconIndirect (&info);
  206524. DeleteObject (mask);
  206525. return hi;
  206526. }
  206527. }
  206528. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206529. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206530. {
  206531. SHORT k = (SHORT) keyCode;
  206532. if ((keyCode & extendedKeyModifier) == 0
  206533. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206534. k += (SHORT) 'A' - (SHORT) 'a';
  206535. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206536. (SHORT) '+', VK_OEM_PLUS,
  206537. (SHORT) '-', VK_OEM_MINUS,
  206538. (SHORT) '.', VK_OEM_PERIOD,
  206539. (SHORT) ';', VK_OEM_1,
  206540. (SHORT) ':', VK_OEM_1,
  206541. (SHORT) '/', VK_OEM_2,
  206542. (SHORT) '?', VK_OEM_2,
  206543. (SHORT) '[', VK_OEM_4,
  206544. (SHORT) ']', VK_OEM_6 };
  206545. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206546. if (k == translatedValues [i])
  206547. k = translatedValues [i + 1];
  206548. return (GetKeyState (k) & 0x8000) != 0;
  206549. }
  206550. class Win32ComponentPeer : public ComponentPeer
  206551. {
  206552. public:
  206553. enum RenderingEngineType
  206554. {
  206555. softwareRenderingEngine = 0,
  206556. direct2DRenderingEngine
  206557. };
  206558. Win32ComponentPeer (Component* const component,
  206559. const int windowStyleFlags,
  206560. HWND parentToAddTo_)
  206561. : ComponentPeer (component, windowStyleFlags),
  206562. dontRepaint (false),
  206563. #if JUCE_DIRECT2D
  206564. currentRenderingEngine (direct2DRenderingEngine),
  206565. #else
  206566. currentRenderingEngine (softwareRenderingEngine),
  206567. #endif
  206568. fullScreen (false),
  206569. isDragging (false),
  206570. isMouseOver (false),
  206571. hasCreatedCaret (false),
  206572. constrainerIsResizing (false),
  206573. currentWindowIcon (0),
  206574. dropTarget (0),
  206575. parentToAddTo (parentToAddTo_),
  206576. updateLayeredWindowAlpha (255)
  206577. {
  206578. callFunctionIfNotLocked (&createWindowCallback, this);
  206579. setTitle (component->getName());
  206580. if ((windowStyleFlags & windowHasDropShadow) != 0
  206581. && Desktop::canUseSemiTransparentWindows())
  206582. {
  206583. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206584. if (shadower != 0)
  206585. shadower->setOwner (component);
  206586. }
  206587. }
  206588. ~Win32ComponentPeer()
  206589. {
  206590. setTaskBarIcon (Image());
  206591. shadower = 0;
  206592. // do this before the next bit to avoid messages arriving for this window
  206593. // before it's destroyed
  206594. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206595. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206596. if (currentWindowIcon != 0)
  206597. DestroyIcon (currentWindowIcon);
  206598. if (dropTarget != 0)
  206599. {
  206600. dropTarget->Release();
  206601. dropTarget = 0;
  206602. }
  206603. #if JUCE_DIRECT2D
  206604. direct2DContext = 0;
  206605. #endif
  206606. }
  206607. void* getNativeHandle() const
  206608. {
  206609. return hwnd;
  206610. }
  206611. void setVisible (bool shouldBeVisible)
  206612. {
  206613. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206614. if (shouldBeVisible)
  206615. InvalidateRect (hwnd, 0, 0);
  206616. else
  206617. lastPaintTime = 0;
  206618. }
  206619. void setTitle (const String& title)
  206620. {
  206621. SetWindowText (hwnd, title.toUTF16());
  206622. }
  206623. void setPosition (int x, int y)
  206624. {
  206625. offsetWithinParent (x, y);
  206626. SetWindowPos (hwnd, 0,
  206627. x - windowBorder.getLeft(),
  206628. y - windowBorder.getTop(),
  206629. 0, 0,
  206630. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206631. }
  206632. void repaintNowIfTransparent()
  206633. {
  206634. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206635. handlePaintMessage();
  206636. }
  206637. void updateBorderSize()
  206638. {
  206639. WINDOWINFO info;
  206640. info.cbSize = sizeof (info);
  206641. if (GetWindowInfo (hwnd, &info))
  206642. {
  206643. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  206644. info.rcClient.left - info.rcWindow.left,
  206645. info.rcWindow.bottom - info.rcClient.bottom,
  206646. info.rcWindow.right - info.rcClient.right);
  206647. }
  206648. #if JUCE_DIRECT2D
  206649. if (direct2DContext != 0)
  206650. direct2DContext->resized();
  206651. #endif
  206652. }
  206653. void setSize (int w, int h)
  206654. {
  206655. SetWindowPos (hwnd, 0, 0, 0,
  206656. w + windowBorder.getLeftAndRight(),
  206657. h + windowBorder.getTopAndBottom(),
  206658. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206659. updateBorderSize();
  206660. repaintNowIfTransparent();
  206661. }
  206662. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206663. {
  206664. fullScreen = isNowFullScreen;
  206665. offsetWithinParent (x, y);
  206666. SetWindowPos (hwnd, 0,
  206667. x - windowBorder.getLeft(),
  206668. y - windowBorder.getTop(),
  206669. w + windowBorder.getLeftAndRight(),
  206670. h + windowBorder.getTopAndBottom(),
  206671. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206672. updateBorderSize();
  206673. repaintNowIfTransparent();
  206674. }
  206675. const Rectangle<int> getBounds() const
  206676. {
  206677. RECT r;
  206678. GetWindowRect (hwnd, &r);
  206679. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206680. HWND parentH = GetParent (hwnd);
  206681. if (parentH != 0)
  206682. {
  206683. GetWindowRect (parentH, &r);
  206684. bounds.translate (-r.left, -r.top);
  206685. }
  206686. return windowBorder.subtractedFrom (bounds);
  206687. }
  206688. const Point<int> getScreenPosition() const
  206689. {
  206690. RECT r;
  206691. GetWindowRect (hwnd, &r);
  206692. return Point<int> (r.left + windowBorder.getLeft(),
  206693. r.top + windowBorder.getTop());
  206694. }
  206695. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206696. {
  206697. return relativePosition + getScreenPosition();
  206698. }
  206699. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206700. {
  206701. return screenPosition - getScreenPosition();
  206702. }
  206703. void setAlpha (float newAlpha)
  206704. {
  206705. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206706. if (component->isOpaque())
  206707. {
  206708. if (newAlpha < 1.0f)
  206709. {
  206710. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206711. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206712. }
  206713. else
  206714. {
  206715. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  206716. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  206717. }
  206718. }
  206719. else
  206720. {
  206721. updateLayeredWindowAlpha = intAlpha;
  206722. component->repaint();
  206723. }
  206724. }
  206725. void setMinimised (bool shouldBeMinimised)
  206726. {
  206727. if (shouldBeMinimised != isMinimised())
  206728. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206729. }
  206730. bool isMinimised() const
  206731. {
  206732. WINDOWPLACEMENT wp;
  206733. wp.length = sizeof (WINDOWPLACEMENT);
  206734. GetWindowPlacement (hwnd, &wp);
  206735. return wp.showCmd == SW_SHOWMINIMIZED;
  206736. }
  206737. void setFullScreen (bool shouldBeFullScreen)
  206738. {
  206739. setMinimised (false);
  206740. if (fullScreen != shouldBeFullScreen)
  206741. {
  206742. fullScreen = shouldBeFullScreen;
  206743. const WeakReference<Component> deletionChecker (component);
  206744. if (! fullScreen)
  206745. {
  206746. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206747. if (hasTitleBar())
  206748. ShowWindow (hwnd, SW_SHOWNORMAL);
  206749. if (! boundsCopy.isEmpty())
  206750. {
  206751. setBounds (boundsCopy.getX(),
  206752. boundsCopy.getY(),
  206753. boundsCopy.getWidth(),
  206754. boundsCopy.getHeight(),
  206755. false);
  206756. }
  206757. }
  206758. else
  206759. {
  206760. if (hasTitleBar())
  206761. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206762. else
  206763. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206764. }
  206765. if (deletionChecker != 0)
  206766. handleMovedOrResized();
  206767. }
  206768. }
  206769. bool isFullScreen() const
  206770. {
  206771. if (! hasTitleBar())
  206772. return fullScreen;
  206773. WINDOWPLACEMENT wp;
  206774. wp.length = sizeof (wp);
  206775. GetWindowPlacement (hwnd, &wp);
  206776. return wp.showCmd == SW_SHOWMAXIMIZED;
  206777. }
  206778. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206779. {
  206780. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  206781. && isPositiveAndBelow (position.getY(), component->getHeight())))
  206782. return false;
  206783. RECT r;
  206784. GetWindowRect (hwnd, &r);
  206785. POINT p;
  206786. p.x = position.getX() + r.left + windowBorder.getLeft();
  206787. p.y = position.getY() + r.top + windowBorder.getTop();
  206788. HWND w = WindowFromPoint (p);
  206789. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206790. }
  206791. const BorderSize<int> getFrameSize() const
  206792. {
  206793. return windowBorder;
  206794. }
  206795. bool setAlwaysOnTop (bool alwaysOnTop)
  206796. {
  206797. const bool oldDeactivate = shouldDeactivateTitleBar;
  206798. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206799. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206800. 0, 0, 0, 0,
  206801. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206802. shouldDeactivateTitleBar = oldDeactivate;
  206803. if (shadower != 0)
  206804. shadower->componentBroughtToFront (*component);
  206805. return true;
  206806. }
  206807. void toFront (bool makeActive)
  206808. {
  206809. setMinimised (false);
  206810. const bool oldDeactivate = shouldDeactivateTitleBar;
  206811. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206812. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206813. shouldDeactivateTitleBar = oldDeactivate;
  206814. if (! makeActive)
  206815. {
  206816. // in this case a broughttofront call won't have occured, so do it now..
  206817. handleBroughtToFront();
  206818. }
  206819. }
  206820. void toBehind (ComponentPeer* other)
  206821. {
  206822. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206823. jassert (otherPeer != 0); // wrong type of window?
  206824. if (otherPeer != 0)
  206825. {
  206826. setMinimised (false);
  206827. // must be careful not to try to put a topmost window behind a normal one, or win32
  206828. // promotes the normal one to be topmost!
  206829. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206830. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206831. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206832. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206833. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206834. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206835. }
  206836. }
  206837. bool isFocused() const
  206838. {
  206839. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206840. }
  206841. void grabFocus()
  206842. {
  206843. const bool oldDeactivate = shouldDeactivateTitleBar;
  206844. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206845. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206846. shouldDeactivateTitleBar = oldDeactivate;
  206847. }
  206848. void textInputRequired (const Point<int>&)
  206849. {
  206850. if (! hasCreatedCaret)
  206851. {
  206852. hasCreatedCaret = true;
  206853. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206854. }
  206855. ShowCaret (hwnd);
  206856. SetCaretPos (0, 0);
  206857. }
  206858. void repaint (const Rectangle<int>& area)
  206859. {
  206860. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  206861. InvalidateRect (hwnd, &r, FALSE);
  206862. }
  206863. void performAnyPendingRepaintsNow()
  206864. {
  206865. MSG m;
  206866. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206867. DispatchMessage (&m);
  206868. }
  206869. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206870. {
  206871. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206872. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  206873. return 0;
  206874. }
  206875. void setTaskBarIcon (const Image& image)
  206876. {
  206877. if (image.isValid())
  206878. {
  206879. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  206880. if (taskBarIcon == 0)
  206881. {
  206882. taskBarIcon = new NOTIFYICONDATA();
  206883. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  206884. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206885. taskBarIcon->hWnd = (HWND) hwnd;
  206886. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206887. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206888. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206889. taskBarIcon->hIcon = hicon;
  206890. taskBarIcon->szTip[0] = 0;
  206891. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206892. }
  206893. else
  206894. {
  206895. HICON oldIcon = taskBarIcon->hIcon;
  206896. taskBarIcon->hIcon = hicon;
  206897. taskBarIcon->uFlags = NIF_ICON;
  206898. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206899. DestroyIcon (oldIcon);
  206900. }
  206901. }
  206902. else if (taskBarIcon != 0)
  206903. {
  206904. taskBarIcon->uFlags = 0;
  206905. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206906. DestroyIcon (taskBarIcon->hIcon);
  206907. taskBarIcon = 0;
  206908. }
  206909. }
  206910. void setTaskBarIconToolTip (const String& toolTip) const
  206911. {
  206912. if (taskBarIcon != 0)
  206913. {
  206914. taskBarIcon->uFlags = NIF_TIP;
  206915. toolTip.copyToUTF16 (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206916. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206917. }
  206918. }
  206919. void handleTaskBarEvent (const LPARAM lParam)
  206920. {
  206921. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206922. {
  206923. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206924. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206925. {
  206926. Component* const current = Component::getCurrentlyModalComponent();
  206927. if (current != 0)
  206928. current->inputAttemptWhenModal();
  206929. }
  206930. }
  206931. else
  206932. {
  206933. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206934. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206935. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206936. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206937. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206938. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206939. eventMods = eventMods.withoutMouseButtons();
  206940. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206941. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  206942. Point<int>(), Time (getMouseEventTime()), 1, false);
  206943. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206944. {
  206945. SetFocus (hwnd);
  206946. SetForegroundWindow (hwnd);
  206947. component->mouseDown (e);
  206948. }
  206949. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206950. {
  206951. component->mouseUp (e);
  206952. }
  206953. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206954. {
  206955. component->mouseDoubleClick (e);
  206956. }
  206957. else if (lParam == WM_MOUSEMOVE)
  206958. {
  206959. component->mouseMove (e);
  206960. }
  206961. }
  206962. }
  206963. bool isInside (HWND h) const
  206964. {
  206965. return GetAncestor (hwnd, GA_ROOT) == h;
  206966. }
  206967. static void updateKeyModifiers() throw()
  206968. {
  206969. int keyMods = 0;
  206970. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  206971. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  206972. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  206973. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  206974. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206975. }
  206976. static void updateModifiersFromWParam (const WPARAM wParam)
  206977. {
  206978. int mouseMods = 0;
  206979. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  206980. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  206981. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  206982. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  206983. updateKeyModifiers();
  206984. }
  206985. static int64 getMouseEventTime()
  206986. {
  206987. static int64 eventTimeOffset = 0;
  206988. static DWORD lastMessageTime = 0;
  206989. const DWORD thisMessageTime = GetMessageTime();
  206990. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  206991. {
  206992. lastMessageTime = thisMessageTime;
  206993. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  206994. }
  206995. return eventTimeOffset + thisMessageTime;
  206996. }
  206997. bool dontRepaint;
  206998. static ModifierKeys currentModifiers;
  206999. static ModifierKeys modifiersAtLastCallback;
  207000. private:
  207001. HWND hwnd, parentToAddTo;
  207002. ScopedPointer<DropShadower> shadower;
  207003. RenderingEngineType currentRenderingEngine;
  207004. #if JUCE_DIRECT2D
  207005. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207006. #endif
  207007. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  207008. BorderSize<int> windowBorder;
  207009. HICON currentWindowIcon;
  207010. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207011. IDropTarget* dropTarget;
  207012. uint8 updateLayeredWindowAlpha;
  207013. class TemporaryImage : public Timer
  207014. {
  207015. public:
  207016. TemporaryImage() {}
  207017. ~TemporaryImage() {}
  207018. const Image& getImage (const bool transparent, const int w, const int h)
  207019. {
  207020. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207021. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207022. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207023. startTimer (3000);
  207024. return image;
  207025. }
  207026. void timerCallback()
  207027. {
  207028. stopTimer();
  207029. image = Image::null;
  207030. }
  207031. private:
  207032. Image image;
  207033. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207034. };
  207035. TemporaryImage offscreenImageGenerator;
  207036. class WindowClassHolder : public DeletedAtShutdown
  207037. {
  207038. public:
  207039. WindowClassHolder()
  207040. : windowClassName ("JUCE_")
  207041. {
  207042. // this name has to be different for each app/dll instance because otherwise
  207043. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207044. // window class).
  207045. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207046. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207047. TCHAR moduleFile [1024];
  207048. moduleFile[0] = 0;
  207049. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207050. WORD iconNum = 0;
  207051. WNDCLASSEX wcex;
  207052. wcex.cbSize = sizeof (wcex);
  207053. wcex.style = CS_OWNDC;
  207054. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207055. wcex.lpszClassName = windowClassName.toUTF16();
  207056. wcex.cbClsExtra = 0;
  207057. wcex.cbWndExtra = 32;
  207058. wcex.hInstance = moduleHandle;
  207059. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207060. iconNum = 1;
  207061. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207062. wcex.hCursor = 0;
  207063. wcex.hbrBackground = 0;
  207064. wcex.lpszMenuName = 0;
  207065. RegisterClassEx (&wcex);
  207066. }
  207067. ~WindowClassHolder()
  207068. {
  207069. if (ComponentPeer::getNumPeers() == 0)
  207070. UnregisterClass (windowClassName.toUTF16(), (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207071. clearSingletonInstance();
  207072. }
  207073. String windowClassName;
  207074. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207075. };
  207076. static void* createWindowCallback (void* userData)
  207077. {
  207078. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207079. return 0;
  207080. }
  207081. void createWindow()
  207082. {
  207083. DWORD exstyle = WS_EX_ACCEPTFILES;
  207084. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207085. if (hasTitleBar())
  207086. {
  207087. type |= WS_OVERLAPPED;
  207088. if ((styleFlags & windowHasCloseButton) != 0)
  207089. {
  207090. type |= WS_SYSMENU;
  207091. }
  207092. else
  207093. {
  207094. // annoyingly, windows won't let you have a min/max button without a close button
  207095. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207096. }
  207097. if ((styleFlags & windowIsResizable) != 0)
  207098. type |= WS_THICKFRAME;
  207099. }
  207100. else if (parentToAddTo != 0)
  207101. {
  207102. type |= WS_CHILD;
  207103. }
  207104. else
  207105. {
  207106. type |= WS_POPUP | WS_SYSMENU;
  207107. }
  207108. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207109. exstyle |= WS_EX_TOOLWINDOW;
  207110. else
  207111. exstyle |= WS_EX_APPWINDOW;
  207112. if ((styleFlags & windowHasMinimiseButton) != 0)
  207113. type |= WS_MINIMIZEBOX;
  207114. if ((styleFlags & windowHasMaximiseButton) != 0)
  207115. type |= WS_MAXIMIZEBOX;
  207116. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207117. exstyle |= WS_EX_TRANSPARENT;
  207118. if ((styleFlags & windowIsSemiTransparent) != 0
  207119. && Desktop::canUseSemiTransparentWindows())
  207120. exstyle |= WS_EX_LAYERED;
  207121. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName.toUTF16(), L"", type, 0, 0, 0, 0,
  207122. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207123. #if JUCE_DIRECT2D
  207124. updateDirect2DContext();
  207125. #endif
  207126. if (hwnd != 0)
  207127. {
  207128. SetWindowLongPtr (hwnd, 0, 0);
  207129. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207130. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207131. if (dropTarget == 0)
  207132. dropTarget = new JuceDropTarget (this);
  207133. RegisterDragDrop (hwnd, dropTarget);
  207134. updateBorderSize();
  207135. // Calling this function here is (for some reason) necessary to make Windows
  207136. // correctly enable the menu items that we specify in the wm_initmenu message.
  207137. GetSystemMenu (hwnd, false);
  207138. const float alpha = component->getAlpha();
  207139. if (alpha < 1.0f)
  207140. setAlpha (alpha);
  207141. }
  207142. else
  207143. {
  207144. jassertfalse;
  207145. }
  207146. }
  207147. static void* destroyWindowCallback (void* handle)
  207148. {
  207149. RevokeDragDrop ((HWND) handle);
  207150. DestroyWindow ((HWND) handle);
  207151. return 0;
  207152. }
  207153. static void* toFrontCallback1 (void* h)
  207154. {
  207155. SetForegroundWindow ((HWND) h);
  207156. return 0;
  207157. }
  207158. static void* toFrontCallback2 (void* h)
  207159. {
  207160. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207161. return 0;
  207162. }
  207163. static void* setFocusCallback (void* h)
  207164. {
  207165. SetFocus ((HWND) h);
  207166. return 0;
  207167. }
  207168. static void* getFocusCallback (void*)
  207169. {
  207170. return GetFocus();
  207171. }
  207172. void offsetWithinParent (int& x, int& y) const
  207173. {
  207174. if (isUsingUpdateLayeredWindow())
  207175. {
  207176. HWND parentHwnd = GetParent (hwnd);
  207177. if (parentHwnd != 0)
  207178. {
  207179. RECT parentRect;
  207180. GetWindowRect (parentHwnd, &parentRect);
  207181. x += parentRect.left;
  207182. y += parentRect.top;
  207183. }
  207184. }
  207185. }
  207186. bool isUsingUpdateLayeredWindow() const
  207187. {
  207188. return ! component->isOpaque();
  207189. }
  207190. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207191. void setIcon (const Image& newIcon)
  207192. {
  207193. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207194. if (hicon != 0)
  207195. {
  207196. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207197. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207198. if (currentWindowIcon != 0)
  207199. DestroyIcon (currentWindowIcon);
  207200. currentWindowIcon = hicon;
  207201. }
  207202. }
  207203. void handlePaintMessage()
  207204. {
  207205. #if JUCE_DIRECT2D
  207206. if (direct2DContext != 0)
  207207. {
  207208. RECT r;
  207209. if (GetUpdateRect (hwnd, &r, false))
  207210. {
  207211. direct2DContext->start();
  207212. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207213. handlePaint (*direct2DContext);
  207214. direct2DContext->end();
  207215. }
  207216. }
  207217. else
  207218. #endif
  207219. {
  207220. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207221. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207222. PAINTSTRUCT paintStruct;
  207223. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207224. // message and become re-entrant, but that's OK
  207225. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207226. // corrupt the image it's using to paint into, so do a check here.
  207227. static bool reentrant = false;
  207228. if (reentrant)
  207229. {
  207230. DeleteObject (rgn);
  207231. EndPaint (hwnd, &paintStruct);
  207232. return;
  207233. }
  207234. const ScopedValueSetter<bool> setter (reentrant, true, false);
  207235. // this is the rectangle to update..
  207236. int x = paintStruct.rcPaint.left;
  207237. int y = paintStruct.rcPaint.top;
  207238. int w = paintStruct.rcPaint.right - x;
  207239. int h = paintStruct.rcPaint.bottom - y;
  207240. const bool transparent = isUsingUpdateLayeredWindow();
  207241. if (transparent)
  207242. {
  207243. // it's not possible to have a transparent window with a title bar at the moment!
  207244. jassert (! hasTitleBar());
  207245. RECT r;
  207246. GetWindowRect (hwnd, &r);
  207247. x = y = 0;
  207248. w = r.right - r.left;
  207249. h = r.bottom - r.top;
  207250. }
  207251. if (w > 0 && h > 0)
  207252. {
  207253. clearMaskedRegion();
  207254. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207255. RectangleList contextClip;
  207256. const Rectangle<int> clipBounds (0, 0, w, h);
  207257. bool needToPaintAll = true;
  207258. if (regionType == COMPLEXREGION && ! transparent)
  207259. {
  207260. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207261. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207262. DeleteObject (clipRgn);
  207263. char rgnData [8192];
  207264. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207265. if (res > 0 && res <= sizeof (rgnData))
  207266. {
  207267. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207268. if (hdr->iType == RDH_RECTANGLES
  207269. && hdr->rcBound.right - hdr->rcBound.left >= w
  207270. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207271. {
  207272. needToPaintAll = false;
  207273. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207274. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207275. while (--num >= 0)
  207276. {
  207277. if (rects->right <= x + w && rects->bottom <= y + h)
  207278. {
  207279. const int cx = jmax (x, (int) rects->left);
  207280. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207281. .getIntersection (clipBounds));
  207282. }
  207283. else
  207284. {
  207285. needToPaintAll = true;
  207286. break;
  207287. }
  207288. ++rects;
  207289. }
  207290. }
  207291. }
  207292. }
  207293. if (needToPaintAll)
  207294. {
  207295. contextClip.clear();
  207296. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207297. }
  207298. if (transparent)
  207299. {
  207300. RectangleList::Iterator i (contextClip);
  207301. while (i.next())
  207302. offscreenImage.clear (*i.getRectangle());
  207303. }
  207304. // if the component's not opaque, this won't draw properly unless the platform can support this
  207305. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207306. updateCurrentModifiers();
  207307. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207308. handlePaint (context);
  207309. if (! dontRepaint)
  207310. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207311. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207312. }
  207313. DeleteObject (rgn);
  207314. EndPaint (hwnd, &paintStruct);
  207315. }
  207316. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207317. _fpreset(); // because some graphics cards can unmask FP exceptions
  207318. #endif
  207319. lastPaintTime = Time::getMillisecondCounter();
  207320. }
  207321. void doMouseEvent (const Point<int>& position)
  207322. {
  207323. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207324. }
  207325. const StringArray getAvailableRenderingEngines()
  207326. {
  207327. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207328. #if JUCE_DIRECT2D
  207329. // xxx is this correct? Seems to enable it on Vista too??
  207330. OSVERSIONINFO info;
  207331. zerostruct (info);
  207332. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207333. GetVersionEx (&info);
  207334. if (info.dwMajorVersion >= 6)
  207335. s.add ("Direct2D");
  207336. #endif
  207337. return s;
  207338. }
  207339. int getCurrentRenderingEngine() throw()
  207340. {
  207341. return currentRenderingEngine;
  207342. }
  207343. #if JUCE_DIRECT2D
  207344. void updateDirect2DContext()
  207345. {
  207346. if (currentRenderingEngine != direct2DRenderingEngine)
  207347. direct2DContext = 0;
  207348. else if (direct2DContext == 0)
  207349. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207350. }
  207351. #endif
  207352. void setCurrentRenderingEngine (int index)
  207353. {
  207354. (void) index;
  207355. #if JUCE_DIRECT2D
  207356. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207357. updateDirect2DContext();
  207358. repaint (component->getLocalBounds());
  207359. #endif
  207360. }
  207361. void doMouseMove (const Point<int>& position)
  207362. {
  207363. if (! isMouseOver)
  207364. {
  207365. isMouseOver = true;
  207366. updateKeyModifiers();
  207367. TRACKMOUSEEVENT tme;
  207368. tme.cbSize = sizeof (tme);
  207369. tme.dwFlags = TME_LEAVE;
  207370. tme.hwndTrack = hwnd;
  207371. tme.dwHoverTime = 0;
  207372. if (! TrackMouseEvent (&tme))
  207373. jassertfalse;
  207374. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207375. }
  207376. else if (! isDragging)
  207377. {
  207378. if (! contains (position, false))
  207379. return;
  207380. }
  207381. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207382. static uint32 lastMouseTime = 0;
  207383. const uint32 now = Time::getMillisecondCounter();
  207384. const int maxMouseMovesPerSecond = 60;
  207385. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207386. {
  207387. lastMouseTime = now;
  207388. doMouseEvent (position);
  207389. }
  207390. }
  207391. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207392. {
  207393. if (GetCapture() != hwnd)
  207394. SetCapture (hwnd);
  207395. doMouseMove (position);
  207396. updateModifiersFromWParam (wParam);
  207397. isDragging = true;
  207398. doMouseEvent (position);
  207399. }
  207400. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207401. {
  207402. updateModifiersFromWParam (wParam);
  207403. isDragging = false;
  207404. // release the mouse capture if the user has released all buttons
  207405. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207406. ReleaseCapture();
  207407. doMouseEvent (position);
  207408. }
  207409. void doCaptureChanged()
  207410. {
  207411. if (constrainerIsResizing)
  207412. {
  207413. if (constrainer != 0)
  207414. constrainer->resizeEnd();
  207415. constrainerIsResizing = false;
  207416. }
  207417. if (isDragging)
  207418. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207419. }
  207420. void doMouseExit()
  207421. {
  207422. isMouseOver = false;
  207423. doMouseEvent (getCurrentMousePos());
  207424. }
  207425. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207426. {
  207427. updateKeyModifiers();
  207428. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207429. handleMouseWheel (0, position, getMouseEventTime(),
  207430. isVertical ? 0.0f : amount,
  207431. isVertical ? amount : 0.0f);
  207432. }
  207433. void sendModifierKeyChangeIfNeeded()
  207434. {
  207435. if (modifiersAtLastCallback != currentModifiers)
  207436. {
  207437. modifiersAtLastCallback = currentModifiers;
  207438. handleModifierKeysChange();
  207439. }
  207440. }
  207441. bool doKeyUp (const WPARAM key)
  207442. {
  207443. updateKeyModifiers();
  207444. switch (key)
  207445. {
  207446. case VK_SHIFT:
  207447. case VK_CONTROL:
  207448. case VK_MENU:
  207449. case VK_CAPITAL:
  207450. case VK_LWIN:
  207451. case VK_RWIN:
  207452. case VK_APPS:
  207453. case VK_NUMLOCK:
  207454. case VK_SCROLL:
  207455. case VK_LSHIFT:
  207456. case VK_RSHIFT:
  207457. case VK_LCONTROL:
  207458. case VK_LMENU:
  207459. case VK_RCONTROL:
  207460. case VK_RMENU:
  207461. sendModifierKeyChangeIfNeeded();
  207462. }
  207463. return handleKeyUpOrDown (false)
  207464. || Component::getCurrentlyModalComponent() != 0;
  207465. }
  207466. bool doKeyDown (const WPARAM key)
  207467. {
  207468. updateKeyModifiers();
  207469. bool used = false;
  207470. switch (key)
  207471. {
  207472. case VK_SHIFT:
  207473. case VK_LSHIFT:
  207474. case VK_RSHIFT:
  207475. case VK_CONTROL:
  207476. case VK_LCONTROL:
  207477. case VK_RCONTROL:
  207478. case VK_MENU:
  207479. case VK_LMENU:
  207480. case VK_RMENU:
  207481. case VK_LWIN:
  207482. case VK_RWIN:
  207483. case VK_CAPITAL:
  207484. case VK_NUMLOCK:
  207485. case VK_SCROLL:
  207486. case VK_APPS:
  207487. sendModifierKeyChangeIfNeeded();
  207488. break;
  207489. case VK_LEFT:
  207490. case VK_RIGHT:
  207491. case VK_UP:
  207492. case VK_DOWN:
  207493. case VK_PRIOR:
  207494. case VK_NEXT:
  207495. case VK_HOME:
  207496. case VK_END:
  207497. case VK_DELETE:
  207498. case VK_INSERT:
  207499. case VK_F1:
  207500. case VK_F2:
  207501. case VK_F3:
  207502. case VK_F4:
  207503. case VK_F5:
  207504. case VK_F6:
  207505. case VK_F7:
  207506. case VK_F8:
  207507. case VK_F9:
  207508. case VK_F10:
  207509. case VK_F11:
  207510. case VK_F12:
  207511. case VK_F13:
  207512. case VK_F14:
  207513. case VK_F15:
  207514. case VK_F16:
  207515. used = handleKeyUpOrDown (true);
  207516. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207517. break;
  207518. case VK_ADD:
  207519. case VK_SUBTRACT:
  207520. case VK_MULTIPLY:
  207521. case VK_DIVIDE:
  207522. case VK_SEPARATOR:
  207523. case VK_DECIMAL:
  207524. used = handleKeyUpOrDown (true);
  207525. break;
  207526. default:
  207527. used = handleKeyUpOrDown (true);
  207528. {
  207529. MSG msg;
  207530. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207531. {
  207532. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207533. // manually generate the key-press event that matches this key-down.
  207534. const UINT keyChar = MapVirtualKey (key, 2);
  207535. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207536. }
  207537. }
  207538. break;
  207539. }
  207540. if (Component::getCurrentlyModalComponent() != 0)
  207541. used = true;
  207542. return used;
  207543. }
  207544. bool doKeyChar (int key, const LPARAM flags)
  207545. {
  207546. updateKeyModifiers();
  207547. juce_wchar textChar = (juce_wchar) key;
  207548. const int virtualScanCode = (flags >> 16) & 0xff;
  207549. if (key >= '0' && key <= '9')
  207550. {
  207551. switch (virtualScanCode) // check for a numeric keypad scan-code
  207552. {
  207553. case 0x52:
  207554. case 0x4f:
  207555. case 0x50:
  207556. case 0x51:
  207557. case 0x4b:
  207558. case 0x4c:
  207559. case 0x4d:
  207560. case 0x47:
  207561. case 0x48:
  207562. case 0x49:
  207563. key = (key - '0') + KeyPress::numberPad0;
  207564. break;
  207565. default:
  207566. break;
  207567. }
  207568. }
  207569. else
  207570. {
  207571. // convert the scan code to an unmodified character code..
  207572. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207573. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207574. keyChar = LOWORD (keyChar);
  207575. if (keyChar != 0)
  207576. key = (int) keyChar;
  207577. // avoid sending junk text characters for some control-key combinations
  207578. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207579. textChar = 0;
  207580. }
  207581. return handleKeyPress (key, textChar);
  207582. }
  207583. bool doAppCommand (const LPARAM lParam)
  207584. {
  207585. int key = 0;
  207586. switch (GET_APPCOMMAND_LPARAM (lParam))
  207587. {
  207588. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207589. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207590. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207591. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207592. default: break;
  207593. }
  207594. if (key != 0)
  207595. {
  207596. updateKeyModifiers();
  207597. if (hwnd == GetActiveWindow())
  207598. {
  207599. handleKeyPress (key, 0);
  207600. return true;
  207601. }
  207602. }
  207603. return false;
  207604. }
  207605. bool isConstrainedNativeWindow() const
  207606. {
  207607. return constrainer != 0
  207608. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  207609. }
  207610. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207611. {
  207612. if (isConstrainedNativeWindow())
  207613. {
  207614. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207615. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207616. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207617. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207618. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207619. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207620. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207621. r->left = pos.getX();
  207622. r->top = pos.getY();
  207623. r->right = pos.getRight();
  207624. r->bottom = pos.getBottom();
  207625. }
  207626. return TRUE;
  207627. }
  207628. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207629. {
  207630. if (isConstrainedNativeWindow())
  207631. {
  207632. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207633. && ! Component::isMouseButtonDownAnywhere())
  207634. {
  207635. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207636. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207637. constrainer->checkBounds (pos, current,
  207638. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207639. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207640. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207641. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207642. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207643. wp->x = pos.getX();
  207644. wp->y = pos.getY();
  207645. wp->cx = pos.getWidth();
  207646. wp->cy = pos.getHeight();
  207647. }
  207648. }
  207649. return 0;
  207650. }
  207651. void handleAppActivation (const WPARAM wParam)
  207652. {
  207653. modifiersAtLastCallback = -1;
  207654. updateKeyModifiers();
  207655. if (isMinimised())
  207656. {
  207657. component->repaint();
  207658. handleMovedOrResized();
  207659. if (! ComponentPeer::isValidPeer (this))
  207660. return;
  207661. }
  207662. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207663. {
  207664. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207665. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207666. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207667. }
  207668. else
  207669. {
  207670. handleBroughtToFront();
  207671. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207672. Component::getCurrentlyModalComponent()->toFront (true);
  207673. }
  207674. }
  207675. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207676. {
  207677. public:
  207678. JuceDropTarget (Win32ComponentPeer* const owner_)
  207679. : owner (owner_)
  207680. {
  207681. }
  207682. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207683. {
  207684. updateFileList (pDataObject);
  207685. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207686. *pdwEffect = DROPEFFECT_COPY;
  207687. return S_OK;
  207688. }
  207689. HRESULT __stdcall DragLeave()
  207690. {
  207691. owner->handleFileDragExit (files);
  207692. return S_OK;
  207693. }
  207694. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207695. {
  207696. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207697. *pdwEffect = DROPEFFECT_COPY;
  207698. return S_OK;
  207699. }
  207700. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207701. {
  207702. updateFileList (pDataObject);
  207703. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207704. *pdwEffect = DROPEFFECT_COPY;
  207705. return S_OK;
  207706. }
  207707. private:
  207708. Win32ComponentPeer* const owner;
  207709. StringArray files;
  207710. void updateFileList (IDataObject* const pDataObject)
  207711. {
  207712. files.clear();
  207713. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207714. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207715. if (pDataObject->GetData (&format, &medium) == S_OK)
  207716. {
  207717. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207718. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207719. unsigned int i = 0;
  207720. if (pDropFiles->fWide)
  207721. {
  207722. const WCHAR* const fname = (WCHAR*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207723. for (;;)
  207724. {
  207725. unsigned int len = 0;
  207726. while (i + len < totalLen && fname [i + len] != 0)
  207727. ++len;
  207728. if (len == 0)
  207729. break;
  207730. files.add (String (fname + i, len));
  207731. i += len + 1;
  207732. }
  207733. }
  207734. else
  207735. {
  207736. const char* const fname = (const char*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207737. for (;;)
  207738. {
  207739. unsigned int len = 0;
  207740. while (i + len < totalLen && fname [i + len] != 0)
  207741. ++len;
  207742. if (len == 0)
  207743. break;
  207744. files.add (String (fname + i, len));
  207745. i += len + 1;
  207746. }
  207747. }
  207748. GlobalUnlock (medium.hGlobal);
  207749. }
  207750. }
  207751. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  207752. };
  207753. void doSettingChange()
  207754. {
  207755. Desktop::getInstance().refreshMonitorSizes();
  207756. if (fullScreen && ! isMinimised())
  207757. {
  207758. const Rectangle<int> r (component->getParentMonitorArea());
  207759. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207760. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207761. }
  207762. }
  207763. public:
  207764. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207765. {
  207766. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207767. if (peer != 0)
  207768. {
  207769. jassert (isValidPeer (peer));
  207770. return peer->peerWindowProc (h, message, wParam, lParam);
  207771. }
  207772. return DefWindowProcW (h, message, wParam, lParam);
  207773. }
  207774. private:
  207775. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  207776. {
  207777. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  207778. return callback (userData);
  207779. else
  207780. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  207781. }
  207782. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207783. {
  207784. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207785. }
  207786. const Point<int> getCurrentMousePos() throw()
  207787. {
  207788. RECT wr;
  207789. GetWindowRect (hwnd, &wr);
  207790. const DWORD mp = GetMessagePos();
  207791. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207792. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207793. }
  207794. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207795. {
  207796. switch (message)
  207797. {
  207798. case WM_NCHITTEST:
  207799. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207800. return HTTRANSPARENT;
  207801. else if (! hasTitleBar())
  207802. return HTCLIENT;
  207803. break;
  207804. case WM_PAINT:
  207805. handlePaintMessage();
  207806. return 0;
  207807. case WM_NCPAINT:
  207808. if (hasTitleBar())
  207809. break;
  207810. else if (wParam != 1)
  207811. handlePaintMessage();
  207812. return 0;
  207813. case WM_ERASEBKGND:
  207814. case WM_NCCALCSIZE:
  207815. if (hasTitleBar())
  207816. break;
  207817. return 1;
  207818. case WM_MOUSEMOVE:
  207819. doMouseMove (getPointFromLParam (lParam));
  207820. return 0;
  207821. case WM_MOUSELEAVE:
  207822. doMouseExit();
  207823. return 0;
  207824. case WM_LBUTTONDOWN:
  207825. case WM_MBUTTONDOWN:
  207826. case WM_RBUTTONDOWN:
  207827. doMouseDown (getPointFromLParam (lParam), wParam);
  207828. return 0;
  207829. case WM_LBUTTONUP:
  207830. case WM_MBUTTONUP:
  207831. case WM_RBUTTONUP:
  207832. doMouseUp (getPointFromLParam (lParam), wParam);
  207833. return 0;
  207834. case WM_CAPTURECHANGED:
  207835. doCaptureChanged();
  207836. return 0;
  207837. case WM_NCMOUSEMOVE:
  207838. if (hasTitleBar())
  207839. break;
  207840. return 0;
  207841. case 0x020A: /* WM_MOUSEWHEEL */
  207842. case 0x020E: /* WM_MOUSEHWHEEL */
  207843. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  207844. return 0;
  207845. case WM_SIZING:
  207846. return handleSizeConstraining ((RECT*) lParam, wParam);
  207847. case WM_WINDOWPOSCHANGING:
  207848. return handlePositionChanging ((WINDOWPOS*) lParam);
  207849. case WM_WINDOWPOSCHANGED:
  207850. {
  207851. const Point<int> pos (getCurrentMousePos());
  207852. if (contains (pos, false))
  207853. doMouseEvent (pos);
  207854. }
  207855. handleMovedOrResized();
  207856. if (dontRepaint)
  207857. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207858. return 0;
  207859. case WM_KEYDOWN:
  207860. case WM_SYSKEYDOWN:
  207861. if (doKeyDown (wParam))
  207862. return 0;
  207863. break;
  207864. case WM_KEYUP:
  207865. case WM_SYSKEYUP:
  207866. if (doKeyUp (wParam))
  207867. return 0;
  207868. break;
  207869. case WM_CHAR:
  207870. if (doKeyChar ((int) wParam, lParam))
  207871. return 0;
  207872. break;
  207873. case WM_APPCOMMAND:
  207874. if (doAppCommand (lParam))
  207875. return TRUE;
  207876. break;
  207877. case WM_SETFOCUS:
  207878. updateKeyModifiers();
  207879. handleFocusGain();
  207880. break;
  207881. case WM_KILLFOCUS:
  207882. if (hasCreatedCaret)
  207883. {
  207884. hasCreatedCaret = false;
  207885. DestroyCaret();
  207886. }
  207887. handleFocusLoss();
  207888. break;
  207889. case WM_ACTIVATEAPP:
  207890. // Windows does weird things to process priority when you swap apps,
  207891. // so this forces an update when the app is brought to the front
  207892. if (wParam != FALSE)
  207893. juce_repeatLastProcessPriority();
  207894. else
  207895. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207896. juce_CheckCurrentlyFocusedTopLevelWindow();
  207897. modifiersAtLastCallback = -1;
  207898. return 0;
  207899. case WM_ACTIVATE:
  207900. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207901. {
  207902. handleAppActivation (wParam);
  207903. return 0;
  207904. }
  207905. break;
  207906. case WM_NCACTIVATE:
  207907. // while a temporary window is being shown, prevent Windows from deactivating the
  207908. // title bars of our main windows.
  207909. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207910. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207911. break;
  207912. case WM_MOUSEACTIVATE:
  207913. if (! component->getMouseClickGrabsKeyboardFocus())
  207914. return MA_NOACTIVATE;
  207915. break;
  207916. case WM_SHOWWINDOW:
  207917. if (wParam != 0)
  207918. handleBroughtToFront();
  207919. break;
  207920. case WM_CLOSE:
  207921. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  207922. handleUserClosingWindow();
  207923. return 0;
  207924. case WM_QUERYENDSESSION:
  207925. if (JUCEApplication::getInstance() != 0)
  207926. {
  207927. JUCEApplication::getInstance()->systemRequestedQuit();
  207928. return MessageManager::getInstance()->hasStopMessageBeenSent();
  207929. }
  207930. return TRUE;
  207931. case WM_TRAYNOTIFY:
  207932. handleTaskBarEvent (lParam);
  207933. break;
  207934. case WM_SYNCPAINT:
  207935. return 0;
  207936. case WM_DISPLAYCHANGE:
  207937. InvalidateRect (h, 0, 0);
  207938. // intentional fall-through...
  207939. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207940. doSettingChange();
  207941. break;
  207942. case WM_INITMENU:
  207943. if (! hasTitleBar())
  207944. {
  207945. if (isFullScreen())
  207946. {
  207947. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207948. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207949. }
  207950. else if (! isMinimised())
  207951. {
  207952. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207953. }
  207954. }
  207955. break;
  207956. case WM_SYSCOMMAND:
  207957. switch (wParam & 0xfff0)
  207958. {
  207959. case SC_CLOSE:
  207960. if (sendInputAttemptWhenModalMessage())
  207961. return 0;
  207962. if (hasTitleBar())
  207963. {
  207964. PostMessage (h, WM_CLOSE, 0, 0);
  207965. return 0;
  207966. }
  207967. break;
  207968. case SC_KEYMENU:
  207969. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  207970. // situations that can arise if a modal loop is started from an alt-key keypress).
  207971. if (hasTitleBar() && h == GetCapture())
  207972. ReleaseCapture();
  207973. break;
  207974. case SC_MAXIMIZE:
  207975. if (! sendInputAttemptWhenModalMessage())
  207976. setFullScreen (true);
  207977. return 0;
  207978. case SC_MINIMIZE:
  207979. if (sendInputAttemptWhenModalMessage())
  207980. return 0;
  207981. if (! hasTitleBar())
  207982. {
  207983. setMinimised (true);
  207984. return 0;
  207985. }
  207986. break;
  207987. case SC_RESTORE:
  207988. if (sendInputAttemptWhenModalMessage())
  207989. return 0;
  207990. if (hasTitleBar())
  207991. {
  207992. if (isFullScreen())
  207993. {
  207994. setFullScreen (false);
  207995. return 0;
  207996. }
  207997. }
  207998. else
  207999. {
  208000. if (isMinimised())
  208001. setMinimised (false);
  208002. else if (isFullScreen())
  208003. setFullScreen (false);
  208004. return 0;
  208005. }
  208006. break;
  208007. }
  208008. break;
  208009. case WM_NCLBUTTONDOWN:
  208010. if (! sendInputAttemptWhenModalMessage())
  208011. {
  208012. switch (wParam)
  208013. {
  208014. case HTBOTTOM:
  208015. case HTBOTTOMLEFT:
  208016. case HTBOTTOMRIGHT:
  208017. case HTGROWBOX:
  208018. case HTLEFT:
  208019. case HTRIGHT:
  208020. case HTTOP:
  208021. case HTTOPLEFT:
  208022. case HTTOPRIGHT:
  208023. if (isConstrainedNativeWindow())
  208024. {
  208025. constrainerIsResizing = true;
  208026. constrainer->resizeStart();
  208027. }
  208028. break;
  208029. default:
  208030. break;
  208031. };
  208032. }
  208033. break;
  208034. case WM_NCRBUTTONDOWN:
  208035. case WM_NCMBUTTONDOWN:
  208036. sendInputAttemptWhenModalMessage();
  208037. break;
  208038. //case WM_IME_STARTCOMPOSITION;
  208039. // return 0;
  208040. case WM_GETDLGCODE:
  208041. return DLGC_WANTALLKEYS;
  208042. default:
  208043. if (taskBarIcon != 0)
  208044. {
  208045. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208046. if (message == taskbarCreatedMessage)
  208047. {
  208048. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208049. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208050. }
  208051. }
  208052. break;
  208053. }
  208054. return DefWindowProcW (h, message, wParam, lParam);
  208055. }
  208056. bool sendInputAttemptWhenModalMessage()
  208057. {
  208058. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208059. {
  208060. Component* const current = Component::getCurrentlyModalComponent();
  208061. if (current != 0)
  208062. current->inputAttemptWhenModal();
  208063. return true;
  208064. }
  208065. return false;
  208066. }
  208067. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208068. };
  208069. ModifierKeys Win32ComponentPeer::currentModifiers;
  208070. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208071. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208072. {
  208073. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208074. }
  208075. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208076. void ModifierKeys::updateCurrentModifiers() throw()
  208077. {
  208078. currentModifiers = Win32ComponentPeer::currentModifiers;
  208079. }
  208080. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208081. {
  208082. Win32ComponentPeer::updateKeyModifiers();
  208083. int mouseMods = 0;
  208084. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208085. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208086. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208087. Win32ComponentPeer::currentModifiers
  208088. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208089. return Win32ComponentPeer::currentModifiers;
  208090. }
  208091. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208092. {
  208093. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208094. if (wp != 0)
  208095. wp->setTaskBarIcon (newImage);
  208096. }
  208097. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208098. {
  208099. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208100. if (wp != 0)
  208101. wp->setTaskBarIconToolTip (tooltip);
  208102. }
  208103. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208104. {
  208105. DWORD val = GetWindowLong (h, styleType);
  208106. if (bitIsSet)
  208107. val |= feature;
  208108. else
  208109. val &= ~feature;
  208110. SetWindowLongPtr (h, styleType, val);
  208111. SetWindowPos (h, 0, 0, 0, 0, 0,
  208112. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208113. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208114. }
  208115. bool Process::isForegroundProcess()
  208116. {
  208117. HWND fg = GetForegroundWindow();
  208118. if (fg == 0)
  208119. return true;
  208120. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208121. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208122. // have to see if any of our windows are children of the foreground window
  208123. fg = GetAncestor (fg, GA_ROOT);
  208124. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208125. {
  208126. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208127. if (wp != 0 && wp->isInside (fg))
  208128. return true;
  208129. }
  208130. return false;
  208131. }
  208132. bool AlertWindow::showNativeDialogBox (const String& title,
  208133. const String& bodyText,
  208134. bool isOkCancel)
  208135. {
  208136. return MessageBox (0, bodyText.toUTF16(), title.toUTF16(),
  208137. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208138. : MB_OK)) == IDOK;
  208139. }
  208140. void Desktop::createMouseInputSources()
  208141. {
  208142. mouseSources.add (new MouseInputSource (0, true));
  208143. }
  208144. const Point<int> MouseInputSource::getCurrentMousePosition()
  208145. {
  208146. POINT mousePos;
  208147. GetCursorPos (&mousePos);
  208148. return Point<int> (mousePos.x, mousePos.y);
  208149. }
  208150. void Desktop::setMousePosition (const Point<int>& newPosition)
  208151. {
  208152. SetCursorPos (newPosition.getX(), newPosition.getY());
  208153. }
  208154. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208155. {
  208156. return createSoftwareImage (format, width, height, clearImage);
  208157. }
  208158. class ScreenSaverDefeater : public Timer,
  208159. public DeletedAtShutdown
  208160. {
  208161. public:
  208162. ScreenSaverDefeater()
  208163. {
  208164. startTimer (10000);
  208165. timerCallback();
  208166. }
  208167. ~ScreenSaverDefeater() {}
  208168. void timerCallback()
  208169. {
  208170. if (Process::isForegroundProcess())
  208171. {
  208172. // simulate a shift key getting pressed..
  208173. INPUT input[2];
  208174. input[0].type = INPUT_KEYBOARD;
  208175. input[0].ki.wVk = VK_SHIFT;
  208176. input[0].ki.dwFlags = 0;
  208177. input[0].ki.dwExtraInfo = 0;
  208178. input[1].type = INPUT_KEYBOARD;
  208179. input[1].ki.wVk = VK_SHIFT;
  208180. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208181. input[1].ki.dwExtraInfo = 0;
  208182. SendInput (2, input, sizeof (INPUT));
  208183. }
  208184. }
  208185. };
  208186. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208187. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208188. {
  208189. if (isEnabled)
  208190. deleteAndZero (screenSaverDefeater);
  208191. else if (screenSaverDefeater == 0)
  208192. screenSaverDefeater = new ScreenSaverDefeater();
  208193. }
  208194. bool Desktop::isScreenSaverEnabled()
  208195. {
  208196. return screenSaverDefeater == 0;
  208197. }
  208198. /* (The code below is the "correct" way to disable the screen saver, but it
  208199. completely fails on winXP when the saver is password-protected...)
  208200. static bool juce_screenSaverEnabled = true;
  208201. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208202. {
  208203. juce_screenSaverEnabled = isEnabled;
  208204. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208205. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208206. }
  208207. bool Desktop::isScreenSaverEnabled() throw()
  208208. {
  208209. return juce_screenSaverEnabled;
  208210. }
  208211. */
  208212. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208213. {
  208214. if (enableOrDisable)
  208215. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208216. }
  208217. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208218. {
  208219. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208220. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208221. return TRUE;
  208222. }
  208223. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208224. {
  208225. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208226. // make sure the first in the list is the main monitor
  208227. for (int i = 1; i < monitorCoords.size(); ++i)
  208228. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208229. monitorCoords.swap (i, 0);
  208230. if (monitorCoords.size() == 0)
  208231. {
  208232. RECT r;
  208233. GetWindowRect (GetDesktopWindow(), &r);
  208234. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208235. }
  208236. if (clipToWorkArea)
  208237. {
  208238. // clip the main monitor to the active non-taskbar area
  208239. RECT r;
  208240. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208241. Rectangle<int>& screen = monitorCoords.getReference (0);
  208242. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208243. jmax (screen.getY(), (int) r.top));
  208244. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208245. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208246. }
  208247. }
  208248. const Image juce_createIconForFile (const File& file)
  208249. {
  208250. Image image;
  208251. WORD iconNum = 0;
  208252. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208253. const_cast <WCHAR*> (file.getFullPathName().toUTF16().getAddress()), &iconNum);
  208254. if (icon != 0)
  208255. {
  208256. image = IconConverters::createImageFromHICON (icon);
  208257. DestroyIcon (icon);
  208258. }
  208259. return image;
  208260. }
  208261. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208262. {
  208263. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208264. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208265. Image im (image);
  208266. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208267. {
  208268. im = im.rescaled (maxW, maxH);
  208269. hotspotX = (hotspotX * maxW) / image.getWidth();
  208270. hotspotY = (hotspotY * maxH) / image.getHeight();
  208271. }
  208272. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208273. }
  208274. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208275. {
  208276. if (cursorHandle != 0 && ! isStandard)
  208277. DestroyCursor ((HCURSOR) cursorHandle);
  208278. }
  208279. enum
  208280. {
  208281. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208282. };
  208283. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208284. {
  208285. LPCTSTR cursorName = IDC_ARROW;
  208286. switch (type)
  208287. {
  208288. case NormalCursor: break;
  208289. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208290. case WaitCursor: cursorName = IDC_WAIT; break;
  208291. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208292. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208293. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208294. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208295. case LeftRightResizeCursor:
  208296. case LeftEdgeResizeCursor:
  208297. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208298. case UpDownResizeCursor:
  208299. case TopEdgeResizeCursor:
  208300. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208301. case TopLeftCornerResizeCursor:
  208302. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208303. case TopRightCornerResizeCursor:
  208304. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208305. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208306. case DraggingHandCursor:
  208307. {
  208308. static void* dragHandCursor = 0;
  208309. if (dragHandCursor == 0)
  208310. {
  208311. static const unsigned char dragHandData[] =
  208312. { 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,
  208313. 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,
  208314. 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 };
  208315. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208316. }
  208317. return dragHandCursor;
  208318. }
  208319. default:
  208320. jassertfalse; break;
  208321. }
  208322. HCURSOR cursorH = LoadCursor (0, cursorName);
  208323. if (cursorH == 0)
  208324. cursorH = LoadCursor (0, IDC_ARROW);
  208325. return cursorH;
  208326. }
  208327. void MouseCursor::showInWindow (ComponentPeer*) const
  208328. {
  208329. HCURSOR c = (HCURSOR) getHandle();
  208330. if (c == 0)
  208331. c = LoadCursor (0, IDC_ARROW);
  208332. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208333. c = 0;
  208334. SetCursor (c);
  208335. }
  208336. void MouseCursor::showInAllWindows() const
  208337. {
  208338. showInWindow (0);
  208339. }
  208340. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208341. {
  208342. public:
  208343. JuceDropSource() {}
  208344. ~JuceDropSource() {}
  208345. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208346. {
  208347. if (escapePressed)
  208348. return DRAGDROP_S_CANCEL;
  208349. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208350. return DRAGDROP_S_DROP;
  208351. return S_OK;
  208352. }
  208353. HRESULT __stdcall GiveFeedback (DWORD)
  208354. {
  208355. return DRAGDROP_S_USEDEFAULTCURSORS;
  208356. }
  208357. };
  208358. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208359. {
  208360. public:
  208361. JuceEnumFormatEtc (const FORMATETC* const format_)
  208362. : format (format_),
  208363. index (0)
  208364. {
  208365. }
  208366. ~JuceEnumFormatEtc() {}
  208367. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208368. {
  208369. if (result == 0)
  208370. return E_POINTER;
  208371. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208372. newOne->index = index;
  208373. *result = newOne;
  208374. return S_OK;
  208375. }
  208376. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208377. {
  208378. if (pceltFetched != 0)
  208379. *pceltFetched = 0;
  208380. else if (celt != 1)
  208381. return S_FALSE;
  208382. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208383. {
  208384. copyFormatEtc (lpFormatEtc [0], *format);
  208385. ++index;
  208386. if (pceltFetched != 0)
  208387. *pceltFetched = 1;
  208388. return S_OK;
  208389. }
  208390. return S_FALSE;
  208391. }
  208392. HRESULT __stdcall Skip (ULONG celt)
  208393. {
  208394. if (index + (int) celt >= 1)
  208395. return S_FALSE;
  208396. index += celt;
  208397. return S_OK;
  208398. }
  208399. HRESULT __stdcall Reset()
  208400. {
  208401. index = 0;
  208402. return S_OK;
  208403. }
  208404. private:
  208405. const FORMATETC* const format;
  208406. int index;
  208407. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208408. {
  208409. dest = source;
  208410. if (source.ptd != 0)
  208411. {
  208412. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208413. *(dest.ptd) = *(source.ptd);
  208414. }
  208415. }
  208416. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208417. };
  208418. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208419. {
  208420. public:
  208421. JuceDataObject (JuceDropSource* const dropSource_,
  208422. const FORMATETC* const format_,
  208423. const STGMEDIUM* const medium_)
  208424. : dropSource (dropSource_),
  208425. format (format_),
  208426. medium (medium_)
  208427. {
  208428. }
  208429. ~JuceDataObject()
  208430. {
  208431. jassert (refCount == 0);
  208432. }
  208433. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208434. {
  208435. if ((pFormatEtc->tymed & format->tymed) != 0
  208436. && pFormatEtc->cfFormat == format->cfFormat
  208437. && pFormatEtc->dwAspect == format->dwAspect)
  208438. {
  208439. pMedium->tymed = format->tymed;
  208440. pMedium->pUnkForRelease = 0;
  208441. if (format->tymed == TYMED_HGLOBAL)
  208442. {
  208443. const SIZE_T len = GlobalSize (medium->hGlobal);
  208444. void* const src = GlobalLock (medium->hGlobal);
  208445. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208446. memcpy (dst, src, len);
  208447. GlobalUnlock (medium->hGlobal);
  208448. pMedium->hGlobal = dst;
  208449. return S_OK;
  208450. }
  208451. }
  208452. return DV_E_FORMATETC;
  208453. }
  208454. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208455. {
  208456. if (f == 0)
  208457. return E_INVALIDARG;
  208458. if (f->tymed == format->tymed
  208459. && f->cfFormat == format->cfFormat
  208460. && f->dwAspect == format->dwAspect)
  208461. return S_OK;
  208462. return DV_E_FORMATETC;
  208463. }
  208464. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208465. {
  208466. pFormatEtcOut->ptd = 0;
  208467. return E_NOTIMPL;
  208468. }
  208469. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208470. {
  208471. if (result == 0)
  208472. return E_POINTER;
  208473. if (direction == DATADIR_GET)
  208474. {
  208475. *result = new JuceEnumFormatEtc (format);
  208476. return S_OK;
  208477. }
  208478. *result = 0;
  208479. return E_NOTIMPL;
  208480. }
  208481. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208482. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208483. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208484. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208485. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208486. private:
  208487. JuceDropSource* const dropSource;
  208488. const FORMATETC* const format;
  208489. const STGMEDIUM* const medium;
  208490. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208491. };
  208492. static HDROP createHDrop (const StringArray& fileNames)
  208493. {
  208494. int totalBytes = 0;
  208495. for (int i = fileNames.size(); --i >= 0;)
  208496. totalBytes += CharPointer_UTF16::getBytesRequiredFor (fileNames[i].getCharPointer()) + sizeof (WCHAR);
  208497. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (DROPFILES) + totalBytes + 4);
  208498. if (hDrop != 0)
  208499. {
  208500. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208501. pDropFiles->pFiles = sizeof (DROPFILES);
  208502. pDropFiles->fWide = true;
  208503. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208504. for (int i = 0; i < fileNames.size(); ++i)
  208505. {
  208506. const int bytesWritten = fileNames[i].copyToUTF16 (fname, 2048);
  208507. fname = reinterpret_cast<WCHAR*> (addBytesToPointer (fname, bytesWritten));
  208508. }
  208509. *fname = 0;
  208510. GlobalUnlock (hDrop);
  208511. }
  208512. return hDrop;
  208513. }
  208514. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208515. {
  208516. JuceDropSource* const source = new JuceDropSource();
  208517. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208518. DWORD effect;
  208519. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208520. data->Release();
  208521. source->Release();
  208522. return res == DRAGDROP_S_DROP;
  208523. }
  208524. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208525. {
  208526. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208527. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208528. medium.hGlobal = createHDrop (files);
  208529. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208530. : DROPEFFECT_COPY);
  208531. }
  208532. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208533. {
  208534. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208535. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208536. const int numBytes = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
  208537. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, numBytes + 2);
  208538. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208539. text.copyToUTF16 (data, numBytes);
  208540. format.cfFormat = CF_UNICODETEXT;
  208541. GlobalUnlock (medium.hGlobal);
  208542. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208543. }
  208544. #endif
  208545. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208546. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208547. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208548. // compiled on its own).
  208549. #if JUCE_INCLUDED_FILE
  208550. namespace FileChooserHelpers
  208551. {
  208552. static bool areThereAnyAlwaysOnTopWindows()
  208553. {
  208554. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208555. {
  208556. Component* c = Desktop::getInstance().getComponent (i);
  208557. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208558. return true;
  208559. }
  208560. return false;
  208561. }
  208562. struct FileChooserCallbackInfo
  208563. {
  208564. String initialPath;
  208565. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208566. ScopedPointer<Component> customComponent;
  208567. };
  208568. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208569. {
  208570. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208571. if (msg == BFFM_INITIALIZED)
  208572. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) info->initialPath.toUTF16().getAddress());
  208573. else if (msg == BFFM_VALIDATEFAILEDW)
  208574. info->returnedString = (LPCWSTR) lParam;
  208575. else if (msg == BFFM_VALIDATEFAILEDA)
  208576. info->returnedString = (const char*) lParam;
  208577. return 0;
  208578. }
  208579. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208580. {
  208581. if (uiMsg == WM_INITDIALOG)
  208582. {
  208583. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208584. HWND dialogH = GetParent (hdlg);
  208585. jassert (dialogH != 0);
  208586. if (dialogH == 0)
  208587. dialogH = hdlg;
  208588. RECT r, cr;
  208589. GetWindowRect (dialogH, &r);
  208590. GetClientRect (dialogH, &cr);
  208591. SetWindowPos (dialogH, 0,
  208592. r.left, r.top,
  208593. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208594. jmax (150, (int) (r.bottom - r.top)),
  208595. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208596. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208597. customComp->addToDesktop (0, dialogH);
  208598. }
  208599. else if (uiMsg == WM_NOTIFY)
  208600. {
  208601. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208602. if (ofn->hdr.code == CDN_SELCHANGE)
  208603. {
  208604. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208605. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208606. if (comp != 0)
  208607. {
  208608. WCHAR path [MAX_PATH * 2];
  208609. zerostruct (path);
  208610. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208611. comp->selectedFileChanged (File (path));
  208612. }
  208613. }
  208614. }
  208615. return 0;
  208616. }
  208617. class CustomComponentHolder : public Component
  208618. {
  208619. public:
  208620. CustomComponentHolder (Component* customComp)
  208621. {
  208622. setVisible (true);
  208623. setOpaque (true);
  208624. addAndMakeVisible (customComp);
  208625. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208626. }
  208627. void paint (Graphics& g)
  208628. {
  208629. g.fillAll (Colours::lightgrey);
  208630. }
  208631. void resized()
  208632. {
  208633. if (getNumChildComponents() > 0)
  208634. getChildComponent(0)->setBounds (getLocalBounds());
  208635. }
  208636. private:
  208637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208638. };
  208639. }
  208640. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208641. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208642. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208643. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208644. {
  208645. using namespace FileChooserHelpers;
  208646. HeapBlock<WCHAR> files;
  208647. const int charsAvailableForResult = 32768;
  208648. files.calloc (charsAvailableForResult + 1);
  208649. int filenameOffset = 0;
  208650. FileChooserCallbackInfo info;
  208651. // use a modal window as the parent for this dialog box
  208652. // to block input from other app windows
  208653. Component parentWindow (String::empty);
  208654. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208655. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208656. mainMon.getY() + mainMon.getHeight() / 4,
  208657. 0, 0);
  208658. parentWindow.setOpaque (true);
  208659. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208660. parentWindow.addToDesktop (0);
  208661. if (extraInfoComponent == 0)
  208662. parentWindow.enterModalState();
  208663. if (currentFileOrDirectory.isDirectory())
  208664. {
  208665. info.initialPath = currentFileOrDirectory.getFullPathName();
  208666. }
  208667. else
  208668. {
  208669. currentFileOrDirectory.getFileName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
  208670. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208671. }
  208672. if (selectsDirectory)
  208673. {
  208674. BROWSEINFO bi;
  208675. zerostruct (bi);
  208676. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208677. bi.pszDisplayName = files;
  208678. bi.lpszTitle = title.toUTF16();
  208679. bi.lParam = (LPARAM) &info;
  208680. bi.lpfn = browseCallbackProc;
  208681. #ifdef BIF_USENEWUI
  208682. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208683. #else
  208684. bi.ulFlags = 0x50;
  208685. #endif
  208686. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208687. if (! SHGetPathFromIDListW (list, files))
  208688. {
  208689. files[0] = 0;
  208690. info.returnedString = String::empty;
  208691. }
  208692. LPMALLOC al;
  208693. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208694. al->Free (list);
  208695. if (info.returnedString.isNotEmpty())
  208696. {
  208697. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208698. return;
  208699. }
  208700. }
  208701. else
  208702. {
  208703. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208704. if (warnAboutOverwritingExistingFiles)
  208705. flags |= OFN_OVERWRITEPROMPT;
  208706. if (selectMultipleFiles)
  208707. flags |= OFN_ALLOWMULTISELECT;
  208708. if (extraInfoComponent != 0)
  208709. {
  208710. flags |= OFN_ENABLEHOOK;
  208711. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208712. info.customComponent->enterModalState();
  208713. }
  208714. const int filterSpace = 2048;
  208715. HeapBlock<char> filters;
  208716. filters.calloc (filterSpace * 2);
  208717. const int bytesWritten = filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters.getData()), filterSpace);
  208718. filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters + bytesWritten), filterSpace);
  208719. OPENFILENAMEW of;
  208720. zerostruct (of);
  208721. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208722. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208723. #else
  208724. of.lStructSize = sizeof (of);
  208725. #endif
  208726. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208727. of.lpstrFilter = reinterpret_cast <WCHAR*> (filters.getData());
  208728. of.nFilterIndex = 1;
  208729. of.lpstrFile = files;
  208730. of.nMaxFile = charsAvailableForResult;
  208731. of.lpstrInitialDir = info.initialPath.toUTF16();
  208732. of.lpstrTitle = title.toUTF16();
  208733. of.Flags = flags;
  208734. of.lCustData = (LPARAM) &info;
  208735. if (extraInfoComponent != 0)
  208736. of.lpfnHook = &openCallback;
  208737. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208738. : GetOpenFileName (&of)))
  208739. return;
  208740. filenameOffset = of.nFileOffset;
  208741. }
  208742. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208743. {
  208744. const WCHAR* filename = files + filenameOffset;
  208745. while (*filename != 0)
  208746. {
  208747. results.add (File (String (files) + "\\" + String (filename)));
  208748. filename += wcslen (filename) + 1;
  208749. }
  208750. }
  208751. else if (files[0] != 0)
  208752. {
  208753. results.add (File (String (files)));
  208754. }
  208755. }
  208756. #endif
  208757. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208758. /*** Start of inlined file: juce_win32_Misc.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. void SystemClipboard::copyTextToClipboard (const String& text)
  208763. {
  208764. if (OpenClipboard (0) != 0)
  208765. {
  208766. if (EmptyClipboard() != 0)
  208767. {
  208768. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  208769. if (bytesNeeded > 0)
  208770. {
  208771. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR));
  208772. if (bufH != 0)
  208773. {
  208774. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208775. text.copyToUTF16 (data, bytesNeeded);
  208776. GlobalUnlock (bufH);
  208777. SetClipboardData (CF_UNICODETEXT, bufH);
  208778. }
  208779. }
  208780. }
  208781. CloseClipboard();
  208782. }
  208783. }
  208784. const String SystemClipboard::getTextFromClipboard()
  208785. {
  208786. String result;
  208787. if (OpenClipboard (0) != 0)
  208788. {
  208789. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208790. if (bufH != 0)
  208791. {
  208792. const WCHAR* const data = (const WCHAR*) GlobalLock (bufH);
  208793. if (data != 0)
  208794. {
  208795. result = String (data, (int) (GlobalSize (bufH) / sizeof (WCHAR)));
  208796. GlobalUnlock (bufH);
  208797. }
  208798. }
  208799. CloseClipboard();
  208800. }
  208801. return result;
  208802. }
  208803. #endif
  208804. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208805. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208806. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208807. // compiled on its own).
  208808. #if JUCE_INCLUDED_FILE
  208809. namespace ActiveXHelpers
  208810. {
  208811. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208812. {
  208813. public:
  208814. JuceIStorage() {}
  208815. ~JuceIStorage() {}
  208816. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208817. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208818. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208819. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208820. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208821. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208822. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208823. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208824. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208825. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208826. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208827. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208828. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208829. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208830. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208831. };
  208832. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208833. {
  208834. HWND window;
  208835. public:
  208836. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208837. ~JuceOleInPlaceFrame() {}
  208838. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208839. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208840. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208841. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208842. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208843. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208844. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208845. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208846. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208847. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208848. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208849. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208850. };
  208851. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208852. {
  208853. HWND window;
  208854. JuceOleInPlaceFrame* frame;
  208855. public:
  208856. JuceIOleInPlaceSite (HWND window_)
  208857. : window (window_),
  208858. frame (new JuceOleInPlaceFrame (window))
  208859. {}
  208860. ~JuceIOleInPlaceSite()
  208861. {
  208862. frame->Release();
  208863. }
  208864. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208865. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208866. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208867. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208868. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208869. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208870. {
  208871. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  208872. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  208873. */
  208874. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  208875. if (lplpDoc != 0) *lplpDoc = 0;
  208876. lpFrameInfo->fMDIApp = FALSE;
  208877. lpFrameInfo->hwndFrame = window;
  208878. lpFrameInfo->haccel = 0;
  208879. lpFrameInfo->cAccelEntries = 0;
  208880. return S_OK;
  208881. }
  208882. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208883. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208884. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208885. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208886. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208887. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208888. };
  208889. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  208890. {
  208891. JuceIOleInPlaceSite* inplaceSite;
  208892. public:
  208893. JuceIOleClientSite (HWND window)
  208894. : inplaceSite (new JuceIOleInPlaceSite (window))
  208895. {}
  208896. ~JuceIOleClientSite()
  208897. {
  208898. inplaceSite->Release();
  208899. }
  208900. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  208901. {
  208902. if (type == IID_IOleInPlaceSite)
  208903. {
  208904. inplaceSite->AddRef();
  208905. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  208906. return S_OK;
  208907. }
  208908. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  208909. }
  208910. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208911. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208912. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208913. HRESULT __stdcall ShowObject() { return S_OK; }
  208914. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208915. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208916. };
  208917. static Array<ActiveXControlComponent*> activeXComps;
  208918. static HWND getHWND (const ActiveXControlComponent* const component)
  208919. {
  208920. HWND hwnd = 0;
  208921. const IID iid = IID_IOleWindow;
  208922. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208923. if (window != 0)
  208924. {
  208925. window->GetWindow (&hwnd);
  208926. window->Release();
  208927. }
  208928. return hwnd;
  208929. }
  208930. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208931. {
  208932. RECT activeXRect, peerRect;
  208933. GetWindowRect (hwnd, &activeXRect);
  208934. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208935. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  208936. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  208937. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  208938. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208939. switch (message)
  208940. {
  208941. case WM_MOUSEMOVE:
  208942. case WM_LBUTTONDOWN:
  208943. case WM_MBUTTONDOWN:
  208944. case WM_RBUTTONDOWN:
  208945. case WM_LBUTTONUP:
  208946. case WM_MBUTTONUP:
  208947. case WM_RBUTTONUP:
  208948. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  208949. break;
  208950. default:
  208951. break;
  208952. }
  208953. }
  208954. }
  208955. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  208956. {
  208957. public:
  208958. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  208959. : ComponentMovementWatcher (&owner_),
  208960. owner (owner_),
  208961. controlHWND (0),
  208962. storage (new ActiveXHelpers::JuceIStorage()),
  208963. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  208964. control (0)
  208965. {
  208966. }
  208967. ~Pimpl()
  208968. {
  208969. if (control != 0)
  208970. {
  208971. control->Close (OLECLOSE_NOSAVE);
  208972. control->Release();
  208973. }
  208974. clientSite->Release();
  208975. storage->Release();
  208976. }
  208977. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  208978. {
  208979. Component* const topComp = owner.getTopLevelComponent();
  208980. if (topComp->getPeer() != 0)
  208981. {
  208982. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  208983. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  208984. }
  208985. }
  208986. void componentPeerChanged()
  208987. {
  208988. componentMovedOrResized (true, true);
  208989. }
  208990. void componentVisibilityChanged()
  208991. {
  208992. owner.setControlVisible (owner.isShowing());
  208993. componentPeerChanged();
  208994. }
  208995. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  208996. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  208997. {
  208998. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  208999. {
  209000. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209001. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209002. {
  209003. switch (message)
  209004. {
  209005. case WM_MOUSEMOVE:
  209006. case WM_LBUTTONDOWN:
  209007. case WM_MBUTTONDOWN:
  209008. case WM_RBUTTONDOWN:
  209009. case WM_LBUTTONUP:
  209010. case WM_MBUTTONUP:
  209011. case WM_RBUTTONUP:
  209012. case WM_LBUTTONDBLCLK:
  209013. case WM_MBUTTONDBLCLK:
  209014. case WM_RBUTTONDBLCLK:
  209015. if (ax->isShowing())
  209016. {
  209017. ComponentPeer* const peer = ax->getPeer();
  209018. if (peer != 0)
  209019. {
  209020. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209021. if (! ax->areMouseEventsAllowed())
  209022. return 0;
  209023. }
  209024. }
  209025. break;
  209026. default:
  209027. break;
  209028. }
  209029. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209030. }
  209031. }
  209032. return DefWindowProc (hwnd, message, wParam, lParam);
  209033. }
  209034. private:
  209035. ActiveXControlComponent& owner;
  209036. public:
  209037. HWND controlHWND;
  209038. IStorage* storage;
  209039. IOleClientSite* clientSite;
  209040. IOleObject* control;
  209041. };
  209042. ActiveXControlComponent::ActiveXControlComponent()
  209043. : originalWndProc (0),
  209044. mouseEventsAllowed (true)
  209045. {
  209046. ActiveXHelpers::activeXComps.add (this);
  209047. }
  209048. ActiveXControlComponent::~ActiveXControlComponent()
  209049. {
  209050. deleteControl();
  209051. ActiveXHelpers::activeXComps.removeValue (this);
  209052. }
  209053. void ActiveXControlComponent::paint (Graphics& g)
  209054. {
  209055. if (control == 0)
  209056. g.fillAll (Colours::lightgrey);
  209057. }
  209058. bool ActiveXControlComponent::createControl (const void* controlIID)
  209059. {
  209060. deleteControl();
  209061. ComponentPeer* const peer = getPeer();
  209062. // the component must have already been added to a real window when you call this!
  209063. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209064. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209065. {
  209066. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209067. HWND hwnd = (HWND) peer->getNativeHandle();
  209068. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209069. HRESULT hr;
  209070. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209071. newControl->clientSite, newControl->storage,
  209072. (void**) &(newControl->control))) == S_OK)
  209073. {
  209074. newControl->control->SetHostNames (L"Juce", 0);
  209075. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209076. {
  209077. RECT rect;
  209078. rect.left = pos.getX();
  209079. rect.top = pos.getY();
  209080. rect.right = pos.getX() + getWidth();
  209081. rect.bottom = pos.getY() + getHeight();
  209082. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209083. {
  209084. control = newControl;
  209085. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209086. control->controlHWND = ActiveXHelpers::getHWND (this);
  209087. if (control->controlHWND != 0)
  209088. {
  209089. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209090. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209091. }
  209092. return true;
  209093. }
  209094. }
  209095. }
  209096. }
  209097. return false;
  209098. }
  209099. void ActiveXControlComponent::deleteControl()
  209100. {
  209101. control = 0;
  209102. originalWndProc = 0;
  209103. }
  209104. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209105. {
  209106. void* result = 0;
  209107. if (control != 0 && control->control != 0
  209108. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209109. return result;
  209110. return 0;
  209111. }
  209112. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209113. {
  209114. if (control->controlHWND != 0)
  209115. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209116. }
  209117. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209118. {
  209119. if (control->controlHWND != 0)
  209120. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209121. }
  209122. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209123. {
  209124. mouseEventsAllowed = eventsCanReachControl;
  209125. }
  209126. #endif
  209127. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209128. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209129. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209130. // compiled on its own).
  209131. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209132. using namespace QTOLibrary;
  209133. using namespace QTOControlLib;
  209134. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209135. static bool isQTAvailable = false;
  209136. class QuickTimeMovieComponent::Pimpl
  209137. {
  209138. public:
  209139. Pimpl() : dataHandle (0)
  209140. {
  209141. }
  209142. ~Pimpl()
  209143. {
  209144. clearHandle();
  209145. }
  209146. void clearHandle()
  209147. {
  209148. if (dataHandle != 0)
  209149. {
  209150. DisposeHandle (dataHandle);
  209151. dataHandle = 0;
  209152. }
  209153. }
  209154. IQTControlPtr qtControl;
  209155. IQTMoviePtr qtMovie;
  209156. Handle dataHandle;
  209157. };
  209158. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209159. : movieLoaded (false),
  209160. controllerVisible (true)
  209161. {
  209162. pimpl = new Pimpl();
  209163. setMouseEventsAllowed (false);
  209164. }
  209165. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209166. {
  209167. closeMovie();
  209168. pimpl->qtControl = 0;
  209169. deleteControl();
  209170. pimpl = 0;
  209171. }
  209172. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209173. {
  209174. if (! isQTAvailable)
  209175. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209176. return isQTAvailable;
  209177. }
  209178. void QuickTimeMovieComponent::createControlIfNeeded()
  209179. {
  209180. if (isShowing() && ! isControlCreated())
  209181. {
  209182. const IID qtIID = __uuidof (QTControl);
  209183. if (createControl (&qtIID))
  209184. {
  209185. const IID qtInterfaceIID = __uuidof (IQTControl);
  209186. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209187. if (pimpl->qtControl != 0)
  209188. {
  209189. pimpl->qtControl->Release(); // it has one ref too many at this point
  209190. pimpl->qtControl->QuickTimeInitialize();
  209191. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209192. if (movieFile != File::nonexistent)
  209193. loadMovie (movieFile, controllerVisible);
  209194. }
  209195. }
  209196. }
  209197. }
  209198. bool QuickTimeMovieComponent::isControlCreated() const
  209199. {
  209200. return isControlOpen();
  209201. }
  209202. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209203. const bool isControllerVisible)
  209204. {
  209205. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209206. movieFile = File::nonexistent;
  209207. movieLoaded = false;
  209208. pimpl->qtMovie = 0;
  209209. controllerVisible = isControllerVisible;
  209210. createControlIfNeeded();
  209211. if (isControlCreated())
  209212. {
  209213. if (pimpl->qtControl != 0)
  209214. {
  209215. pimpl->qtControl->Put_MovieHandle (0);
  209216. pimpl->clearHandle();
  209217. Movie movie;
  209218. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209219. {
  209220. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209221. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209222. if (pimpl->qtMovie != 0)
  209223. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209224. : qtMovieControllerTypeNone);
  209225. }
  209226. if (movie == 0)
  209227. pimpl->clearHandle();
  209228. }
  209229. movieLoaded = (pimpl->qtMovie != 0);
  209230. }
  209231. else
  209232. {
  209233. // You're trying to open a movie when the control hasn't yet been created, probably because
  209234. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209235. jassertfalse;
  209236. }
  209237. return movieLoaded;
  209238. }
  209239. void QuickTimeMovieComponent::closeMovie()
  209240. {
  209241. stop();
  209242. movieFile = File::nonexistent;
  209243. movieLoaded = false;
  209244. pimpl->qtMovie = 0;
  209245. if (pimpl->qtControl != 0)
  209246. pimpl->qtControl->Put_MovieHandle (0);
  209247. pimpl->clearHandle();
  209248. }
  209249. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209250. {
  209251. return movieFile;
  209252. }
  209253. bool QuickTimeMovieComponent::isMovieOpen() const
  209254. {
  209255. return movieLoaded;
  209256. }
  209257. double QuickTimeMovieComponent::getMovieDuration() const
  209258. {
  209259. if (pimpl->qtMovie != 0)
  209260. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209261. return 0.0;
  209262. }
  209263. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209264. {
  209265. if (pimpl->qtMovie != 0)
  209266. {
  209267. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209268. width = r.right - r.left;
  209269. height = r.bottom - r.top;
  209270. }
  209271. else
  209272. {
  209273. width = height = 0;
  209274. }
  209275. }
  209276. void QuickTimeMovieComponent::play()
  209277. {
  209278. if (pimpl->qtMovie != 0)
  209279. pimpl->qtMovie->Play();
  209280. }
  209281. void QuickTimeMovieComponent::stop()
  209282. {
  209283. if (pimpl->qtMovie != 0)
  209284. pimpl->qtMovie->Stop();
  209285. }
  209286. bool QuickTimeMovieComponent::isPlaying() const
  209287. {
  209288. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209289. }
  209290. void QuickTimeMovieComponent::setPosition (const double seconds)
  209291. {
  209292. if (pimpl->qtMovie != 0)
  209293. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209294. }
  209295. double QuickTimeMovieComponent::getPosition() const
  209296. {
  209297. if (pimpl->qtMovie != 0)
  209298. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209299. return 0.0;
  209300. }
  209301. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209302. {
  209303. if (pimpl->qtMovie != 0)
  209304. pimpl->qtMovie->PutRate (newSpeed);
  209305. }
  209306. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209307. {
  209308. if (pimpl->qtMovie != 0)
  209309. {
  209310. pimpl->qtMovie->PutAudioVolume (newVolume);
  209311. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209312. }
  209313. }
  209314. float QuickTimeMovieComponent::getMovieVolume() const
  209315. {
  209316. if (pimpl->qtMovie != 0)
  209317. return pimpl->qtMovie->GetAudioVolume();
  209318. return 0.0f;
  209319. }
  209320. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209321. {
  209322. if (pimpl->qtMovie != 0)
  209323. pimpl->qtMovie->PutLoop (shouldLoop);
  209324. }
  209325. bool QuickTimeMovieComponent::isLooping() const
  209326. {
  209327. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209328. }
  209329. bool QuickTimeMovieComponent::isControllerVisible() const
  209330. {
  209331. return controllerVisible;
  209332. }
  209333. void QuickTimeMovieComponent::parentHierarchyChanged()
  209334. {
  209335. createControlIfNeeded();
  209336. QTCompBaseClass::parentHierarchyChanged();
  209337. }
  209338. void QuickTimeMovieComponent::visibilityChanged()
  209339. {
  209340. createControlIfNeeded();
  209341. QTCompBaseClass::visibilityChanged();
  209342. }
  209343. void QuickTimeMovieComponent::paint (Graphics& g)
  209344. {
  209345. if (! isControlCreated())
  209346. g.fillAll (Colours::black);
  209347. }
  209348. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209349. {
  209350. Handle dataRef = 0;
  209351. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209352. if (err == noErr)
  209353. {
  209354. Str255 suffix;
  209355. strncpy ((char*) suffix, fileName, 128);
  209356. StringPtr name = suffix;
  209357. err = PtrAndHand (name, dataRef, name[0] + 1);
  209358. if (err == noErr)
  209359. {
  209360. long atoms[3];
  209361. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209362. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209363. atoms[2] = EndianU32_NtoB (MovieFileType);
  209364. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209365. if (err == noErr)
  209366. return dataRef;
  209367. }
  209368. DisposeHandle (dataRef);
  209369. }
  209370. return 0;
  209371. }
  209372. static CFStringRef juceStringToCFString (const String& s)
  209373. {
  209374. return CFStringCreateWithCString (kCFAllocatorDefault, s.toUTF8(), kCFStringEncodingUTF8);
  209375. }
  209376. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209377. {
  209378. Boolean trueBool = true;
  209379. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209380. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209381. props[prop].propValueSize = sizeof (trueBool);
  209382. props[prop].propValueAddress = &trueBool;
  209383. ++prop;
  209384. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209385. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209386. props[prop].propValueSize = sizeof (trueBool);
  209387. props[prop].propValueAddress = &trueBool;
  209388. ++prop;
  209389. Boolean isActive = true;
  209390. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209391. props[prop].propID = kQTNewMoviePropertyID_Active;
  209392. props[prop].propValueSize = sizeof (isActive);
  209393. props[prop].propValueAddress = &isActive;
  209394. ++prop;
  209395. MacSetPort (0);
  209396. jassert (prop <= 5);
  209397. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209398. return err == noErr;
  209399. }
  209400. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209401. {
  209402. if (input == 0)
  209403. return false;
  209404. dataHandle = 0;
  209405. bool ok = false;
  209406. QTNewMoviePropertyElement props[5];
  209407. zeromem (props, sizeof (props));
  209408. int prop = 0;
  209409. DataReferenceRecord dr;
  209410. props[prop].propClass = kQTPropertyClass_DataLocation;
  209411. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209412. props[prop].propValueSize = sizeof (dr);
  209413. props[prop].propValueAddress = &dr;
  209414. ++prop;
  209415. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209416. if (fin != 0)
  209417. {
  209418. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209419. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209420. &dr.dataRef, &dr.dataRefType);
  209421. ok = openMovie (props, prop, movie);
  209422. DisposeHandle (dr.dataRef);
  209423. CFRelease (filePath);
  209424. }
  209425. else
  209426. {
  209427. // sanity-check because this currently needs to load the whole stream into memory..
  209428. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209429. dataHandle = NewHandle ((Size) input->getTotalLength());
  209430. HLock (dataHandle);
  209431. // read the entire stream into memory - this is a pain, but can't get it to work
  209432. // properly using a custom callback to supply the data.
  209433. input->read (*dataHandle, (int) input->getTotalLength());
  209434. HUnlock (dataHandle);
  209435. // different types to get QT to try. (We should really be a bit smarter here by
  209436. // working out in advance which one the stream contains, rather than just trying
  209437. // each one)
  209438. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209439. "\04.avi", "\04.m4a" };
  209440. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209441. {
  209442. /* // this fails for some bizarre reason - it can be bodged to work with
  209443. // movies, but can't seem to do it for other file types..
  209444. QTNewMovieUserProcRecord procInfo;
  209445. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209446. procInfo.getMovieUserProcRefcon = this;
  209447. procInfo.defaultDataRef.dataRef = dataRef;
  209448. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209449. props[prop].propClass = kQTPropertyClass_DataLocation;
  209450. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209451. props[prop].propValueSize = sizeof (procInfo);
  209452. props[prop].propValueAddress = (void*) &procInfo;
  209453. ++prop; */
  209454. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209455. dr.dataRefType = HandleDataHandlerSubType;
  209456. ok = openMovie (props, prop, movie);
  209457. DisposeHandle (dr.dataRef);
  209458. }
  209459. }
  209460. return ok;
  209461. }
  209462. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209463. const bool isControllerVisible)
  209464. {
  209465. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209466. movieFile = movieFile_;
  209467. return ok;
  209468. }
  209469. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209470. const bool isControllerVisible)
  209471. {
  209472. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209473. }
  209474. void QuickTimeMovieComponent::goToStart()
  209475. {
  209476. setPosition (0.0);
  209477. }
  209478. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209479. const RectanglePlacement& placement)
  209480. {
  209481. int normalWidth, normalHeight;
  209482. getMovieNormalSize (normalWidth, normalHeight);
  209483. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  209484. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  209485. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  209486. else
  209487. setBounds (spaceToFitWithin);
  209488. }
  209489. #endif
  209490. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209491. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209492. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209493. // compiled on its own).
  209494. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209495. class WebBrowserComponentInternal : public ActiveXControlComponent
  209496. {
  209497. public:
  209498. WebBrowserComponentInternal()
  209499. : browser (0),
  209500. connectionPoint (0),
  209501. adviseCookie (0)
  209502. {
  209503. }
  209504. ~WebBrowserComponentInternal()
  209505. {
  209506. if (connectionPoint != 0)
  209507. connectionPoint->Unadvise (adviseCookie);
  209508. if (browser != 0)
  209509. browser->Release();
  209510. }
  209511. void createBrowser()
  209512. {
  209513. createControl (&CLSID_WebBrowser);
  209514. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209515. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209516. if (connectionPointContainer != 0)
  209517. {
  209518. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209519. &connectionPoint);
  209520. if (connectionPoint != 0)
  209521. {
  209522. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209523. jassert (owner != 0);
  209524. EventHandler* handler = new EventHandler (*owner);
  209525. connectionPoint->Advise (handler, &adviseCookie);
  209526. handler->Release();
  209527. }
  209528. }
  209529. }
  209530. void goToURL (const String& url,
  209531. const StringArray* headers,
  209532. const MemoryBlock* postData)
  209533. {
  209534. if (browser != 0)
  209535. {
  209536. LPSAFEARRAY sa = 0;
  209537. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209538. VariantInit (&flags);
  209539. VariantInit (&frame);
  209540. VariantInit (&postDataVar);
  209541. VariantInit (&headersVar);
  209542. if (headers != 0)
  209543. {
  209544. V_VT (&headersVar) = VT_BSTR;
  209545. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n").toUTF16().getAddress());
  209546. }
  209547. if (postData != 0 && postData->getSize() > 0)
  209548. {
  209549. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209550. if (sa != 0)
  209551. {
  209552. void* data = 0;
  209553. SafeArrayAccessData (sa, &data);
  209554. jassert (data != 0);
  209555. if (data != 0)
  209556. {
  209557. postData->copyTo (data, 0, postData->getSize());
  209558. SafeArrayUnaccessData (sa);
  209559. VARIANT postDataVar2;
  209560. VariantInit (&postDataVar2);
  209561. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209562. V_ARRAY (&postDataVar2) = sa;
  209563. postDataVar = postDataVar2;
  209564. }
  209565. }
  209566. }
  209567. browser->Navigate ((BSTR) (const OLECHAR*) url.toUTF16().getAddress(),
  209568. &flags, &frame,
  209569. &postDataVar, &headersVar);
  209570. if (sa != 0)
  209571. SafeArrayDestroy (sa);
  209572. VariantClear (&flags);
  209573. VariantClear (&frame);
  209574. VariantClear (&postDataVar);
  209575. VariantClear (&headersVar);
  209576. }
  209577. }
  209578. IWebBrowser2* browser;
  209579. private:
  209580. IConnectionPoint* connectionPoint;
  209581. DWORD adviseCookie;
  209582. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209583. public ComponentMovementWatcher
  209584. {
  209585. public:
  209586. EventHandler (WebBrowserComponent& owner_)
  209587. : ComponentMovementWatcher (&owner_),
  209588. owner (owner_)
  209589. {
  209590. }
  209591. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209592. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209593. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209594. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209595. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209596. {
  209597. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  209598. {
  209599. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209600. String url;
  209601. if ((vurl->vt & VT_BYREF) != 0)
  209602. url = *vurl->pbstrVal;
  209603. else
  209604. url = vurl->bstrVal;
  209605. *pDispParams->rgvarg->pboolVal
  209606. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  209607. : VARIANT_TRUE;
  209608. return S_OK;
  209609. }
  209610. return E_NOTIMPL;
  209611. }
  209612. void componentMovedOrResized (bool, bool ) {}
  209613. void componentPeerChanged() {}
  209614. void componentVisibilityChanged() { owner.visibilityChanged(); }
  209615. private:
  209616. WebBrowserComponent& owner;
  209617. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209618. };
  209619. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209620. };
  209621. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209622. : browser (0),
  209623. blankPageShown (false),
  209624. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209625. {
  209626. setOpaque (true);
  209627. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209628. }
  209629. WebBrowserComponent::~WebBrowserComponent()
  209630. {
  209631. delete browser;
  209632. }
  209633. void WebBrowserComponent::goToURL (const String& url,
  209634. const StringArray* headers,
  209635. const MemoryBlock* postData)
  209636. {
  209637. lastURL = url;
  209638. lastHeaders.clear();
  209639. if (headers != 0)
  209640. lastHeaders = *headers;
  209641. lastPostData.setSize (0);
  209642. if (postData != 0)
  209643. lastPostData = *postData;
  209644. blankPageShown = false;
  209645. browser->goToURL (url, headers, postData);
  209646. }
  209647. void WebBrowserComponent::stop()
  209648. {
  209649. if (browser->browser != 0)
  209650. browser->browser->Stop();
  209651. }
  209652. void WebBrowserComponent::goBack()
  209653. {
  209654. lastURL = String::empty;
  209655. blankPageShown = false;
  209656. if (browser->browser != 0)
  209657. browser->browser->GoBack();
  209658. }
  209659. void WebBrowserComponent::goForward()
  209660. {
  209661. lastURL = String::empty;
  209662. if (browser->browser != 0)
  209663. browser->browser->GoForward();
  209664. }
  209665. void WebBrowserComponent::refresh()
  209666. {
  209667. if (browser->browser != 0)
  209668. browser->browser->Refresh();
  209669. }
  209670. void WebBrowserComponent::paint (Graphics& g)
  209671. {
  209672. if (browser->browser == 0)
  209673. g.fillAll (Colours::white);
  209674. }
  209675. void WebBrowserComponent::checkWindowAssociation()
  209676. {
  209677. if (isShowing())
  209678. {
  209679. if (browser->browser == 0 && getPeer() != 0)
  209680. {
  209681. browser->createBrowser();
  209682. reloadLastURL();
  209683. }
  209684. else
  209685. {
  209686. if (blankPageShown)
  209687. goBack();
  209688. }
  209689. }
  209690. else
  209691. {
  209692. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209693. {
  209694. // when the component becomes invisible, some stuff like flash
  209695. // carries on playing audio, so we need to force it onto a blank
  209696. // page to avoid this..
  209697. blankPageShown = true;
  209698. browser->goToURL ("about:blank", 0, 0);
  209699. }
  209700. }
  209701. }
  209702. void WebBrowserComponent::reloadLastURL()
  209703. {
  209704. if (lastURL.isNotEmpty())
  209705. {
  209706. goToURL (lastURL, &lastHeaders, &lastPostData);
  209707. lastURL = String::empty;
  209708. }
  209709. }
  209710. void WebBrowserComponent::parentHierarchyChanged()
  209711. {
  209712. checkWindowAssociation();
  209713. }
  209714. void WebBrowserComponent::resized()
  209715. {
  209716. browser->setSize (getWidth(), getHeight());
  209717. }
  209718. void WebBrowserComponent::visibilityChanged()
  209719. {
  209720. checkWindowAssociation();
  209721. }
  209722. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209723. {
  209724. return true;
  209725. }
  209726. #endif
  209727. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209728. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209729. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209730. // compiled on its own).
  209731. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209732. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209733. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209734. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209735. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209736. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209737. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209738. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209739. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209740. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209741. #define WGL_ACCELERATION_ARB 0x2003
  209742. #define WGL_SWAP_METHOD_ARB 0x2007
  209743. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209744. #define WGL_PIXEL_TYPE_ARB 0x2013
  209745. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209746. #define WGL_COLOR_BITS_ARB 0x2014
  209747. #define WGL_RED_BITS_ARB 0x2015
  209748. #define WGL_GREEN_BITS_ARB 0x2017
  209749. #define WGL_BLUE_BITS_ARB 0x2019
  209750. #define WGL_ALPHA_BITS_ARB 0x201B
  209751. #define WGL_DEPTH_BITS_ARB 0x2022
  209752. #define WGL_STENCIL_BITS_ARB 0x2023
  209753. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209754. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209755. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209756. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209757. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209758. #define WGL_STEREO_ARB 0x2012
  209759. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209760. #define WGL_SAMPLES_ARB 0x2042
  209761. #define WGL_TYPE_RGBA_ARB 0x202B
  209762. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209763. {
  209764. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209765. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209766. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209767. else
  209768. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209769. }
  209770. class WindowedGLContext : public OpenGLContext
  209771. {
  209772. public:
  209773. WindowedGLContext (Component* const component_,
  209774. HGLRC contextToShareWith,
  209775. const OpenGLPixelFormat& pixelFormat)
  209776. : renderContext (0),
  209777. component (component_),
  209778. dc (0)
  209779. {
  209780. jassert (component != 0);
  209781. createNativeWindow();
  209782. // Use a default pixel format that should be supported everywhere
  209783. PIXELFORMATDESCRIPTOR pfd;
  209784. zerostruct (pfd);
  209785. pfd.nSize = sizeof (pfd);
  209786. pfd.nVersion = 1;
  209787. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209788. pfd.iPixelType = PFD_TYPE_RGBA;
  209789. pfd.cColorBits = 24;
  209790. pfd.cDepthBits = 16;
  209791. const int format = ChoosePixelFormat (dc, &pfd);
  209792. if (format != 0)
  209793. SetPixelFormat (dc, format, &pfd);
  209794. renderContext = wglCreateContext (dc);
  209795. makeActive();
  209796. setPixelFormat (pixelFormat);
  209797. if (contextToShareWith != 0 && renderContext != 0)
  209798. wglShareLists (contextToShareWith, renderContext);
  209799. }
  209800. ~WindowedGLContext()
  209801. {
  209802. deleteContext();
  209803. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209804. nativeWindow = 0;
  209805. }
  209806. void deleteContext()
  209807. {
  209808. makeInactive();
  209809. if (renderContext != 0)
  209810. {
  209811. wglDeleteContext (renderContext);
  209812. renderContext = 0;
  209813. }
  209814. }
  209815. bool makeActive() const throw()
  209816. {
  209817. jassert (renderContext != 0);
  209818. return wglMakeCurrent (dc, renderContext) != 0;
  209819. }
  209820. bool makeInactive() const throw()
  209821. {
  209822. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209823. }
  209824. bool isActive() const throw()
  209825. {
  209826. return wglGetCurrentContext() == renderContext;
  209827. }
  209828. const OpenGLPixelFormat getPixelFormat() const
  209829. {
  209830. OpenGLPixelFormat pf;
  209831. makeActive();
  209832. StringArray availableExtensions;
  209833. getWglExtensions (dc, availableExtensions);
  209834. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209835. return pf;
  209836. }
  209837. void* getRawContext() const throw()
  209838. {
  209839. return renderContext;
  209840. }
  209841. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209842. {
  209843. makeActive();
  209844. PIXELFORMATDESCRIPTOR pfd;
  209845. zerostruct (pfd);
  209846. pfd.nSize = sizeof (pfd);
  209847. pfd.nVersion = 1;
  209848. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  209849. pfd.iPixelType = PFD_TYPE_RGBA;
  209850. pfd.iLayerType = PFD_MAIN_PLANE;
  209851. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  209852. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  209853. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  209854. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  209855. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  209856. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  209857. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  209858. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  209859. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  209860. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  209861. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  209862. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  209863. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  209864. int format = 0;
  209865. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  209866. StringArray availableExtensions;
  209867. getWglExtensions (dc, availableExtensions);
  209868. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209869. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  209870. {
  209871. int attributes[64];
  209872. int n = 0;
  209873. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  209874. attributes[n++] = GL_TRUE;
  209875. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  209876. attributes[n++] = GL_TRUE;
  209877. attributes[n++] = WGL_ACCELERATION_ARB;
  209878. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  209879. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  209880. attributes[n++] = GL_TRUE;
  209881. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  209882. attributes[n++] = WGL_TYPE_RGBA_ARB;
  209883. attributes[n++] = WGL_COLOR_BITS_ARB;
  209884. attributes[n++] = pfd.cColorBits;
  209885. attributes[n++] = WGL_RED_BITS_ARB;
  209886. attributes[n++] = pixelFormat.redBits;
  209887. attributes[n++] = WGL_GREEN_BITS_ARB;
  209888. attributes[n++] = pixelFormat.greenBits;
  209889. attributes[n++] = WGL_BLUE_BITS_ARB;
  209890. attributes[n++] = pixelFormat.blueBits;
  209891. attributes[n++] = WGL_ALPHA_BITS_ARB;
  209892. attributes[n++] = pixelFormat.alphaBits;
  209893. attributes[n++] = WGL_DEPTH_BITS_ARB;
  209894. attributes[n++] = pixelFormat.depthBufferBits;
  209895. if (pixelFormat.stencilBufferBits > 0)
  209896. {
  209897. attributes[n++] = WGL_STENCIL_BITS_ARB;
  209898. attributes[n++] = pixelFormat.stencilBufferBits;
  209899. }
  209900. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  209901. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  209902. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  209903. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  209904. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  209905. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  209906. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  209907. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  209908. if (availableExtensions.contains ("WGL_ARB_multisample")
  209909. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  209910. {
  209911. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  209912. attributes[n++] = 1;
  209913. attributes[n++] = WGL_SAMPLES_ARB;
  209914. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  209915. }
  209916. attributes[n++] = 0;
  209917. UINT formatsCount;
  209918. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  209919. (void) ok;
  209920. jassert (ok);
  209921. }
  209922. else
  209923. {
  209924. format = ChoosePixelFormat (dc, &pfd);
  209925. }
  209926. if (format != 0)
  209927. {
  209928. makeInactive();
  209929. // win32 can't change the pixel format of a window, so need to delete the
  209930. // old one and create a new one..
  209931. jassert (nativeWindow != 0);
  209932. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209933. nativeWindow = 0;
  209934. createNativeWindow();
  209935. if (SetPixelFormat (dc, format, &pfd))
  209936. {
  209937. wglDeleteContext (renderContext);
  209938. renderContext = wglCreateContext (dc);
  209939. jassert (renderContext != 0);
  209940. return renderContext != 0;
  209941. }
  209942. }
  209943. return false;
  209944. }
  209945. void updateWindowPosition (int x, int y, int w, int h, int)
  209946. {
  209947. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  209948. x, y, w, h,
  209949. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  209950. }
  209951. void repaint()
  209952. {
  209953. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  209954. }
  209955. void swapBuffers()
  209956. {
  209957. SwapBuffers (dc);
  209958. }
  209959. bool setSwapInterval (int numFramesPerSwap)
  209960. {
  209961. makeActive();
  209962. StringArray availableExtensions;
  209963. getWglExtensions (dc, availableExtensions);
  209964. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  209965. return availableExtensions.contains ("WGL_EXT_swap_control")
  209966. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  209967. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  209968. }
  209969. int getSwapInterval() const
  209970. {
  209971. makeActive();
  209972. StringArray availableExtensions;
  209973. getWglExtensions (dc, availableExtensions);
  209974. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  209975. if (availableExtensions.contains ("WGL_EXT_swap_control")
  209976. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  209977. return wglGetSwapIntervalEXT();
  209978. return 0;
  209979. }
  209980. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  209981. {
  209982. jassert (isActive());
  209983. StringArray availableExtensions;
  209984. getWglExtensions (dc, availableExtensions);
  209985. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  209986. int numTypes = 0;
  209987. if (availableExtensions.contains("WGL_ARB_pixel_format")
  209988. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  209989. {
  209990. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  209991. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  209992. jassertfalse;
  209993. }
  209994. else
  209995. {
  209996. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  209997. }
  209998. OpenGLPixelFormat pf;
  209999. for (int i = 0; i < numTypes; ++i)
  210000. {
  210001. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210002. {
  210003. bool alreadyListed = false;
  210004. for (int j = results.size(); --j >= 0;)
  210005. if (pf == *results.getUnchecked(j))
  210006. alreadyListed = true;
  210007. if (! alreadyListed)
  210008. results.add (new OpenGLPixelFormat (pf));
  210009. }
  210010. }
  210011. }
  210012. void* getNativeWindowHandle() const
  210013. {
  210014. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210015. }
  210016. HGLRC renderContext;
  210017. private:
  210018. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210019. Component* const component;
  210020. HDC dc;
  210021. void createNativeWindow()
  210022. {
  210023. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210024. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210025. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210026. nativeWindow->dontRepaint = true;
  210027. nativeWindow->setVisible (true);
  210028. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210029. }
  210030. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210031. OpenGLPixelFormat& result,
  210032. const StringArray& availableExtensions) const throw()
  210033. {
  210034. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210035. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210036. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210037. {
  210038. int attributes[32];
  210039. int numAttributes = 0;
  210040. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210041. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210042. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210043. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210044. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210045. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210046. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210047. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210048. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210049. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210050. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210051. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210052. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210053. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210054. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210055. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210056. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210057. int values[32];
  210058. zeromem (values, sizeof (values));
  210059. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210060. {
  210061. int n = 0;
  210062. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210063. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210064. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210065. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210066. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210067. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210068. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210069. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210070. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210071. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210072. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210073. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210074. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210075. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210076. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210077. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210078. return isValidFormat;
  210079. }
  210080. else
  210081. {
  210082. jassertfalse;
  210083. }
  210084. }
  210085. else
  210086. {
  210087. PIXELFORMATDESCRIPTOR pfd;
  210088. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210089. {
  210090. result.redBits = pfd.cRedBits;
  210091. result.greenBits = pfd.cGreenBits;
  210092. result.blueBits = pfd.cBlueBits;
  210093. result.alphaBits = pfd.cAlphaBits;
  210094. result.depthBufferBits = pfd.cDepthBits;
  210095. result.stencilBufferBits = pfd.cStencilBits;
  210096. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210097. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210098. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210099. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210100. result.fullSceneAntiAliasingNumSamples = 0;
  210101. return true;
  210102. }
  210103. else
  210104. {
  210105. jassertfalse;
  210106. }
  210107. }
  210108. return false;
  210109. }
  210110. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210111. };
  210112. OpenGLContext* OpenGLComponent::createContext()
  210113. {
  210114. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210115. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210116. preferredPixelFormat));
  210117. return (c->renderContext != 0) ? c.release() : 0;
  210118. }
  210119. void* OpenGLComponent::getNativeWindowHandle() const
  210120. {
  210121. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210122. }
  210123. void juce_glViewport (const int w, const int h)
  210124. {
  210125. glViewport (0, 0, w, h);
  210126. }
  210127. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210128. OwnedArray <OpenGLPixelFormat>& results)
  210129. {
  210130. Component tempComp;
  210131. {
  210132. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210133. wc.makeActive();
  210134. wc.findAlternativeOpenGLPixelFormats (results);
  210135. }
  210136. }
  210137. #endif
  210138. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210139. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210140. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210141. // compiled on its own).
  210142. #if JUCE_INCLUDED_FILE
  210143. #if JUCE_USE_CDREADER
  210144. namespace CDReaderHelpers
  210145. {
  210146. #define FILE_ANY_ACCESS 0
  210147. #ifndef FILE_READ_ACCESS
  210148. #define FILE_READ_ACCESS 1
  210149. #endif
  210150. #ifndef FILE_WRITE_ACCESS
  210151. #define FILE_WRITE_ACCESS 2
  210152. #endif
  210153. #define METHOD_BUFFERED 0
  210154. #define IOCTL_SCSI_BASE 4
  210155. #define SCSI_IOCTL_DATA_OUT 0
  210156. #define SCSI_IOCTL_DATA_IN 1
  210157. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210158. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210159. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210160. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210161. #define SENSE_LEN 14
  210162. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210163. #define SRB_DIR_IN 0x08
  210164. #define SRB_DIR_OUT 0x10
  210165. #define SRB_EVENT_NOTIFY 0x40
  210166. #define SC_HA_INQUIRY 0x00
  210167. #define SC_GET_DEV_TYPE 0x01
  210168. #define SC_EXEC_SCSI_CMD 0x02
  210169. #define SS_PENDING 0x00
  210170. #define SS_COMP 0x01
  210171. #define SS_ERR 0x04
  210172. enum
  210173. {
  210174. READTYPE_ANY = 0,
  210175. READTYPE_ATAPI1 = 1,
  210176. READTYPE_ATAPI2 = 2,
  210177. READTYPE_READ6 = 3,
  210178. READTYPE_READ10 = 4,
  210179. READTYPE_READ_D8 = 5,
  210180. READTYPE_READ_D4 = 6,
  210181. READTYPE_READ_D4_1 = 7,
  210182. READTYPE_READ10_2 = 8
  210183. };
  210184. struct SCSI_PASS_THROUGH
  210185. {
  210186. USHORT Length;
  210187. UCHAR ScsiStatus;
  210188. UCHAR PathId;
  210189. UCHAR TargetId;
  210190. UCHAR Lun;
  210191. UCHAR CdbLength;
  210192. UCHAR SenseInfoLength;
  210193. UCHAR DataIn;
  210194. ULONG DataTransferLength;
  210195. ULONG TimeOutValue;
  210196. ULONG DataBufferOffset;
  210197. ULONG SenseInfoOffset;
  210198. UCHAR Cdb[16];
  210199. };
  210200. struct SCSI_PASS_THROUGH_DIRECT
  210201. {
  210202. USHORT Length;
  210203. UCHAR ScsiStatus;
  210204. UCHAR PathId;
  210205. UCHAR TargetId;
  210206. UCHAR Lun;
  210207. UCHAR CdbLength;
  210208. UCHAR SenseInfoLength;
  210209. UCHAR DataIn;
  210210. ULONG DataTransferLength;
  210211. ULONG TimeOutValue;
  210212. PVOID DataBuffer;
  210213. ULONG SenseInfoOffset;
  210214. UCHAR Cdb[16];
  210215. };
  210216. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210217. {
  210218. SCSI_PASS_THROUGH_DIRECT spt;
  210219. ULONG Filler;
  210220. UCHAR ucSenseBuf[32];
  210221. };
  210222. struct SCSI_ADDRESS
  210223. {
  210224. ULONG Length;
  210225. UCHAR PortNumber;
  210226. UCHAR PathId;
  210227. UCHAR TargetId;
  210228. UCHAR Lun;
  210229. };
  210230. #pragma pack(1)
  210231. struct SRB_GDEVBlock
  210232. {
  210233. BYTE SRB_Cmd;
  210234. BYTE SRB_Status;
  210235. BYTE SRB_HaID;
  210236. BYTE SRB_Flags;
  210237. DWORD SRB_Hdr_Rsvd;
  210238. BYTE SRB_Target;
  210239. BYTE SRB_Lun;
  210240. BYTE SRB_DeviceType;
  210241. BYTE SRB_Rsvd1;
  210242. BYTE pad[68];
  210243. };
  210244. struct SRB_ExecSCSICmd
  210245. {
  210246. BYTE SRB_Cmd;
  210247. BYTE SRB_Status;
  210248. BYTE SRB_HaID;
  210249. BYTE SRB_Flags;
  210250. DWORD SRB_Hdr_Rsvd;
  210251. BYTE SRB_Target;
  210252. BYTE SRB_Lun;
  210253. WORD SRB_Rsvd1;
  210254. DWORD SRB_BufLen;
  210255. BYTE *SRB_BufPointer;
  210256. BYTE SRB_SenseLen;
  210257. BYTE SRB_CDBLen;
  210258. BYTE SRB_HaStat;
  210259. BYTE SRB_TargStat;
  210260. VOID *SRB_PostProc;
  210261. BYTE SRB_Rsvd2[20];
  210262. BYTE CDBByte[16];
  210263. BYTE SenseArea[SENSE_LEN + 2];
  210264. };
  210265. struct SRB
  210266. {
  210267. BYTE SRB_Cmd;
  210268. BYTE SRB_Status;
  210269. BYTE SRB_HaId;
  210270. BYTE SRB_Flags;
  210271. DWORD SRB_Hdr_Rsvd;
  210272. };
  210273. struct TOCTRACK
  210274. {
  210275. BYTE rsvd;
  210276. BYTE ADR;
  210277. BYTE trackNumber;
  210278. BYTE rsvd2;
  210279. BYTE addr[4];
  210280. };
  210281. struct TOC
  210282. {
  210283. WORD tocLen;
  210284. BYTE firstTrack;
  210285. BYTE lastTrack;
  210286. TOCTRACK tracks[100];
  210287. };
  210288. #pragma pack()
  210289. struct CDDeviceDescription
  210290. {
  210291. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210292. {
  210293. }
  210294. void createDescription (const char* data)
  210295. {
  210296. description << String (data + 8, 8).trim() // vendor
  210297. << ' ' << String (data + 16, 16).trim() // product id
  210298. << ' ' << String (data + 32, 4).trim(); // rev
  210299. }
  210300. String description;
  210301. BYTE ha, tgt, lun;
  210302. char scsiDriveLetter; // will be 0 if not using scsi
  210303. };
  210304. class CDReadBuffer
  210305. {
  210306. public:
  210307. CDReadBuffer (const int numberOfFrames)
  210308. : startFrame (0), numFrames (0), dataStartOffset (0),
  210309. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210310. buffer (bufferSize), wantsIndex (false)
  210311. {
  210312. }
  210313. bool isZero() const throw()
  210314. {
  210315. for (int i = 0; i < dataLength; ++i)
  210316. if (buffer [dataStartOffset + i] != 0)
  210317. return false;
  210318. return true;
  210319. }
  210320. int startFrame, numFrames, dataStartOffset;
  210321. int dataLength, bufferSize, index;
  210322. HeapBlock<BYTE> buffer;
  210323. bool wantsIndex;
  210324. };
  210325. class CDDeviceHandle;
  210326. class CDController
  210327. {
  210328. public:
  210329. CDController() : initialised (false) {}
  210330. virtual ~CDController() {}
  210331. virtual bool read (CDReadBuffer&) = 0;
  210332. virtual void shutDown() {}
  210333. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210334. int getLastIndex();
  210335. public:
  210336. CDDeviceHandle* deviceInfo;
  210337. int framesToCheck, framesOverlap;
  210338. bool initialised;
  210339. void prepare (SRB_ExecSCSICmd& s);
  210340. void perform (SRB_ExecSCSICmd& s);
  210341. void setPaused (bool paused);
  210342. };
  210343. class CDDeviceHandle
  210344. {
  210345. public:
  210346. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210347. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210348. {
  210349. }
  210350. ~CDDeviceHandle()
  210351. {
  210352. if (controller != 0)
  210353. {
  210354. controller->shutDown();
  210355. controller = 0;
  210356. }
  210357. if (scsiHandle != 0)
  210358. CloseHandle (scsiHandle);
  210359. }
  210360. bool readTOC (TOC* lpToc);
  210361. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210362. void openDrawer (bool shouldBeOpen);
  210363. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210364. CDDeviceDescription info;
  210365. HANDLE scsiHandle;
  210366. BYTE readType;
  210367. private:
  210368. ScopedPointer<CDController> controller;
  210369. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210370. };
  210371. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210372. {
  210373. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210374. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210375. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210376. if (h == INVALID_HANDLE_VALUE)
  210377. {
  210378. flags ^= GENERIC_WRITE;
  210379. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210380. }
  210381. return h;
  210382. }
  210383. void findCDDevices (Array<CDDeviceDescription>& list)
  210384. {
  210385. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210386. {
  210387. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210388. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210389. {
  210390. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210391. if (h != INVALID_HANDLE_VALUE)
  210392. {
  210393. char buffer[100];
  210394. zeromem (buffer, sizeof (buffer));
  210395. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210396. zerostruct (p);
  210397. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210398. p.spt.CdbLength = 6;
  210399. p.spt.SenseInfoLength = 24;
  210400. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210401. p.spt.DataTransferLength = sizeof (buffer);
  210402. p.spt.TimeOutValue = 2;
  210403. p.spt.DataBuffer = buffer;
  210404. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210405. p.spt.Cdb[0] = 0x12;
  210406. p.spt.Cdb[4] = 100;
  210407. DWORD bytesReturned = 0;
  210408. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210409. &p, sizeof (p), &p, sizeof (p),
  210410. &bytesReturned, 0) != 0)
  210411. {
  210412. CDDeviceDescription dev;
  210413. dev.scsiDriveLetter = driveLetter;
  210414. dev.createDescription (buffer);
  210415. SCSI_ADDRESS scsiAddr;
  210416. zerostruct (scsiAddr);
  210417. scsiAddr.Length = sizeof (scsiAddr);
  210418. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210419. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210420. &bytesReturned, 0) != 0)
  210421. {
  210422. dev.ha = scsiAddr.PortNumber;
  210423. dev.tgt = scsiAddr.TargetId;
  210424. dev.lun = scsiAddr.Lun;
  210425. list.add (dev);
  210426. }
  210427. }
  210428. CloseHandle (h);
  210429. }
  210430. }
  210431. }
  210432. }
  210433. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210434. HANDLE& deviceHandle, const bool retryOnFailure)
  210435. {
  210436. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210437. zerostruct (s);
  210438. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210439. s.spt.CdbLength = srb->SRB_CDBLen;
  210440. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210441. ? SCSI_IOCTL_DATA_IN
  210442. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210443. ? SCSI_IOCTL_DATA_OUT
  210444. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210445. s.spt.DataTransferLength = srb->SRB_BufLen;
  210446. s.spt.TimeOutValue = 5;
  210447. s.spt.DataBuffer = srb->SRB_BufPointer;
  210448. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210449. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210450. srb->SRB_Status = SS_ERR;
  210451. srb->SRB_TargStat = 0x0004;
  210452. DWORD bytesReturned = 0;
  210453. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210454. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210455. {
  210456. srb->SRB_Status = SS_COMP;
  210457. }
  210458. else if (retryOnFailure)
  210459. {
  210460. const DWORD error = GetLastError();
  210461. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210462. {
  210463. if (error != ERROR_INVALID_HANDLE)
  210464. CloseHandle (deviceHandle);
  210465. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210466. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210467. }
  210468. }
  210469. return srb->SRB_Status;
  210470. }
  210471. // Controller types..
  210472. class ControllerType1 : public CDController
  210473. {
  210474. public:
  210475. ControllerType1() {}
  210476. bool read (CDReadBuffer& rb)
  210477. {
  210478. if (rb.numFrames * 2352 > rb.bufferSize)
  210479. return false;
  210480. SRB_ExecSCSICmd s;
  210481. prepare (s);
  210482. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210483. s.SRB_BufLen = rb.bufferSize;
  210484. s.SRB_BufPointer = rb.buffer;
  210485. s.SRB_CDBLen = 12;
  210486. s.CDBByte[0] = 0xBE;
  210487. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210488. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210489. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210490. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210491. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210492. perform (s);
  210493. if (s.SRB_Status != SS_COMP)
  210494. return false;
  210495. rb.dataLength = rb.numFrames * 2352;
  210496. rb.dataStartOffset = 0;
  210497. return true;
  210498. }
  210499. };
  210500. class ControllerType2 : public CDController
  210501. {
  210502. public:
  210503. ControllerType2() {}
  210504. void shutDown()
  210505. {
  210506. if (initialised)
  210507. {
  210508. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210509. SRB_ExecSCSICmd s;
  210510. prepare (s);
  210511. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210512. s.SRB_BufLen = 0x0C;
  210513. s.SRB_BufPointer = bufPointer;
  210514. s.SRB_CDBLen = 6;
  210515. s.CDBByte[0] = 0x15;
  210516. s.CDBByte[4] = 0x0C;
  210517. perform (s);
  210518. }
  210519. }
  210520. bool init()
  210521. {
  210522. SRB_ExecSCSICmd s;
  210523. s.SRB_Status = SS_ERR;
  210524. if (deviceInfo->readType == READTYPE_READ10_2)
  210525. {
  210526. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210527. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210528. for (int i = 0; i < 2; ++i)
  210529. {
  210530. prepare (s);
  210531. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210532. s.SRB_BufLen = 0x14;
  210533. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210534. s.SRB_CDBLen = 6;
  210535. s.CDBByte[0] = 0x15;
  210536. s.CDBByte[1] = 0x10;
  210537. s.CDBByte[4] = 0x14;
  210538. perform (s);
  210539. if (s.SRB_Status != SS_COMP)
  210540. return false;
  210541. }
  210542. }
  210543. else
  210544. {
  210545. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210546. prepare (s);
  210547. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210548. s.SRB_BufLen = 0x0C;
  210549. s.SRB_BufPointer = bufPointer;
  210550. s.SRB_CDBLen = 6;
  210551. s.CDBByte[0] = 0x15;
  210552. s.CDBByte[4] = 0x0C;
  210553. perform (s);
  210554. }
  210555. return s.SRB_Status == SS_COMP;
  210556. }
  210557. bool read (CDReadBuffer& rb)
  210558. {
  210559. if (rb.numFrames * 2352 > rb.bufferSize)
  210560. return false;
  210561. if (! initialised)
  210562. {
  210563. initialised = init();
  210564. if (! initialised)
  210565. return false;
  210566. }
  210567. SRB_ExecSCSICmd s;
  210568. prepare (s);
  210569. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210570. s.SRB_BufLen = rb.bufferSize;
  210571. s.SRB_BufPointer = rb.buffer;
  210572. s.SRB_CDBLen = 10;
  210573. s.CDBByte[0] = 0x28;
  210574. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210575. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210576. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210577. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210578. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210579. perform (s);
  210580. if (s.SRB_Status != SS_COMP)
  210581. return false;
  210582. rb.dataLength = rb.numFrames * 2352;
  210583. rb.dataStartOffset = 0;
  210584. return true;
  210585. }
  210586. };
  210587. class ControllerType3 : public CDController
  210588. {
  210589. public:
  210590. ControllerType3() {}
  210591. bool read (CDReadBuffer& rb)
  210592. {
  210593. if (rb.numFrames * 2352 > rb.bufferSize)
  210594. return false;
  210595. if (! initialised)
  210596. {
  210597. setPaused (false);
  210598. initialised = true;
  210599. }
  210600. SRB_ExecSCSICmd s;
  210601. prepare (s);
  210602. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210603. s.SRB_BufLen = rb.numFrames * 2352;
  210604. s.SRB_BufPointer = rb.buffer;
  210605. s.SRB_CDBLen = 12;
  210606. s.CDBByte[0] = 0xD8;
  210607. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210608. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210609. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210610. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  210611. perform (s);
  210612. if (s.SRB_Status != SS_COMP)
  210613. return false;
  210614. rb.dataLength = rb.numFrames * 2352;
  210615. rb.dataStartOffset = 0;
  210616. return true;
  210617. }
  210618. };
  210619. class ControllerType4 : public CDController
  210620. {
  210621. public:
  210622. ControllerType4() {}
  210623. bool selectD4Mode()
  210624. {
  210625. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  210626. SRB_ExecSCSICmd s;
  210627. prepare (s);
  210628. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210629. s.SRB_CDBLen = 6;
  210630. s.SRB_BufLen = 12;
  210631. s.SRB_BufPointer = bufPointer;
  210632. s.CDBByte[0] = 0x15;
  210633. s.CDBByte[1] = 0x10;
  210634. s.CDBByte[4] = 0x08;
  210635. perform (s);
  210636. return s.SRB_Status == SS_COMP;
  210637. }
  210638. bool read (CDReadBuffer& rb)
  210639. {
  210640. if (rb.numFrames * 2352 > rb.bufferSize)
  210641. return false;
  210642. if (! initialised)
  210643. {
  210644. setPaused (true);
  210645. if (deviceInfo->readType == READTYPE_READ_D4_1)
  210646. selectD4Mode();
  210647. initialised = true;
  210648. }
  210649. SRB_ExecSCSICmd s;
  210650. prepare (s);
  210651. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210652. s.SRB_BufLen = rb.bufferSize;
  210653. s.SRB_BufPointer = rb.buffer;
  210654. s.SRB_CDBLen = 10;
  210655. s.CDBByte[0] = 0xD4;
  210656. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210657. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210658. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210659. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210660. perform (s);
  210661. if (s.SRB_Status != SS_COMP)
  210662. return false;
  210663. rb.dataLength = rb.numFrames * 2352;
  210664. rb.dataStartOffset = 0;
  210665. return true;
  210666. }
  210667. };
  210668. void CDController::prepare (SRB_ExecSCSICmd& s)
  210669. {
  210670. zerostruct (s);
  210671. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210672. s.SRB_HaID = deviceInfo->info.ha;
  210673. s.SRB_Target = deviceInfo->info.tgt;
  210674. s.SRB_Lun = deviceInfo->info.lun;
  210675. s.SRB_SenseLen = SENSE_LEN;
  210676. }
  210677. void CDController::perform (SRB_ExecSCSICmd& s)
  210678. {
  210679. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210680. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  210681. }
  210682. void CDController::setPaused (bool paused)
  210683. {
  210684. SRB_ExecSCSICmd s;
  210685. prepare (s);
  210686. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210687. s.SRB_CDBLen = 10;
  210688. s.CDBByte[0] = 0x4B;
  210689. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  210690. perform (s);
  210691. }
  210692. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  210693. {
  210694. if (overlapBuffer != 0)
  210695. {
  210696. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  210697. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  210698. if (doJitter
  210699. && overlapBuffer->startFrame > 0
  210700. && overlapBuffer->numFrames > 0
  210701. && overlapBuffer->dataLength > 0)
  210702. {
  210703. const int numFrames = rb.numFrames;
  210704. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  210705. {
  210706. rb.startFrame -= framesOverlap;
  210707. if (framesToCheck < framesOverlap
  210708. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  210709. rb.numFrames += framesOverlap;
  210710. }
  210711. else
  210712. {
  210713. overlapBuffer->dataLength = 0;
  210714. overlapBuffer->startFrame = 0;
  210715. overlapBuffer->numFrames = 0;
  210716. }
  210717. }
  210718. if (! read (rb))
  210719. return false;
  210720. if (doJitter)
  210721. {
  210722. const int checkLen = framesToCheck * 2352;
  210723. const int maxToCheck = rb.dataLength - checkLen;
  210724. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  210725. return true;
  210726. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  210727. bool found = false;
  210728. for (int i = 0; i < maxToCheck; ++i)
  210729. {
  210730. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  210731. {
  210732. i += checkLen;
  210733. rb.dataStartOffset = i;
  210734. rb.dataLength -= i;
  210735. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  210736. found = true;
  210737. break;
  210738. }
  210739. }
  210740. rb.numFrames = rb.dataLength / 2352;
  210741. rb.dataLength = 2352 * rb.numFrames;
  210742. if (! found)
  210743. return false;
  210744. }
  210745. if (canDoJitter)
  210746. {
  210747. memcpy (overlapBuffer->buffer,
  210748. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  210749. 2352 * framesToCheck);
  210750. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  210751. overlapBuffer->numFrames = framesToCheck;
  210752. overlapBuffer->dataLength = 2352 * framesToCheck;
  210753. overlapBuffer->dataStartOffset = 0;
  210754. }
  210755. else
  210756. {
  210757. overlapBuffer->startFrame = 0;
  210758. overlapBuffer->numFrames = 0;
  210759. overlapBuffer->dataLength = 0;
  210760. }
  210761. return true;
  210762. }
  210763. return read (rb);
  210764. }
  210765. int CDController::getLastIndex()
  210766. {
  210767. char qdata[100];
  210768. SRB_ExecSCSICmd s;
  210769. prepare (s);
  210770. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210771. s.SRB_BufLen = sizeof (qdata);
  210772. s.SRB_BufPointer = (BYTE*) qdata;
  210773. s.SRB_CDBLen = 12;
  210774. s.CDBByte[0] = 0x42;
  210775. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210776. s.CDBByte[2] = 64;
  210777. s.CDBByte[3] = 1; // get current position
  210778. s.CDBByte[7] = 0;
  210779. s.CDBByte[8] = (BYTE) sizeof (qdata);
  210780. perform (s);
  210781. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  210782. }
  210783. bool CDDeviceHandle::readTOC (TOC* lpToc)
  210784. {
  210785. SRB_ExecSCSICmd s;
  210786. zerostruct (s);
  210787. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210788. s.SRB_HaID = info.ha;
  210789. s.SRB_Target = info.tgt;
  210790. s.SRB_Lun = info.lun;
  210791. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210792. s.SRB_BufLen = 0x324;
  210793. s.SRB_BufPointer = (BYTE*) lpToc;
  210794. s.SRB_SenseLen = 0x0E;
  210795. s.SRB_CDBLen = 0x0A;
  210796. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210797. s.CDBByte[0] = 0x43;
  210798. s.CDBByte[1] = 0x00;
  210799. s.CDBByte[7] = 0x03;
  210800. s.CDBByte[8] = 0x24;
  210801. performScsiCommand (s.SRB_PostProc, s);
  210802. return (s.SRB_Status == SS_COMP);
  210803. }
  210804. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  210805. {
  210806. ResetEvent (event);
  210807. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  210808. if (status == SS_PENDING)
  210809. WaitForSingleObject (event, 4000);
  210810. CloseHandle (event);
  210811. }
  210812. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  210813. {
  210814. if (controller == 0)
  210815. {
  210816. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  210817. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  210818. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  210819. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  210820. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  210821. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  210822. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  210823. }
  210824. buffer.index = 0;
  210825. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  210826. {
  210827. if (buffer.wantsIndex)
  210828. buffer.index = controller->getLastIndex();
  210829. return true;
  210830. }
  210831. return false;
  210832. }
  210833. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210834. {
  210835. if (shouldBeOpen)
  210836. {
  210837. if (controller != 0)
  210838. {
  210839. controller->shutDown();
  210840. controller = 0;
  210841. }
  210842. if (scsiHandle != 0)
  210843. {
  210844. CloseHandle (scsiHandle);
  210845. scsiHandle = 0;
  210846. }
  210847. }
  210848. SRB_ExecSCSICmd s;
  210849. zerostruct (s);
  210850. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210851. s.SRB_HaID = info.ha;
  210852. s.SRB_Target = info.tgt;
  210853. s.SRB_Lun = info.lun;
  210854. s.SRB_SenseLen = SENSE_LEN;
  210855. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210856. s.SRB_BufLen = 0;
  210857. s.SRB_BufPointer = 0;
  210858. s.SRB_CDBLen = 12;
  210859. s.CDBByte[0] = 0x1b;
  210860. s.CDBByte[1] = (BYTE) (info.lun << 5);
  210861. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  210862. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210863. performScsiCommand (s.SRB_PostProc, s);
  210864. }
  210865. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  210866. {
  210867. controller = newController;
  210868. readType = (BYTE) type;
  210869. controller->deviceInfo = this;
  210870. controller->framesToCheck = 1;
  210871. controller->framesOverlap = 3;
  210872. bool passed = false;
  210873. memset (rb.buffer, 0xcd, rb.bufferSize);
  210874. if (controller->read (rb))
  210875. {
  210876. passed = true;
  210877. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  210878. int wrong = 0;
  210879. for (int i = rb.dataLength / 4; --i >= 0;)
  210880. {
  210881. if (*p++ == (int) 0xcdcdcdcd)
  210882. {
  210883. if (++wrong == 4)
  210884. {
  210885. passed = false;
  210886. break;
  210887. }
  210888. }
  210889. else
  210890. {
  210891. wrong = 0;
  210892. }
  210893. }
  210894. }
  210895. if (! passed)
  210896. {
  210897. controller->shutDown();
  210898. controller = 0;
  210899. }
  210900. return passed;
  210901. }
  210902. struct CDDeviceWrapper
  210903. {
  210904. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  210905. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  210906. {
  210907. // xxx jitter never seemed to actually be enabled (??)
  210908. }
  210909. CDDeviceHandle deviceHandle;
  210910. CDReadBuffer overlapBuffer;
  210911. bool jitter;
  210912. };
  210913. int getAddressOfTrack (const TOCTRACK& t) throw()
  210914. {
  210915. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  210916. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  210917. }
  210918. const int samplesPerFrame = 44100 / 75;
  210919. const int bytesPerFrame = samplesPerFrame * 4;
  210920. const int framesPerIndexRead = 4;
  210921. }
  210922. const StringArray AudioCDReader::getAvailableCDNames()
  210923. {
  210924. using namespace CDReaderHelpers;
  210925. StringArray results;
  210926. Array<CDDeviceDescription> list;
  210927. findCDDevices (list);
  210928. for (int i = 0; i < list.size(); ++i)
  210929. {
  210930. String s;
  210931. if (list[i].scsiDriveLetter > 0)
  210932. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210933. s << list[i].description;
  210934. results.add (s);
  210935. }
  210936. return results;
  210937. }
  210938. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210939. {
  210940. using namespace CDReaderHelpers;
  210941. Array<CDDeviceDescription> list;
  210942. findCDDevices (list);
  210943. if (isPositiveAndBelow (deviceIndex, list.size()))
  210944. {
  210945. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  210946. if (h != INVALID_HANDLE_VALUE)
  210947. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  210948. }
  210949. return 0;
  210950. }
  210951. AudioCDReader::AudioCDReader (void* handle_)
  210952. : AudioFormatReader (0, "CD Audio"),
  210953. handle (handle_),
  210954. indexingEnabled (false),
  210955. lastIndex (0),
  210956. firstFrameInBuffer (0),
  210957. samplesInBuffer (0)
  210958. {
  210959. using namespace CDReaderHelpers;
  210960. jassert (handle_ != 0);
  210961. refreshTrackLengths();
  210962. sampleRate = 44100.0;
  210963. bitsPerSample = 16;
  210964. numChannels = 2;
  210965. usesFloatingPointData = false;
  210966. buffer.setSize (4 * bytesPerFrame, true);
  210967. }
  210968. AudioCDReader::~AudioCDReader()
  210969. {
  210970. using namespace CDReaderHelpers;
  210971. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210972. delete device;
  210973. }
  210974. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210975. int64 startSampleInFile, int numSamples)
  210976. {
  210977. using namespace CDReaderHelpers;
  210978. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210979. bool ok = true;
  210980. while (numSamples > 0)
  210981. {
  210982. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210983. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210984. if (startSampleInFile >= bufferStartSample
  210985. && startSampleInFile < bufferEndSample)
  210986. {
  210987. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210988. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210989. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210990. const short* src = (const short*) buffer.getData();
  210991. src += 2 * (startSampleInFile - bufferStartSample);
  210992. for (int i = 0; i < toDo; ++i)
  210993. {
  210994. l[i] = src [i << 1] << 16;
  210995. if (r != 0)
  210996. r[i] = src [(i << 1) + 1] << 16;
  210997. }
  210998. startOffsetInDestBuffer += toDo;
  210999. startSampleInFile += toDo;
  211000. numSamples -= toDo;
  211001. }
  211002. else
  211003. {
  211004. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211005. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211006. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211007. {
  211008. device->overlapBuffer.dataLength = 0;
  211009. device->overlapBuffer.startFrame = 0;
  211010. device->overlapBuffer.numFrames = 0;
  211011. device->jitter = false;
  211012. }
  211013. firstFrameInBuffer = frameNeeded;
  211014. lastIndex = 0;
  211015. CDReadBuffer readBuffer (framesInBuffer + 4);
  211016. readBuffer.wantsIndex = indexingEnabled;
  211017. int i;
  211018. for (i = 5; --i >= 0;)
  211019. {
  211020. readBuffer.startFrame = frameNeeded;
  211021. readBuffer.numFrames = framesInBuffer;
  211022. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211023. break;
  211024. else
  211025. device->overlapBuffer.dataLength = 0;
  211026. }
  211027. if (i >= 0)
  211028. {
  211029. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211030. samplesInBuffer = readBuffer.dataLength >> 2;
  211031. lastIndex = readBuffer.index;
  211032. }
  211033. else
  211034. {
  211035. int* l = destSamples[0] + startOffsetInDestBuffer;
  211036. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211037. while (--numSamples >= 0)
  211038. {
  211039. *l++ = 0;
  211040. if (r != 0)
  211041. *r++ = 0;
  211042. }
  211043. // sometimes the read fails for just the very last couple of blocks, so
  211044. // we'll ignore and errors in the last half-second of the disk..
  211045. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211046. break;
  211047. }
  211048. }
  211049. }
  211050. return ok;
  211051. }
  211052. bool AudioCDReader::isCDStillPresent() const
  211053. {
  211054. using namespace CDReaderHelpers;
  211055. TOC toc;
  211056. zerostruct (toc);
  211057. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211058. }
  211059. void AudioCDReader::refreshTrackLengths()
  211060. {
  211061. using namespace CDReaderHelpers;
  211062. trackStartSamples.clear();
  211063. zeromem (audioTracks, sizeof (audioTracks));
  211064. TOC toc;
  211065. zerostruct (toc);
  211066. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211067. {
  211068. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211069. for (int i = 0; i <= numTracks; ++i)
  211070. {
  211071. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211072. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211073. }
  211074. }
  211075. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211076. }
  211077. bool AudioCDReader::isTrackAudio (int trackNum) const
  211078. {
  211079. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211080. }
  211081. void AudioCDReader::enableIndexScanning (bool b)
  211082. {
  211083. indexingEnabled = b;
  211084. }
  211085. int AudioCDReader::getLastIndex() const
  211086. {
  211087. return lastIndex;
  211088. }
  211089. int AudioCDReader::getIndexAt (int samplePos)
  211090. {
  211091. using namespace CDReaderHelpers;
  211092. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211093. const int frameNeeded = samplePos / samplesPerFrame;
  211094. device->overlapBuffer.dataLength = 0;
  211095. device->overlapBuffer.startFrame = 0;
  211096. device->overlapBuffer.numFrames = 0;
  211097. device->jitter = false;
  211098. firstFrameInBuffer = 0;
  211099. lastIndex = 0;
  211100. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211101. readBuffer.wantsIndex = true;
  211102. int i;
  211103. for (i = 5; --i >= 0;)
  211104. {
  211105. readBuffer.startFrame = frameNeeded;
  211106. readBuffer.numFrames = framesPerIndexRead;
  211107. if (device->deviceHandle.readAudio (readBuffer))
  211108. break;
  211109. }
  211110. if (i >= 0)
  211111. return readBuffer.index;
  211112. return -1;
  211113. }
  211114. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211115. {
  211116. using namespace CDReaderHelpers;
  211117. Array <int> indexes;
  211118. const int trackStart = getPositionOfTrackStart (trackNumber);
  211119. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211120. bool needToScan = true;
  211121. if (trackEnd - trackStart > 20 * 44100)
  211122. {
  211123. // check the end of the track for indexes before scanning the whole thing
  211124. needToScan = false;
  211125. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211126. bool seenAnIndex = false;
  211127. while (pos <= trackEnd - samplesPerFrame)
  211128. {
  211129. const int index = getIndexAt (pos);
  211130. if (index == 0)
  211131. {
  211132. // lead-out, so skip back a bit if we've not found any indexes yet..
  211133. if (seenAnIndex)
  211134. break;
  211135. pos -= 44100 * 5;
  211136. if (pos < trackStart)
  211137. break;
  211138. }
  211139. else
  211140. {
  211141. if (index > 0)
  211142. seenAnIndex = true;
  211143. if (index > 1)
  211144. {
  211145. needToScan = true;
  211146. break;
  211147. }
  211148. pos += samplesPerFrame * framesPerIndexRead;
  211149. }
  211150. }
  211151. }
  211152. if (needToScan)
  211153. {
  211154. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211155. int pos = trackStart;
  211156. int last = -1;
  211157. while (pos < trackEnd - samplesPerFrame * 10)
  211158. {
  211159. const int frameNeeded = pos / samplesPerFrame;
  211160. device->overlapBuffer.dataLength = 0;
  211161. device->overlapBuffer.startFrame = 0;
  211162. device->overlapBuffer.numFrames = 0;
  211163. device->jitter = false;
  211164. firstFrameInBuffer = 0;
  211165. CDReadBuffer readBuffer (4);
  211166. readBuffer.wantsIndex = true;
  211167. int i;
  211168. for (i = 5; --i >= 0;)
  211169. {
  211170. readBuffer.startFrame = frameNeeded;
  211171. readBuffer.numFrames = framesPerIndexRead;
  211172. if (device->deviceHandle.readAudio (readBuffer))
  211173. break;
  211174. }
  211175. if (i < 0)
  211176. break;
  211177. if (readBuffer.index > last && readBuffer.index > 1)
  211178. {
  211179. last = readBuffer.index;
  211180. indexes.add (pos);
  211181. }
  211182. pos += samplesPerFrame * framesPerIndexRead;
  211183. }
  211184. indexes.removeValue (trackStart);
  211185. }
  211186. return indexes;
  211187. }
  211188. void AudioCDReader::ejectDisk()
  211189. {
  211190. using namespace CDReaderHelpers;
  211191. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211192. }
  211193. #endif
  211194. #if JUCE_USE_CDBURNER
  211195. namespace CDBurnerHelpers
  211196. {
  211197. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211198. {
  211199. CoInitialize (0);
  211200. IDiscMaster* dm;
  211201. IDiscRecorder* result = 0;
  211202. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211203. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211204. IID_IDiscMaster,
  211205. (void**) &dm)))
  211206. {
  211207. if (SUCCEEDED (dm->Open()))
  211208. {
  211209. IEnumDiscRecorders* drEnum = 0;
  211210. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211211. {
  211212. IDiscRecorder* dr = 0;
  211213. DWORD dummy;
  211214. int index = 0;
  211215. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211216. {
  211217. if (indexToOpen == index)
  211218. {
  211219. result = dr;
  211220. break;
  211221. }
  211222. else if (list != 0)
  211223. {
  211224. BSTR path;
  211225. if (SUCCEEDED (dr->GetPath (&path)))
  211226. list->add ((const WCHAR*) path);
  211227. }
  211228. ++index;
  211229. dr->Release();
  211230. }
  211231. drEnum->Release();
  211232. }
  211233. if (master == 0)
  211234. dm->Close();
  211235. }
  211236. if (master != 0)
  211237. *master = dm;
  211238. else
  211239. dm->Release();
  211240. }
  211241. return result;
  211242. }
  211243. }
  211244. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211245. public Timer
  211246. {
  211247. public:
  211248. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211249. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211250. listener (0), progress (0), shouldCancel (false)
  211251. {
  211252. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211253. jassert (SUCCEEDED (hr));
  211254. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211255. //jassert (SUCCEEDED (hr));
  211256. lastState = getDiskState();
  211257. startTimer (2000);
  211258. }
  211259. ~Pimpl() {}
  211260. void releaseObjects()
  211261. {
  211262. discRecorder->Close();
  211263. if (redbook != 0)
  211264. redbook->Release();
  211265. discRecorder->Release();
  211266. discMaster->Release();
  211267. Release();
  211268. }
  211269. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211270. {
  211271. if (listener != 0 && ! shouldCancel)
  211272. shouldCancel = listener->audioCDBurnProgress (progress);
  211273. *pbCancel = shouldCancel;
  211274. return S_OK;
  211275. }
  211276. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211277. {
  211278. progress = nCompleted / (float) nTotal;
  211279. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211280. return E_NOTIMPL;
  211281. }
  211282. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211283. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211284. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211285. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211286. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211287. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211288. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211289. class ScopedDiscOpener
  211290. {
  211291. public:
  211292. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211293. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211294. private:
  211295. Pimpl& pimpl;
  211296. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211297. };
  211298. DiskState getDiskState()
  211299. {
  211300. const ScopedDiscOpener opener (*this);
  211301. long type, flags;
  211302. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211303. if (FAILED (hr))
  211304. return unknown;
  211305. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211306. return writableDiskPresent;
  211307. if (type == 0)
  211308. return noDisc;
  211309. else
  211310. return readOnlyDiskPresent;
  211311. }
  211312. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211313. {
  211314. ComSmartPtr<IPropertyStorage> prop;
  211315. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211316. return defaultReturn;
  211317. PROPSPEC iPropSpec;
  211318. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211319. iPropSpec.lpwstr = name;
  211320. PROPVARIANT iPropVariant;
  211321. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211322. ? defaultReturn : (int) iPropVariant.lVal;
  211323. }
  211324. bool setIntProperty (const LPOLESTR name, const int value) const
  211325. {
  211326. ComSmartPtr<IPropertyStorage> prop;
  211327. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211328. return false;
  211329. PROPSPEC iPropSpec;
  211330. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211331. iPropSpec.lpwstr = name;
  211332. PROPVARIANT iPropVariant;
  211333. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211334. return false;
  211335. iPropVariant.lVal = (long) value;
  211336. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211337. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211338. }
  211339. void timerCallback()
  211340. {
  211341. const DiskState state = getDiskState();
  211342. if (state != lastState)
  211343. {
  211344. lastState = state;
  211345. owner.sendChangeMessage();
  211346. }
  211347. }
  211348. AudioCDBurner& owner;
  211349. DiskState lastState;
  211350. IDiscMaster* discMaster;
  211351. IDiscRecorder* discRecorder;
  211352. IRedbookDiscMaster* redbook;
  211353. AudioCDBurner::BurnProgressListener* listener;
  211354. float progress;
  211355. bool shouldCancel;
  211356. };
  211357. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211358. {
  211359. IDiscMaster* discMaster = 0;
  211360. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211361. if (discRecorder != 0)
  211362. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211363. }
  211364. AudioCDBurner::~AudioCDBurner()
  211365. {
  211366. if (pimpl != 0)
  211367. pimpl.release()->releaseObjects();
  211368. }
  211369. const StringArray AudioCDBurner::findAvailableDevices()
  211370. {
  211371. StringArray devs;
  211372. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211373. return devs;
  211374. }
  211375. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211376. {
  211377. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211378. if (b->pimpl == 0)
  211379. b = 0;
  211380. return b.release();
  211381. }
  211382. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211383. {
  211384. return pimpl->getDiskState();
  211385. }
  211386. bool AudioCDBurner::isDiskPresent() const
  211387. {
  211388. return getDiskState() == writableDiskPresent;
  211389. }
  211390. bool AudioCDBurner::openTray()
  211391. {
  211392. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211393. return SUCCEEDED (pimpl->discRecorder->Eject());
  211394. }
  211395. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211396. {
  211397. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211398. DiskState oldState = getDiskState();
  211399. DiskState newState = oldState;
  211400. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211401. {
  211402. newState = getDiskState();
  211403. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211404. }
  211405. return newState;
  211406. }
  211407. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211408. {
  211409. Array<int> results;
  211410. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211411. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211412. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211413. if (speeds[i] <= maxSpeed)
  211414. results.add (speeds[i]);
  211415. results.addIfNotAlreadyThere (maxSpeed);
  211416. return results;
  211417. }
  211418. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211419. {
  211420. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211421. return false;
  211422. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211423. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211424. }
  211425. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211426. {
  211427. long blocksFree = 0;
  211428. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211429. return blocksFree;
  211430. }
  211431. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211432. bool performFakeBurnForTesting, int writeSpeed)
  211433. {
  211434. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211435. pimpl->listener = listener;
  211436. pimpl->progress = 0;
  211437. pimpl->shouldCancel = false;
  211438. UINT_PTR cookie;
  211439. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211440. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211441. ejectDiscAfterwards);
  211442. String error;
  211443. if (hr != S_OK)
  211444. {
  211445. const char* e = "Couldn't open or write to the CD device";
  211446. if (hr == IMAPI_E_USERABORT)
  211447. e = "User cancelled the write operation";
  211448. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211449. e = "No Disk present";
  211450. error = e;
  211451. }
  211452. pimpl->discMaster->ProgressUnadvise (cookie);
  211453. pimpl->listener = 0;
  211454. return error;
  211455. }
  211456. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211457. {
  211458. if (audioSource == 0)
  211459. return false;
  211460. ScopedPointer<AudioSource> source (audioSource);
  211461. long bytesPerBlock;
  211462. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211463. const int samplesPerBlock = bytesPerBlock / 4;
  211464. bool ok = true;
  211465. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211466. HeapBlock <byte> buffer (bytesPerBlock);
  211467. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211468. int samplesDone = 0;
  211469. source->prepareToPlay (samplesPerBlock, 44100.0);
  211470. while (ok)
  211471. {
  211472. {
  211473. AudioSourceChannelInfo info;
  211474. info.buffer = &sourceBuffer;
  211475. info.numSamples = samplesPerBlock;
  211476. info.startSample = 0;
  211477. sourceBuffer.clear();
  211478. source->getNextAudioBlock (info);
  211479. }
  211480. zeromem (buffer, bytesPerBlock);
  211481. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211482. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211483. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211484. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211485. CDSampleFormat left (buffer, 2);
  211486. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211487. CDSampleFormat right (buffer + 2, 2);
  211488. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211489. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211490. if (FAILED (hr))
  211491. ok = false;
  211492. samplesDone += samplesPerBlock;
  211493. if (samplesDone >= numSamples)
  211494. break;
  211495. }
  211496. hr = pimpl->redbook->CloseAudioTrack();
  211497. return ok && hr == S_OK;
  211498. }
  211499. #endif
  211500. #endif
  211501. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  211502. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  211503. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211504. // compiled on its own).
  211505. #if JUCE_INCLUDED_FILE
  211506. class MidiInCollector
  211507. {
  211508. public:
  211509. MidiInCollector (MidiInput* const input_,
  211510. MidiInputCallback& callback_)
  211511. : deviceHandle (0),
  211512. input (input_),
  211513. callback (callback_),
  211514. concatenator (4096),
  211515. isStarted (false),
  211516. startTime (0)
  211517. {
  211518. }
  211519. ~MidiInCollector()
  211520. {
  211521. stop();
  211522. if (deviceHandle != 0)
  211523. {
  211524. int count = 5;
  211525. while (--count >= 0)
  211526. {
  211527. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  211528. break;
  211529. Sleep (20);
  211530. }
  211531. }
  211532. }
  211533. void handleMessage (const uint32 message, const uint32 timeStamp)
  211534. {
  211535. if ((message & 0xff) >= 0x80 && isStarted)
  211536. {
  211537. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  211538. writeFinishedBlocks();
  211539. }
  211540. }
  211541. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211542. {
  211543. if (isStarted)
  211544. {
  211545. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  211546. writeFinishedBlocks();
  211547. }
  211548. }
  211549. void start()
  211550. {
  211551. jassert (deviceHandle != 0);
  211552. if (deviceHandle != 0 && ! isStarted)
  211553. {
  211554. activeMidiCollectors.addIfNotAlreadyThere (this);
  211555. for (int i = 0; i < (int) numHeaders; ++i)
  211556. headers[i].write (deviceHandle);
  211557. startTime = Time::getMillisecondCounter();
  211558. MMRESULT res = midiInStart (deviceHandle);
  211559. if (res == MMSYSERR_NOERROR)
  211560. {
  211561. concatenator.reset();
  211562. isStarted = true;
  211563. }
  211564. else
  211565. {
  211566. unprepareAllHeaders();
  211567. }
  211568. }
  211569. }
  211570. void stop()
  211571. {
  211572. if (isStarted)
  211573. {
  211574. isStarted = false;
  211575. midiInReset (deviceHandle);
  211576. midiInStop (deviceHandle);
  211577. activeMidiCollectors.removeValue (this);
  211578. unprepareAllHeaders();
  211579. concatenator.reset();
  211580. }
  211581. }
  211582. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211583. {
  211584. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  211585. if (activeMidiCollectors.contains (collector))
  211586. {
  211587. if (uMsg == MIM_DATA)
  211588. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  211589. else if (uMsg == MIM_LONGDATA)
  211590. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211591. }
  211592. }
  211593. HMIDIIN deviceHandle;
  211594. private:
  211595. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  211596. MidiInput* input;
  211597. MidiInputCallback& callback;
  211598. MidiDataConcatenator concatenator;
  211599. bool volatile isStarted;
  211600. uint32 startTime;
  211601. class MidiHeader
  211602. {
  211603. public:
  211604. MidiHeader()
  211605. {
  211606. zerostruct (hdr);
  211607. hdr.lpData = data;
  211608. hdr.dwBufferLength = numElementsInArray (data);
  211609. }
  211610. void write (HMIDIIN deviceHandle)
  211611. {
  211612. hdr.dwBytesRecorded = 0;
  211613. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211614. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  211615. }
  211616. void writeIfFinished (HMIDIIN deviceHandle)
  211617. {
  211618. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211619. {
  211620. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211621. (void) res;
  211622. write (deviceHandle);
  211623. }
  211624. }
  211625. void unprepare (HMIDIIN deviceHandle)
  211626. {
  211627. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211628. {
  211629. int c = 10;
  211630. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  211631. Thread::sleep (20);
  211632. jassert (c >= 0);
  211633. }
  211634. }
  211635. private:
  211636. MIDIHDR hdr;
  211637. char data [256];
  211638. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  211639. };
  211640. enum { numHeaders = 32 };
  211641. MidiHeader headers [numHeaders];
  211642. void writeFinishedBlocks()
  211643. {
  211644. for (int i = 0; i < (int) numHeaders; ++i)
  211645. headers[i].writeIfFinished (deviceHandle);
  211646. }
  211647. void unprepareAllHeaders()
  211648. {
  211649. for (int i = 0; i < (int) numHeaders; ++i)
  211650. headers[i].unprepare (deviceHandle);
  211651. }
  211652. double convertTimeStamp (uint32 timeStamp)
  211653. {
  211654. timeStamp += startTime;
  211655. const uint32 now = Time::getMillisecondCounter();
  211656. if (timeStamp > now)
  211657. {
  211658. if (timeStamp > now + 2)
  211659. --startTime;
  211660. timeStamp = now;
  211661. }
  211662. return timeStamp * 0.001;
  211663. }
  211664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  211665. };
  211666. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  211667. const StringArray MidiInput::getDevices()
  211668. {
  211669. StringArray s;
  211670. const int num = midiInGetNumDevs();
  211671. for (int i = 0; i < num; ++i)
  211672. {
  211673. MIDIINCAPS mc;
  211674. zerostruct (mc);
  211675. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211676. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211677. }
  211678. return s;
  211679. }
  211680. int MidiInput::getDefaultDeviceIndex()
  211681. {
  211682. return 0;
  211683. }
  211684. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211685. {
  211686. if (callback == 0)
  211687. return 0;
  211688. UINT deviceId = MIDI_MAPPER;
  211689. int n = 0;
  211690. String name;
  211691. const int num = midiInGetNumDevs();
  211692. for (int i = 0; i < num; ++i)
  211693. {
  211694. MIDIINCAPS mc;
  211695. zerostruct (mc);
  211696. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211697. {
  211698. if (index == n)
  211699. {
  211700. deviceId = i;
  211701. name = String (mc.szPname, numElementsInArray (mc.szPname));
  211702. break;
  211703. }
  211704. ++n;
  211705. }
  211706. }
  211707. ScopedPointer <MidiInput> in (new MidiInput (name));
  211708. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  211709. HMIDIIN h;
  211710. HRESULT err = midiInOpen (&h, deviceId,
  211711. (DWORD_PTR) &MidiInCollector::midiInCallback,
  211712. (DWORD_PTR) (MidiInCollector*) collector,
  211713. CALLBACK_FUNCTION);
  211714. if (err == MMSYSERR_NOERROR)
  211715. {
  211716. collector->deviceHandle = h;
  211717. in->internal = collector.release();
  211718. return in.release();
  211719. }
  211720. return 0;
  211721. }
  211722. MidiInput::MidiInput (const String& name_)
  211723. : name (name_),
  211724. internal (0)
  211725. {
  211726. }
  211727. MidiInput::~MidiInput()
  211728. {
  211729. delete static_cast <MidiInCollector*> (internal);
  211730. }
  211731. void MidiInput::start()
  211732. {
  211733. static_cast <MidiInCollector*> (internal)->start();
  211734. }
  211735. void MidiInput::stop()
  211736. {
  211737. static_cast <MidiInCollector*> (internal)->stop();
  211738. }
  211739. struct MidiOutHandle
  211740. {
  211741. int refCount;
  211742. UINT deviceId;
  211743. HMIDIOUT handle;
  211744. static Array<MidiOutHandle*> activeHandles;
  211745. private:
  211746. JUCE_LEAK_DETECTOR (MidiOutHandle);
  211747. };
  211748. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211749. const StringArray MidiOutput::getDevices()
  211750. {
  211751. StringArray s;
  211752. const int num = midiOutGetNumDevs();
  211753. for (int i = 0; i < num; ++i)
  211754. {
  211755. MIDIOUTCAPS mc;
  211756. zerostruct (mc);
  211757. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211758. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211759. }
  211760. return s;
  211761. }
  211762. int MidiOutput::getDefaultDeviceIndex()
  211763. {
  211764. const int num = midiOutGetNumDevs();
  211765. int n = 0;
  211766. for (int i = 0; i < num; ++i)
  211767. {
  211768. MIDIOUTCAPS mc;
  211769. zerostruct (mc);
  211770. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211771. {
  211772. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211773. return n;
  211774. ++n;
  211775. }
  211776. }
  211777. return 0;
  211778. }
  211779. MidiOutput* MidiOutput::openDevice (int index)
  211780. {
  211781. UINT deviceId = MIDI_MAPPER;
  211782. const int num = midiOutGetNumDevs();
  211783. int i, n = 0;
  211784. for (i = 0; i < num; ++i)
  211785. {
  211786. MIDIOUTCAPS mc;
  211787. zerostruct (mc);
  211788. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211789. {
  211790. // use the microsoft sw synth as a default - best not to allow deviceId
  211791. // to be MIDI_MAPPER, or else device sharing breaks
  211792. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211793. deviceId = i;
  211794. if (index == n)
  211795. {
  211796. deviceId = i;
  211797. break;
  211798. }
  211799. ++n;
  211800. }
  211801. }
  211802. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211803. {
  211804. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211805. if (han != 0 && han->deviceId == deviceId)
  211806. {
  211807. han->refCount++;
  211808. MidiOutput* const out = new MidiOutput();
  211809. out->internal = han;
  211810. return out;
  211811. }
  211812. }
  211813. for (i = 4; --i >= 0;)
  211814. {
  211815. HMIDIOUT h = 0;
  211816. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211817. if (res == MMSYSERR_NOERROR)
  211818. {
  211819. MidiOutHandle* const han = new MidiOutHandle();
  211820. han->deviceId = deviceId;
  211821. han->refCount = 1;
  211822. han->handle = h;
  211823. MidiOutHandle::activeHandles.add (han);
  211824. MidiOutput* const out = new MidiOutput();
  211825. out->internal = han;
  211826. return out;
  211827. }
  211828. else if (res == MMSYSERR_ALLOCATED)
  211829. {
  211830. Sleep (100);
  211831. }
  211832. else
  211833. {
  211834. break;
  211835. }
  211836. }
  211837. return 0;
  211838. }
  211839. MidiOutput::~MidiOutput()
  211840. {
  211841. stopBackgroundThread();
  211842. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211843. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211844. {
  211845. midiOutClose (h->handle);
  211846. MidiOutHandle::activeHandles.removeValue (h);
  211847. delete h;
  211848. }
  211849. }
  211850. void MidiOutput::reset()
  211851. {
  211852. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211853. midiOutReset (h->handle);
  211854. }
  211855. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  211856. {
  211857. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211858. DWORD n;
  211859. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211860. {
  211861. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  211862. rightVol = nn[0] / (float) 0xffff;
  211863. leftVol = nn[1] / (float) 0xffff;
  211864. return true;
  211865. }
  211866. else
  211867. {
  211868. rightVol = leftVol = 1.0f;
  211869. return false;
  211870. }
  211871. }
  211872. void MidiOutput::setVolume (float leftVol, float rightVol)
  211873. {
  211874. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211875. DWORD n;
  211876. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  211877. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211878. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211879. midiOutSetVolume (handle->handle, n);
  211880. }
  211881. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211882. {
  211883. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211884. if (message.getRawDataSize() > 3
  211885. || message.isSysEx())
  211886. {
  211887. MIDIHDR h;
  211888. zerostruct (h);
  211889. h.lpData = (char*) message.getRawData();
  211890. h.dwBufferLength = message.getRawDataSize();
  211891. h.dwBytesRecorded = message.getRawDataSize();
  211892. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211893. {
  211894. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211895. if (res == MMSYSERR_NOERROR)
  211896. {
  211897. while ((h.dwFlags & MHDR_DONE) == 0)
  211898. Sleep (1);
  211899. int count = 500; // 1 sec timeout
  211900. while (--count >= 0)
  211901. {
  211902. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211903. if (res == MIDIERR_STILLPLAYING)
  211904. Sleep (2);
  211905. else
  211906. break;
  211907. }
  211908. }
  211909. }
  211910. }
  211911. else
  211912. {
  211913. midiOutShortMsg (handle->handle,
  211914. *(unsigned int*) message.getRawData());
  211915. }
  211916. }
  211917. #endif
  211918. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211919. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211920. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211921. // compiled on its own).
  211922. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211923. #undef WINDOWS
  211924. // #define ASIO_DEBUGGING 1
  211925. #undef log
  211926. #if ASIO_DEBUGGING
  211927. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211928. #else
  211929. #define log(a) {}
  211930. #endif
  211931. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  211932. to be pretty random about whether or not they do this. If you hit an error using these functions
  211933. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  211934. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  211935. */
  211936. #define JUCE_ASIOCALLBACK __cdecl
  211937. namespace ASIODebugging
  211938. {
  211939. #if ASIO_DEBUGGING
  211940. static void log (const String& context, long error)
  211941. {
  211942. String err ("unknown error");
  211943. if (error == ASE_NotPresent) err = "Not Present";
  211944. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  211945. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  211946. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  211947. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  211948. else if (error == ASE_NoClock) err = "No Clock";
  211949. else if (error == ASE_NoMemory) err = "Out of memory";
  211950. log ("!!error: " + context + " - " + err);
  211951. }
  211952. #define logError(a, b) ASIODebugging::log ((a), (b))
  211953. #else
  211954. #define logError(a, b) {}
  211955. #endif
  211956. }
  211957. class ASIOAudioIODevice;
  211958. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211959. static const int maxASIOChannels = 160;
  211960. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211961. private Timer
  211962. {
  211963. public:
  211964. Component ourWindow;
  211965. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211966. const String& optionalDllForDirectLoading_)
  211967. : AudioIODevice (name_, "ASIO"),
  211968. asioObject (0),
  211969. classId (classId_),
  211970. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211971. currentBitDepth (16),
  211972. currentSampleRate (0),
  211973. isOpen_ (false),
  211974. isStarted (false),
  211975. postOutput (true),
  211976. insideControlPanelModalLoop (false),
  211977. shouldUsePreferredSize (false)
  211978. {
  211979. name = name_;
  211980. ourWindow.addToDesktop (0);
  211981. windowHandle = ourWindow.getWindowHandle();
  211982. jassert (currentASIODev [slotNumber] == 0);
  211983. currentASIODev [slotNumber] = this;
  211984. openDevice();
  211985. }
  211986. ~ASIOAudioIODevice()
  211987. {
  211988. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211989. if (currentASIODev[i] == this)
  211990. currentASIODev[i] = 0;
  211991. close();
  211992. log ("ASIO - exiting");
  211993. removeCurrentDriver();
  211994. }
  211995. void updateSampleRates()
  211996. {
  211997. // find a list of sample rates..
  211998. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211999. sampleRates.clear();
  212000. if (asioObject != 0)
  212001. {
  212002. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212003. {
  212004. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212005. if (err == 0)
  212006. {
  212007. sampleRates.add ((int) possibleSampleRates[index]);
  212008. log ("rate: " + String ((int) possibleSampleRates[index]));
  212009. }
  212010. else if (err != ASE_NoClock)
  212011. {
  212012. logError ("CanSampleRate", err);
  212013. }
  212014. }
  212015. if (sampleRates.size() == 0)
  212016. {
  212017. double cr = 0;
  212018. const long err = asioObject->getSampleRate (&cr);
  212019. log ("No sample rates supported - current rate: " + String ((int) cr));
  212020. if (err == 0)
  212021. sampleRates.add ((int) cr);
  212022. }
  212023. }
  212024. }
  212025. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212026. const StringArray getInputChannelNames() { return inputChannelNames; }
  212027. int getNumSampleRates() { return sampleRates.size(); }
  212028. double getSampleRate (int index) { return sampleRates [index]; }
  212029. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212030. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212031. int getDefaultBufferSize() { return preferredSize; }
  212032. const String open (const BigInteger& inputChannels,
  212033. const BigInteger& outputChannels,
  212034. double sr,
  212035. int bufferSizeSamples)
  212036. {
  212037. close();
  212038. currentCallback = 0;
  212039. if (bufferSizeSamples <= 0)
  212040. shouldUsePreferredSize = true;
  212041. if (asioObject == 0 || ! isASIOOpen)
  212042. {
  212043. log ("Warning: device not open");
  212044. const String err (openDevice());
  212045. if (asioObject == 0 || ! isASIOOpen)
  212046. return err;
  212047. }
  212048. isStarted = false;
  212049. bufferIndex = -1;
  212050. long err = 0;
  212051. long newPreferredSize = 0;
  212052. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212053. minSize = 0;
  212054. maxSize = 0;
  212055. newPreferredSize = 0;
  212056. granularity = 0;
  212057. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212058. {
  212059. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212060. shouldUsePreferredSize = true;
  212061. preferredSize = newPreferredSize;
  212062. }
  212063. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212064. // dynamic changes to the buffer size...
  212065. shouldUsePreferredSize = shouldUsePreferredSize
  212066. || getName().containsIgnoreCase ("Digidesign");
  212067. if (shouldUsePreferredSize)
  212068. {
  212069. log ("Using preferred size for buffer..");
  212070. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212071. {
  212072. bufferSizeSamples = preferredSize;
  212073. }
  212074. else
  212075. {
  212076. bufferSizeSamples = 1024;
  212077. logError ("GetBufferSize1", err);
  212078. }
  212079. shouldUsePreferredSize = false;
  212080. }
  212081. int sampleRate = roundDoubleToInt (sr);
  212082. currentSampleRate = sampleRate;
  212083. currentBlockSizeSamples = bufferSizeSamples;
  212084. currentChansOut.clear();
  212085. currentChansIn.clear();
  212086. zeromem (inBuffers, sizeof (inBuffers));
  212087. zeromem (outBuffers, sizeof (outBuffers));
  212088. updateSampleRates();
  212089. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212090. sampleRate = sampleRates[0];
  212091. jassert (sampleRate != 0);
  212092. if (sampleRate == 0)
  212093. sampleRate = 44100;
  212094. long numSources = 32;
  212095. ASIOClockSource clocks[32];
  212096. zeromem (clocks, sizeof (clocks));
  212097. asioObject->getClockSources (clocks, &numSources);
  212098. bool isSourceSet = false;
  212099. // careful not to remove this loop because it does more than just logging!
  212100. int i;
  212101. for (i = 0; i < numSources; ++i)
  212102. {
  212103. String s ("clock: ");
  212104. s += clocks[i].name;
  212105. if (clocks[i].isCurrentSource)
  212106. {
  212107. isSourceSet = true;
  212108. s << " (cur)";
  212109. }
  212110. log (s);
  212111. }
  212112. if (numSources > 1 && ! isSourceSet)
  212113. {
  212114. log ("setting clock source");
  212115. asioObject->setClockSource (clocks[0].index);
  212116. Thread::sleep (20);
  212117. }
  212118. else
  212119. {
  212120. if (numSources == 0)
  212121. {
  212122. log ("ASIO - no clock sources!");
  212123. }
  212124. }
  212125. double cr = 0;
  212126. err = asioObject->getSampleRate (&cr);
  212127. if (err == 0)
  212128. {
  212129. currentSampleRate = cr;
  212130. }
  212131. else
  212132. {
  212133. logError ("GetSampleRate", err);
  212134. currentSampleRate = 0;
  212135. }
  212136. error = String::empty;
  212137. needToReset = false;
  212138. isReSync = false;
  212139. err = 0;
  212140. bool buffersCreated = false;
  212141. if (currentSampleRate != sampleRate)
  212142. {
  212143. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212144. err = asioObject->setSampleRate (sampleRate);
  212145. if (err == ASE_NoClock && numSources > 0)
  212146. {
  212147. log ("trying to set a clock source..");
  212148. Thread::sleep (10);
  212149. err = asioObject->setClockSource (clocks[0].index);
  212150. if (err != 0)
  212151. {
  212152. logError ("SetClock", err);
  212153. }
  212154. Thread::sleep (10);
  212155. err = asioObject->setSampleRate (sampleRate);
  212156. }
  212157. }
  212158. if (err == 0)
  212159. {
  212160. currentSampleRate = sampleRate;
  212161. if (needToReset)
  212162. {
  212163. if (isReSync)
  212164. {
  212165. log ("Resync request");
  212166. }
  212167. log ("! Resetting ASIO after sample rate change");
  212168. removeCurrentDriver();
  212169. loadDriver();
  212170. const String error (initDriver());
  212171. if (error.isNotEmpty())
  212172. {
  212173. log ("ASIOInit: " + error);
  212174. }
  212175. needToReset = false;
  212176. isReSync = false;
  212177. }
  212178. numActiveInputChans = 0;
  212179. numActiveOutputChans = 0;
  212180. ASIOBufferInfo* info = bufferInfos;
  212181. int i;
  212182. for (i = 0; i < totalNumInputChans; ++i)
  212183. {
  212184. if (inputChannels[i])
  212185. {
  212186. currentChansIn.setBit (i);
  212187. info->isInput = 1;
  212188. info->channelNum = i;
  212189. info->buffers[0] = info->buffers[1] = 0;
  212190. ++info;
  212191. ++numActiveInputChans;
  212192. }
  212193. }
  212194. for (i = 0; i < totalNumOutputChans; ++i)
  212195. {
  212196. if (outputChannels[i])
  212197. {
  212198. currentChansOut.setBit (i);
  212199. info->isInput = 0;
  212200. info->channelNum = i;
  212201. info->buffers[0] = info->buffers[1] = 0;
  212202. ++info;
  212203. ++numActiveOutputChans;
  212204. }
  212205. }
  212206. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212207. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212208. if (currentASIODev[0] == this)
  212209. {
  212210. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212211. callbacks.asioMessage = &asioMessagesCallback0;
  212212. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212213. }
  212214. else if (currentASIODev[1] == this)
  212215. {
  212216. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212217. callbacks.asioMessage = &asioMessagesCallback1;
  212218. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212219. }
  212220. else if (currentASIODev[2] == this)
  212221. {
  212222. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212223. callbacks.asioMessage = &asioMessagesCallback2;
  212224. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212225. }
  212226. else
  212227. {
  212228. jassertfalse;
  212229. }
  212230. log ("disposing buffers");
  212231. err = asioObject->disposeBuffers();
  212232. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212233. err = asioObject->createBuffers (bufferInfos,
  212234. totalBuffers,
  212235. currentBlockSizeSamples,
  212236. &callbacks);
  212237. if (err != 0)
  212238. {
  212239. currentBlockSizeSamples = preferredSize;
  212240. logError ("create buffers 2", err);
  212241. asioObject->disposeBuffers();
  212242. err = asioObject->createBuffers (bufferInfos,
  212243. totalBuffers,
  212244. currentBlockSizeSamples,
  212245. &callbacks);
  212246. }
  212247. if (err == 0)
  212248. {
  212249. buffersCreated = true;
  212250. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212251. int n = 0;
  212252. Array <int> types;
  212253. currentBitDepth = 16;
  212254. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212255. {
  212256. if (inputChannels[i])
  212257. {
  212258. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212259. ASIOChannelInfo channelInfo;
  212260. zerostruct (channelInfo);
  212261. channelInfo.channel = i;
  212262. channelInfo.isInput = 1;
  212263. asioObject->getChannelInfo (&channelInfo);
  212264. types.addIfNotAlreadyThere (channelInfo.type);
  212265. typeToFormatParameters (channelInfo.type,
  212266. inputChannelBitDepths[n],
  212267. inputChannelBytesPerSample[n],
  212268. inputChannelIsFloat[n],
  212269. inputChannelLittleEndian[n]);
  212270. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212271. ++n;
  212272. }
  212273. }
  212274. jassert (numActiveInputChans == n);
  212275. n = 0;
  212276. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212277. {
  212278. if (outputChannels[i])
  212279. {
  212280. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212281. ASIOChannelInfo channelInfo;
  212282. zerostruct (channelInfo);
  212283. channelInfo.channel = i;
  212284. channelInfo.isInput = 0;
  212285. asioObject->getChannelInfo (&channelInfo);
  212286. types.addIfNotAlreadyThere (channelInfo.type);
  212287. typeToFormatParameters (channelInfo.type,
  212288. outputChannelBitDepths[n],
  212289. outputChannelBytesPerSample[n],
  212290. outputChannelIsFloat[n],
  212291. outputChannelLittleEndian[n]);
  212292. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212293. ++n;
  212294. }
  212295. }
  212296. jassert (numActiveOutputChans == n);
  212297. for (i = types.size(); --i >= 0;)
  212298. {
  212299. log ("channel format: " + String (types[i]));
  212300. }
  212301. jassert (n <= totalBuffers);
  212302. for (i = 0; i < numActiveOutputChans; ++i)
  212303. {
  212304. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212305. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212306. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212307. {
  212308. log ("!! Null buffers");
  212309. }
  212310. else
  212311. {
  212312. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212313. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212314. }
  212315. }
  212316. inputLatency = outputLatency = 0;
  212317. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212318. {
  212319. log ("ASIO - no latencies");
  212320. }
  212321. else
  212322. {
  212323. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212324. }
  212325. isOpen_ = true;
  212326. log ("starting ASIO");
  212327. calledback = false;
  212328. err = asioObject->start();
  212329. if (err != 0)
  212330. {
  212331. isOpen_ = false;
  212332. log ("ASIO - stop on failure");
  212333. Thread::sleep (10);
  212334. asioObject->stop();
  212335. error = "Can't start device";
  212336. Thread::sleep (10);
  212337. }
  212338. else
  212339. {
  212340. int count = 300;
  212341. while (--count > 0 && ! calledback)
  212342. Thread::sleep (10);
  212343. isStarted = true;
  212344. if (! calledback)
  212345. {
  212346. error = "Device didn't start correctly";
  212347. log ("ASIO didn't callback - stopping..");
  212348. asioObject->stop();
  212349. }
  212350. }
  212351. }
  212352. else
  212353. {
  212354. error = "Can't create i/o buffers";
  212355. }
  212356. }
  212357. else
  212358. {
  212359. error = "Can't set sample rate: ";
  212360. error << sampleRate;
  212361. }
  212362. if (error.isNotEmpty())
  212363. {
  212364. logError (error, err);
  212365. if (asioObject != 0 && buffersCreated)
  212366. asioObject->disposeBuffers();
  212367. Thread::sleep (20);
  212368. isStarted = false;
  212369. isOpen_ = false;
  212370. const String errorCopy (error);
  212371. close(); // (this resets the error string)
  212372. error = errorCopy;
  212373. }
  212374. needToReset = false;
  212375. isReSync = false;
  212376. return error;
  212377. }
  212378. void close()
  212379. {
  212380. error = String::empty;
  212381. stopTimer();
  212382. stop();
  212383. if (isASIOOpen && isOpen_)
  212384. {
  212385. const ScopedLock sl (callbackLock);
  212386. isOpen_ = false;
  212387. isStarted = false;
  212388. needToReset = false;
  212389. isReSync = false;
  212390. log ("ASIO - stopping");
  212391. if (asioObject != 0)
  212392. {
  212393. Thread::sleep (20);
  212394. asioObject->stop();
  212395. Thread::sleep (10);
  212396. asioObject->disposeBuffers();
  212397. }
  212398. Thread::sleep (10);
  212399. }
  212400. }
  212401. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212402. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212403. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212404. double getCurrentSampleRate() { return currentSampleRate; }
  212405. int getCurrentBitDepth() { return currentBitDepth; }
  212406. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212407. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212408. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212409. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212410. void start (AudioIODeviceCallback* callback)
  212411. {
  212412. if (callback != 0)
  212413. {
  212414. callback->audioDeviceAboutToStart (this);
  212415. const ScopedLock sl (callbackLock);
  212416. currentCallback = callback;
  212417. }
  212418. }
  212419. void stop()
  212420. {
  212421. AudioIODeviceCallback* const lastCallback = currentCallback;
  212422. {
  212423. const ScopedLock sl (callbackLock);
  212424. currentCallback = 0;
  212425. }
  212426. if (lastCallback != 0)
  212427. lastCallback->audioDeviceStopped();
  212428. }
  212429. const String getLastError() { return error; }
  212430. bool hasControlPanel() const { return true; }
  212431. bool showControlPanel()
  212432. {
  212433. log ("ASIO - showing control panel");
  212434. Component modalWindow (String::empty);
  212435. modalWindow.setOpaque (true);
  212436. modalWindow.addToDesktop (0);
  212437. modalWindow.enterModalState();
  212438. bool done = false;
  212439. JUCE_TRY
  212440. {
  212441. // are there are devices that need to be closed before showing their control panel?
  212442. // close();
  212443. insideControlPanelModalLoop = true;
  212444. const uint32 started = Time::getMillisecondCounter();
  212445. if (asioObject != 0)
  212446. {
  212447. asioObject->controlPanel();
  212448. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212449. log ("spent: " + String (spent));
  212450. if (spent > 300)
  212451. {
  212452. shouldUsePreferredSize = true;
  212453. done = true;
  212454. }
  212455. }
  212456. }
  212457. JUCE_CATCH_ALL
  212458. insideControlPanelModalLoop = false;
  212459. return done;
  212460. }
  212461. void resetRequest() throw()
  212462. {
  212463. needToReset = true;
  212464. }
  212465. void resyncRequest() throw()
  212466. {
  212467. needToReset = true;
  212468. isReSync = true;
  212469. }
  212470. void timerCallback()
  212471. {
  212472. if (! insideControlPanelModalLoop)
  212473. {
  212474. stopTimer();
  212475. // used to cause a reset
  212476. log ("! ASIO restart request!");
  212477. if (isOpen_)
  212478. {
  212479. AudioIODeviceCallback* const oldCallback = currentCallback;
  212480. close();
  212481. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212482. currentSampleRate, currentBlockSizeSamples);
  212483. if (oldCallback != 0)
  212484. start (oldCallback);
  212485. }
  212486. }
  212487. else
  212488. {
  212489. startTimer (100);
  212490. }
  212491. }
  212492. private:
  212493. IASIO* volatile asioObject;
  212494. ASIOCallbacks callbacks;
  212495. void* windowHandle;
  212496. CLSID classId;
  212497. const String optionalDllForDirectLoading;
  212498. String error;
  212499. long totalNumInputChans, totalNumOutputChans;
  212500. StringArray inputChannelNames, outputChannelNames;
  212501. Array<int> sampleRates, bufferSizes;
  212502. long inputLatency, outputLatency;
  212503. long minSize, maxSize, preferredSize, granularity;
  212504. int volatile currentBlockSizeSamples;
  212505. int volatile currentBitDepth;
  212506. double volatile currentSampleRate;
  212507. BigInteger currentChansOut, currentChansIn;
  212508. AudioIODeviceCallback* volatile currentCallback;
  212509. CriticalSection callbackLock;
  212510. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212511. float* inBuffers [maxASIOChannels];
  212512. float* outBuffers [maxASIOChannels];
  212513. int inputChannelBitDepths [maxASIOChannels];
  212514. int outputChannelBitDepths [maxASIOChannels];
  212515. int inputChannelBytesPerSample [maxASIOChannels];
  212516. int outputChannelBytesPerSample [maxASIOChannels];
  212517. bool inputChannelIsFloat [maxASIOChannels];
  212518. bool outputChannelIsFloat [maxASIOChannels];
  212519. bool inputChannelLittleEndian [maxASIOChannels];
  212520. bool outputChannelLittleEndian [maxASIOChannels];
  212521. WaitableEvent event1;
  212522. HeapBlock <float> tempBuffer;
  212523. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212524. bool isOpen_, isStarted;
  212525. bool volatile isASIOOpen;
  212526. bool volatile calledback;
  212527. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212528. bool volatile insideControlPanelModalLoop;
  212529. bool volatile shouldUsePreferredSize;
  212530. void removeCurrentDriver()
  212531. {
  212532. if (asioObject != 0)
  212533. {
  212534. asioObject->Release();
  212535. asioObject = 0;
  212536. }
  212537. }
  212538. bool loadDriver()
  212539. {
  212540. removeCurrentDriver();
  212541. JUCE_TRY
  212542. {
  212543. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212544. classId, (void**) &asioObject) == S_OK)
  212545. {
  212546. return true;
  212547. }
  212548. // If a class isn't registered but we have a path for it, we can fallback to
  212549. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212550. if (optionalDllForDirectLoading.isNotEmpty())
  212551. {
  212552. HMODULE h = LoadLibrary (optionalDllForDirectLoading.toUTF16());
  212553. if (h != 0)
  212554. {
  212555. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212556. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212557. if (dllGetClassObject != 0)
  212558. {
  212559. IClassFactory* classFactory = 0;
  212560. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212561. if (classFactory != 0)
  212562. {
  212563. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212564. classFactory->Release();
  212565. }
  212566. return asioObject != 0;
  212567. }
  212568. }
  212569. }
  212570. }
  212571. JUCE_CATCH_ALL
  212572. asioObject = 0;
  212573. return false;
  212574. }
  212575. const String initDriver()
  212576. {
  212577. if (asioObject != 0)
  212578. {
  212579. char buffer [256];
  212580. zeromem (buffer, sizeof (buffer));
  212581. if (! asioObject->init (windowHandle))
  212582. {
  212583. asioObject->getErrorMessage (buffer);
  212584. return String (buffer, sizeof (buffer) - 1);
  212585. }
  212586. // just in case any daft drivers expect this to be called..
  212587. asioObject->getDriverName (buffer);
  212588. return String::empty;
  212589. }
  212590. return "No Driver";
  212591. }
  212592. const String openDevice()
  212593. {
  212594. // use this in case the driver starts opening dialog boxes..
  212595. Component modalWindow (String::empty);
  212596. modalWindow.setOpaque (true);
  212597. modalWindow.addToDesktop (0);
  212598. modalWindow.enterModalState();
  212599. // open the device and get its info..
  212600. log ("opening ASIO device: " + getName());
  212601. needToReset = false;
  212602. isReSync = false;
  212603. outputChannelNames.clear();
  212604. inputChannelNames.clear();
  212605. bufferSizes.clear();
  212606. sampleRates.clear();
  212607. isASIOOpen = false;
  212608. isOpen_ = false;
  212609. totalNumInputChans = 0;
  212610. totalNumOutputChans = 0;
  212611. numActiveInputChans = 0;
  212612. numActiveOutputChans = 0;
  212613. currentCallback = 0;
  212614. error = String::empty;
  212615. if (getName().isEmpty())
  212616. return error;
  212617. long err = 0;
  212618. if (loadDriver())
  212619. {
  212620. if ((error = initDriver()).isEmpty())
  212621. {
  212622. numActiveInputChans = 0;
  212623. numActiveOutputChans = 0;
  212624. totalNumInputChans = 0;
  212625. totalNumOutputChans = 0;
  212626. if (asioObject != 0
  212627. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212628. {
  212629. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212630. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212631. {
  212632. // find a list of buffer sizes..
  212633. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212634. if (granularity >= 0)
  212635. {
  212636. granularity = jmax (1, (int) granularity);
  212637. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212638. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212639. }
  212640. else if (granularity < 0)
  212641. {
  212642. for (int i = 0; i < 18; ++i)
  212643. {
  212644. const int s = (1 << i);
  212645. if (s >= minSize && s <= maxSize)
  212646. bufferSizes.add (s);
  212647. }
  212648. }
  212649. if (! bufferSizes.contains (preferredSize))
  212650. bufferSizes.insert (0, preferredSize);
  212651. double currentRate = 0;
  212652. asioObject->getSampleRate (&currentRate);
  212653. if (currentRate <= 0.0 || currentRate > 192001.0)
  212654. {
  212655. log ("setting sample rate");
  212656. err = asioObject->setSampleRate (44100.0);
  212657. if (err != 0)
  212658. {
  212659. logError ("setting sample rate", err);
  212660. }
  212661. asioObject->getSampleRate (&currentRate);
  212662. }
  212663. currentSampleRate = currentRate;
  212664. postOutput = (asioObject->outputReady() == 0);
  212665. if (postOutput)
  212666. {
  212667. log ("ASIO outputReady = ok");
  212668. }
  212669. updateSampleRates();
  212670. // ..because cubase does it at this point
  212671. inputLatency = outputLatency = 0;
  212672. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212673. {
  212674. log ("ASIO - no latencies");
  212675. }
  212676. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212677. // create some dummy buffers now.. because cubase does..
  212678. numActiveInputChans = 0;
  212679. numActiveOutputChans = 0;
  212680. ASIOBufferInfo* info = bufferInfos;
  212681. int i, numChans = 0;
  212682. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212683. {
  212684. info->isInput = 1;
  212685. info->channelNum = i;
  212686. info->buffers[0] = info->buffers[1] = 0;
  212687. ++info;
  212688. ++numChans;
  212689. }
  212690. const int outputBufferIndex = numChans;
  212691. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212692. {
  212693. info->isInput = 0;
  212694. info->channelNum = i;
  212695. info->buffers[0] = info->buffers[1] = 0;
  212696. ++info;
  212697. ++numChans;
  212698. }
  212699. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212700. if (currentASIODev[0] == this)
  212701. {
  212702. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212703. callbacks.asioMessage = &asioMessagesCallback0;
  212704. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212705. }
  212706. else if (currentASIODev[1] == this)
  212707. {
  212708. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212709. callbacks.asioMessage = &asioMessagesCallback1;
  212710. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212711. }
  212712. else if (currentASIODev[2] == this)
  212713. {
  212714. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212715. callbacks.asioMessage = &asioMessagesCallback2;
  212716. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212717. }
  212718. else
  212719. {
  212720. jassertfalse;
  212721. }
  212722. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212723. if (preferredSize > 0)
  212724. {
  212725. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212726. if (err != 0)
  212727. {
  212728. logError ("dummy buffers", err);
  212729. }
  212730. }
  212731. long newInps = 0, newOuts = 0;
  212732. asioObject->getChannels (&newInps, &newOuts);
  212733. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212734. {
  212735. totalNumInputChans = newInps;
  212736. totalNumOutputChans = newOuts;
  212737. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212738. }
  212739. updateSampleRates();
  212740. ASIOChannelInfo channelInfo;
  212741. channelInfo.type = 0;
  212742. for (i = 0; i < totalNumInputChans; ++i)
  212743. {
  212744. zerostruct (channelInfo);
  212745. channelInfo.channel = i;
  212746. channelInfo.isInput = 1;
  212747. asioObject->getChannelInfo (&channelInfo);
  212748. inputChannelNames.add (String (channelInfo.name));
  212749. }
  212750. for (i = 0; i < totalNumOutputChans; ++i)
  212751. {
  212752. zerostruct (channelInfo);
  212753. channelInfo.channel = i;
  212754. channelInfo.isInput = 0;
  212755. asioObject->getChannelInfo (&channelInfo);
  212756. outputChannelNames.add (String (channelInfo.name));
  212757. typeToFormatParameters (channelInfo.type,
  212758. outputChannelBitDepths[i],
  212759. outputChannelBytesPerSample[i],
  212760. outputChannelIsFloat[i],
  212761. outputChannelLittleEndian[i]);
  212762. if (i < 2)
  212763. {
  212764. // clear the channels that are used with the dummy stuff
  212765. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212766. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212767. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212768. }
  212769. }
  212770. outputChannelNames.trim();
  212771. inputChannelNames.trim();
  212772. outputChannelNames.appendNumbersToDuplicates (false, true);
  212773. inputChannelNames.appendNumbersToDuplicates (false, true);
  212774. // start and stop because cubase does it..
  212775. asioObject->getLatencies (&inputLatency, &outputLatency);
  212776. if ((err = asioObject->start()) != 0)
  212777. {
  212778. // ignore an error here, as it might start later after setting other stuff up
  212779. logError ("ASIO start", err);
  212780. }
  212781. Thread::sleep (100);
  212782. asioObject->stop();
  212783. }
  212784. else
  212785. {
  212786. error = "Can't detect buffer sizes";
  212787. }
  212788. }
  212789. else
  212790. {
  212791. error = "Can't detect asio channels";
  212792. }
  212793. }
  212794. }
  212795. else
  212796. {
  212797. error = "No such device";
  212798. }
  212799. if (error.isNotEmpty())
  212800. {
  212801. logError (error, err);
  212802. if (asioObject != 0)
  212803. asioObject->disposeBuffers();
  212804. removeCurrentDriver();
  212805. isASIOOpen = false;
  212806. }
  212807. else
  212808. {
  212809. isASIOOpen = true;
  212810. log ("ASIO device open");
  212811. }
  212812. isOpen_ = false;
  212813. needToReset = false;
  212814. isReSync = false;
  212815. return error;
  212816. }
  212817. void JUCE_ASIOCALLBACK callback (const long index)
  212818. {
  212819. if (isStarted)
  212820. {
  212821. bufferIndex = index;
  212822. processBuffer();
  212823. }
  212824. else
  212825. {
  212826. if (postOutput && (asioObject != 0))
  212827. asioObject->outputReady();
  212828. }
  212829. calledback = true;
  212830. }
  212831. void processBuffer()
  212832. {
  212833. const ASIOBufferInfo* const infos = bufferInfos;
  212834. const int bi = bufferIndex;
  212835. const ScopedLock sl (callbackLock);
  212836. if (needToReset)
  212837. {
  212838. needToReset = false;
  212839. if (isReSync)
  212840. {
  212841. log ("! ASIO resync");
  212842. isReSync = false;
  212843. }
  212844. else
  212845. {
  212846. startTimer (20);
  212847. }
  212848. }
  212849. if (bi >= 0)
  212850. {
  212851. const int samps = currentBlockSizeSamples;
  212852. if (currentCallback != 0)
  212853. {
  212854. int i;
  212855. for (i = 0; i < numActiveInputChans; ++i)
  212856. {
  212857. float* const dst = inBuffers[i];
  212858. jassert (dst != 0);
  212859. const char* const src = (const char*) (infos[i].buffers[bi]);
  212860. if (inputChannelIsFloat[i])
  212861. {
  212862. memcpy (dst, src, samps * sizeof (float));
  212863. }
  212864. else
  212865. {
  212866. jassert (dst == tempBuffer + (samps * i));
  212867. switch (inputChannelBitDepths[i])
  212868. {
  212869. case 16:
  212870. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212871. samps, inputChannelLittleEndian[i]);
  212872. break;
  212873. case 24:
  212874. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212875. samps, inputChannelLittleEndian[i]);
  212876. break;
  212877. case 32:
  212878. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212879. samps, inputChannelLittleEndian[i]);
  212880. break;
  212881. case 64:
  212882. jassertfalse;
  212883. break;
  212884. }
  212885. }
  212886. }
  212887. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  212888. outBuffers, numActiveOutputChans, samps);
  212889. for (i = 0; i < numActiveOutputChans; ++i)
  212890. {
  212891. float* const src = outBuffers[i];
  212892. jassert (src != 0);
  212893. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212894. if (outputChannelIsFloat[i])
  212895. {
  212896. memcpy (dst, src, samps * sizeof (float));
  212897. }
  212898. else
  212899. {
  212900. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212901. switch (outputChannelBitDepths[i])
  212902. {
  212903. case 16:
  212904. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212905. samps, outputChannelLittleEndian[i]);
  212906. break;
  212907. case 24:
  212908. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212909. samps, outputChannelLittleEndian[i]);
  212910. break;
  212911. case 32:
  212912. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212913. samps, outputChannelLittleEndian[i]);
  212914. break;
  212915. case 64:
  212916. jassertfalse;
  212917. break;
  212918. }
  212919. }
  212920. }
  212921. }
  212922. else
  212923. {
  212924. for (int i = 0; i < numActiveOutputChans; ++i)
  212925. {
  212926. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212927. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212928. }
  212929. }
  212930. }
  212931. if (postOutput)
  212932. asioObject->outputReady();
  212933. }
  212934. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212935. {
  212936. if (currentASIODev[0] != 0)
  212937. currentASIODev[0]->callback (index);
  212938. return 0;
  212939. }
  212940. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212941. {
  212942. if (currentASIODev[1] != 0)
  212943. currentASIODev[1]->callback (index);
  212944. return 0;
  212945. }
  212946. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212947. {
  212948. if (currentASIODev[2] != 0)
  212949. currentASIODev[2]->callback (index);
  212950. return 0;
  212951. }
  212952. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  212953. {
  212954. if (currentASIODev[0] != 0)
  212955. currentASIODev[0]->callback (index);
  212956. }
  212957. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  212958. {
  212959. if (currentASIODev[1] != 0)
  212960. currentASIODev[1]->callback (index);
  212961. }
  212962. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  212963. {
  212964. if (currentASIODev[2] != 0)
  212965. currentASIODev[2]->callback (index);
  212966. }
  212967. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  212968. {
  212969. return asioMessagesCallback (selector, value, 0);
  212970. }
  212971. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  212972. {
  212973. return asioMessagesCallback (selector, value, 1);
  212974. }
  212975. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  212976. {
  212977. return asioMessagesCallback (selector, value, 2);
  212978. }
  212979. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  212980. {
  212981. switch (selector)
  212982. {
  212983. case kAsioSelectorSupported:
  212984. if (value == kAsioResetRequest
  212985. || value == kAsioEngineVersion
  212986. || value == kAsioResyncRequest
  212987. || value == kAsioLatenciesChanged
  212988. || value == kAsioSupportsInputMonitor)
  212989. return 1;
  212990. break;
  212991. case kAsioBufferSizeChange:
  212992. break;
  212993. case kAsioResetRequest:
  212994. if (currentASIODev[deviceIndex] != 0)
  212995. currentASIODev[deviceIndex]->resetRequest();
  212996. return 1;
  212997. case kAsioResyncRequest:
  212998. if (currentASIODev[deviceIndex] != 0)
  212999. currentASIODev[deviceIndex]->resyncRequest();
  213000. return 1;
  213001. case kAsioLatenciesChanged:
  213002. return 1;
  213003. case kAsioEngineVersion:
  213004. return 2;
  213005. case kAsioSupportsTimeInfo:
  213006. case kAsioSupportsTimeCode:
  213007. return 0;
  213008. }
  213009. return 0;
  213010. }
  213011. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213012. {
  213013. }
  213014. static void convertInt16ToFloat (const char* src,
  213015. float* dest,
  213016. const int srcStrideBytes,
  213017. int numSamples,
  213018. const bool littleEndian) throw()
  213019. {
  213020. const double g = 1.0 / 32768.0;
  213021. if (littleEndian)
  213022. {
  213023. while (--numSamples >= 0)
  213024. {
  213025. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213026. src += srcStrideBytes;
  213027. }
  213028. }
  213029. else
  213030. {
  213031. while (--numSamples >= 0)
  213032. {
  213033. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213034. src += srcStrideBytes;
  213035. }
  213036. }
  213037. }
  213038. static void convertFloatToInt16 (const float* src,
  213039. char* dest,
  213040. const int dstStrideBytes,
  213041. int numSamples,
  213042. const bool littleEndian) throw()
  213043. {
  213044. const double maxVal = (double) 0x7fff;
  213045. if (littleEndian)
  213046. {
  213047. while (--numSamples >= 0)
  213048. {
  213049. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213050. dest += dstStrideBytes;
  213051. }
  213052. }
  213053. else
  213054. {
  213055. while (--numSamples >= 0)
  213056. {
  213057. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213058. dest += dstStrideBytes;
  213059. }
  213060. }
  213061. }
  213062. static void convertInt24ToFloat (const char* src,
  213063. float* dest,
  213064. const int srcStrideBytes,
  213065. int numSamples,
  213066. const bool littleEndian) throw()
  213067. {
  213068. const double g = 1.0 / 0x7fffff;
  213069. if (littleEndian)
  213070. {
  213071. while (--numSamples >= 0)
  213072. {
  213073. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213074. src += srcStrideBytes;
  213075. }
  213076. }
  213077. else
  213078. {
  213079. while (--numSamples >= 0)
  213080. {
  213081. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213082. src += srcStrideBytes;
  213083. }
  213084. }
  213085. }
  213086. static void convertFloatToInt24 (const float* src,
  213087. char* dest,
  213088. const int dstStrideBytes,
  213089. int numSamples,
  213090. const bool littleEndian) throw()
  213091. {
  213092. const double maxVal = (double) 0x7fffff;
  213093. if (littleEndian)
  213094. {
  213095. while (--numSamples >= 0)
  213096. {
  213097. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213098. dest += dstStrideBytes;
  213099. }
  213100. }
  213101. else
  213102. {
  213103. while (--numSamples >= 0)
  213104. {
  213105. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213106. dest += dstStrideBytes;
  213107. }
  213108. }
  213109. }
  213110. static void convertInt32ToFloat (const char* src,
  213111. float* dest,
  213112. const int srcStrideBytes,
  213113. int numSamples,
  213114. const bool littleEndian) throw()
  213115. {
  213116. const double g = 1.0 / 0x7fffffff;
  213117. if (littleEndian)
  213118. {
  213119. while (--numSamples >= 0)
  213120. {
  213121. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213122. src += srcStrideBytes;
  213123. }
  213124. }
  213125. else
  213126. {
  213127. while (--numSamples >= 0)
  213128. {
  213129. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213130. src += srcStrideBytes;
  213131. }
  213132. }
  213133. }
  213134. static void convertFloatToInt32 (const float* src,
  213135. char* dest,
  213136. const int dstStrideBytes,
  213137. int numSamples,
  213138. const bool littleEndian) throw()
  213139. {
  213140. const double maxVal = (double) 0x7fffffff;
  213141. if (littleEndian)
  213142. {
  213143. while (--numSamples >= 0)
  213144. {
  213145. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213146. dest += dstStrideBytes;
  213147. }
  213148. }
  213149. else
  213150. {
  213151. while (--numSamples >= 0)
  213152. {
  213153. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213154. dest += dstStrideBytes;
  213155. }
  213156. }
  213157. }
  213158. static void typeToFormatParameters (const long type,
  213159. int& bitDepth,
  213160. int& byteStride,
  213161. bool& formatIsFloat,
  213162. bool& littleEndian) throw()
  213163. {
  213164. bitDepth = 0;
  213165. littleEndian = false;
  213166. formatIsFloat = false;
  213167. switch (type)
  213168. {
  213169. case ASIOSTInt16MSB:
  213170. case ASIOSTInt16LSB:
  213171. case ASIOSTInt32MSB16:
  213172. case ASIOSTInt32LSB16:
  213173. bitDepth = 16; break;
  213174. case ASIOSTFloat32MSB:
  213175. case ASIOSTFloat32LSB:
  213176. formatIsFloat = true;
  213177. bitDepth = 32; break;
  213178. case ASIOSTInt32MSB:
  213179. case ASIOSTInt32LSB:
  213180. bitDepth = 32; break;
  213181. case ASIOSTInt24MSB:
  213182. case ASIOSTInt24LSB:
  213183. case ASIOSTInt32MSB24:
  213184. case ASIOSTInt32LSB24:
  213185. case ASIOSTInt32MSB18:
  213186. case ASIOSTInt32MSB20:
  213187. case ASIOSTInt32LSB18:
  213188. case ASIOSTInt32LSB20:
  213189. bitDepth = 24; break;
  213190. case ASIOSTFloat64MSB:
  213191. case ASIOSTFloat64LSB:
  213192. default:
  213193. bitDepth = 64;
  213194. break;
  213195. }
  213196. switch (type)
  213197. {
  213198. case ASIOSTInt16MSB:
  213199. case ASIOSTInt32MSB16:
  213200. case ASIOSTFloat32MSB:
  213201. case ASIOSTFloat64MSB:
  213202. case ASIOSTInt32MSB:
  213203. case ASIOSTInt32MSB18:
  213204. case ASIOSTInt32MSB20:
  213205. case ASIOSTInt32MSB24:
  213206. case ASIOSTInt24MSB:
  213207. littleEndian = false; break;
  213208. case ASIOSTInt16LSB:
  213209. case ASIOSTInt32LSB16:
  213210. case ASIOSTFloat32LSB:
  213211. case ASIOSTFloat64LSB:
  213212. case ASIOSTInt32LSB:
  213213. case ASIOSTInt32LSB18:
  213214. case ASIOSTInt32LSB20:
  213215. case ASIOSTInt32LSB24:
  213216. case ASIOSTInt24LSB:
  213217. littleEndian = true; break;
  213218. default:
  213219. break;
  213220. }
  213221. switch (type)
  213222. {
  213223. case ASIOSTInt16LSB:
  213224. case ASIOSTInt16MSB:
  213225. byteStride = 2; break;
  213226. case ASIOSTInt24LSB:
  213227. case ASIOSTInt24MSB:
  213228. byteStride = 3; break;
  213229. case ASIOSTInt32MSB16:
  213230. case ASIOSTInt32LSB16:
  213231. case ASIOSTInt32MSB:
  213232. case ASIOSTInt32MSB18:
  213233. case ASIOSTInt32MSB20:
  213234. case ASIOSTInt32MSB24:
  213235. case ASIOSTInt32LSB:
  213236. case ASIOSTInt32LSB18:
  213237. case ASIOSTInt32LSB20:
  213238. case ASIOSTInt32LSB24:
  213239. case ASIOSTFloat32LSB:
  213240. case ASIOSTFloat32MSB:
  213241. byteStride = 4; break;
  213242. case ASIOSTFloat64MSB:
  213243. case ASIOSTFloat64LSB:
  213244. byteStride = 8; break;
  213245. default:
  213246. break;
  213247. }
  213248. }
  213249. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213250. };
  213251. class ASIOAudioIODeviceType : public AudioIODeviceType
  213252. {
  213253. public:
  213254. ASIOAudioIODeviceType()
  213255. : AudioIODeviceType ("ASIO"),
  213256. hasScanned (false)
  213257. {
  213258. CoInitialize (0);
  213259. }
  213260. ~ASIOAudioIODeviceType()
  213261. {
  213262. }
  213263. void scanForDevices()
  213264. {
  213265. hasScanned = true;
  213266. deviceNames.clear();
  213267. classIds.clear();
  213268. HKEY hk = 0;
  213269. int index = 0;
  213270. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213271. {
  213272. for (;;)
  213273. {
  213274. char name [256];
  213275. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213276. {
  213277. addDriverInfo (name, hk);
  213278. }
  213279. else
  213280. {
  213281. break;
  213282. }
  213283. }
  213284. RegCloseKey (hk);
  213285. }
  213286. }
  213287. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213288. {
  213289. jassert (hasScanned); // need to call scanForDevices() before doing this
  213290. return deviceNames;
  213291. }
  213292. int getDefaultDeviceIndex (bool) const
  213293. {
  213294. jassert (hasScanned); // need to call scanForDevices() before doing this
  213295. for (int i = deviceNames.size(); --i >= 0;)
  213296. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213297. return i; // asio4all is a safe choice for a default..
  213298. #if JUCE_DEBUG
  213299. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213300. return 1; // (the digi m-box driver crashes the app when you run
  213301. // it in the debugger, which can be a bit annoying)
  213302. #endif
  213303. return 0;
  213304. }
  213305. static int findFreeSlot()
  213306. {
  213307. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213308. if (currentASIODev[i] == 0)
  213309. return i;
  213310. jassertfalse; // unfortunately you can only have a finite number
  213311. // of ASIO devices open at the same time..
  213312. return -1;
  213313. }
  213314. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213315. {
  213316. jassert (hasScanned); // need to call scanForDevices() before doing this
  213317. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213318. }
  213319. bool hasSeparateInputsAndOutputs() const { return false; }
  213320. AudioIODevice* createDevice (const String& outputDeviceName,
  213321. const String& inputDeviceName)
  213322. {
  213323. // ASIO can't open two different devices for input and output - they must be the same one.
  213324. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213325. jassert (hasScanned); // need to call scanForDevices() before doing this
  213326. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213327. : inputDeviceName);
  213328. if (index >= 0)
  213329. {
  213330. const int freeSlot = findFreeSlot();
  213331. if (freeSlot >= 0)
  213332. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213333. }
  213334. return 0;
  213335. }
  213336. private:
  213337. StringArray deviceNames;
  213338. OwnedArray <CLSID> classIds;
  213339. bool hasScanned;
  213340. static bool checkClassIsOk (const String& classId)
  213341. {
  213342. HKEY hk = 0;
  213343. bool ok = false;
  213344. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213345. {
  213346. int index = 0;
  213347. for (;;)
  213348. {
  213349. WCHAR buf [512];
  213350. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213351. {
  213352. if (classId.equalsIgnoreCase (buf))
  213353. {
  213354. HKEY subKey, pathKey;
  213355. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213356. {
  213357. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213358. {
  213359. WCHAR pathName [1024];
  213360. DWORD dtype = REG_SZ;
  213361. DWORD dsize = sizeof (pathName);
  213362. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213363. ok = File (pathName).exists();
  213364. RegCloseKey (pathKey);
  213365. }
  213366. RegCloseKey (subKey);
  213367. }
  213368. break;
  213369. }
  213370. }
  213371. else
  213372. {
  213373. break;
  213374. }
  213375. }
  213376. RegCloseKey (hk);
  213377. }
  213378. return ok;
  213379. }
  213380. void addDriverInfo (const String& keyName, HKEY hk)
  213381. {
  213382. HKEY subKey;
  213383. if (RegOpenKeyEx (hk, keyName.toUTF16(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213384. {
  213385. WCHAR buf [256];
  213386. zerostruct (buf);
  213387. DWORD dtype = REG_SZ;
  213388. DWORD dsize = sizeof (buf);
  213389. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213390. {
  213391. if (dsize > 0 && checkClassIsOk (buf))
  213392. {
  213393. CLSID classId;
  213394. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213395. {
  213396. dtype = REG_SZ;
  213397. dsize = sizeof (buf);
  213398. String deviceName;
  213399. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213400. deviceName = buf;
  213401. else
  213402. deviceName = keyName;
  213403. log ("found " + deviceName);
  213404. deviceNames.add (deviceName);
  213405. classIds.add (new CLSID (classId));
  213406. }
  213407. }
  213408. RegCloseKey (subKey);
  213409. }
  213410. }
  213411. }
  213412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213413. };
  213414. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213415. {
  213416. return new ASIOAudioIODeviceType();
  213417. }
  213418. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213419. void* guid,
  213420. const String& optionalDllForDirectLoading)
  213421. {
  213422. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213423. if (freeSlot < 0)
  213424. return 0;
  213425. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213426. }
  213427. #undef logError
  213428. #undef log
  213429. #endif
  213430. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213431. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213432. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213433. // compiled on its own).
  213434. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213435. END_JUCE_NAMESPACE
  213436. extern "C"
  213437. {
  213438. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213439. typedef struct typeDSBUFFERDESC
  213440. {
  213441. DWORD dwSize;
  213442. DWORD dwFlags;
  213443. DWORD dwBufferBytes;
  213444. DWORD dwReserved;
  213445. LPWAVEFORMATEX lpwfxFormat;
  213446. GUID guid3DAlgorithm;
  213447. } DSBUFFERDESC;
  213448. struct IDirectSoundBuffer;
  213449. #undef INTERFACE
  213450. #define INTERFACE IDirectSound
  213451. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213452. {
  213453. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213454. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213455. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213456. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213457. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213458. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213459. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213460. STDMETHOD(Compact) (THIS) PURE;
  213461. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213462. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213463. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213464. };
  213465. #undef INTERFACE
  213466. #define INTERFACE IDirectSoundBuffer
  213467. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213468. {
  213469. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213470. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213471. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213472. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213473. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213474. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213475. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213476. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213477. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213478. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213479. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213480. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213481. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213482. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213483. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213484. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213485. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213486. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213487. STDMETHOD(Stop) (THIS) PURE;
  213488. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213489. STDMETHOD(Restore) (THIS) PURE;
  213490. };
  213491. typedef struct typeDSCBUFFERDESC
  213492. {
  213493. DWORD dwSize;
  213494. DWORD dwFlags;
  213495. DWORD dwBufferBytes;
  213496. DWORD dwReserved;
  213497. LPWAVEFORMATEX lpwfxFormat;
  213498. } DSCBUFFERDESC;
  213499. struct IDirectSoundCaptureBuffer;
  213500. #undef INTERFACE
  213501. #define INTERFACE IDirectSoundCapture
  213502. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213503. {
  213504. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213505. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213506. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213507. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213508. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213509. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213510. };
  213511. #undef INTERFACE
  213512. #define INTERFACE IDirectSoundCaptureBuffer
  213513. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213514. {
  213515. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213516. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213517. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213518. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213519. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213520. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213521. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213522. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213523. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213524. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213525. STDMETHOD(Stop) (THIS) PURE;
  213526. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213527. };
  213528. };
  213529. BEGIN_JUCE_NAMESPACE
  213530. namespace
  213531. {
  213532. const String getDSErrorMessage (HRESULT hr)
  213533. {
  213534. const char* result = 0;
  213535. switch (hr)
  213536. {
  213537. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213538. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213539. case E_INVALIDARG: result = "Invalid parameter"; break;
  213540. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213541. case E_FAIL: result = "Generic error"; break;
  213542. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213543. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213544. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213545. case E_NOTIMPL: result = "Unsupported function"; break;
  213546. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213547. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213548. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213549. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213550. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213551. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213552. case E_NOINTERFACE: result = "No interface"; break;
  213553. case S_OK: result = "No error"; break;
  213554. default: return "Unknown error: " + String ((int) hr);
  213555. }
  213556. return result;
  213557. }
  213558. #define DS_DEBUGGING 1
  213559. #ifdef DS_DEBUGGING
  213560. #define CATCH JUCE_CATCH_EXCEPTION
  213561. #undef log
  213562. #define log(a) Logger::writeToLog(a);
  213563. #undef logError
  213564. #define logError(a) logDSError(a, __LINE__);
  213565. static void logDSError (HRESULT hr, int lineNum)
  213566. {
  213567. if (hr != S_OK)
  213568. {
  213569. String error ("DS error at line ");
  213570. error << lineNum << " - " << getDSErrorMessage (hr);
  213571. log (error);
  213572. }
  213573. }
  213574. #else
  213575. #define CATCH JUCE_CATCH_ALL
  213576. #define log(a)
  213577. #define logError(a)
  213578. #endif
  213579. #define DSOUND_FUNCTION(functionName, params) \
  213580. typedef HRESULT (WINAPI *type##functionName) params; \
  213581. static type##functionName ds##functionName = 0;
  213582. #define DSOUND_FUNCTION_LOAD(functionName) \
  213583. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213584. jassert (ds##functionName != 0);
  213585. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213586. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213587. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213588. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213589. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213590. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213591. void initialiseDSoundFunctions()
  213592. {
  213593. if (dsDirectSoundCreate == 0)
  213594. {
  213595. HMODULE h = LoadLibraryA ("dsound.dll");
  213596. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213597. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213598. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213599. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213600. }
  213601. }
  213602. }
  213603. class DSoundInternalOutChannel
  213604. {
  213605. public:
  213606. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  213607. int bufferSize, float* left, float* right)
  213608. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213609. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213610. pDirectSound (0), pOutputBuffer (0)
  213611. {
  213612. }
  213613. ~DSoundInternalOutChannel()
  213614. {
  213615. close();
  213616. }
  213617. void close()
  213618. {
  213619. HRESULT hr;
  213620. if (pOutputBuffer != 0)
  213621. {
  213622. log ("closing dsound out: " + name);
  213623. hr = pOutputBuffer->Stop();
  213624. logError (hr);
  213625. hr = pOutputBuffer->Release();
  213626. pOutputBuffer = 0;
  213627. logError (hr);
  213628. }
  213629. if (pDirectSound != 0)
  213630. {
  213631. hr = pDirectSound->Release();
  213632. pDirectSound = 0;
  213633. logError (hr);
  213634. }
  213635. }
  213636. const String open()
  213637. {
  213638. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213639. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213640. pDirectSound = 0;
  213641. pOutputBuffer = 0;
  213642. writeOffset = 0;
  213643. String error;
  213644. HRESULT hr = E_NOINTERFACE;
  213645. if (dsDirectSoundCreate != 0)
  213646. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213647. if (hr == S_OK)
  213648. {
  213649. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213650. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213651. const int numChannels = 2;
  213652. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213653. logError (hr);
  213654. if (hr == S_OK)
  213655. {
  213656. IDirectSoundBuffer* pPrimaryBuffer;
  213657. DSBUFFERDESC primaryDesc;
  213658. zerostruct (primaryDesc);
  213659. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213660. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213661. primaryDesc.dwBufferBytes = 0;
  213662. primaryDesc.lpwfxFormat = 0;
  213663. log ("opening dsound out step 2");
  213664. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213665. logError (hr);
  213666. if (hr == S_OK)
  213667. {
  213668. WAVEFORMATEX wfFormat;
  213669. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213670. wfFormat.nChannels = (unsigned short) numChannels;
  213671. wfFormat.nSamplesPerSec = sampleRate;
  213672. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213673. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213674. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213675. wfFormat.cbSize = 0;
  213676. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213677. logError (hr);
  213678. if (hr == S_OK)
  213679. {
  213680. DSBUFFERDESC secondaryDesc;
  213681. zerostruct (secondaryDesc);
  213682. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213683. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213684. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213685. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213686. secondaryDesc.lpwfxFormat = &wfFormat;
  213687. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213688. logError (hr);
  213689. if (hr == S_OK)
  213690. {
  213691. log ("opening dsound out step 3");
  213692. DWORD dwDataLen;
  213693. unsigned char* pDSBuffData;
  213694. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213695. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213696. logError (hr);
  213697. if (hr == S_OK)
  213698. {
  213699. zeromem (pDSBuffData, dwDataLen);
  213700. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213701. if (hr == S_OK)
  213702. {
  213703. hr = pOutputBuffer->SetCurrentPosition (0);
  213704. if (hr == S_OK)
  213705. {
  213706. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213707. if (hr == S_OK)
  213708. return String::empty;
  213709. }
  213710. }
  213711. }
  213712. }
  213713. }
  213714. }
  213715. }
  213716. }
  213717. error = getDSErrorMessage (hr);
  213718. close();
  213719. return error;
  213720. }
  213721. void synchronisePosition()
  213722. {
  213723. if (pOutputBuffer != 0)
  213724. {
  213725. DWORD playCursor;
  213726. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213727. }
  213728. }
  213729. bool service()
  213730. {
  213731. if (pOutputBuffer == 0)
  213732. return true;
  213733. DWORD playCursor, writeCursor;
  213734. for (;;)
  213735. {
  213736. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213737. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213738. {
  213739. pOutputBuffer->Restore();
  213740. continue;
  213741. }
  213742. if (hr == S_OK)
  213743. break;
  213744. logError (hr);
  213745. jassertfalse;
  213746. return true;
  213747. }
  213748. int playWriteGap = writeCursor - playCursor;
  213749. if (playWriteGap < 0)
  213750. playWriteGap += totalBytesPerBuffer;
  213751. int bytesEmpty = playCursor - writeOffset;
  213752. if (bytesEmpty < 0)
  213753. bytesEmpty += totalBytesPerBuffer;
  213754. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213755. {
  213756. writeOffset = writeCursor;
  213757. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213758. }
  213759. if (bytesEmpty >= bytesPerBuffer)
  213760. {
  213761. void* lpbuf1 = 0;
  213762. void* lpbuf2 = 0;
  213763. DWORD dwSize1 = 0;
  213764. DWORD dwSize2 = 0;
  213765. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213766. &lpbuf1, &dwSize1,
  213767. &lpbuf2, &dwSize2, 0);
  213768. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213769. {
  213770. pOutputBuffer->Restore();
  213771. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213772. &lpbuf1, &dwSize1,
  213773. &lpbuf2, &dwSize2, 0);
  213774. }
  213775. if (hr == S_OK)
  213776. {
  213777. if (bitDepth == 16)
  213778. {
  213779. int* dest = static_cast<int*> (lpbuf1);
  213780. const float* left = leftBuffer;
  213781. const float* right = rightBuffer;
  213782. int samples1 = dwSize1 >> 2;
  213783. int samples2 = dwSize2 >> 2;
  213784. if (left == 0)
  213785. {
  213786. while (--samples1 >= 0)
  213787. *dest++ = (convertInputValue (*right++) << 16);
  213788. dest = static_cast<int*> (lpbuf2);
  213789. while (--samples2 >= 0)
  213790. *dest++ = (convertInputValue (*right++) << 16);
  213791. }
  213792. else if (right == 0)
  213793. {
  213794. while (--samples1 >= 0)
  213795. *dest++ = (0xffff & convertInputValue (*left++));
  213796. dest = static_cast<int*> (lpbuf2);
  213797. while (--samples2 >= 0)
  213798. *dest++ = (0xffff & convertInputValue (*left++));
  213799. }
  213800. else
  213801. {
  213802. while (--samples1 >= 0)
  213803. {
  213804. const int l = convertInputValue (*left++);
  213805. const int r = convertInputValue (*right++);
  213806. *dest++ = (r << 16) | (0xffff & l);
  213807. }
  213808. dest = static_cast<int*> (lpbuf2);
  213809. while (--samples2 >= 0)
  213810. {
  213811. const int l = convertInputValue (*left++);
  213812. const int r = convertInputValue (*right++);
  213813. *dest++ = (r << 16) | (0xffff & l);
  213814. }
  213815. }
  213816. }
  213817. else
  213818. {
  213819. jassertfalse;
  213820. }
  213821. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213822. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213823. }
  213824. else
  213825. {
  213826. jassertfalse;
  213827. logError (hr);
  213828. }
  213829. bytesEmpty -= bytesPerBuffer;
  213830. return true;
  213831. }
  213832. else
  213833. {
  213834. return false;
  213835. }
  213836. }
  213837. int bitDepth;
  213838. bool doneFlag;
  213839. private:
  213840. String name;
  213841. LPGUID guid;
  213842. int sampleRate, bufferSizeSamples;
  213843. float* leftBuffer;
  213844. float* rightBuffer;
  213845. IDirectSound* pDirectSound;
  213846. IDirectSoundBuffer* pOutputBuffer;
  213847. DWORD writeOffset;
  213848. int totalBytesPerBuffer, bytesPerBuffer;
  213849. unsigned int lastPlayCursor;
  213850. static inline int convertInputValue (const float v) throw()
  213851. {
  213852. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  213853. }
  213854. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  213855. };
  213856. struct DSoundInternalInChannel
  213857. {
  213858. public:
  213859. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  213860. int bufferSize, float* left, float* right)
  213861. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213862. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213863. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  213864. {
  213865. }
  213866. ~DSoundInternalInChannel()
  213867. {
  213868. close();
  213869. }
  213870. void close()
  213871. {
  213872. HRESULT hr;
  213873. if (pInputBuffer != 0)
  213874. {
  213875. log ("closing dsound in: " + name);
  213876. hr = pInputBuffer->Stop();
  213877. logError (hr);
  213878. hr = pInputBuffer->Release();
  213879. pInputBuffer = 0;
  213880. logError (hr);
  213881. }
  213882. if (pDirectSoundCapture != 0)
  213883. {
  213884. hr = pDirectSoundCapture->Release();
  213885. pDirectSoundCapture = 0;
  213886. logError (hr);
  213887. }
  213888. if (pDirectSound != 0)
  213889. {
  213890. hr = pDirectSound->Release();
  213891. pDirectSound = 0;
  213892. logError (hr);
  213893. }
  213894. }
  213895. const String open()
  213896. {
  213897. log ("opening dsound in device: " + name
  213898. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213899. pDirectSound = 0;
  213900. pDirectSoundCapture = 0;
  213901. pInputBuffer = 0;
  213902. readOffset = 0;
  213903. totalBytesPerBuffer = 0;
  213904. String error;
  213905. HRESULT hr = E_NOINTERFACE;
  213906. if (dsDirectSoundCaptureCreate != 0)
  213907. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213908. logError (hr);
  213909. if (hr == S_OK)
  213910. {
  213911. const int numChannels = 2;
  213912. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213913. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213914. WAVEFORMATEX wfFormat;
  213915. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213916. wfFormat.nChannels = (unsigned short)numChannels;
  213917. wfFormat.nSamplesPerSec = sampleRate;
  213918. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213919. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213920. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213921. wfFormat.cbSize = 0;
  213922. DSCBUFFERDESC captureDesc;
  213923. zerostruct (captureDesc);
  213924. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213925. captureDesc.dwFlags = 0;
  213926. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213927. captureDesc.lpwfxFormat = &wfFormat;
  213928. log ("opening dsound in step 2");
  213929. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213930. logError (hr);
  213931. if (hr == S_OK)
  213932. {
  213933. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213934. logError (hr);
  213935. if (hr == S_OK)
  213936. return String::empty;
  213937. }
  213938. }
  213939. error = getDSErrorMessage (hr);
  213940. close();
  213941. return error;
  213942. }
  213943. void synchronisePosition()
  213944. {
  213945. if (pInputBuffer != 0)
  213946. {
  213947. DWORD capturePos;
  213948. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213949. }
  213950. }
  213951. bool service()
  213952. {
  213953. if (pInputBuffer == 0)
  213954. return true;
  213955. DWORD capturePos, readPos;
  213956. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213957. logError (hr);
  213958. if (hr != S_OK)
  213959. return true;
  213960. int bytesFilled = readPos - readOffset;
  213961. if (bytesFilled < 0)
  213962. bytesFilled += totalBytesPerBuffer;
  213963. if (bytesFilled >= bytesPerBuffer)
  213964. {
  213965. LPBYTE lpbuf1 = 0;
  213966. LPBYTE lpbuf2 = 0;
  213967. DWORD dwsize1 = 0;
  213968. DWORD dwsize2 = 0;
  213969. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  213970. (void**) &lpbuf1, &dwsize1,
  213971. (void**) &lpbuf2, &dwsize2, 0);
  213972. if (hr == S_OK)
  213973. {
  213974. if (bitDepth == 16)
  213975. {
  213976. const float g = 1.0f / 32768.0f;
  213977. float* destL = leftBuffer;
  213978. float* destR = rightBuffer;
  213979. int samples1 = dwsize1 >> 2;
  213980. int samples2 = dwsize2 >> 2;
  213981. const short* src = (const short*)lpbuf1;
  213982. if (destL == 0)
  213983. {
  213984. while (--samples1 >= 0)
  213985. {
  213986. ++src;
  213987. *destR++ = *src++ * g;
  213988. }
  213989. src = (const short*)lpbuf2;
  213990. while (--samples2 >= 0)
  213991. {
  213992. ++src;
  213993. *destR++ = *src++ * g;
  213994. }
  213995. }
  213996. else if (destR == 0)
  213997. {
  213998. while (--samples1 >= 0)
  213999. {
  214000. *destL++ = *src++ * g;
  214001. ++src;
  214002. }
  214003. src = (const short*)lpbuf2;
  214004. while (--samples2 >= 0)
  214005. {
  214006. *destL++ = *src++ * g;
  214007. ++src;
  214008. }
  214009. }
  214010. else
  214011. {
  214012. while (--samples1 >= 0)
  214013. {
  214014. *destL++ = *src++ * g;
  214015. *destR++ = *src++ * g;
  214016. }
  214017. src = (const short*)lpbuf2;
  214018. while (--samples2 >= 0)
  214019. {
  214020. *destL++ = *src++ * g;
  214021. *destR++ = *src++ * g;
  214022. }
  214023. }
  214024. }
  214025. else
  214026. {
  214027. jassertfalse;
  214028. }
  214029. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214030. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214031. }
  214032. else
  214033. {
  214034. logError (hr);
  214035. jassertfalse;
  214036. }
  214037. bytesFilled -= bytesPerBuffer;
  214038. return true;
  214039. }
  214040. else
  214041. {
  214042. return false;
  214043. }
  214044. }
  214045. unsigned int readOffset;
  214046. int bytesPerBuffer, totalBytesPerBuffer;
  214047. int bitDepth;
  214048. bool doneFlag;
  214049. private:
  214050. String name;
  214051. LPGUID guid;
  214052. int sampleRate, bufferSizeSamples;
  214053. float* leftBuffer;
  214054. float* rightBuffer;
  214055. IDirectSound* pDirectSound;
  214056. IDirectSoundCapture* pDirectSoundCapture;
  214057. IDirectSoundCaptureBuffer* pInputBuffer;
  214058. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214059. };
  214060. class DSoundAudioIODevice : public AudioIODevice,
  214061. public Thread
  214062. {
  214063. public:
  214064. DSoundAudioIODevice (const String& deviceName,
  214065. const int outputDeviceIndex_,
  214066. const int inputDeviceIndex_)
  214067. : AudioIODevice (deviceName, "DirectSound"),
  214068. Thread ("Juce DSound"),
  214069. outputDeviceIndex (outputDeviceIndex_),
  214070. inputDeviceIndex (inputDeviceIndex_),
  214071. isOpen_ (false),
  214072. isStarted (false),
  214073. bufferSizeSamples (0),
  214074. totalSamplesOut (0),
  214075. sampleRate (0.0),
  214076. inputBuffers (1, 1),
  214077. outputBuffers (1, 1),
  214078. callback (0)
  214079. {
  214080. if (outputDeviceIndex_ >= 0)
  214081. {
  214082. outChannels.add (TRANS("Left"));
  214083. outChannels.add (TRANS("Right"));
  214084. }
  214085. if (inputDeviceIndex_ >= 0)
  214086. {
  214087. inChannels.add (TRANS("Left"));
  214088. inChannels.add (TRANS("Right"));
  214089. }
  214090. }
  214091. ~DSoundAudioIODevice()
  214092. {
  214093. close();
  214094. }
  214095. const String open (const BigInteger& inputChannels,
  214096. const BigInteger& outputChannels,
  214097. double sampleRate, int bufferSizeSamples)
  214098. {
  214099. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214100. isOpen_ = lastError.isEmpty();
  214101. return lastError;
  214102. }
  214103. void close()
  214104. {
  214105. stop();
  214106. if (isOpen_)
  214107. {
  214108. closeDevice();
  214109. isOpen_ = false;
  214110. }
  214111. }
  214112. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214113. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214114. double getCurrentSampleRate() { return sampleRate; }
  214115. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214116. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214117. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214118. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214119. const StringArray getOutputChannelNames() { return outChannels; }
  214120. const StringArray getInputChannelNames() { return inChannels; }
  214121. int getNumSampleRates() { return 4; }
  214122. int getDefaultBufferSize() { return 2560; }
  214123. int getNumBufferSizesAvailable() { return 50; }
  214124. double getSampleRate (int index)
  214125. {
  214126. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214127. return samps [jlimit (0, 3, index)];
  214128. }
  214129. int getBufferSizeSamples (int index)
  214130. {
  214131. int n = 64;
  214132. for (int i = 0; i < index; ++i)
  214133. n += (n < 512) ? 32
  214134. : ((n < 1024) ? 64
  214135. : ((n < 2048) ? 128 : 256));
  214136. return n;
  214137. }
  214138. int getCurrentBitDepth()
  214139. {
  214140. int i, bits = 256;
  214141. for (i = inChans.size(); --i >= 0;)
  214142. bits = jmin (bits, inChans[i]->bitDepth);
  214143. for (i = outChans.size(); --i >= 0;)
  214144. bits = jmin (bits, outChans[i]->bitDepth);
  214145. if (bits > 32)
  214146. bits = 16;
  214147. return bits;
  214148. }
  214149. void start (AudioIODeviceCallback* call)
  214150. {
  214151. if (isOpen_ && call != 0 && ! isStarted)
  214152. {
  214153. if (! isThreadRunning())
  214154. {
  214155. // something gone wrong and the thread's stopped..
  214156. isOpen_ = false;
  214157. return;
  214158. }
  214159. call->audioDeviceAboutToStart (this);
  214160. const ScopedLock sl (startStopLock);
  214161. callback = call;
  214162. isStarted = true;
  214163. }
  214164. }
  214165. void stop()
  214166. {
  214167. if (isStarted)
  214168. {
  214169. AudioIODeviceCallback* const callbackLocal = callback;
  214170. {
  214171. const ScopedLock sl (startStopLock);
  214172. isStarted = false;
  214173. }
  214174. if (callbackLocal != 0)
  214175. callbackLocal->audioDeviceStopped();
  214176. }
  214177. }
  214178. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214179. const String getLastError() { return lastError; }
  214180. StringArray inChannels, outChannels;
  214181. int outputDeviceIndex, inputDeviceIndex;
  214182. private:
  214183. bool isOpen_;
  214184. bool isStarted;
  214185. String lastError;
  214186. OwnedArray <DSoundInternalInChannel> inChans;
  214187. OwnedArray <DSoundInternalOutChannel> outChans;
  214188. WaitableEvent startEvent;
  214189. int bufferSizeSamples;
  214190. int volatile totalSamplesOut;
  214191. int64 volatile lastBlockTime;
  214192. double sampleRate;
  214193. BigInteger enabledInputs, enabledOutputs;
  214194. AudioSampleBuffer inputBuffers, outputBuffers;
  214195. AudioIODeviceCallback* callback;
  214196. CriticalSection startStopLock;
  214197. const String openDevice (const BigInteger& inputChannels,
  214198. const BigInteger& outputChannels,
  214199. double sampleRate_, int bufferSizeSamples_);
  214200. void closeDevice()
  214201. {
  214202. isStarted = false;
  214203. stopThread (5000);
  214204. inChans.clear();
  214205. outChans.clear();
  214206. inputBuffers.setSize (1, 1);
  214207. outputBuffers.setSize (1, 1);
  214208. }
  214209. void resync()
  214210. {
  214211. if (! threadShouldExit())
  214212. {
  214213. sleep (5);
  214214. int i;
  214215. for (i = 0; i < outChans.size(); ++i)
  214216. outChans.getUnchecked(i)->synchronisePosition();
  214217. for (i = 0; i < inChans.size(); ++i)
  214218. inChans.getUnchecked(i)->synchronisePosition();
  214219. }
  214220. }
  214221. public:
  214222. void run()
  214223. {
  214224. while (! threadShouldExit())
  214225. {
  214226. if (wait (100))
  214227. break;
  214228. }
  214229. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214230. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214231. while (! threadShouldExit())
  214232. {
  214233. int numToDo = 0;
  214234. uint32 startTime = Time::getMillisecondCounter();
  214235. int i;
  214236. for (i = inChans.size(); --i >= 0;)
  214237. {
  214238. inChans.getUnchecked(i)->doneFlag = false;
  214239. ++numToDo;
  214240. }
  214241. for (i = outChans.size(); --i >= 0;)
  214242. {
  214243. outChans.getUnchecked(i)->doneFlag = false;
  214244. ++numToDo;
  214245. }
  214246. if (numToDo > 0)
  214247. {
  214248. const int maxCount = 3;
  214249. int count = maxCount;
  214250. for (;;)
  214251. {
  214252. for (i = inChans.size(); --i >= 0;)
  214253. {
  214254. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214255. if ((! in->doneFlag) && in->service())
  214256. {
  214257. in->doneFlag = true;
  214258. --numToDo;
  214259. }
  214260. }
  214261. for (i = outChans.size(); --i >= 0;)
  214262. {
  214263. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214264. if ((! out->doneFlag) && out->service())
  214265. {
  214266. out->doneFlag = true;
  214267. --numToDo;
  214268. }
  214269. }
  214270. if (numToDo <= 0)
  214271. break;
  214272. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214273. {
  214274. resync();
  214275. break;
  214276. }
  214277. if (--count <= 0)
  214278. {
  214279. Sleep (1);
  214280. count = maxCount;
  214281. }
  214282. if (threadShouldExit())
  214283. return;
  214284. }
  214285. }
  214286. else
  214287. {
  214288. sleep (1);
  214289. }
  214290. const ScopedLock sl (startStopLock);
  214291. if (isStarted)
  214292. {
  214293. JUCE_TRY
  214294. {
  214295. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214296. inputBuffers.getNumChannels(),
  214297. outputBuffers.getArrayOfChannels(),
  214298. outputBuffers.getNumChannels(),
  214299. bufferSizeSamples);
  214300. }
  214301. JUCE_CATCH_EXCEPTION
  214302. totalSamplesOut += bufferSizeSamples;
  214303. }
  214304. else
  214305. {
  214306. outputBuffers.clear();
  214307. totalSamplesOut = 0;
  214308. sleep (1);
  214309. }
  214310. }
  214311. }
  214312. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214313. };
  214314. class DSoundAudioIODeviceType : public AudioIODeviceType
  214315. {
  214316. public:
  214317. DSoundAudioIODeviceType()
  214318. : AudioIODeviceType ("DirectSound"),
  214319. hasScanned (false)
  214320. {
  214321. initialiseDSoundFunctions();
  214322. }
  214323. void scanForDevices()
  214324. {
  214325. hasScanned = true;
  214326. outputDeviceNames.clear();
  214327. outputGuids.clear();
  214328. inputDeviceNames.clear();
  214329. inputGuids.clear();
  214330. if (dsDirectSoundEnumerateW != 0)
  214331. {
  214332. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214333. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214334. }
  214335. }
  214336. const StringArray getDeviceNames (bool wantInputNames) const
  214337. {
  214338. jassert (hasScanned); // need to call scanForDevices() before doing this
  214339. return wantInputNames ? inputDeviceNames
  214340. : outputDeviceNames;
  214341. }
  214342. int getDefaultDeviceIndex (bool /*forInput*/) const
  214343. {
  214344. jassert (hasScanned); // need to call scanForDevices() before doing this
  214345. return 0;
  214346. }
  214347. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214348. {
  214349. jassert (hasScanned); // need to call scanForDevices() before doing this
  214350. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214351. if (d == 0)
  214352. return -1;
  214353. return asInput ? d->inputDeviceIndex
  214354. : d->outputDeviceIndex;
  214355. }
  214356. bool hasSeparateInputsAndOutputs() const { return true; }
  214357. AudioIODevice* createDevice (const String& outputDeviceName,
  214358. const String& inputDeviceName)
  214359. {
  214360. jassert (hasScanned); // need to call scanForDevices() before doing this
  214361. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214362. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214363. if (outputIndex >= 0 || inputIndex >= 0)
  214364. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214365. : inputDeviceName,
  214366. outputIndex, inputIndex);
  214367. return 0;
  214368. }
  214369. StringArray outputDeviceNames, inputDeviceNames;
  214370. OwnedArray <GUID> outputGuids, inputGuids;
  214371. private:
  214372. bool hasScanned;
  214373. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214374. {
  214375. desc = desc.trim();
  214376. if (desc.isNotEmpty())
  214377. {
  214378. const String origDesc (desc);
  214379. int n = 2;
  214380. while (outputDeviceNames.contains (desc))
  214381. desc = origDesc + " (" + String (n++) + ")";
  214382. outputDeviceNames.add (desc);
  214383. if (lpGUID != 0)
  214384. outputGuids.add (new GUID (*lpGUID));
  214385. else
  214386. outputGuids.add (0);
  214387. }
  214388. return TRUE;
  214389. }
  214390. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214391. {
  214392. return ((DSoundAudioIODeviceType*) object)
  214393. ->outputEnumProc (lpGUID, String (description));
  214394. }
  214395. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214396. {
  214397. return ((DSoundAudioIODeviceType*) object)
  214398. ->outputEnumProc (lpGUID, String (description));
  214399. }
  214400. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214401. {
  214402. desc = desc.trim();
  214403. if (desc.isNotEmpty())
  214404. {
  214405. const String origDesc (desc);
  214406. int n = 2;
  214407. while (inputDeviceNames.contains (desc))
  214408. desc = origDesc + " (" + String (n++) + ")";
  214409. inputDeviceNames.add (desc);
  214410. if (lpGUID != 0)
  214411. inputGuids.add (new GUID (*lpGUID));
  214412. else
  214413. inputGuids.add (0);
  214414. }
  214415. return TRUE;
  214416. }
  214417. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214418. {
  214419. return ((DSoundAudioIODeviceType*) object)
  214420. ->inputEnumProc (lpGUID, String (description));
  214421. }
  214422. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214423. {
  214424. return ((DSoundAudioIODeviceType*) object)
  214425. ->inputEnumProc (lpGUID, String (description));
  214426. }
  214427. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214428. };
  214429. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214430. const BigInteger& outputChannels,
  214431. double sampleRate_, int bufferSizeSamples_)
  214432. {
  214433. closeDevice();
  214434. totalSamplesOut = 0;
  214435. sampleRate = sampleRate_;
  214436. if (bufferSizeSamples_ <= 0)
  214437. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214438. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214439. DSoundAudioIODeviceType dlh;
  214440. dlh.scanForDevices();
  214441. enabledInputs = inputChannels;
  214442. enabledInputs.setRange (inChannels.size(),
  214443. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214444. false);
  214445. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214446. inputBuffers.clear();
  214447. int i, numIns = 0;
  214448. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214449. {
  214450. float* left = 0;
  214451. if (enabledInputs[i])
  214452. left = inputBuffers.getSampleData (numIns++);
  214453. float* right = 0;
  214454. if (enabledInputs[i + 1])
  214455. right = inputBuffers.getSampleData (numIns++);
  214456. if (left != 0 || right != 0)
  214457. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214458. dlh.inputGuids [inputDeviceIndex],
  214459. (int) sampleRate, bufferSizeSamples,
  214460. left, right));
  214461. }
  214462. enabledOutputs = outputChannels;
  214463. enabledOutputs.setRange (outChannels.size(),
  214464. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214465. false);
  214466. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214467. outputBuffers.clear();
  214468. int numOuts = 0;
  214469. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214470. {
  214471. float* left = 0;
  214472. if (enabledOutputs[i])
  214473. left = outputBuffers.getSampleData (numOuts++);
  214474. float* right = 0;
  214475. if (enabledOutputs[i + 1])
  214476. right = outputBuffers.getSampleData (numOuts++);
  214477. if (left != 0 || right != 0)
  214478. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214479. dlh.outputGuids [outputDeviceIndex],
  214480. (int) sampleRate, bufferSizeSamples,
  214481. left, right));
  214482. }
  214483. String error;
  214484. // boost our priority while opening the devices to try to get better sync between them
  214485. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214486. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214487. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214488. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214489. for (i = 0; i < outChans.size(); ++i)
  214490. {
  214491. error = outChans[i]->open();
  214492. if (error.isNotEmpty())
  214493. {
  214494. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214495. break;
  214496. }
  214497. }
  214498. if (error.isEmpty())
  214499. {
  214500. for (i = 0; i < inChans.size(); ++i)
  214501. {
  214502. error = inChans[i]->open();
  214503. if (error.isNotEmpty())
  214504. {
  214505. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214506. break;
  214507. }
  214508. }
  214509. }
  214510. if (error.isEmpty())
  214511. {
  214512. totalSamplesOut = 0;
  214513. for (i = 0; i < outChans.size(); ++i)
  214514. outChans.getUnchecked(i)->synchronisePosition();
  214515. for (i = 0; i < inChans.size(); ++i)
  214516. inChans.getUnchecked(i)->synchronisePosition();
  214517. startThread (9);
  214518. sleep (10);
  214519. notify();
  214520. }
  214521. else
  214522. {
  214523. log (error);
  214524. }
  214525. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214526. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214527. return error;
  214528. }
  214529. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214530. {
  214531. return new DSoundAudioIODeviceType();
  214532. }
  214533. #undef log
  214534. #endif
  214535. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214536. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214537. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214538. // compiled on its own).
  214539. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214540. #ifndef WASAPI_ENABLE_LOGGING
  214541. #define WASAPI_ENABLE_LOGGING 0
  214542. #endif
  214543. namespace WasapiClasses
  214544. {
  214545. void logFailure (HRESULT hr)
  214546. {
  214547. (void) hr;
  214548. #if WASAPI_ENABLE_LOGGING
  214549. if (FAILED (hr))
  214550. {
  214551. String e;
  214552. e << Time::getCurrentTime().toString (true, true, true, true)
  214553. << " -- WASAPI error: ";
  214554. switch (hr)
  214555. {
  214556. case E_POINTER: e << "E_POINTER"; break;
  214557. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  214558. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  214559. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214560. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214561. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214562. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  214563. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214564. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  214565. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214566. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  214567. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  214568. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214569. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214570. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214571. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214572. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214573. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214574. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214575. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214576. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214577. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214578. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214579. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  214580. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214581. default: e << String::toHexString ((int) hr); break;
  214582. }
  214583. DBG (e);
  214584. jassertfalse;
  214585. }
  214586. #endif
  214587. }
  214588. #undef check
  214589. bool check (HRESULT hr)
  214590. {
  214591. logFailure (hr);
  214592. return SUCCEEDED (hr);
  214593. }
  214594. const String getDeviceID (IMMDevice* const device)
  214595. {
  214596. String s;
  214597. WCHAR* deviceId = 0;
  214598. if (check (device->GetId (&deviceId)))
  214599. {
  214600. s = String (deviceId);
  214601. CoTaskMemFree (deviceId);
  214602. }
  214603. return s;
  214604. }
  214605. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  214606. {
  214607. EDataFlow flow = eRender;
  214608. ComSmartPtr <IMMEndpoint> endPoint;
  214609. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  214610. (void) check (endPoint->GetDataFlow (&flow));
  214611. return flow;
  214612. }
  214613. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214614. {
  214615. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214616. }
  214617. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214618. {
  214619. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214620. : sizeof (WAVEFORMATEX));
  214621. }
  214622. class WASAPIDeviceBase
  214623. {
  214624. public:
  214625. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214626. : device (device_),
  214627. sampleRate (0),
  214628. defaultSampleRate (0),
  214629. numChannels (0),
  214630. actualNumChannels (0),
  214631. minBufferSize (0),
  214632. defaultBufferSize (0),
  214633. latencySamples (0),
  214634. useExclusiveMode (useExclusiveMode_)
  214635. {
  214636. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214637. ComSmartPtr <IAudioClient> tempClient (createClient());
  214638. if (tempClient == 0)
  214639. return;
  214640. REFERENCE_TIME defaultPeriod, minPeriod;
  214641. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214642. return;
  214643. WAVEFORMATEX* mixFormat = 0;
  214644. if (! check (tempClient->GetMixFormat (&mixFormat)))
  214645. return;
  214646. WAVEFORMATEXTENSIBLE format;
  214647. copyWavFormat (format, mixFormat);
  214648. CoTaskMemFree (mixFormat);
  214649. actualNumChannels = numChannels = format.Format.nChannels;
  214650. defaultSampleRate = format.Format.nSamplesPerSec;
  214651. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  214652. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  214653. rates.addUsingDefaultSort (defaultSampleRate);
  214654. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214655. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214656. {
  214657. if (ratesToTest[i] == defaultSampleRate)
  214658. continue;
  214659. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214660. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214661. (WAVEFORMATEX*) &format, 0)))
  214662. if (! rates.contains (ratesToTest[i]))
  214663. rates.addUsingDefaultSort (ratesToTest[i]);
  214664. }
  214665. }
  214666. ~WASAPIDeviceBase()
  214667. {
  214668. device = 0;
  214669. CloseHandle (clientEvent);
  214670. }
  214671. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214672. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214673. {
  214674. sampleRate = newSampleRate;
  214675. channels = newChannels;
  214676. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214677. numChannels = channels.getHighestBit() + 1;
  214678. if (numChannels == 0)
  214679. return true;
  214680. client = createClient();
  214681. if (client != 0
  214682. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214683. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214684. {
  214685. channelMaps.clear();
  214686. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214687. if (channels[i])
  214688. channelMaps.add (i);
  214689. REFERENCE_TIME latency;
  214690. if (check (client->GetStreamLatency (&latency)))
  214691. latencySamples = refTimeToSamples (latency, sampleRate);
  214692. (void) check (client->GetBufferSize (&actualBufferSize));
  214693. return check (client->SetEventHandle (clientEvent));
  214694. }
  214695. return false;
  214696. }
  214697. void closeClient()
  214698. {
  214699. if (client != 0)
  214700. client->Stop();
  214701. client = 0;
  214702. ResetEvent (clientEvent);
  214703. }
  214704. ComSmartPtr <IMMDevice> device;
  214705. ComSmartPtr <IAudioClient> client;
  214706. double sampleRate, defaultSampleRate;
  214707. int numChannels, actualNumChannels;
  214708. int minBufferSize, defaultBufferSize, latencySamples;
  214709. const bool useExclusiveMode;
  214710. Array <double> rates;
  214711. HANDLE clientEvent;
  214712. BigInteger channels;
  214713. Array <int> channelMaps;
  214714. UINT32 actualBufferSize;
  214715. int bytesPerSample;
  214716. virtual void updateFormat (bool isFloat) = 0;
  214717. private:
  214718. const ComSmartPtr <IAudioClient> createClient()
  214719. {
  214720. ComSmartPtr <IAudioClient> client;
  214721. if (device != 0)
  214722. {
  214723. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  214724. logFailure (hr);
  214725. }
  214726. return client;
  214727. }
  214728. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214729. {
  214730. WAVEFORMATEXTENSIBLE format;
  214731. zerostruct (format);
  214732. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214733. {
  214734. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214735. }
  214736. else
  214737. {
  214738. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214739. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214740. }
  214741. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214742. format.Format.nChannels = (WORD) numChannels;
  214743. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214744. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214745. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214746. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214747. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214748. switch (numChannels)
  214749. {
  214750. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214751. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214752. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214753. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214754. 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;
  214755. default: break;
  214756. }
  214757. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214758. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214759. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214760. logFailure (hr);
  214761. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214762. {
  214763. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214764. hr = S_OK;
  214765. }
  214766. CoTaskMemFree (nearestFormat);
  214767. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214768. if (useExclusiveMode)
  214769. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214770. GUID session;
  214771. if (hr == S_OK
  214772. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214773. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214774. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214775. {
  214776. actualNumChannels = format.Format.nChannels;
  214777. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214778. bytesPerSample = format.Format.wBitsPerSample / 8;
  214779. updateFormat (isFloat);
  214780. return true;
  214781. }
  214782. return false;
  214783. }
  214784. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  214785. };
  214786. class WASAPIInputDevice : public WASAPIDeviceBase
  214787. {
  214788. public:
  214789. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214790. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214791. reservoir (1, 1)
  214792. {
  214793. }
  214794. ~WASAPIInputDevice()
  214795. {
  214796. close();
  214797. }
  214798. bool open (const double newSampleRate, const BigInteger& newChannels)
  214799. {
  214800. reservoirSize = 0;
  214801. reservoirCapacity = 16384;
  214802. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214803. return openClient (newSampleRate, newChannels)
  214804. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  214805. (void**) captureClient.resetAndGetPointerAddress())));
  214806. }
  214807. void close()
  214808. {
  214809. closeClient();
  214810. captureClient = 0;
  214811. reservoir.setSize (0);
  214812. }
  214813. template <class SourceType>
  214814. void updateFormatWithType (SourceType*)
  214815. {
  214816. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  214817. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  214818. }
  214819. void updateFormat (bool isFloat)
  214820. {
  214821. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214822. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214823. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214824. else updateFormatWithType ((AudioData::Int16*) 0);
  214825. }
  214826. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214827. {
  214828. if (numChannels <= 0)
  214829. return;
  214830. int offset = 0;
  214831. while (bufferSize > 0)
  214832. {
  214833. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214834. {
  214835. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214836. for (int i = 0; i < numDestBuffers; ++i)
  214837. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  214838. bufferSize -= samplesToDo;
  214839. offset += samplesToDo;
  214840. reservoirSize = 0;
  214841. }
  214842. else
  214843. {
  214844. UINT32 packetLength = 0;
  214845. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  214846. break;
  214847. if (packetLength == 0)
  214848. {
  214849. if (thread.threadShouldExit()
  214850. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214851. break;
  214852. continue;
  214853. }
  214854. uint8* inputData;
  214855. UINT32 numSamplesAvailable;
  214856. DWORD flags;
  214857. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214858. {
  214859. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214860. for (int i = 0; i < numDestBuffers; ++i)
  214861. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  214862. bufferSize -= samplesToDo;
  214863. offset += samplesToDo;
  214864. if (samplesToDo < (int) numSamplesAvailable)
  214865. {
  214866. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214867. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214868. bytesPerSample * actualNumChannels * reservoirSize);
  214869. }
  214870. captureClient->ReleaseBuffer (numSamplesAvailable);
  214871. }
  214872. }
  214873. }
  214874. }
  214875. ComSmartPtr <IAudioCaptureClient> captureClient;
  214876. MemoryBlock reservoir;
  214877. int reservoirSize, reservoirCapacity;
  214878. ScopedPointer <AudioData::Converter> converter;
  214879. private:
  214880. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  214881. };
  214882. class WASAPIOutputDevice : public WASAPIDeviceBase
  214883. {
  214884. public:
  214885. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214886. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214887. {
  214888. }
  214889. ~WASAPIOutputDevice()
  214890. {
  214891. close();
  214892. }
  214893. bool open (const double newSampleRate, const BigInteger& newChannels)
  214894. {
  214895. return openClient (newSampleRate, newChannels)
  214896. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  214897. }
  214898. void close()
  214899. {
  214900. closeClient();
  214901. renderClient = 0;
  214902. }
  214903. template <class DestType>
  214904. void updateFormatWithType (DestType*)
  214905. {
  214906. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  214907. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  214908. }
  214909. void updateFormat (bool isFloat)
  214910. {
  214911. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214912. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214913. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214914. else updateFormatWithType ((AudioData::Int16*) 0);
  214915. }
  214916. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214917. {
  214918. if (numChannels <= 0)
  214919. return;
  214920. int offset = 0;
  214921. while (bufferSize > 0)
  214922. {
  214923. UINT32 padding = 0;
  214924. if (! check (client->GetCurrentPadding (&padding)))
  214925. return;
  214926. int samplesToDo = useExclusiveMode ? bufferSize
  214927. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214928. if (samplesToDo <= 0)
  214929. {
  214930. if (thread.threadShouldExit()
  214931. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214932. break;
  214933. continue;
  214934. }
  214935. uint8* outputData = 0;
  214936. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  214937. {
  214938. for (int i = 0; i < numSrcBuffers; ++i)
  214939. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  214940. renderClient->ReleaseBuffer (samplesToDo, 0);
  214941. offset += samplesToDo;
  214942. bufferSize -= samplesToDo;
  214943. }
  214944. }
  214945. }
  214946. ComSmartPtr <IAudioRenderClient> renderClient;
  214947. ScopedPointer <AudioData::Converter> converter;
  214948. private:
  214949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  214950. };
  214951. class WASAPIAudioIODevice : public AudioIODevice,
  214952. public Thread
  214953. {
  214954. public:
  214955. WASAPIAudioIODevice (const String& deviceName,
  214956. const String& outputDeviceId_,
  214957. const String& inputDeviceId_,
  214958. const bool useExclusiveMode_)
  214959. : AudioIODevice (deviceName, "Windows Audio"),
  214960. Thread ("Juce WASAPI"),
  214961. outputDeviceId (outputDeviceId_),
  214962. inputDeviceId (inputDeviceId_),
  214963. useExclusiveMode (useExclusiveMode_),
  214964. isOpen_ (false),
  214965. isStarted (false),
  214966. currentBufferSizeSamples (0),
  214967. currentSampleRate (0),
  214968. callback (0)
  214969. {
  214970. }
  214971. ~WASAPIAudioIODevice()
  214972. {
  214973. close();
  214974. }
  214975. bool initialise()
  214976. {
  214977. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214978. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214979. latencyIn = latencyOut = 0;
  214980. Array <double> ratesIn, ratesOut;
  214981. if (createDevices())
  214982. {
  214983. jassert (inputDevice != 0 || outputDevice != 0);
  214984. if (inputDevice != 0 && outputDevice != 0)
  214985. {
  214986. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214987. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214988. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214989. sampleRates = inputDevice->rates;
  214990. sampleRates.removeValuesNotIn (outputDevice->rates);
  214991. }
  214992. else
  214993. {
  214994. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  214995. : static_cast<WASAPIDeviceBase*> (outputDevice);
  214996. defaultSampleRate = d->defaultSampleRate;
  214997. minBufferSize = d->minBufferSize;
  214998. defaultBufferSize = d->defaultBufferSize;
  214999. sampleRates = d->rates;
  215000. }
  215001. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215002. if (minBufferSize != defaultBufferSize)
  215003. bufferSizes.addUsingDefaultSort (minBufferSize);
  215004. int n = 64;
  215005. for (int i = 0; i < 40; ++i)
  215006. {
  215007. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215008. bufferSizes.addUsingDefaultSort (n);
  215009. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215010. }
  215011. return true;
  215012. }
  215013. return false;
  215014. }
  215015. const StringArray getOutputChannelNames()
  215016. {
  215017. StringArray outChannels;
  215018. if (outputDevice != 0)
  215019. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215020. outChannels.add ("Output channel " + String (i));
  215021. return outChannels;
  215022. }
  215023. const StringArray getInputChannelNames()
  215024. {
  215025. StringArray inChannels;
  215026. if (inputDevice != 0)
  215027. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215028. inChannels.add ("Input channel " + String (i));
  215029. return inChannels;
  215030. }
  215031. int getNumSampleRates() { return sampleRates.size(); }
  215032. double getSampleRate (int index) { return sampleRates [index]; }
  215033. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215034. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215035. int getDefaultBufferSize() { return defaultBufferSize; }
  215036. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215037. double getCurrentSampleRate() { return currentSampleRate; }
  215038. int getCurrentBitDepth() { return 32; }
  215039. int getOutputLatencyInSamples() { return latencyOut; }
  215040. int getInputLatencyInSamples() { return latencyIn; }
  215041. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215042. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215043. const String getLastError() { return lastError; }
  215044. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215045. double sampleRate, int bufferSizeSamples)
  215046. {
  215047. close();
  215048. lastError = String::empty;
  215049. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215050. {
  215051. lastError = "The input and output devices don't share a common sample rate!";
  215052. return lastError;
  215053. }
  215054. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215055. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215056. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215057. {
  215058. lastError = "Couldn't open the input device!";
  215059. return lastError;
  215060. }
  215061. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215062. {
  215063. close();
  215064. lastError = "Couldn't open the output device!";
  215065. return lastError;
  215066. }
  215067. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215068. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215069. startThread (8);
  215070. Thread::sleep (5);
  215071. if (inputDevice != 0 && inputDevice->client != 0)
  215072. {
  215073. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215074. HRESULT hr = inputDevice->client->Start();
  215075. logFailure (hr); //xxx handle this
  215076. }
  215077. if (outputDevice != 0 && outputDevice->client != 0)
  215078. {
  215079. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215080. HRESULT hr = outputDevice->client->Start();
  215081. logFailure (hr); //xxx handle this
  215082. }
  215083. isOpen_ = true;
  215084. return lastError;
  215085. }
  215086. void close()
  215087. {
  215088. stop();
  215089. signalThreadShouldExit();
  215090. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215091. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215092. stopThread (5000);
  215093. if (inputDevice != 0) inputDevice->close();
  215094. if (outputDevice != 0) outputDevice->close();
  215095. isOpen_ = false;
  215096. }
  215097. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215098. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215099. void start (AudioIODeviceCallback* call)
  215100. {
  215101. if (isOpen_ && call != 0 && ! isStarted)
  215102. {
  215103. if (! isThreadRunning())
  215104. {
  215105. // something's gone wrong and the thread's stopped..
  215106. isOpen_ = false;
  215107. return;
  215108. }
  215109. call->audioDeviceAboutToStart (this);
  215110. const ScopedLock sl (startStopLock);
  215111. callback = call;
  215112. isStarted = true;
  215113. }
  215114. }
  215115. void stop()
  215116. {
  215117. if (isStarted)
  215118. {
  215119. AudioIODeviceCallback* const callbackLocal = callback;
  215120. {
  215121. const ScopedLock sl (startStopLock);
  215122. isStarted = false;
  215123. }
  215124. if (callbackLocal != 0)
  215125. callbackLocal->audioDeviceStopped();
  215126. }
  215127. }
  215128. void setMMThreadPriority()
  215129. {
  215130. DynamicLibraryLoader dll ("avrt.dll");
  215131. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215132. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215133. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215134. {
  215135. DWORD dummy = 0;
  215136. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215137. if (h != 0)
  215138. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215139. }
  215140. }
  215141. void run()
  215142. {
  215143. setMMThreadPriority();
  215144. const int bufferSize = currentBufferSizeSamples;
  215145. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215146. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215147. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215148. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215149. float** const inputBuffers = ins.getArrayOfChannels();
  215150. float** const outputBuffers = outs.getArrayOfChannels();
  215151. ins.clear();
  215152. while (! threadShouldExit())
  215153. {
  215154. if (inputDevice != 0)
  215155. {
  215156. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215157. if (threadShouldExit())
  215158. break;
  215159. }
  215160. JUCE_TRY
  215161. {
  215162. const ScopedLock sl (startStopLock);
  215163. if (isStarted)
  215164. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215165. outputBuffers, numOutputBuffers, bufferSize);
  215166. else
  215167. outs.clear();
  215168. }
  215169. JUCE_CATCH_EXCEPTION
  215170. if (outputDevice != 0)
  215171. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215172. }
  215173. }
  215174. String outputDeviceId, inputDeviceId;
  215175. String lastError;
  215176. private:
  215177. // Device stats...
  215178. ScopedPointer<WASAPIInputDevice> inputDevice;
  215179. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215180. const bool useExclusiveMode;
  215181. double defaultSampleRate;
  215182. int minBufferSize, defaultBufferSize;
  215183. int latencyIn, latencyOut;
  215184. Array <double> sampleRates;
  215185. Array <int> bufferSizes;
  215186. // Active state...
  215187. bool isOpen_, isStarted;
  215188. int currentBufferSizeSamples;
  215189. double currentSampleRate;
  215190. AudioIODeviceCallback* callback;
  215191. CriticalSection startStopLock;
  215192. bool createDevices()
  215193. {
  215194. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215195. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215196. return false;
  215197. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215198. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215199. return false;
  215200. UINT32 numDevices = 0;
  215201. if (! check (deviceCollection->GetCount (&numDevices)))
  215202. return false;
  215203. for (UINT32 i = 0; i < numDevices; ++i)
  215204. {
  215205. ComSmartPtr <IMMDevice> device;
  215206. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215207. continue;
  215208. const String deviceId (getDeviceID (device));
  215209. if (deviceId.isEmpty())
  215210. continue;
  215211. const EDataFlow flow = getDataFlow (device);
  215212. if (deviceId == inputDeviceId && flow == eCapture)
  215213. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215214. else if (deviceId == outputDeviceId && flow == eRender)
  215215. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215216. }
  215217. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215218. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215219. }
  215220. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215221. };
  215222. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215223. {
  215224. public:
  215225. WASAPIAudioIODeviceType()
  215226. : AudioIODeviceType ("Windows Audio"),
  215227. hasScanned (false)
  215228. {
  215229. }
  215230. ~WASAPIAudioIODeviceType()
  215231. {
  215232. }
  215233. void scanForDevices()
  215234. {
  215235. hasScanned = true;
  215236. outputDeviceNames.clear();
  215237. inputDeviceNames.clear();
  215238. outputDeviceIds.clear();
  215239. inputDeviceIds.clear();
  215240. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215241. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215242. return;
  215243. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215244. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215245. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215246. UINT32 numDevices = 0;
  215247. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215248. && check (deviceCollection->GetCount (&numDevices))))
  215249. return;
  215250. for (UINT32 i = 0; i < numDevices; ++i)
  215251. {
  215252. ComSmartPtr <IMMDevice> device;
  215253. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215254. continue;
  215255. const String deviceId (getDeviceID (device));
  215256. DWORD state = 0;
  215257. if (! check (device->GetState (&state)))
  215258. continue;
  215259. if (state != DEVICE_STATE_ACTIVE)
  215260. continue;
  215261. String name;
  215262. {
  215263. ComSmartPtr <IPropertyStore> properties;
  215264. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215265. continue;
  215266. PROPVARIANT value;
  215267. PropVariantInit (&value);
  215268. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215269. name = value.pwszVal;
  215270. PropVariantClear (&value);
  215271. }
  215272. const EDataFlow flow = getDataFlow (device);
  215273. if (flow == eRender)
  215274. {
  215275. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215276. outputDeviceIds.insert (index, deviceId);
  215277. outputDeviceNames.insert (index, name);
  215278. }
  215279. else if (flow == eCapture)
  215280. {
  215281. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215282. inputDeviceIds.insert (index, deviceId);
  215283. inputDeviceNames.insert (index, name);
  215284. }
  215285. }
  215286. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215287. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215288. }
  215289. const StringArray getDeviceNames (bool wantInputNames) const
  215290. {
  215291. jassert (hasScanned); // need to call scanForDevices() before doing this
  215292. return wantInputNames ? inputDeviceNames
  215293. : outputDeviceNames;
  215294. }
  215295. int getDefaultDeviceIndex (bool /*forInput*/) const
  215296. {
  215297. jassert (hasScanned); // need to call scanForDevices() before doing this
  215298. return 0;
  215299. }
  215300. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215301. {
  215302. jassert (hasScanned); // need to call scanForDevices() before doing this
  215303. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215304. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215305. : outputDeviceIds.indexOf (d->outputDeviceId));
  215306. }
  215307. bool hasSeparateInputsAndOutputs() const { return true; }
  215308. AudioIODevice* createDevice (const String& outputDeviceName,
  215309. const String& inputDeviceName)
  215310. {
  215311. jassert (hasScanned); // need to call scanForDevices() before doing this
  215312. const bool useExclusiveMode = false;
  215313. ScopedPointer<WASAPIAudioIODevice> device;
  215314. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215315. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215316. if (outputIndex >= 0 || inputIndex >= 0)
  215317. {
  215318. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215319. : inputDeviceName,
  215320. outputDeviceIds [outputIndex],
  215321. inputDeviceIds [inputIndex],
  215322. useExclusiveMode);
  215323. if (! device->initialise())
  215324. device = 0;
  215325. }
  215326. return device.release();
  215327. }
  215328. StringArray outputDeviceNames, outputDeviceIds;
  215329. StringArray inputDeviceNames, inputDeviceIds;
  215330. private:
  215331. bool hasScanned;
  215332. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215333. {
  215334. String s;
  215335. IMMDevice* dev = 0;
  215336. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215337. eMultimedia, &dev)))
  215338. {
  215339. WCHAR* deviceId = 0;
  215340. if (check (dev->GetId (&deviceId)))
  215341. {
  215342. s = String (deviceId);
  215343. CoTaskMemFree (deviceId);
  215344. }
  215345. dev->Release();
  215346. }
  215347. return s;
  215348. }
  215349. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215350. };
  215351. }
  215352. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215353. {
  215354. return new WasapiClasses::WASAPIAudioIODeviceType();
  215355. }
  215356. #endif
  215357. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215358. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215359. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215360. // compiled on its own).
  215361. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215362. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215363. {
  215364. public:
  215365. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215366. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215367. const ComSmartPtr <IBaseFilter>& filter_,
  215368. int minWidth, int minHeight,
  215369. int maxWidth, int maxHeight)
  215370. : owner (owner_),
  215371. captureGraphBuilder (captureGraphBuilder_),
  215372. filter (filter_),
  215373. ok (false),
  215374. imageNeedsFlipping (false),
  215375. width (0),
  215376. height (0),
  215377. activeUsers (0),
  215378. recordNextFrameTime (false),
  215379. previewMaxFPS (60)
  215380. {
  215381. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215382. if (FAILED (hr))
  215383. return;
  215384. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215385. if (FAILED (hr))
  215386. return;
  215387. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215388. if (FAILED (hr))
  215389. return;
  215390. {
  215391. ComSmartPtr <IAMStreamConfig> streamConfig;
  215392. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215393. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215394. if (streamConfig != 0)
  215395. {
  215396. getVideoSizes (streamConfig);
  215397. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215398. return;
  215399. }
  215400. }
  215401. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215402. if (FAILED (hr))
  215403. return;
  215404. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215405. if (FAILED (hr))
  215406. return;
  215407. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215408. if (FAILED (hr))
  215409. return;
  215410. if (! connectFilters (filter, smartTee))
  215411. return;
  215412. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215413. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215414. if (FAILED (hr))
  215415. return;
  215416. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215417. if (FAILED (hr))
  215418. return;
  215419. AM_MEDIA_TYPE mt;
  215420. zerostruct (mt);
  215421. mt.majortype = MEDIATYPE_Video;
  215422. mt.subtype = MEDIASUBTYPE_RGB24;
  215423. mt.formattype = FORMAT_VideoInfo;
  215424. sampleGrabber->SetMediaType (&mt);
  215425. callback = new GrabberCallback (*this);
  215426. hr = sampleGrabber->SetCallback (callback, 1);
  215427. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215428. if (FAILED (hr))
  215429. return;
  215430. ComSmartPtr <IPin> grabberInputPin;
  215431. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215432. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215433. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215434. return;
  215435. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215436. if (FAILED (hr))
  215437. return;
  215438. zerostruct (mt);
  215439. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215440. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215441. width = pVih->bmiHeader.biWidth;
  215442. height = pVih->bmiHeader.biHeight;
  215443. ComSmartPtr <IBaseFilter> nullFilter;
  215444. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215445. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215446. if (connectFilters (sampleGrabberBase, nullFilter)
  215447. && addGraphToRot())
  215448. {
  215449. activeImage = Image (Image::RGB, width, height, true);
  215450. loadingImage = Image (Image::RGB, width, height, true);
  215451. ok = true;
  215452. }
  215453. }
  215454. ~DShowCameraDeviceInteral()
  215455. {
  215456. if (mediaControl != 0)
  215457. mediaControl->Stop();
  215458. removeGraphFromRot();
  215459. for (int i = viewerComps.size(); --i >= 0;)
  215460. viewerComps.getUnchecked(i)->ownerDeleted();
  215461. callback = 0;
  215462. graphBuilder = 0;
  215463. sampleGrabber = 0;
  215464. mediaControl = 0;
  215465. filter = 0;
  215466. captureGraphBuilder = 0;
  215467. smartTee = 0;
  215468. smartTeePreviewOutputPin = 0;
  215469. smartTeeCaptureOutputPin = 0;
  215470. asfWriter = 0;
  215471. }
  215472. void addUser()
  215473. {
  215474. if (ok && activeUsers++ == 0)
  215475. mediaControl->Run();
  215476. }
  215477. void removeUser()
  215478. {
  215479. if (ok && --activeUsers == 0)
  215480. mediaControl->Stop();
  215481. }
  215482. int getPreviewMaxFPS() const
  215483. {
  215484. return previewMaxFPS;
  215485. }
  215486. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215487. {
  215488. if (recordNextFrameTime)
  215489. {
  215490. const double defaultCameraLatency = 0.1;
  215491. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215492. recordNextFrameTime = false;
  215493. ComSmartPtr <IPin> pin;
  215494. if (getPin (filter, PINDIR_OUTPUT, pin))
  215495. {
  215496. ComSmartPtr <IAMPushSource> pushSource;
  215497. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215498. if (pushSource != 0)
  215499. {
  215500. REFERENCE_TIME latency = 0;
  215501. hr = pushSource->GetLatency (&latency);
  215502. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215503. }
  215504. }
  215505. }
  215506. {
  215507. const int lineStride = width * 3;
  215508. const ScopedLock sl (imageSwapLock);
  215509. {
  215510. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215511. for (int i = 0; i < height; ++i)
  215512. memcpy (destData.getLinePointer ((height - 1) - i),
  215513. buffer + lineStride * i,
  215514. lineStride);
  215515. }
  215516. imageNeedsFlipping = true;
  215517. }
  215518. if (listeners.size() > 0)
  215519. callListeners (loadingImage);
  215520. sendChangeMessage();
  215521. }
  215522. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215523. {
  215524. if (imageNeedsFlipping)
  215525. {
  215526. const ScopedLock sl (imageSwapLock);
  215527. swapVariables (loadingImage, activeImage);
  215528. imageNeedsFlipping = false;
  215529. }
  215530. RectanglePlacement rp (RectanglePlacement::centred);
  215531. double dx = 0, dy = 0, dw = width, dh = height;
  215532. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215533. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215534. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215535. {
  215536. Graphics::ScopedSaveState ss (g);
  215537. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215538. g.fillAll (Colours::black);
  215539. }
  215540. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215541. }
  215542. bool createFileCaptureFilter (const File& file, int quality)
  215543. {
  215544. removeFileCaptureFilter();
  215545. file.deleteFile();
  215546. mediaControl->Stop();
  215547. firstRecordedTime = Time();
  215548. recordNextFrameTime = true;
  215549. previewMaxFPS = 60;
  215550. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215551. if (SUCCEEDED (hr))
  215552. {
  215553. ComSmartPtr <IFileSinkFilter> fileSink;
  215554. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  215555. if (SUCCEEDED (hr))
  215556. {
  215557. hr = fileSink->SetFileName (file.getFullPathName().toUTF16(), 0);
  215558. if (SUCCEEDED (hr))
  215559. {
  215560. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215561. if (SUCCEEDED (hr))
  215562. {
  215563. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215564. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  215565. asfConfig->SetIndexMode (true);
  215566. ComSmartPtr <IWMProfileManager> profileManager;
  215567. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  215568. // This gibberish is the DirectShow profile for a video-only wmv file.
  215569. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  215570. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  215571. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215572. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  215573. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215574. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  215575. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  215576. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  215577. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215578. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215579. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215580. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  215581. "biclrused=\"0\" biclrimportant=\"0\"/>"
  215582. "</videoinfoheader>"
  215583. "</wmmediatype>"
  215584. "</streamconfig>"
  215585. "</profile>");
  215586. const int fps[] = { 10, 15, 30 };
  215587. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  215588. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215589. maxFramesPerSecond = (quality >> 24) & 0xff;
  215590. prof = prof.replace ("$WIDTH", String (width))
  215591. .replace ("$HEIGHT", String (height))
  215592. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  215593. ComSmartPtr <IWMProfile> currentProfile;
  215594. hr = profileManager->LoadProfileByData (prof.toUTF16(), currentProfile.resetAndGetPointerAddress());
  215595. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215596. if (SUCCEEDED (hr))
  215597. {
  215598. ComSmartPtr <IPin> asfWriterInputPin;
  215599. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  215600. {
  215601. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215602. if (SUCCEEDED (hr) && ok && activeUsers > 0
  215603. && SUCCEEDED (mediaControl->Run()))
  215604. {
  215605. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  215606. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215607. previewMaxFPS = (quality >> 16) & 0xff;
  215608. return true;
  215609. }
  215610. }
  215611. }
  215612. }
  215613. }
  215614. }
  215615. }
  215616. removeFileCaptureFilter();
  215617. if (ok && activeUsers > 0)
  215618. mediaControl->Run();
  215619. return false;
  215620. }
  215621. void removeFileCaptureFilter()
  215622. {
  215623. mediaControl->Stop();
  215624. if (asfWriter != 0)
  215625. {
  215626. graphBuilder->RemoveFilter (asfWriter);
  215627. asfWriter = 0;
  215628. }
  215629. if (ok && activeUsers > 0)
  215630. mediaControl->Run();
  215631. previewMaxFPS = 60;
  215632. }
  215633. void addListener (CameraDevice::Listener* listenerToAdd)
  215634. {
  215635. const ScopedLock sl (listenerLock);
  215636. if (listeners.size() == 0)
  215637. addUser();
  215638. listeners.addIfNotAlreadyThere (listenerToAdd);
  215639. }
  215640. void removeListener (CameraDevice::Listener* listenerToRemove)
  215641. {
  215642. const ScopedLock sl (listenerLock);
  215643. listeners.removeValue (listenerToRemove);
  215644. if (listeners.size() == 0)
  215645. removeUser();
  215646. }
  215647. void callListeners (const Image& image)
  215648. {
  215649. const ScopedLock sl (listenerLock);
  215650. for (int i = listeners.size(); --i >= 0;)
  215651. {
  215652. CameraDevice::Listener* const l = listeners[i];
  215653. if (l != 0)
  215654. l->imageReceived (image);
  215655. }
  215656. }
  215657. class DShowCaptureViewerComp : public Component,
  215658. public ChangeListener
  215659. {
  215660. public:
  215661. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215662. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  215663. {
  215664. setOpaque (true);
  215665. owner->addChangeListener (this);
  215666. owner->addUser();
  215667. owner->viewerComps.add (this);
  215668. setSize (owner->width, owner->height);
  215669. }
  215670. ~DShowCaptureViewerComp()
  215671. {
  215672. if (owner != 0)
  215673. {
  215674. owner->viewerComps.removeValue (this);
  215675. owner->removeUser();
  215676. owner->removeChangeListener (this);
  215677. }
  215678. }
  215679. void ownerDeleted()
  215680. {
  215681. owner = 0;
  215682. }
  215683. void paint (Graphics& g)
  215684. {
  215685. g.setColour (Colours::black);
  215686. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215687. if (owner != 0)
  215688. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215689. else
  215690. g.fillAll (Colours::black);
  215691. }
  215692. void changeListenerCallback (ChangeBroadcaster*)
  215693. {
  215694. const int64 now = Time::currentTimeMillis();
  215695. if (now >= lastRepaintTime + (1000 / maxFPS))
  215696. {
  215697. lastRepaintTime = now;
  215698. repaint();
  215699. if (owner != 0)
  215700. maxFPS = owner->getPreviewMaxFPS();
  215701. }
  215702. }
  215703. private:
  215704. DShowCameraDeviceInteral* owner;
  215705. int maxFPS;
  215706. int64 lastRepaintTime;
  215707. };
  215708. bool ok;
  215709. int width, height;
  215710. Time firstRecordedTime;
  215711. Array <DShowCaptureViewerComp*> viewerComps;
  215712. private:
  215713. CameraDevice* const owner;
  215714. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215715. ComSmartPtr <IBaseFilter> filter;
  215716. ComSmartPtr <IBaseFilter> smartTee;
  215717. ComSmartPtr <IGraphBuilder> graphBuilder;
  215718. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215719. ComSmartPtr <IMediaControl> mediaControl;
  215720. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215721. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215722. ComSmartPtr <IBaseFilter> asfWriter;
  215723. int activeUsers;
  215724. Array <int> widths, heights;
  215725. DWORD graphRegistrationID;
  215726. CriticalSection imageSwapLock;
  215727. bool imageNeedsFlipping;
  215728. Image loadingImage;
  215729. Image activeImage;
  215730. bool recordNextFrameTime;
  215731. int previewMaxFPS;
  215732. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215733. {
  215734. widths.clear();
  215735. heights.clear();
  215736. int count = 0, size = 0;
  215737. streamConfig->GetNumberOfCapabilities (&count, &size);
  215738. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215739. {
  215740. for (int i = 0; i < count; ++i)
  215741. {
  215742. VIDEO_STREAM_CONFIG_CAPS scc;
  215743. AM_MEDIA_TYPE* config;
  215744. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215745. if (SUCCEEDED (hr))
  215746. {
  215747. const int w = scc.InputSize.cx;
  215748. const int h = scc.InputSize.cy;
  215749. bool duplicate = false;
  215750. for (int j = widths.size(); --j >= 0;)
  215751. {
  215752. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215753. {
  215754. duplicate = true;
  215755. break;
  215756. }
  215757. }
  215758. if (! duplicate)
  215759. {
  215760. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215761. widths.add (w);
  215762. heights.add (h);
  215763. }
  215764. deleteMediaType (config);
  215765. }
  215766. }
  215767. }
  215768. }
  215769. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215770. const int minWidth, const int minHeight,
  215771. const int maxWidth, const int maxHeight)
  215772. {
  215773. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215774. streamConfig->GetNumberOfCapabilities (&count, &size);
  215775. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215776. {
  215777. AM_MEDIA_TYPE* config;
  215778. VIDEO_STREAM_CONFIG_CAPS scc;
  215779. for (int i = 0; i < count; ++i)
  215780. {
  215781. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215782. if (SUCCEEDED (hr))
  215783. {
  215784. if (scc.InputSize.cx >= minWidth
  215785. && scc.InputSize.cy >= minHeight
  215786. && scc.InputSize.cx <= maxWidth
  215787. && scc.InputSize.cy <= maxHeight)
  215788. {
  215789. int area = scc.InputSize.cx * scc.InputSize.cy;
  215790. if (area > bestArea)
  215791. {
  215792. bestIndex = i;
  215793. bestArea = area;
  215794. }
  215795. }
  215796. deleteMediaType (config);
  215797. }
  215798. }
  215799. if (bestIndex >= 0)
  215800. {
  215801. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215802. hr = streamConfig->SetFormat (config);
  215803. deleteMediaType (config);
  215804. return SUCCEEDED (hr);
  215805. }
  215806. }
  215807. return false;
  215808. }
  215809. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  215810. {
  215811. ComSmartPtr <IEnumPins> enumerator;
  215812. ComSmartPtr <IPin> pin;
  215813. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  215814. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  215815. {
  215816. PIN_DIRECTION dir;
  215817. pin->QueryDirection (&dir);
  215818. if (wantedDirection == dir)
  215819. {
  215820. PIN_INFO info;
  215821. zerostruct (info);
  215822. pin->QueryPinInfo (&info);
  215823. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215824. {
  215825. result = pin;
  215826. return true;
  215827. }
  215828. }
  215829. }
  215830. return false;
  215831. }
  215832. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215833. {
  215834. ComSmartPtr <IPin> in, out;
  215835. return getPin (first, PINDIR_OUTPUT, out)
  215836. && getPin (second, PINDIR_INPUT, in)
  215837. && SUCCEEDED (graphBuilder->Connect (out, in));
  215838. }
  215839. bool addGraphToRot()
  215840. {
  215841. ComSmartPtr <IRunningObjectTable> rot;
  215842. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215843. return false;
  215844. ComSmartPtr <IMoniker> moniker;
  215845. WCHAR buffer[128];
  215846. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  215847. if (FAILED (hr))
  215848. return false;
  215849. graphRegistrationID = 0;
  215850. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215851. }
  215852. void removeGraphFromRot()
  215853. {
  215854. ComSmartPtr <IRunningObjectTable> rot;
  215855. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215856. rot->Revoke (graphRegistrationID);
  215857. }
  215858. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215859. {
  215860. if (pmt->cbFormat != 0)
  215861. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215862. if (pmt->pUnk != 0)
  215863. pmt->pUnk->Release();
  215864. CoTaskMemFree (pmt);
  215865. }
  215866. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215867. {
  215868. public:
  215869. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215870. : owner (owner_)
  215871. {
  215872. }
  215873. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215874. {
  215875. return E_FAIL;
  215876. }
  215877. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215878. {
  215879. owner.handleFrame (time, buffer, bufferSize);
  215880. return S_OK;
  215881. }
  215882. private:
  215883. DShowCameraDeviceInteral& owner;
  215884. GrabberCallback (const GrabberCallback&);
  215885. GrabberCallback& operator= (const GrabberCallback&);
  215886. };
  215887. ComSmartPtr <GrabberCallback> callback;
  215888. Array <CameraDevice::Listener*> listeners;
  215889. CriticalSection listenerLock;
  215890. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  215891. };
  215892. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215893. : name (name_)
  215894. {
  215895. isRecording = false;
  215896. }
  215897. CameraDevice::~CameraDevice()
  215898. {
  215899. stopRecording();
  215900. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215901. internal = 0;
  215902. }
  215903. Component* CameraDevice::createViewerComponent()
  215904. {
  215905. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215906. }
  215907. const String CameraDevice::getFileExtension()
  215908. {
  215909. return ".wmv";
  215910. }
  215911. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215912. {
  215913. stopRecording();
  215914. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215915. d->addUser();
  215916. isRecording = d->createFileCaptureFilter (file, quality);
  215917. }
  215918. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215919. {
  215920. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215921. return d->firstRecordedTime;
  215922. }
  215923. void CameraDevice::stopRecording()
  215924. {
  215925. if (isRecording)
  215926. {
  215927. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215928. d->removeFileCaptureFilter();
  215929. d->removeUser();
  215930. isRecording = false;
  215931. }
  215932. }
  215933. void CameraDevice::addListener (Listener* listenerToAdd)
  215934. {
  215935. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215936. if (listenerToAdd != 0)
  215937. d->addListener (listenerToAdd);
  215938. }
  215939. void CameraDevice::removeListener (Listener* listenerToRemove)
  215940. {
  215941. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215942. if (listenerToRemove != 0)
  215943. d->removeListener (listenerToRemove);
  215944. }
  215945. namespace
  215946. {
  215947. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215948. const int deviceIndexToOpen,
  215949. String& name)
  215950. {
  215951. int index = 0;
  215952. ComSmartPtr <IBaseFilter> result;
  215953. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215954. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215955. if (SUCCEEDED (hr))
  215956. {
  215957. ComSmartPtr <IEnumMoniker> enumerator;
  215958. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  215959. if (SUCCEEDED (hr) && enumerator != 0)
  215960. {
  215961. ComSmartPtr <IMoniker> moniker;
  215962. ULONG fetched;
  215963. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  215964. {
  215965. ComSmartPtr <IBaseFilter> captureFilter;
  215966. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  215967. if (SUCCEEDED (hr))
  215968. {
  215969. ComSmartPtr <IPropertyBag> propertyBag;
  215970. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  215971. if (SUCCEEDED (hr))
  215972. {
  215973. VARIANT var;
  215974. var.vt = VT_BSTR;
  215975. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215976. propertyBag = 0;
  215977. if (SUCCEEDED (hr))
  215978. {
  215979. if (names != 0)
  215980. names->add (var.bstrVal);
  215981. if (index == deviceIndexToOpen)
  215982. {
  215983. name = var.bstrVal;
  215984. result = captureFilter;
  215985. break;
  215986. }
  215987. ++index;
  215988. }
  215989. }
  215990. }
  215991. }
  215992. }
  215993. }
  215994. return result;
  215995. }
  215996. }
  215997. const StringArray CameraDevice::getAvailableDevices()
  215998. {
  215999. StringArray devs;
  216000. String dummy;
  216001. enumerateCameras (&devs, -1, dummy);
  216002. return devs;
  216003. }
  216004. CameraDevice* CameraDevice::openDevice (int index,
  216005. int minWidth, int minHeight,
  216006. int maxWidth, int maxHeight)
  216007. {
  216008. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216009. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216010. if (SUCCEEDED (hr))
  216011. {
  216012. String name;
  216013. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216014. if (filter != 0)
  216015. {
  216016. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216017. DShowCameraDeviceInteral* const intern
  216018. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216019. minWidth, minHeight, maxWidth, maxHeight);
  216020. cam->internal = intern;
  216021. if (intern->ok)
  216022. return cam.release();
  216023. }
  216024. }
  216025. return 0;
  216026. }
  216027. #endif
  216028. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216029. #endif
  216030. // Auto-link the other win32 libs that are needed by library calls..
  216031. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216032. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216033. // Auto-links to various win32 libs that are needed by library calls..
  216034. #pragma comment(lib, "kernel32.lib")
  216035. #pragma comment(lib, "user32.lib")
  216036. #pragma comment(lib, "shell32.lib")
  216037. #pragma comment(lib, "gdi32.lib")
  216038. #pragma comment(lib, "vfw32.lib")
  216039. #pragma comment(lib, "comdlg32.lib")
  216040. #pragma comment(lib, "winmm.lib")
  216041. #pragma comment(lib, "wininet.lib")
  216042. #pragma comment(lib, "ole32.lib")
  216043. #pragma comment(lib, "oleaut32.lib")
  216044. #pragma comment(lib, "advapi32.lib")
  216045. #pragma comment(lib, "ws2_32.lib")
  216046. #pragma comment(lib, "version.lib")
  216047. #pragma comment(lib, "shlwapi.lib")
  216048. #ifdef _NATIVE_WCHAR_T_DEFINED
  216049. #ifdef _DEBUG
  216050. #pragma comment(lib, "comsuppwd.lib")
  216051. #else
  216052. #pragma comment(lib, "comsuppw.lib")
  216053. #endif
  216054. #else
  216055. #ifdef _DEBUG
  216056. #pragma comment(lib, "comsuppd.lib")
  216057. #else
  216058. #pragma comment(lib, "comsupp.lib")
  216059. #endif
  216060. #endif
  216061. #if JUCE_OPENGL
  216062. #pragma comment(lib, "OpenGL32.Lib")
  216063. #pragma comment(lib, "GlU32.Lib")
  216064. #endif
  216065. #if JUCE_QUICKTIME
  216066. #pragma comment (lib, "QTMLClient.lib")
  216067. #endif
  216068. #if JUCE_USE_CAMERA
  216069. #pragma comment (lib, "Strmiids.lib")
  216070. #pragma comment (lib, "wmvcore.lib")
  216071. #endif
  216072. #if JUCE_DIRECT2D
  216073. #pragma comment (lib, "Dwrite.lib")
  216074. #pragma comment (lib, "D2d1.lib")
  216075. #endif
  216076. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216077. #endif
  216078. END_JUCE_NAMESPACE
  216079. #endif
  216080. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216081. #elif JUCE_LINUX
  216082. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216083. /*
  216084. This file wraps together all the mac-specific code, so that
  216085. we can include all the native headers just once, and compile all our
  216086. platform-specific stuff in one big lump, keeping it out of the way of
  216087. the rest of the codebase.
  216088. */
  216089. #if JUCE_LINUX
  216090. #undef JUCE_BUILD_NATIVE
  216091. #define JUCE_BUILD_NATIVE 1
  216092. BEGIN_JUCE_NAMESPACE
  216093. #define JUCE_INCLUDED_FILE 1
  216094. // Now include the actual code files..
  216095. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216096. /*
  216097. This file contains posix routines that are common to both the Linux and Mac builds.
  216098. It gets included directly in the cpp files for these platforms.
  216099. */
  216100. CriticalSection::CriticalSection() throw()
  216101. {
  216102. pthread_mutexattr_t atts;
  216103. pthread_mutexattr_init (&atts);
  216104. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216105. #if ! JUCE_ANDROID
  216106. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216107. #endif
  216108. pthread_mutex_init (&internal, &atts);
  216109. }
  216110. CriticalSection::~CriticalSection() throw()
  216111. {
  216112. pthread_mutex_destroy (&internal);
  216113. }
  216114. void CriticalSection::enter() const throw()
  216115. {
  216116. pthread_mutex_lock (&internal);
  216117. }
  216118. bool CriticalSection::tryEnter() const throw()
  216119. {
  216120. return pthread_mutex_trylock (&internal) == 0;
  216121. }
  216122. void CriticalSection::exit() const throw()
  216123. {
  216124. pthread_mutex_unlock (&internal);
  216125. }
  216126. class WaitableEventImpl
  216127. {
  216128. public:
  216129. WaitableEventImpl (const bool manualReset_)
  216130. : triggered (false),
  216131. manualReset (manualReset_)
  216132. {
  216133. pthread_cond_init (&condition, 0);
  216134. pthread_mutexattr_t atts;
  216135. pthread_mutexattr_init (&atts);
  216136. #if ! JUCE_ANDROID
  216137. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216138. #endif
  216139. pthread_mutex_init (&mutex, &atts);
  216140. }
  216141. ~WaitableEventImpl()
  216142. {
  216143. pthread_cond_destroy (&condition);
  216144. pthread_mutex_destroy (&mutex);
  216145. }
  216146. bool wait (const int timeOutMillisecs) throw()
  216147. {
  216148. pthread_mutex_lock (&mutex);
  216149. if (! triggered)
  216150. {
  216151. if (timeOutMillisecs < 0)
  216152. {
  216153. do
  216154. {
  216155. pthread_cond_wait (&condition, &mutex);
  216156. }
  216157. while (! triggered);
  216158. }
  216159. else
  216160. {
  216161. struct timeval now;
  216162. gettimeofday (&now, 0);
  216163. struct timespec time;
  216164. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216165. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216166. if (time.tv_nsec >= 1000000000)
  216167. {
  216168. time.tv_nsec -= 1000000000;
  216169. time.tv_sec++;
  216170. }
  216171. do
  216172. {
  216173. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216174. {
  216175. pthread_mutex_unlock (&mutex);
  216176. return false;
  216177. }
  216178. }
  216179. while (! triggered);
  216180. }
  216181. }
  216182. if (! manualReset)
  216183. triggered = false;
  216184. pthread_mutex_unlock (&mutex);
  216185. return true;
  216186. }
  216187. void signal() throw()
  216188. {
  216189. pthread_mutex_lock (&mutex);
  216190. triggered = true;
  216191. pthread_cond_broadcast (&condition);
  216192. pthread_mutex_unlock (&mutex);
  216193. }
  216194. void reset() throw()
  216195. {
  216196. pthread_mutex_lock (&mutex);
  216197. triggered = false;
  216198. pthread_mutex_unlock (&mutex);
  216199. }
  216200. private:
  216201. pthread_cond_t condition;
  216202. pthread_mutex_t mutex;
  216203. bool triggered;
  216204. const bool manualReset;
  216205. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216206. };
  216207. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216208. : internal (new WaitableEventImpl (manualReset))
  216209. {
  216210. }
  216211. WaitableEvent::~WaitableEvent() throw()
  216212. {
  216213. delete static_cast <WaitableEventImpl*> (internal);
  216214. }
  216215. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216216. {
  216217. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216218. }
  216219. void WaitableEvent::signal() const throw()
  216220. {
  216221. static_cast <WaitableEventImpl*> (internal)->signal();
  216222. }
  216223. void WaitableEvent::reset() const throw()
  216224. {
  216225. static_cast <WaitableEventImpl*> (internal)->reset();
  216226. }
  216227. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216228. {
  216229. struct timespec time;
  216230. time.tv_sec = millisecs / 1000;
  216231. time.tv_nsec = (millisecs % 1000) * 1000000;
  216232. nanosleep (&time, 0);
  216233. }
  216234. const juce_wchar File::separator = '/';
  216235. const String File::separatorString ("/");
  216236. const File File::getCurrentWorkingDirectory()
  216237. {
  216238. HeapBlock<char> heapBuffer;
  216239. char localBuffer [1024];
  216240. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216241. int bufferSize = 4096;
  216242. while (cwd == 0 && errno == ERANGE)
  216243. {
  216244. heapBuffer.malloc (bufferSize);
  216245. cwd = getcwd (heapBuffer, bufferSize - 1);
  216246. bufferSize += 1024;
  216247. }
  216248. return File (String::fromUTF8 (cwd));
  216249. }
  216250. bool File::setAsCurrentWorkingDirectory() const
  216251. {
  216252. return chdir (getFullPathName().toUTF8()) == 0;
  216253. }
  216254. namespace
  216255. {
  216256. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216257. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216258. #else
  216259. typedef struct stat juce_statStruct;
  216260. #endif
  216261. bool juce_stat (const String& fileName, juce_statStruct& info)
  216262. {
  216263. return fileName.isNotEmpty()
  216264. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216265. && (stat64 (fileName.toUTF8(), &info) == 0);
  216266. #else
  216267. && (stat (fileName.toUTF8(), &info) == 0);
  216268. #endif
  216269. }
  216270. // if this file doesn't exist, find a parent of it that does..
  216271. bool juce_doStatFS (File f, struct statfs& result)
  216272. {
  216273. for (int i = 5; --i >= 0;)
  216274. {
  216275. if (f.exists())
  216276. break;
  216277. f = f.getParentDirectory();
  216278. }
  216279. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216280. }
  216281. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216282. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216283. {
  216284. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216285. {
  216286. juce_statStruct info;
  216287. const bool statOk = juce_stat (path, info);
  216288. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216289. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216290. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216291. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216292. }
  216293. if (isReadOnly != 0)
  216294. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216295. }
  216296. }
  216297. bool File::isDirectory() const
  216298. {
  216299. juce_statStruct info;
  216300. return fullPath.isEmpty()
  216301. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216302. }
  216303. bool File::exists() const
  216304. {
  216305. juce_statStruct info;
  216306. return fullPath.isNotEmpty()
  216307. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216308. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216309. #else
  216310. && (lstat (fullPath.toUTF8(), &info) == 0);
  216311. #endif
  216312. }
  216313. bool File::existsAsFile() const
  216314. {
  216315. return exists() && ! isDirectory();
  216316. }
  216317. int64 File::getSize() const
  216318. {
  216319. juce_statStruct info;
  216320. return juce_stat (fullPath, info) ? info.st_size : 0;
  216321. }
  216322. bool File::hasWriteAccess() const
  216323. {
  216324. if (exists())
  216325. return access (fullPath.toUTF8(), W_OK) == 0;
  216326. if ((! isDirectory()) && fullPath.containsChar (separator))
  216327. return getParentDirectory().hasWriteAccess();
  216328. return false;
  216329. }
  216330. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216331. {
  216332. juce_statStruct info;
  216333. if (! juce_stat (fullPath, info))
  216334. return false;
  216335. info.st_mode &= 0777; // Just permissions
  216336. if (shouldBeReadOnly)
  216337. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216338. else
  216339. // Give everybody write permission?
  216340. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216341. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216342. }
  216343. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216344. {
  216345. modificationTime = 0;
  216346. accessTime = 0;
  216347. creationTime = 0;
  216348. juce_statStruct info;
  216349. if (juce_stat (fullPath, info))
  216350. {
  216351. modificationTime = (int64) info.st_mtime * 1000;
  216352. accessTime = (int64) info.st_atime * 1000;
  216353. creationTime = (int64) info.st_ctime * 1000;
  216354. }
  216355. }
  216356. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216357. {
  216358. juce_statStruct info;
  216359. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  216360. {
  216361. struct utimbuf times;
  216362. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  216363. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  216364. return utime (fullPath.toUTF8(), &times) == 0;
  216365. }
  216366. return false;
  216367. }
  216368. bool File::deleteFile() const
  216369. {
  216370. if (! exists())
  216371. return true;
  216372. if (isDirectory())
  216373. return rmdir (fullPath.toUTF8()) == 0;
  216374. return remove (fullPath.toUTF8()) == 0;
  216375. }
  216376. bool File::moveInternal (const File& dest) const
  216377. {
  216378. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216379. return true;
  216380. if (hasWriteAccess() && copyInternal (dest))
  216381. {
  216382. if (deleteFile())
  216383. return true;
  216384. dest.deleteFile();
  216385. }
  216386. return false;
  216387. }
  216388. void File::createDirectoryInternal (const String& fileName) const
  216389. {
  216390. mkdir (fileName.toUTF8(), 0777);
  216391. }
  216392. int64 juce_fileSetPosition (void* handle, int64 pos)
  216393. {
  216394. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216395. return pos;
  216396. return -1;
  216397. }
  216398. void FileInputStream::openHandle()
  216399. {
  216400. totalSize = file.getSize();
  216401. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216402. if (f != -1)
  216403. fileHandle = (void*) f;
  216404. }
  216405. void FileInputStream::closeHandle()
  216406. {
  216407. if (fileHandle != 0)
  216408. {
  216409. close ((int) (pointer_sized_int) fileHandle);
  216410. fileHandle = 0;
  216411. }
  216412. }
  216413. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216414. {
  216415. if (fileHandle != 0)
  216416. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216417. return 0;
  216418. }
  216419. void FileOutputStream::openHandle()
  216420. {
  216421. if (file.exists())
  216422. {
  216423. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216424. if (f != -1)
  216425. {
  216426. currentPosition = lseek (f, 0, SEEK_END);
  216427. if (currentPosition >= 0)
  216428. fileHandle = (void*) f;
  216429. else
  216430. close (f);
  216431. }
  216432. }
  216433. else
  216434. {
  216435. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216436. if (f != -1)
  216437. fileHandle = (void*) f;
  216438. }
  216439. }
  216440. void FileOutputStream::closeHandle()
  216441. {
  216442. if (fileHandle != 0)
  216443. {
  216444. close ((int) (pointer_sized_int) fileHandle);
  216445. fileHandle = 0;
  216446. }
  216447. }
  216448. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216449. {
  216450. if (fileHandle != 0)
  216451. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216452. return 0;
  216453. }
  216454. void FileOutputStream::flushInternal()
  216455. {
  216456. if (fileHandle != 0)
  216457. fsync ((int) (pointer_sized_int) fileHandle);
  216458. }
  216459. const File juce_getExecutableFile()
  216460. {
  216461. #if JUCE_ANDROID
  216462. // TODO
  216463. return File::nonexistent;
  216464. #else
  216465. Dl_info exeInfo;
  216466. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  216467. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216468. #endif
  216469. }
  216470. int64 File::getBytesFreeOnVolume() const
  216471. {
  216472. struct statfs buf;
  216473. if (juce_doStatFS (*this, buf))
  216474. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216475. return 0;
  216476. }
  216477. int64 File::getVolumeTotalSize() const
  216478. {
  216479. struct statfs buf;
  216480. if (juce_doStatFS (*this, buf))
  216481. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216482. return 0;
  216483. }
  216484. const String File::getVolumeLabel() const
  216485. {
  216486. #if JUCE_MAC
  216487. struct VolAttrBuf
  216488. {
  216489. u_int32_t length;
  216490. attrreference_t mountPointRef;
  216491. char mountPointSpace [MAXPATHLEN];
  216492. } attrBuf;
  216493. struct attrlist attrList;
  216494. zerostruct (attrList);
  216495. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216496. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216497. File f (*this);
  216498. for (;;)
  216499. {
  216500. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216501. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216502. (int) attrBuf.mountPointRef.attr_length);
  216503. const File parent (f.getParentDirectory());
  216504. if (f == parent)
  216505. break;
  216506. f = parent;
  216507. }
  216508. #endif
  216509. return String::empty;
  216510. }
  216511. int File::getVolumeSerialNumber() const
  216512. {
  216513. int result = 0;
  216514. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  216515. char info [512];
  216516. #ifndef HDIO_GET_IDENTITY
  216517. #define HDIO_GET_IDENTITY 0x030d
  216518. #endif
  216519. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  216520. {
  216521. DBG (String (info + 20, 20));
  216522. result = String (info + 20, 20).trim().getIntValue();
  216523. }
  216524. close (fd);*/
  216525. return result;
  216526. }
  216527. void juce_runSystemCommand (const String& command)
  216528. {
  216529. int result = system (command.toUTF8());
  216530. (void) result;
  216531. }
  216532. const String juce_getOutputFromCommand (const String& command)
  216533. {
  216534. // slight bodge here, as we just pipe the output into a temp file and read it...
  216535. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216536. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216537. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216538. String result (tempFile.loadFileAsString());
  216539. tempFile.deleteFile();
  216540. return result;
  216541. }
  216542. class InterProcessLock::Pimpl
  216543. {
  216544. public:
  216545. Pimpl (const String& name, const int timeOutMillisecs)
  216546. : handle (0), refCount (1)
  216547. {
  216548. #if JUCE_MAC
  216549. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216550. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216551. #else
  216552. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216553. #endif
  216554. temp.create();
  216555. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216556. if (handle != 0)
  216557. {
  216558. struct flock fl;
  216559. zerostruct (fl);
  216560. fl.l_whence = SEEK_SET;
  216561. fl.l_type = F_WRLCK;
  216562. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216563. for (;;)
  216564. {
  216565. const int result = fcntl (handle, F_SETLK, &fl);
  216566. if (result >= 0)
  216567. return;
  216568. if (errno != EINTR)
  216569. {
  216570. if (timeOutMillisecs == 0
  216571. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216572. break;
  216573. Thread::sleep (10);
  216574. }
  216575. }
  216576. }
  216577. closeFile();
  216578. }
  216579. ~Pimpl()
  216580. {
  216581. closeFile();
  216582. }
  216583. void closeFile()
  216584. {
  216585. if (handle != 0)
  216586. {
  216587. struct flock fl;
  216588. zerostruct (fl);
  216589. fl.l_whence = SEEK_SET;
  216590. fl.l_type = F_UNLCK;
  216591. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216592. {}
  216593. close (handle);
  216594. handle = 0;
  216595. }
  216596. }
  216597. int handle, refCount;
  216598. };
  216599. InterProcessLock::InterProcessLock (const String& name_)
  216600. : name (name_)
  216601. {
  216602. }
  216603. InterProcessLock::~InterProcessLock()
  216604. {
  216605. }
  216606. bool InterProcessLock::enter (const int timeOutMillisecs)
  216607. {
  216608. const ScopedLock sl (lock);
  216609. if (pimpl == 0)
  216610. {
  216611. pimpl = new Pimpl (name, timeOutMillisecs);
  216612. if (pimpl->handle == 0)
  216613. pimpl = 0;
  216614. }
  216615. else
  216616. {
  216617. pimpl->refCount++;
  216618. }
  216619. return pimpl != 0;
  216620. }
  216621. void InterProcessLock::exit()
  216622. {
  216623. const ScopedLock sl (lock);
  216624. // Trying to release the lock too many times!
  216625. jassert (pimpl != 0);
  216626. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216627. pimpl = 0;
  216628. }
  216629. void JUCE_API juce_threadEntryPoint (void*);
  216630. void* threadEntryProc (void* userData)
  216631. {
  216632. JUCE_AUTORELEASEPOOL
  216633. juce_threadEntryPoint (userData);
  216634. return 0;
  216635. }
  216636. void Thread::launchThread()
  216637. {
  216638. threadHandle_ = 0;
  216639. pthread_t handle = 0;
  216640. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  216641. {
  216642. pthread_detach (handle);
  216643. threadHandle_ = (void*) handle;
  216644. threadId_ = (ThreadID) threadHandle_;
  216645. }
  216646. }
  216647. void Thread::closeThreadHandle()
  216648. {
  216649. threadId_ = 0;
  216650. threadHandle_ = 0;
  216651. }
  216652. void Thread::killThread()
  216653. {
  216654. if (threadHandle_ != 0)
  216655. {
  216656. #if JUCE_ANDROID
  216657. jassertfalse; // pthread_cancel not available!
  216658. #else
  216659. pthread_cancel ((pthread_t) threadHandle_);
  216660. #endif
  216661. }
  216662. }
  216663. void Thread::setCurrentThreadName (const String& /*name*/)
  216664. {
  216665. }
  216666. bool Thread::setThreadPriority (void* handle, int priority)
  216667. {
  216668. struct sched_param param;
  216669. int policy;
  216670. priority = jlimit (0, 10, priority);
  216671. if (handle == 0)
  216672. handle = (void*) pthread_self();
  216673. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  216674. return false;
  216675. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  216676. const int minPriority = sched_get_priority_min (policy);
  216677. const int maxPriority = sched_get_priority_max (policy);
  216678. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  216679. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216680. }
  216681. Thread::ThreadID Thread::getCurrentThreadId()
  216682. {
  216683. return (ThreadID) pthread_self();
  216684. }
  216685. void Thread::yield()
  216686. {
  216687. sched_yield();
  216688. }
  216689. /* Remove this macro if you're having problems compiling the cpu affinity
  216690. calls (the API for these has changed about quite a bit in various Linux
  216691. versions, and a lot of distros seem to ship with obsolete versions)
  216692. */
  216693. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216694. #define SUPPORT_AFFINITIES 1
  216695. #endif
  216696. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216697. {
  216698. #if SUPPORT_AFFINITIES
  216699. cpu_set_t affinity;
  216700. CPU_ZERO (&affinity);
  216701. for (int i = 0; i < 32; ++i)
  216702. if ((affinityMask & (1 << i)) != 0)
  216703. CPU_SET (i, &affinity);
  216704. /*
  216705. N.B. If this line causes a compile error, then you've probably not got the latest
  216706. version of glibc installed.
  216707. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216708. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216709. */
  216710. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216711. sched_yield();
  216712. #else
  216713. /* affinities aren't supported because either the appropriate header files weren't found,
  216714. or the SUPPORT_AFFINITIES macro was turned off
  216715. */
  216716. jassertfalse;
  216717. (void) affinityMask;
  216718. #endif
  216719. }
  216720. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216721. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216722. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216723. // compiled on its own).
  216724. #if JUCE_INCLUDED_FILE
  216725. enum
  216726. {
  216727. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  216728. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  216729. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  216730. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  216731. };
  216732. bool File::copyInternal (const File& dest) const
  216733. {
  216734. FileInputStream in (*this);
  216735. if (dest.deleteFile())
  216736. {
  216737. {
  216738. FileOutputStream out (dest);
  216739. if (out.failedToOpen())
  216740. return false;
  216741. if (out.writeFromInputStream (in, -1) == getSize())
  216742. return true;
  216743. }
  216744. dest.deleteFile();
  216745. }
  216746. return false;
  216747. }
  216748. void File::findFileSystemRoots (Array<File>& destArray)
  216749. {
  216750. destArray.add (File ("/"));
  216751. }
  216752. bool File::isOnCDRomDrive() const
  216753. {
  216754. struct statfs buf;
  216755. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216756. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  216757. }
  216758. bool File::isOnHardDisk() const
  216759. {
  216760. struct statfs buf;
  216761. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216762. {
  216763. switch (buf.f_type)
  216764. {
  216765. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216766. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216767. case U_NFS_SUPER_MAGIC: // Network NFS
  216768. case U_SMB_SUPER_MAGIC: // Network Samba
  216769. return false;
  216770. default:
  216771. // Assume anything else is a hard-disk (but note it could
  216772. // be a RAM disk. There isn't a good way of determining
  216773. // this for sure)
  216774. return true;
  216775. }
  216776. }
  216777. // Assume so if this fails for some reason
  216778. return true;
  216779. }
  216780. bool File::isOnRemovableDrive() const
  216781. {
  216782. jassertfalse; // xxx not implemented for linux!
  216783. return false;
  216784. }
  216785. bool File::isHidden() const
  216786. {
  216787. return getFileName().startsWithChar ('.');
  216788. }
  216789. namespace
  216790. {
  216791. const File juce_readlink (const String& file, const File& defaultFile)
  216792. {
  216793. const int size = 8192;
  216794. HeapBlock<char> buffer;
  216795. buffer.malloc (size + 4);
  216796. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  216797. if (numBytes > 0 && numBytes <= size)
  216798. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  216799. return defaultFile;
  216800. }
  216801. }
  216802. const File File::getLinkedTarget() const
  216803. {
  216804. return juce_readlink (getFullPathName().toUTF8(), *this);
  216805. }
  216806. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216807. const File File::getSpecialLocation (const SpecialLocationType type)
  216808. {
  216809. switch (type)
  216810. {
  216811. case userHomeDirectory:
  216812. {
  216813. const char* homeDir = getenv ("HOME");
  216814. if (homeDir == 0)
  216815. {
  216816. struct passwd* const pw = getpwuid (getuid());
  216817. if (pw != 0)
  216818. homeDir = pw->pw_dir;
  216819. }
  216820. return File (String::fromUTF8 (homeDir));
  216821. }
  216822. case userDocumentsDirectory:
  216823. case userMusicDirectory:
  216824. case userMoviesDirectory:
  216825. case userApplicationDataDirectory:
  216826. return File ("~");
  216827. case userDesktopDirectory:
  216828. return File ("~/Desktop");
  216829. case commonApplicationDataDirectory:
  216830. return File ("/var");
  216831. case globalApplicationsDirectory:
  216832. return File ("/usr");
  216833. case tempDirectory:
  216834. {
  216835. File tmp ("/var/tmp");
  216836. if (! tmp.isDirectory())
  216837. {
  216838. tmp = "/tmp";
  216839. if (! tmp.isDirectory())
  216840. tmp = File::getCurrentWorkingDirectory();
  216841. }
  216842. return tmp;
  216843. }
  216844. case invokedExecutableFile:
  216845. if (juce_Argv0 != 0)
  216846. return File (String::fromUTF8 (juce_Argv0));
  216847. // deliberate fall-through...
  216848. case currentExecutableFile:
  216849. case currentApplicationFile:
  216850. return juce_getExecutableFile();
  216851. case hostApplicationPath:
  216852. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  216853. default:
  216854. jassertfalse; // unknown type?
  216855. break;
  216856. }
  216857. return File::nonexistent;
  216858. }
  216859. const String File::getVersion() const
  216860. {
  216861. return String::empty; // xxx not yet implemented
  216862. }
  216863. bool File::moveToTrash() const
  216864. {
  216865. if (! exists())
  216866. return true;
  216867. File trashCan ("~/.Trash");
  216868. if (! trashCan.isDirectory())
  216869. trashCan = "~/.local/share/Trash/files";
  216870. if (! trashCan.isDirectory())
  216871. return false;
  216872. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216873. getFileExtension()));
  216874. }
  216875. class DirectoryIterator::NativeIterator::Pimpl
  216876. {
  216877. public:
  216878. Pimpl (const File& directory, const String& wildCard_)
  216879. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216880. wildCard (wildCard_),
  216881. dir (opendir (directory.getFullPathName().toUTF8()))
  216882. {
  216883. wildcardUTF8 = wildCard.toUTF8();
  216884. }
  216885. ~Pimpl()
  216886. {
  216887. if (dir != 0)
  216888. closedir (dir);
  216889. }
  216890. bool next (String& filenameFound,
  216891. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216892. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216893. {
  216894. if (dir != 0)
  216895. {
  216896. for (;;)
  216897. {
  216898. struct dirent* const de = readdir (dir);
  216899. if (de == 0)
  216900. break;
  216901. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216902. {
  216903. filenameFound = String::fromUTF8 (de->d_name);
  216904. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  216905. if (isHidden != 0)
  216906. *isHidden = filenameFound.startsWithChar ('.');
  216907. return true;
  216908. }
  216909. }
  216910. }
  216911. return false;
  216912. }
  216913. private:
  216914. String parentDir, wildCard;
  216915. const char* wildcardUTF8;
  216916. DIR* dir;
  216917. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  216918. };
  216919. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216920. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216921. {
  216922. }
  216923. DirectoryIterator::NativeIterator::~NativeIterator()
  216924. {
  216925. }
  216926. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216927. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216928. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216929. {
  216930. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216931. }
  216932. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216933. {
  216934. String cmdString (fileName.replace (" ", "\\ ",false));
  216935. cmdString << " " << parameters;
  216936. if (URL::isProbablyAWebsiteURL (fileName)
  216937. || cmdString.startsWithIgnoreCase ("file:")
  216938. || URL::isProbablyAnEmailAddress (fileName))
  216939. {
  216940. // create a command that tries to launch a bunch of likely browsers
  216941. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216942. StringArray cmdLines;
  216943. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216944. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216945. cmdString = cmdLines.joinIntoString (" || ");
  216946. }
  216947. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216948. const int cpid = fork();
  216949. if (cpid == 0)
  216950. {
  216951. setsid();
  216952. // Child process
  216953. execve (argv[0], (char**) argv, environ);
  216954. exit (0);
  216955. }
  216956. return cpid >= 0;
  216957. }
  216958. void File::revealToUser() const
  216959. {
  216960. if (isDirectory())
  216961. startAsProcess();
  216962. else if (getParentDirectory().exists())
  216963. getParentDirectory().startAsProcess();
  216964. }
  216965. #endif
  216966. /*** End of inlined file: juce_linux_Files.cpp ***/
  216967. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216968. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216969. // compiled on its own).
  216970. #if JUCE_INCLUDED_FILE
  216971. struct NamedPipeInternal
  216972. {
  216973. String pipeInName, pipeOutName;
  216974. int pipeIn, pipeOut;
  216975. bool volatile createdPipe, blocked, stopReadOperation;
  216976. static void signalHandler (int) {}
  216977. };
  216978. void NamedPipe::cancelPendingReads()
  216979. {
  216980. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  216981. {
  216982. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216983. intern->stopReadOperation = true;
  216984. char buffer [1] = { 0 };
  216985. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216986. (void) bytesWritten;
  216987. int timeout = 2000;
  216988. while (intern->blocked && --timeout >= 0)
  216989. Thread::sleep (2);
  216990. intern->stopReadOperation = false;
  216991. }
  216992. }
  216993. void NamedPipe::close()
  216994. {
  216995. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216996. if (intern != 0)
  216997. {
  216998. internal = 0;
  216999. if (intern->pipeIn != -1)
  217000. ::close (intern->pipeIn);
  217001. if (intern->pipeOut != -1)
  217002. ::close (intern->pipeOut);
  217003. if (intern->createdPipe)
  217004. {
  217005. unlink (intern->pipeInName.toUTF8());
  217006. unlink (intern->pipeOutName.toUTF8());
  217007. }
  217008. delete intern;
  217009. }
  217010. }
  217011. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217012. {
  217013. close();
  217014. NamedPipeInternal* const intern = new NamedPipeInternal();
  217015. internal = intern;
  217016. intern->createdPipe = createPipe;
  217017. intern->blocked = false;
  217018. intern->stopReadOperation = false;
  217019. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217020. siginterrupt (SIGPIPE, 1);
  217021. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217022. intern->pipeInName = pipePath + "_in";
  217023. intern->pipeOutName = pipePath + "_out";
  217024. intern->pipeIn = -1;
  217025. intern->pipeOut = -1;
  217026. if (createPipe)
  217027. {
  217028. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217029. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217030. {
  217031. delete intern;
  217032. internal = 0;
  217033. return false;
  217034. }
  217035. }
  217036. return true;
  217037. }
  217038. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217039. {
  217040. int bytesRead = -1;
  217041. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217042. if (intern != 0)
  217043. {
  217044. intern->blocked = true;
  217045. if (intern->pipeIn == -1)
  217046. {
  217047. if (intern->createdPipe)
  217048. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217049. else
  217050. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217051. if (intern->pipeIn == -1)
  217052. {
  217053. intern->blocked = false;
  217054. return -1;
  217055. }
  217056. }
  217057. bytesRead = 0;
  217058. char* p = static_cast<char*> (destBuffer);
  217059. while (bytesRead < maxBytesToRead)
  217060. {
  217061. const int bytesThisTime = maxBytesToRead - bytesRead;
  217062. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217063. if (numRead <= 0 || intern->stopReadOperation)
  217064. {
  217065. bytesRead = -1;
  217066. break;
  217067. }
  217068. bytesRead += numRead;
  217069. p += bytesRead;
  217070. }
  217071. intern->blocked = false;
  217072. }
  217073. return bytesRead;
  217074. }
  217075. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217076. {
  217077. int bytesWritten = -1;
  217078. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217079. if (intern != 0)
  217080. {
  217081. if (intern->pipeOut == -1)
  217082. {
  217083. if (intern->createdPipe)
  217084. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217085. else
  217086. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217087. if (intern->pipeOut == -1)
  217088. {
  217089. return -1;
  217090. }
  217091. }
  217092. const char* p = static_cast<const char*> (sourceBuffer);
  217093. bytesWritten = 0;
  217094. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217095. while (bytesWritten < numBytesToWrite
  217096. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217097. {
  217098. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217099. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217100. if (numWritten <= 0)
  217101. {
  217102. bytesWritten = -1;
  217103. break;
  217104. }
  217105. bytesWritten += numWritten;
  217106. p += bytesWritten;
  217107. }
  217108. }
  217109. return bytesWritten;
  217110. }
  217111. #endif
  217112. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217113. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217114. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217115. // compiled on its own).
  217116. #if JUCE_INCLUDED_FILE
  217117. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217118. {
  217119. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217120. if (s != -1)
  217121. {
  217122. char buf [1024];
  217123. struct ifconf ifc;
  217124. ifc.ifc_len = sizeof (buf);
  217125. ifc.ifc_buf = buf;
  217126. ioctl (s, SIOCGIFCONF, &ifc);
  217127. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217128. {
  217129. struct ifreq ifr;
  217130. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217131. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217132. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217133. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217134. {
  217135. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217136. }
  217137. }
  217138. close (s);
  217139. }
  217140. }
  217141. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217142. const String& emailSubject,
  217143. const String& bodyText,
  217144. const StringArray& filesToAttach)
  217145. {
  217146. jassertfalse; // xxx todo
  217147. return false;
  217148. }
  217149. class WebInputStream : public InputStream
  217150. {
  217151. public:
  217152. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217153. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217154. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217155. : socketHandle (-1), levelsOfRedirection (0),
  217156. address (address_), headers (headers_), postData (postData_), position (0),
  217157. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217158. {
  217159. createConnection (progressCallback, progressCallbackContext);
  217160. if (responseHeaders != 0 && ! isError())
  217161. {
  217162. for (int i = 0; i < headerLines.size(); ++i)
  217163. {
  217164. const String& headersEntry = headerLines[i];
  217165. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217166. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217167. const String previousValue ((*responseHeaders) [key]);
  217168. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217169. }
  217170. }
  217171. }
  217172. ~WebInputStream()
  217173. {
  217174. closeSocket();
  217175. }
  217176. bool isError() const { return socketHandle < 0; }
  217177. bool isExhausted() { return finished; }
  217178. int64 getPosition() { return position; }
  217179. int64 getTotalLength()
  217180. {
  217181. jassertfalse; //xxx to do
  217182. return -1;
  217183. }
  217184. int read (void* buffer, int bytesToRead)
  217185. {
  217186. if (finished || isError())
  217187. return 0;
  217188. fd_set readbits;
  217189. FD_ZERO (&readbits);
  217190. FD_SET (socketHandle, &readbits);
  217191. struct timeval tv;
  217192. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217193. tv.tv_usec = 0;
  217194. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217195. return 0; // (timeout)
  217196. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217197. if (bytesRead == 0)
  217198. finished = true;
  217199. position += bytesRead;
  217200. return bytesRead;
  217201. }
  217202. bool setPosition (int64 wantedPos)
  217203. {
  217204. if (isError())
  217205. return false;
  217206. if (wantedPos != position)
  217207. {
  217208. finished = false;
  217209. if (wantedPos < position)
  217210. {
  217211. closeSocket();
  217212. position = 0;
  217213. createConnection (0, 0);
  217214. }
  217215. skipNextBytes (wantedPos - position);
  217216. }
  217217. return true;
  217218. }
  217219. private:
  217220. int socketHandle, levelsOfRedirection;
  217221. StringArray headerLines;
  217222. String address, headers;
  217223. MemoryBlock postData;
  217224. int64 position;
  217225. bool finished;
  217226. const bool isPost;
  217227. const int timeOutMs;
  217228. void closeSocket()
  217229. {
  217230. if (socketHandle >= 0)
  217231. close (socketHandle);
  217232. socketHandle = -1;
  217233. levelsOfRedirection = 0;
  217234. }
  217235. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217236. {
  217237. closeSocket();
  217238. uint32 timeOutTime = Time::getMillisecondCounter();
  217239. if (timeOutMs == 0)
  217240. timeOutTime += 60000;
  217241. else if (timeOutMs < 0)
  217242. timeOutTime = 0xffffffff;
  217243. else
  217244. timeOutTime += timeOutMs;
  217245. String hostName, hostPath;
  217246. int hostPort;
  217247. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217248. return;
  217249. const struct hostent* host = 0;
  217250. int port = 0;
  217251. String proxyName, proxyPath;
  217252. int proxyPort = 0;
  217253. String proxyURL (getenv ("http_proxy"));
  217254. if (proxyURL.startsWithIgnoreCase ("http://"))
  217255. {
  217256. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217257. return;
  217258. host = gethostbyname (proxyName.toUTF8());
  217259. port = proxyPort;
  217260. }
  217261. else
  217262. {
  217263. host = gethostbyname (hostName.toUTF8());
  217264. port = hostPort;
  217265. }
  217266. if (host == 0)
  217267. return;
  217268. {
  217269. struct sockaddr_in socketAddress;
  217270. zerostruct (socketAddress);
  217271. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217272. socketAddress.sin_family = host->h_addrtype;
  217273. socketAddress.sin_port = htons (port);
  217274. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217275. if (socketHandle == -1)
  217276. return;
  217277. int receiveBufferSize = 16384;
  217278. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217279. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217280. #if JUCE_MAC
  217281. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217282. #endif
  217283. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217284. {
  217285. closeSocket();
  217286. return;
  217287. }
  217288. }
  217289. {
  217290. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217291. hostPath, address, headers, postData, isPost));
  217292. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217293. {
  217294. closeSocket();
  217295. return;
  217296. }
  217297. }
  217298. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217299. if (responseHeader.isNotEmpty())
  217300. {
  217301. headerLines.clear();
  217302. headerLines.addLines (responseHeader);
  217303. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217304. .substring (0, 3).getIntValue();
  217305. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217306. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217307. String location (findHeaderItem (headerLines, "Location:"));
  217308. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217309. {
  217310. if (! location.startsWithIgnoreCase ("http://"))
  217311. location = "http://" + location;
  217312. if (++levelsOfRedirection <= 3)
  217313. {
  217314. address = location;
  217315. createConnection (progressCallback, progressCallbackContext);
  217316. return;
  217317. }
  217318. }
  217319. else
  217320. {
  217321. levelsOfRedirection = 0;
  217322. return;
  217323. }
  217324. }
  217325. closeSocket();
  217326. }
  217327. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217328. {
  217329. int bytesRead = 0, numConsecutiveLFs = 0;
  217330. MemoryBlock buffer (1024, true);
  217331. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217332. && Time::getMillisecondCounter() <= timeOutTime)
  217333. {
  217334. fd_set readbits;
  217335. FD_ZERO (&readbits);
  217336. FD_SET (socketHandle, &readbits);
  217337. struct timeval tv;
  217338. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217339. tv.tv_usec = 0;
  217340. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217341. return String::empty; // (timeout)
  217342. buffer.ensureSize (bytesRead + 8, true);
  217343. char* const dest = (char*) buffer.getData() + bytesRead;
  217344. if (recv (socketHandle, dest, 1, 0) == -1)
  217345. return String::empty;
  217346. const char lastByte = *dest;
  217347. ++bytesRead;
  217348. if (lastByte == '\n')
  217349. ++numConsecutiveLFs;
  217350. else if (lastByte != '\r')
  217351. numConsecutiveLFs = 0;
  217352. }
  217353. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217354. if (header.startsWithIgnoreCase ("HTTP/"))
  217355. return header.trimEnd();
  217356. return String::empty;
  217357. }
  217358. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217359. const String& proxyName, const int proxyPort,
  217360. const String& hostPath, const String& originalURL,
  217361. const String& headers, const MemoryBlock& postData,
  217362. const bool isPost)
  217363. {
  217364. String header (isPost ? "POST " : "GET ");
  217365. if (proxyName.isEmpty())
  217366. {
  217367. header << hostPath << " HTTP/1.0\r\nHost: "
  217368. << hostName << ':' << hostPort;
  217369. }
  217370. else
  217371. {
  217372. header << originalURL << " HTTP/1.0\r\nHost: "
  217373. << proxyName << ':' << proxyPort;
  217374. }
  217375. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217376. << "\r\nConnection: Close\r\nContent-Length: "
  217377. << (int) postData.getSize() << "\r\n"
  217378. << headers << "\r\n";
  217379. MemoryBlock mb;
  217380. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217381. mb.append (postData.getData(), postData.getSize());
  217382. return mb;
  217383. }
  217384. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217385. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217386. {
  217387. size_t totalHeaderSent = 0;
  217388. while (totalHeaderSent < requestHeader.getSize())
  217389. {
  217390. if (Time::getMillisecondCounter() > timeOutTime)
  217391. return false;
  217392. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217393. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217394. return false;
  217395. totalHeaderSent += numToSend;
  217396. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217397. return false;
  217398. }
  217399. return true;
  217400. }
  217401. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217402. {
  217403. if (! url.startsWithIgnoreCase ("http://"))
  217404. return false;
  217405. const int nextSlash = url.indexOfChar (7, '/');
  217406. int nextColon = url.indexOfChar (7, ':');
  217407. if (nextColon > nextSlash && nextSlash > 0)
  217408. nextColon = -1;
  217409. if (nextColon >= 0)
  217410. {
  217411. host = url.substring (7, nextColon);
  217412. if (nextSlash >= 0)
  217413. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217414. else
  217415. port = url.substring (nextColon + 1).getIntValue();
  217416. }
  217417. else
  217418. {
  217419. port = 80;
  217420. if (nextSlash >= 0)
  217421. host = url.substring (7, nextSlash);
  217422. else
  217423. host = url.substring (7);
  217424. }
  217425. if (nextSlash >= 0)
  217426. path = url.substring (nextSlash);
  217427. else
  217428. path = "/";
  217429. return true;
  217430. }
  217431. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217432. {
  217433. for (int i = 0; i < lines.size(); ++i)
  217434. if (lines[i].startsWithIgnoreCase (itemName))
  217435. return lines[i].substring (itemName.length()).trim();
  217436. return String::empty;
  217437. }
  217438. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217439. };
  217440. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217441. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217442. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217443. {
  217444. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217445. progressCallback, progressCallbackContext,
  217446. headers, timeOutMs, responseHeaders));
  217447. return wi->isError() ? 0 : wi.release();
  217448. }
  217449. #endif
  217450. /*** End of inlined file: juce_linux_Network.cpp ***/
  217451. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217452. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217453. // compiled on its own).
  217454. #if JUCE_INCLUDED_FILE
  217455. void Logger::outputDebugString (const String& text)
  217456. {
  217457. std::cerr << text << std::endl;
  217458. }
  217459. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217460. {
  217461. return Linux;
  217462. }
  217463. const String SystemStats::getOperatingSystemName()
  217464. {
  217465. return "Linux";
  217466. }
  217467. bool SystemStats::isOperatingSystem64Bit()
  217468. {
  217469. #if JUCE_64BIT
  217470. return true;
  217471. #else
  217472. //xxx not sure how to find this out?..
  217473. return false;
  217474. #endif
  217475. }
  217476. namespace LinuxStatsHelpers
  217477. {
  217478. const String getCpuInfo (const char* const key)
  217479. {
  217480. StringArray lines;
  217481. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217482. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217483. if (lines[i].startsWithIgnoreCase (key))
  217484. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217485. return String::empty;
  217486. }
  217487. }
  217488. const String SystemStats::getCpuVendor()
  217489. {
  217490. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217491. }
  217492. int SystemStats::getCpuSpeedInMegaherz()
  217493. {
  217494. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217495. }
  217496. int SystemStats::getMemorySizeInMegabytes()
  217497. {
  217498. struct sysinfo sysi;
  217499. if (sysinfo (&sysi) == 0)
  217500. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217501. return 0;
  217502. }
  217503. int SystemStats::getPageSize()
  217504. {
  217505. return sysconf (_SC_PAGESIZE);
  217506. }
  217507. const String SystemStats::getLogonName()
  217508. {
  217509. const char* user = getenv ("USER");
  217510. if (user == 0)
  217511. {
  217512. struct passwd* const pw = getpwuid (getuid());
  217513. if (pw != 0)
  217514. user = pw->pw_name;
  217515. }
  217516. return String::fromUTF8 (user);
  217517. }
  217518. const String SystemStats::getFullUserName()
  217519. {
  217520. return getLogonName();
  217521. }
  217522. void SystemStats::initialiseStats()
  217523. {
  217524. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  217525. cpuFlags.hasMMX = flags.contains ("mmx");
  217526. cpuFlags.hasSSE = flags.contains ("sse");
  217527. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217528. cpuFlags.has3DNow = flags.contains ("3dnow");
  217529. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  217530. }
  217531. void PlatformUtilities::fpuReset()
  217532. {
  217533. }
  217534. uint32 juce_millisecondsSinceStartup() throw()
  217535. {
  217536. timespec t;
  217537. clock_gettime (CLOCK_MONOTONIC, &t);
  217538. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  217539. }
  217540. int64 Time::getHighResolutionTicks() throw()
  217541. {
  217542. timespec t;
  217543. clock_gettime (CLOCK_MONOTONIC, &t);
  217544. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  217545. }
  217546. int64 Time::getHighResolutionTicksPerSecond() throw()
  217547. {
  217548. return 1000000; // (microseconds)
  217549. }
  217550. double Time::getMillisecondCounterHiRes() throw()
  217551. {
  217552. return getHighResolutionTicks() * 0.001;
  217553. }
  217554. bool Time::setSystemTimeToThisTime() const
  217555. {
  217556. timeval t;
  217557. t.tv_sec = millisSinceEpoch / 1000;
  217558. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  217559. return settimeofday (&t, 0) == 0;
  217560. }
  217561. #endif
  217562. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217563. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217564. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217565. // compiled on its own).
  217566. #if JUCE_INCLUDED_FILE
  217567. /*
  217568. Note that a lot of methods that you'd expect to find in this file actually
  217569. live in juce_posix_SharedCode.h!
  217570. */
  217571. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217572. void Process::setPriority (ProcessPriority prior)
  217573. {
  217574. struct sched_param param;
  217575. int policy, maxp, minp;
  217576. const int p = (int) prior;
  217577. if (p <= 1)
  217578. policy = SCHED_OTHER;
  217579. else
  217580. policy = SCHED_RR;
  217581. minp = sched_get_priority_min (policy);
  217582. maxp = sched_get_priority_max (policy);
  217583. if (p < 2)
  217584. param.sched_priority = 0;
  217585. else if (p == 2 )
  217586. // Set to middle of lower realtime priority range
  217587. param.sched_priority = minp + (maxp - minp) / 4;
  217588. else
  217589. // Set to middle of higher realtime priority range
  217590. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217591. pthread_setschedparam (pthread_self(), policy, &param);
  217592. }
  217593. void Process::terminate()
  217594. {
  217595. exit (0);
  217596. }
  217597. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  217598. {
  217599. static char testResult = 0;
  217600. if (testResult == 0)
  217601. {
  217602. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217603. if (testResult >= 0)
  217604. {
  217605. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217606. testResult = 1;
  217607. }
  217608. }
  217609. return testResult < 0;
  217610. }
  217611. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217612. {
  217613. return juce_isRunningUnderDebugger();
  217614. }
  217615. void Process::raisePrivilege()
  217616. {
  217617. // If running suid root, change effective user
  217618. // to root
  217619. if (geteuid() != 0 && getuid() == 0)
  217620. {
  217621. setreuid (geteuid(), getuid());
  217622. setregid (getegid(), getgid());
  217623. }
  217624. }
  217625. void Process::lowerPrivilege()
  217626. {
  217627. // If runing suid root, change effective user
  217628. // back to real user
  217629. if (geteuid() == 0 && getuid() != 0)
  217630. {
  217631. setreuid (geteuid(), getuid());
  217632. setregid (getegid(), getgid());
  217633. }
  217634. }
  217635. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217636. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217637. {
  217638. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217639. }
  217640. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217641. {
  217642. dlclose(handle);
  217643. }
  217644. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217645. {
  217646. return dlsym (libraryHandle, procedureName.toCString());
  217647. }
  217648. #endif
  217649. #endif
  217650. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217651. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217652. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217653. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217654. // compiled on its own).
  217655. #if JUCE_INCLUDED_FILE
  217656. extern Display* display;
  217657. extern Window juce_messageWindowHandle;
  217658. namespace ClipboardHelpers
  217659. {
  217660. static String localClipboardContent;
  217661. static Atom atom_UTF8_STRING;
  217662. static Atom atom_CLIPBOARD;
  217663. static Atom atom_TARGETS;
  217664. static void initSelectionAtoms()
  217665. {
  217666. static bool isInitialised = false;
  217667. if (! isInitialised)
  217668. {
  217669. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217670. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217671. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217672. }
  217673. }
  217674. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217675. // works only for strings shorter than 1000000 bytes
  217676. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217677. {
  217678. String returnData;
  217679. char* clipData;
  217680. Atom actualType;
  217681. int actualFormat;
  217682. unsigned long numItems, bytesLeft;
  217683. if (XGetWindowProperty (display, window, prop,
  217684. 0L /* offset */, 1000000 /* length (max) */, False,
  217685. AnyPropertyType /* format */,
  217686. &actualType, &actualFormat, &numItems, &bytesLeft,
  217687. (unsigned char**) &clipData) == Success)
  217688. {
  217689. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217690. returnData = String::fromUTF8 (clipData, numItems);
  217691. else if (actualType == XA_STRING && actualFormat == 8)
  217692. returnData = String (clipData, numItems);
  217693. if (clipData != 0)
  217694. XFree (clipData);
  217695. jassert (bytesLeft == 0 || numItems == 1000000);
  217696. }
  217697. XDeleteProperty (display, window, prop);
  217698. return returnData;
  217699. }
  217700. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217701. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217702. {
  217703. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217704. // The selection owner will be asked to set the JUCE_SEL property on the
  217705. // juce_messageWindowHandle with the selection content
  217706. XConvertSelection (display, selection, requestedFormat, property_name,
  217707. juce_messageWindowHandle, CurrentTime);
  217708. int count = 50; // will wait at most for 200 ms
  217709. while (--count >= 0)
  217710. {
  217711. XEvent event;
  217712. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217713. {
  217714. if (event.xselection.property == property_name)
  217715. {
  217716. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217717. selectionContent = readWindowProperty (event.xselection.requestor,
  217718. event.xselection.property,
  217719. requestedFormat);
  217720. return true;
  217721. }
  217722. else
  217723. {
  217724. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217725. }
  217726. }
  217727. // not very elegant.. we could do a select() or something like that...
  217728. // however clipboard content requesting is inherently slow on x11, it
  217729. // often takes 50ms or more so...
  217730. Thread::sleep (4);
  217731. }
  217732. return false;
  217733. }
  217734. }
  217735. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217736. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217737. {
  217738. ClipboardHelpers::initSelectionAtoms();
  217739. // the selection content is sent to the target window as a window property
  217740. XSelectionEvent reply;
  217741. reply.type = SelectionNotify;
  217742. reply.display = evt.display;
  217743. reply.requestor = evt.requestor;
  217744. reply.selection = evt.selection;
  217745. reply.target = evt.target;
  217746. reply.property = None; // == "fail"
  217747. reply.time = evt.time;
  217748. HeapBlock <char> data;
  217749. int propertyFormat = 0, numDataItems = 0;
  217750. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217751. {
  217752. if (evt.target == XA_STRING)
  217753. {
  217754. // format data according to system locale
  217755. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217756. data.calloc (numDataItems + 1);
  217757. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217758. propertyFormat = 8; // bits/item
  217759. }
  217760. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217761. {
  217762. // translate to utf8
  217763. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217764. data.calloc (numDataItems + 1);
  217765. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217766. propertyFormat = 8; // bits/item
  217767. }
  217768. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217769. {
  217770. // another application wants to know what we are able to send
  217771. numDataItems = 2;
  217772. propertyFormat = 32; // atoms are 32-bit
  217773. data.calloc (numDataItems * 4);
  217774. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217775. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217776. atoms[1] = XA_STRING;
  217777. }
  217778. }
  217779. else
  217780. {
  217781. DBG ("requested unsupported clipboard");
  217782. }
  217783. if (data != 0)
  217784. {
  217785. const int maxReasonableSelectionSize = 1000000;
  217786. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217787. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217788. {
  217789. XChangeProperty (evt.display, evt.requestor,
  217790. evt.property, evt.target,
  217791. propertyFormat /* 8 or 32 */, PropModeReplace,
  217792. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217793. reply.property = evt.property; // " == success"
  217794. }
  217795. }
  217796. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217797. }
  217798. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217799. {
  217800. ClipboardHelpers::initSelectionAtoms();
  217801. ClipboardHelpers::localClipboardContent = clipText;
  217802. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217803. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217804. }
  217805. const String SystemClipboard::getTextFromClipboard()
  217806. {
  217807. ClipboardHelpers::initSelectionAtoms();
  217808. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217809. level" clipboard that is supposed to be filled by ctrl-C
  217810. etc). When a clipboard manager is running, the content of this
  217811. selection is preserved even when the original selection owner
  217812. exits.
  217813. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217814. filled by good old x11 apps such as xterm)
  217815. */
  217816. String content;
  217817. Atom selection = XA_PRIMARY;
  217818. Window selectionOwner = None;
  217819. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217820. {
  217821. selection = ClipboardHelpers::atom_CLIPBOARD;
  217822. selectionOwner = XGetSelectionOwner (display, selection);
  217823. }
  217824. if (selectionOwner != None)
  217825. {
  217826. if (selectionOwner == juce_messageWindowHandle)
  217827. {
  217828. content = ClipboardHelpers::localClipboardContent;
  217829. }
  217830. else
  217831. {
  217832. // first try: we want an utf8 string
  217833. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217834. if (! ok)
  217835. {
  217836. // second chance, ask for a good old locale-dependent string ..
  217837. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217838. }
  217839. }
  217840. }
  217841. return content;
  217842. }
  217843. #endif
  217844. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217845. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217846. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217847. // compiled on its own).
  217848. #if JUCE_INCLUDED_FILE
  217849. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217850. #define JUCE_DEBUG_XERRORS 1
  217851. #endif
  217852. Display* display = 0;
  217853. Window juce_messageWindowHandle = None;
  217854. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217855. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217856. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217857. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217858. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217859. class InternalMessageQueue
  217860. {
  217861. public:
  217862. InternalMessageQueue()
  217863. : bytesInSocket (0),
  217864. totalEventCount (0)
  217865. {
  217866. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217867. (void) ret; jassert (ret == 0);
  217868. //setNonBlocking (fd[0]);
  217869. //setNonBlocking (fd[1]);
  217870. }
  217871. ~InternalMessageQueue()
  217872. {
  217873. close (fd[0]);
  217874. close (fd[1]);
  217875. clearSingletonInstance();
  217876. }
  217877. void postMessage (Message* msg)
  217878. {
  217879. const int maxBytesInSocketQueue = 128;
  217880. ScopedLock sl (lock);
  217881. queue.add (msg);
  217882. if (bytesInSocket < maxBytesInSocketQueue)
  217883. {
  217884. ++bytesInSocket;
  217885. ScopedUnlock ul (lock);
  217886. const unsigned char x = 0xff;
  217887. size_t bytesWritten = write (fd[0], &x, 1);
  217888. (void) bytesWritten;
  217889. }
  217890. }
  217891. bool isEmpty() const
  217892. {
  217893. ScopedLock sl (lock);
  217894. return queue.size() == 0;
  217895. }
  217896. bool dispatchNextEvent()
  217897. {
  217898. // This alternates between giving priority to XEvents or internal messages,
  217899. // to keep everything running smoothly..
  217900. if ((++totalEventCount & 1) != 0)
  217901. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217902. else
  217903. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217904. }
  217905. // Wait for an event (either XEvent, or an internal Message)
  217906. bool sleepUntilEvent (const int timeoutMs)
  217907. {
  217908. if (! isEmpty())
  217909. return true;
  217910. if (display != 0)
  217911. {
  217912. ScopedXLock xlock;
  217913. if (XPending (display))
  217914. return true;
  217915. }
  217916. struct timeval tv;
  217917. tv.tv_sec = 0;
  217918. tv.tv_usec = timeoutMs * 1000;
  217919. int fd0 = getWaitHandle();
  217920. int fdmax = fd0;
  217921. fd_set readset;
  217922. FD_ZERO (&readset);
  217923. FD_SET (fd0, &readset);
  217924. if (display != 0)
  217925. {
  217926. ScopedXLock xlock;
  217927. int fd1 = XConnectionNumber (display);
  217928. FD_SET (fd1, &readset);
  217929. fdmax = jmax (fd0, fd1);
  217930. }
  217931. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217932. return (ret > 0); // ret <= 0 if error or timeout
  217933. }
  217934. struct MessageThreadFuncCall
  217935. {
  217936. enum { uniqueID = 0x73774623 };
  217937. MessageCallbackFunction* func;
  217938. void* parameter;
  217939. void* result;
  217940. CriticalSection lock;
  217941. WaitableEvent event;
  217942. };
  217943. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217944. private:
  217945. CriticalSection lock;
  217946. ReferenceCountedArray <Message> queue;
  217947. int fd[2];
  217948. int bytesInSocket;
  217949. int totalEventCount;
  217950. int getWaitHandle() const throw() { return fd[1]; }
  217951. static bool setNonBlocking (int handle)
  217952. {
  217953. int socketFlags = fcntl (handle, F_GETFL, 0);
  217954. if (socketFlags == -1)
  217955. return false;
  217956. socketFlags |= O_NONBLOCK;
  217957. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217958. }
  217959. static bool dispatchNextXEvent()
  217960. {
  217961. if (display == 0)
  217962. return false;
  217963. XEvent evt;
  217964. {
  217965. ScopedXLock xlock;
  217966. if (! XPending (display))
  217967. return false;
  217968. XNextEvent (display, &evt);
  217969. }
  217970. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217971. juce_handleSelectionRequest (evt.xselectionrequest);
  217972. else if (evt.xany.window != juce_messageWindowHandle)
  217973. juce_windowMessageReceive (&evt);
  217974. return true;
  217975. }
  217976. const Message::Ptr popNextMessage()
  217977. {
  217978. const ScopedLock sl (lock);
  217979. if (bytesInSocket > 0)
  217980. {
  217981. --bytesInSocket;
  217982. const ScopedUnlock ul (lock);
  217983. unsigned char x;
  217984. size_t numBytes = read (fd[1], &x, 1);
  217985. (void) numBytes;
  217986. }
  217987. return queue.removeAndReturn (0);
  217988. }
  217989. bool dispatchNextInternalMessage()
  217990. {
  217991. const Message::Ptr msg (popNextMessage());
  217992. if (msg == 0)
  217993. return false;
  217994. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217995. {
  217996. // Handle callback message
  217997. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217998. call->result = (*(call->func)) (call->parameter);
  217999. call->event.signal();
  218000. }
  218001. else
  218002. {
  218003. // Handle "normal" messages
  218004. MessageManager::getInstance()->deliverMessage (msg);
  218005. }
  218006. return true;
  218007. }
  218008. };
  218009. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218010. namespace LinuxErrorHandling
  218011. {
  218012. static bool errorOccurred = false;
  218013. static bool keyboardBreakOccurred = false;
  218014. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218015. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218016. // Usually happens when client-server connection is broken
  218017. static int ioErrorHandler (Display* display)
  218018. {
  218019. DBG ("ERROR: connection to X server broken.. terminating.");
  218020. if (JUCEApplication::isStandaloneApp())
  218021. MessageManager::getInstance()->stopDispatchLoop();
  218022. errorOccurred = true;
  218023. return 0;
  218024. }
  218025. // A protocol error has occurred
  218026. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218027. {
  218028. #if JUCE_DEBUG_XERRORS
  218029. char errorStr[64] = { 0 };
  218030. char requestStr[64] = { 0 };
  218031. XGetErrorText (display, event->error_code, errorStr, 64);
  218032. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218033. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218034. #endif
  218035. return 0;
  218036. }
  218037. static void installXErrorHandlers()
  218038. {
  218039. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218040. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218041. }
  218042. static void removeXErrorHandlers()
  218043. {
  218044. if (JUCEApplication::isStandaloneApp())
  218045. {
  218046. XSetIOErrorHandler (oldIOErrorHandler);
  218047. oldIOErrorHandler = 0;
  218048. XSetErrorHandler (oldErrorHandler);
  218049. oldErrorHandler = 0;
  218050. }
  218051. }
  218052. static void keyboardBreakSignalHandler (int sig)
  218053. {
  218054. if (sig == SIGINT)
  218055. keyboardBreakOccurred = true;
  218056. }
  218057. static void installKeyboardBreakHandler()
  218058. {
  218059. struct sigaction saction;
  218060. sigset_t maskSet;
  218061. sigemptyset (&maskSet);
  218062. saction.sa_handler = keyboardBreakSignalHandler;
  218063. saction.sa_mask = maskSet;
  218064. saction.sa_flags = 0;
  218065. sigaction (SIGINT, &saction, 0);
  218066. }
  218067. }
  218068. void MessageManager::doPlatformSpecificInitialisation()
  218069. {
  218070. if (JUCEApplication::isStandaloneApp())
  218071. {
  218072. // Initialise xlib for multiple thread support
  218073. static bool initThreadCalled = false;
  218074. if (! initThreadCalled)
  218075. {
  218076. if (! XInitThreads())
  218077. {
  218078. // This is fatal! Print error and closedown
  218079. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218080. Process::terminate();
  218081. return;
  218082. }
  218083. initThreadCalled = true;
  218084. }
  218085. LinuxErrorHandling::installXErrorHandlers();
  218086. LinuxErrorHandling::installKeyboardBreakHandler();
  218087. }
  218088. // Create the internal message queue
  218089. InternalMessageQueue::getInstance();
  218090. // Try to connect to a display
  218091. String displayName (getenv ("DISPLAY"));
  218092. if (displayName.isEmpty())
  218093. displayName = ":0.0";
  218094. display = XOpenDisplay (displayName.toCString());
  218095. if (display != 0) // This is not fatal! we can run headless.
  218096. {
  218097. // Create a context to store user data associated with Windows we create in WindowDriver
  218098. windowHandleXContext = XUniqueContext();
  218099. // We're only interested in client messages for this window, which are always sent
  218100. XSetWindowAttributes swa;
  218101. swa.event_mask = NoEventMask;
  218102. // Create our message window (this will never be mapped)
  218103. const int screen = DefaultScreen (display);
  218104. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218105. 0, 0, 1, 1, 0, 0, InputOnly,
  218106. DefaultVisual (display, screen),
  218107. CWEventMask, &swa);
  218108. }
  218109. }
  218110. void MessageManager::doPlatformSpecificShutdown()
  218111. {
  218112. InternalMessageQueue::deleteInstance();
  218113. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218114. {
  218115. XDestroyWindow (display, juce_messageWindowHandle);
  218116. XCloseDisplay (display);
  218117. juce_messageWindowHandle = 0;
  218118. display = 0;
  218119. LinuxErrorHandling::removeXErrorHandlers();
  218120. }
  218121. }
  218122. bool juce_postMessageToSystemQueue (Message* message)
  218123. {
  218124. if (LinuxErrorHandling::errorOccurred)
  218125. return false;
  218126. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218127. return true;
  218128. }
  218129. void MessageManager::broadcastMessage (const String& value)
  218130. {
  218131. /* TODO */
  218132. }
  218133. class AsyncFunctionCaller : public AsyncUpdater
  218134. {
  218135. public:
  218136. static void* call (MessageCallbackFunction* func_, void* parameter_)
  218137. {
  218138. if (MessageManager::getInstance()->isThisTheMessageThread())
  218139. return func_ (parameter_);
  218140. AsyncFunctionCaller caller (func_, parameter_);
  218141. caller.triggerAsyncUpdate();
  218142. caller.finished.wait();
  218143. return caller.result;
  218144. }
  218145. void handleAsyncUpdate()
  218146. {
  218147. result = (*func) (parameter);
  218148. finished.signal();
  218149. }
  218150. private:
  218151. WaitableEvent finished;
  218152. MessageCallbackFunction* func;
  218153. void* parameter;
  218154. void* volatile result;
  218155. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  218156. : result (0), func (func_), parameter (parameter_)
  218157. {}
  218158. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  218159. };
  218160. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218161. {
  218162. if (LinuxErrorHandling::errorOccurred)
  218163. return 0;
  218164. return AsyncFunctionCaller::call (func, parameter);
  218165. }
  218166. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218167. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218168. {
  218169. while (! LinuxErrorHandling::errorOccurred)
  218170. {
  218171. if (LinuxErrorHandling::keyboardBreakOccurred)
  218172. {
  218173. LinuxErrorHandling::errorOccurred = true;
  218174. if (JUCEApplication::isStandaloneApp())
  218175. Process::terminate();
  218176. break;
  218177. }
  218178. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218179. return true;
  218180. if (returnIfNoPendingMessages)
  218181. break;
  218182. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218183. }
  218184. return false;
  218185. }
  218186. #endif
  218187. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218188. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218189. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218190. // compiled on its own).
  218191. #if JUCE_INCLUDED_FILE
  218192. class FreeTypeFontFace
  218193. {
  218194. public:
  218195. enum FontStyle
  218196. {
  218197. Plain = 0,
  218198. Bold = 1,
  218199. Italic = 2
  218200. };
  218201. FreeTypeFontFace (const String& familyName)
  218202. : hasSerif (false),
  218203. monospaced (false)
  218204. {
  218205. family = familyName;
  218206. }
  218207. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218208. {
  218209. if (names [(int) style].fileName.isEmpty())
  218210. {
  218211. names [(int) style].fileName = name;
  218212. names [(int) style].faceIndex = faceIndex;
  218213. }
  218214. }
  218215. const String& getFamilyName() const throw() { return family; }
  218216. const String& getFileName (const int style, int& faceIndex) const throw()
  218217. {
  218218. faceIndex = names[style].faceIndex;
  218219. return names[style].fileName;
  218220. }
  218221. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218222. bool getMonospaced() const throw() { return monospaced; }
  218223. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218224. bool getSerif() const throw() { return hasSerif; }
  218225. private:
  218226. String family;
  218227. struct FontNameIndex
  218228. {
  218229. String fileName;
  218230. int faceIndex;
  218231. };
  218232. FontNameIndex names[4];
  218233. bool hasSerif, monospaced;
  218234. };
  218235. class FreeTypeInterface : public DeletedAtShutdown
  218236. {
  218237. public:
  218238. FreeTypeInterface()
  218239. : ftLib (0),
  218240. lastFace (0),
  218241. lastBold (false),
  218242. lastItalic (false)
  218243. {
  218244. if (FT_Init_FreeType (&ftLib) != 0)
  218245. {
  218246. ftLib = 0;
  218247. DBG ("Failed to initialize FreeType");
  218248. }
  218249. StringArray fontDirs;
  218250. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218251. fontDirs.removeEmptyStrings (true);
  218252. if (fontDirs.size() == 0)
  218253. {
  218254. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218255. if (fontsInfo != 0)
  218256. {
  218257. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218258. {
  218259. fontDirs.add (e->getAllSubText().trim());
  218260. }
  218261. }
  218262. }
  218263. if (fontDirs.size() == 0)
  218264. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218265. for (int i = 0; i < fontDirs.size(); ++i)
  218266. enumerateFaces (fontDirs[i]);
  218267. }
  218268. ~FreeTypeInterface()
  218269. {
  218270. if (lastFace != 0)
  218271. FT_Done_Face (lastFace);
  218272. if (ftLib != 0)
  218273. FT_Done_FreeType (ftLib);
  218274. clearSingletonInstance();
  218275. }
  218276. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218277. {
  218278. for (int i = 0; i < faces.size(); i++)
  218279. if (faces[i]->getFamilyName() == familyName)
  218280. return faces[i];
  218281. if (! create)
  218282. return 0;
  218283. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218284. faces.add (newFace);
  218285. return newFace;
  218286. }
  218287. // Enumerate all font faces available in a given directory
  218288. void enumerateFaces (const String& path)
  218289. {
  218290. File dirPath (path);
  218291. if (path.isEmpty() || ! dirPath.isDirectory())
  218292. return;
  218293. DirectoryIterator di (dirPath, true);
  218294. while (di.next())
  218295. {
  218296. File possible (di.getFile());
  218297. if (possible.hasFileExtension ("ttf")
  218298. || possible.hasFileExtension ("pfb")
  218299. || possible.hasFileExtension ("pcf"))
  218300. {
  218301. FT_Face face;
  218302. int faceIndex = 0;
  218303. int numFaces = 0;
  218304. do
  218305. {
  218306. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218307. faceIndex, &face) == 0)
  218308. {
  218309. if (faceIndex == 0)
  218310. numFaces = face->num_faces;
  218311. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218312. {
  218313. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218314. int style = (int) FreeTypeFontFace::Plain;
  218315. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218316. style |= (int) FreeTypeFontFace::Bold;
  218317. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218318. style |= (int) FreeTypeFontFace::Italic;
  218319. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218320. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218321. // Surely there must be a better way to do this?
  218322. const String name (face->family_name);
  218323. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218324. || name.containsIgnoreCase ("Verdana")
  218325. || name.containsIgnoreCase ("Arial")));
  218326. }
  218327. FT_Done_Face (face);
  218328. }
  218329. ++faceIndex;
  218330. }
  218331. while (faceIndex < numFaces);
  218332. }
  218333. }
  218334. }
  218335. // Create a FreeType face object for a given font
  218336. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218337. {
  218338. FT_Face face = 0;
  218339. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218340. {
  218341. face = lastFace;
  218342. }
  218343. else
  218344. {
  218345. if (lastFace != 0)
  218346. {
  218347. FT_Done_Face (lastFace);
  218348. lastFace = 0;
  218349. }
  218350. lastFontName = fontName;
  218351. lastBold = bold;
  218352. lastItalic = italic;
  218353. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218354. if (ftFace != 0)
  218355. {
  218356. int style = (int) FreeTypeFontFace::Plain;
  218357. if (bold)
  218358. style |= (int) FreeTypeFontFace::Bold;
  218359. if (italic)
  218360. style |= (int) FreeTypeFontFace::Italic;
  218361. int faceIndex;
  218362. String fileName (ftFace->getFileName (style, faceIndex));
  218363. if (fileName.isEmpty())
  218364. {
  218365. style ^= (int) FreeTypeFontFace::Bold;
  218366. fileName = ftFace->getFileName (style, faceIndex);
  218367. if (fileName.isEmpty())
  218368. {
  218369. style ^= (int) FreeTypeFontFace::Bold;
  218370. style ^= (int) FreeTypeFontFace::Italic;
  218371. fileName = ftFace->getFileName (style, faceIndex);
  218372. if (! fileName.length())
  218373. {
  218374. style ^= (int) FreeTypeFontFace::Bold;
  218375. fileName = ftFace->getFileName (style, faceIndex);
  218376. }
  218377. }
  218378. }
  218379. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218380. {
  218381. face = lastFace;
  218382. // If there isn't a unicode charmap then select the first one.
  218383. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218384. FT_Set_Charmap (face, face->charmaps[0]);
  218385. }
  218386. }
  218387. }
  218388. return face;
  218389. }
  218390. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218391. {
  218392. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218393. const float height = (float) (face->ascender - face->descender);
  218394. const float scaleX = 1.0f / height;
  218395. const float scaleY = -1.0f / height;
  218396. Path destShape;
  218397. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218398. || face->glyph->format != ft_glyph_format_outline)
  218399. {
  218400. return false;
  218401. }
  218402. const FT_Outline* const outline = &face->glyph->outline;
  218403. const short* const contours = outline->contours;
  218404. const char* const tags = outline->tags;
  218405. FT_Vector* const points = outline->points;
  218406. for (int c = 0; c < outline->n_contours; c++)
  218407. {
  218408. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218409. const int endPoint = contours[c];
  218410. for (int p = startPoint; p <= endPoint; p++)
  218411. {
  218412. const float x = scaleX * points[p].x;
  218413. const float y = scaleY * points[p].y;
  218414. if (p == startPoint)
  218415. {
  218416. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218417. {
  218418. float x2 = scaleX * points [endPoint].x;
  218419. float y2 = scaleY * points [endPoint].y;
  218420. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218421. {
  218422. x2 = (x + x2) * 0.5f;
  218423. y2 = (y + y2) * 0.5f;
  218424. }
  218425. destShape.startNewSubPath (x2, y2);
  218426. }
  218427. else
  218428. {
  218429. destShape.startNewSubPath (x, y);
  218430. }
  218431. }
  218432. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218433. {
  218434. if (p != startPoint)
  218435. destShape.lineTo (x, y);
  218436. }
  218437. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218438. {
  218439. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218440. float x2 = scaleX * points [nextIndex].x;
  218441. float y2 = scaleY * points [nextIndex].y;
  218442. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218443. {
  218444. x2 = (x + x2) * 0.5f;
  218445. y2 = (y + y2) * 0.5f;
  218446. }
  218447. else
  218448. {
  218449. ++p;
  218450. }
  218451. destShape.quadraticTo (x, y, x2, y2);
  218452. }
  218453. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218454. {
  218455. if (p >= endPoint)
  218456. return false;
  218457. const int next1 = p + 1;
  218458. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218459. const float x2 = scaleX * points [next1].x;
  218460. const float y2 = scaleY * points [next1].y;
  218461. const float x3 = scaleX * points [next2].x;
  218462. const float y3 = scaleY * points [next2].y;
  218463. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218464. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218465. return false;
  218466. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218467. p += 2;
  218468. }
  218469. }
  218470. destShape.closeSubPath();
  218471. }
  218472. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218473. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218474. addKerning (face, dest, character, glyphIndex);
  218475. return true;
  218476. }
  218477. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218478. {
  218479. const float height = (float) (face->ascender - face->descender);
  218480. uint32 rightGlyphIndex;
  218481. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218482. while (rightGlyphIndex != 0)
  218483. {
  218484. FT_Vector kerning;
  218485. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218486. {
  218487. if (kerning.x != 0)
  218488. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218489. }
  218490. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218491. }
  218492. }
  218493. // Add a glyph to a font
  218494. bool addGlyphToFont (const uint32 character, const String& fontName,
  218495. bool bold, bool italic, CustomTypeface& dest)
  218496. {
  218497. FT_Face face = createFT_Face (fontName, bold, italic);
  218498. return face != 0 && addGlyph (face, dest, character);
  218499. }
  218500. void getFamilyNames (StringArray& familyNames) const
  218501. {
  218502. for (int i = 0; i < faces.size(); i++)
  218503. familyNames.add (faces[i]->getFamilyName());
  218504. }
  218505. void getMonospacedNames (StringArray& monoSpaced) const
  218506. {
  218507. for (int i = 0; i < faces.size(); i++)
  218508. if (faces[i]->getMonospaced())
  218509. monoSpaced.add (faces[i]->getFamilyName());
  218510. }
  218511. void getSerifNames (StringArray& serif) const
  218512. {
  218513. for (int i = 0; i < faces.size(); i++)
  218514. if (faces[i]->getSerif())
  218515. serif.add (faces[i]->getFamilyName());
  218516. }
  218517. void getSansSerifNames (StringArray& sansSerif) const
  218518. {
  218519. for (int i = 0; i < faces.size(); i++)
  218520. if (! faces[i]->getSerif())
  218521. sansSerif.add (faces[i]->getFamilyName());
  218522. }
  218523. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218524. private:
  218525. FT_Library ftLib;
  218526. FT_Face lastFace;
  218527. String lastFontName;
  218528. bool lastBold, lastItalic;
  218529. OwnedArray<FreeTypeFontFace> faces;
  218530. };
  218531. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218532. class FreetypeTypeface : public CustomTypeface
  218533. {
  218534. public:
  218535. FreetypeTypeface (const Font& font)
  218536. {
  218537. FT_Face face = FreeTypeInterface::getInstance()
  218538. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218539. if (face == 0)
  218540. {
  218541. #if JUCE_DEBUG
  218542. String msg ("Failed to create typeface: ");
  218543. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218544. DBG (msg);
  218545. #endif
  218546. }
  218547. else
  218548. {
  218549. setCharacteristics (font.getTypefaceName(),
  218550. face->ascender / (float) (face->ascender - face->descender),
  218551. font.isBold(), font.isItalic(),
  218552. L' ');
  218553. }
  218554. }
  218555. bool loadGlyphIfPossible (juce_wchar character)
  218556. {
  218557. return FreeTypeInterface::getInstance()
  218558. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218559. }
  218560. };
  218561. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218562. {
  218563. return new FreetypeTypeface (font);
  218564. }
  218565. const StringArray Font::findAllTypefaceNames()
  218566. {
  218567. StringArray s;
  218568. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218569. s.sort (true);
  218570. return s;
  218571. }
  218572. namespace
  218573. {
  218574. const String pickBestFont (const StringArray& names,
  218575. const char* const choicesString)
  218576. {
  218577. StringArray choices;
  218578. choices.addTokens (String (choicesString), ",", String::empty);
  218579. choices.trim();
  218580. choices.removeEmptyStrings();
  218581. int i, j;
  218582. for (j = 0; j < choices.size(); ++j)
  218583. if (names.contains (choices[j], true))
  218584. return choices[j];
  218585. for (j = 0; j < choices.size(); ++j)
  218586. for (i = 0; i < names.size(); i++)
  218587. if (names[i].startsWithIgnoreCase (choices[j]))
  218588. return names[i];
  218589. for (j = 0; j < choices.size(); ++j)
  218590. for (i = 0; i < names.size(); i++)
  218591. if (names[i].containsIgnoreCase (choices[j]))
  218592. return names[i];
  218593. return names[0];
  218594. }
  218595. const String linux_getDefaultSansSerifFontName()
  218596. {
  218597. StringArray allFonts;
  218598. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218599. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218600. }
  218601. const String linux_getDefaultSerifFontName()
  218602. {
  218603. StringArray allFonts;
  218604. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218605. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218606. }
  218607. const String linux_getDefaultMonospacedFontName()
  218608. {
  218609. StringArray allFonts;
  218610. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218611. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218612. }
  218613. }
  218614. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  218615. {
  218616. defaultSans = linux_getDefaultSansSerifFontName();
  218617. defaultSerif = linux_getDefaultSerifFontName();
  218618. defaultFixed = linux_getDefaultMonospacedFontName();
  218619. }
  218620. #endif
  218621. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218622. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218623. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218624. // compiled on its own).
  218625. #if JUCE_INCLUDED_FILE
  218626. // These are defined in juce_linux_Messaging.cpp
  218627. extern Display* display;
  218628. extern XContext windowHandleXContext;
  218629. namespace Atoms
  218630. {
  218631. enum ProtocolItems
  218632. {
  218633. TAKE_FOCUS = 0,
  218634. DELETE_WINDOW = 1,
  218635. PING = 2
  218636. };
  218637. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218638. ActiveWin, Pid, WindowType, WindowState,
  218639. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218640. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218641. XdndActionDescription, XdndActionCopy,
  218642. allowedActions[5],
  218643. allowedMimeTypes[2];
  218644. const unsigned long DndVersion = 3;
  218645. static void initialiseAtoms()
  218646. {
  218647. static bool atomsInitialised = false;
  218648. if (! atomsInitialised)
  218649. {
  218650. atomsInitialised = true;
  218651. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218652. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218653. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218654. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218655. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218656. State = XInternAtom (display, "WM_STATE", True);
  218657. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218658. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218659. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218660. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218661. XdndAware = XInternAtom (display, "XdndAware", False);
  218662. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218663. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218664. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218665. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218666. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218667. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218668. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218669. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218670. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218671. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218672. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218673. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218674. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218675. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218676. allowedActions[1] = XdndActionCopy;
  218677. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218678. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218679. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218680. }
  218681. }
  218682. }
  218683. namespace Keys
  218684. {
  218685. enum MouseButtons
  218686. {
  218687. NoButton = 0,
  218688. LeftButton = 1,
  218689. MiddleButton = 2,
  218690. RightButton = 3,
  218691. WheelUp = 4,
  218692. WheelDown = 5
  218693. };
  218694. static int AltMask = 0;
  218695. static int NumLockMask = 0;
  218696. static bool numLock = false;
  218697. static bool capsLock = false;
  218698. static char keyStates [32];
  218699. static const int extendedKeyModifier = 0x10000000;
  218700. }
  218701. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218702. {
  218703. int keysym;
  218704. if (keyCode & Keys::extendedKeyModifier)
  218705. {
  218706. keysym = 0xff00 | (keyCode & 0xff);
  218707. }
  218708. else
  218709. {
  218710. keysym = keyCode;
  218711. if (keysym == (XK_Tab & 0xff)
  218712. || keysym == (XK_Return & 0xff)
  218713. || keysym == (XK_Escape & 0xff)
  218714. || keysym == (XK_BackSpace & 0xff))
  218715. {
  218716. keysym |= 0xff00;
  218717. }
  218718. }
  218719. ScopedXLock xlock;
  218720. const int keycode = XKeysymToKeycode (display, keysym);
  218721. const int keybyte = keycode >> 3;
  218722. const int keybit = (1 << (keycode & 7));
  218723. return (Keys::keyStates [keybyte] & keybit) != 0;
  218724. }
  218725. #if JUCE_USE_XSHM
  218726. namespace XSHMHelpers
  218727. {
  218728. static int trappedErrorCode = 0;
  218729. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218730. {
  218731. trappedErrorCode = err->error_code;
  218732. return 0;
  218733. }
  218734. static bool isShmAvailable() throw()
  218735. {
  218736. static bool isChecked = false;
  218737. static bool isAvailable = false;
  218738. if (! isChecked)
  218739. {
  218740. isChecked = true;
  218741. int major, minor;
  218742. Bool pixmaps;
  218743. ScopedXLock xlock;
  218744. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218745. {
  218746. trappedErrorCode = 0;
  218747. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218748. XShmSegmentInfo segmentInfo;
  218749. zerostruct (segmentInfo);
  218750. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218751. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218752. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218753. xImage->bytes_per_line * xImage->height,
  218754. IPC_CREAT | 0777)) >= 0)
  218755. {
  218756. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218757. if (segmentInfo.shmaddr != (void*) -1)
  218758. {
  218759. segmentInfo.readOnly = False;
  218760. xImage->data = segmentInfo.shmaddr;
  218761. XSync (display, False);
  218762. if (XShmAttach (display, &segmentInfo) != 0)
  218763. {
  218764. XSync (display, False);
  218765. XShmDetach (display, &segmentInfo);
  218766. isAvailable = true;
  218767. }
  218768. }
  218769. XFlush (display);
  218770. XDestroyImage (xImage);
  218771. shmdt (segmentInfo.shmaddr);
  218772. }
  218773. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218774. XSetErrorHandler (oldHandler);
  218775. if (trappedErrorCode != 0)
  218776. isAvailable = false;
  218777. }
  218778. }
  218779. return isAvailable;
  218780. }
  218781. }
  218782. #endif
  218783. #if JUCE_USE_XRENDER
  218784. namespace XRender
  218785. {
  218786. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218787. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218788. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218789. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218790. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218791. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218792. static tXRenderFindFormat xRenderFindFormat = 0;
  218793. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218794. static bool isAvailable()
  218795. {
  218796. static bool hasLoaded = false;
  218797. if (! hasLoaded)
  218798. {
  218799. ScopedXLock xlock;
  218800. hasLoaded = true;
  218801. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218802. if (h != 0)
  218803. {
  218804. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218805. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218806. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218807. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218808. }
  218809. if (xRenderQueryVersion != 0
  218810. && xRenderFindStandardFormat != 0
  218811. && xRenderFindFormat != 0
  218812. && xRenderFindVisualFormat != 0)
  218813. {
  218814. int major, minor;
  218815. if (xRenderQueryVersion (display, &major, &minor))
  218816. return true;
  218817. }
  218818. xRenderQueryVersion = 0;
  218819. }
  218820. return xRenderQueryVersion != 0;
  218821. }
  218822. static XRenderPictFormat* findPictureFormat()
  218823. {
  218824. ScopedXLock xlock;
  218825. XRenderPictFormat* pictFormat = 0;
  218826. if (isAvailable())
  218827. {
  218828. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218829. if (pictFormat == 0)
  218830. {
  218831. XRenderPictFormat desiredFormat;
  218832. desiredFormat.type = PictTypeDirect;
  218833. desiredFormat.depth = 32;
  218834. desiredFormat.direct.alphaMask = 0xff;
  218835. desiredFormat.direct.redMask = 0xff;
  218836. desiredFormat.direct.greenMask = 0xff;
  218837. desiredFormat.direct.blueMask = 0xff;
  218838. desiredFormat.direct.alpha = 24;
  218839. desiredFormat.direct.red = 16;
  218840. desiredFormat.direct.green = 8;
  218841. desiredFormat.direct.blue = 0;
  218842. pictFormat = xRenderFindFormat (display,
  218843. PictFormatType | PictFormatDepth
  218844. | PictFormatRedMask | PictFormatRed
  218845. | PictFormatGreenMask | PictFormatGreen
  218846. | PictFormatBlueMask | PictFormatBlue
  218847. | PictFormatAlphaMask | PictFormatAlpha,
  218848. &desiredFormat,
  218849. 0);
  218850. }
  218851. }
  218852. return pictFormat;
  218853. }
  218854. }
  218855. #endif
  218856. namespace Visuals
  218857. {
  218858. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218859. {
  218860. ScopedXLock xlock;
  218861. Visual* visual = 0;
  218862. int numVisuals = 0;
  218863. long desiredMask = VisualNoMask;
  218864. XVisualInfo desiredVisual;
  218865. desiredVisual.screen = DefaultScreen (display);
  218866. desiredVisual.depth = desiredDepth;
  218867. desiredMask = VisualScreenMask | VisualDepthMask;
  218868. if (desiredDepth == 32)
  218869. {
  218870. desiredVisual.c_class = TrueColor;
  218871. desiredVisual.red_mask = 0x00FF0000;
  218872. desiredVisual.green_mask = 0x0000FF00;
  218873. desiredVisual.blue_mask = 0x000000FF;
  218874. desiredVisual.bits_per_rgb = 8;
  218875. desiredMask |= VisualClassMask;
  218876. desiredMask |= VisualRedMaskMask;
  218877. desiredMask |= VisualGreenMaskMask;
  218878. desiredMask |= VisualBlueMaskMask;
  218879. desiredMask |= VisualBitsPerRGBMask;
  218880. }
  218881. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218882. desiredMask,
  218883. &desiredVisual,
  218884. &numVisuals);
  218885. if (xvinfos != 0)
  218886. {
  218887. for (int i = 0; i < numVisuals; i++)
  218888. {
  218889. if (xvinfos[i].depth == desiredDepth)
  218890. {
  218891. visual = xvinfos[i].visual;
  218892. break;
  218893. }
  218894. }
  218895. XFree (xvinfos);
  218896. }
  218897. return visual;
  218898. }
  218899. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218900. {
  218901. Visual* visual = 0;
  218902. if (desiredDepth == 32)
  218903. {
  218904. #if JUCE_USE_XSHM
  218905. if (XSHMHelpers::isShmAvailable())
  218906. {
  218907. #if JUCE_USE_XRENDER
  218908. if (XRender::isAvailable())
  218909. {
  218910. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218911. if (pictFormat != 0)
  218912. {
  218913. int numVisuals = 0;
  218914. XVisualInfo desiredVisual;
  218915. desiredVisual.screen = DefaultScreen (display);
  218916. desiredVisual.depth = 32;
  218917. desiredVisual.bits_per_rgb = 8;
  218918. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218919. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218920. &desiredVisual, &numVisuals);
  218921. if (xvinfos != 0)
  218922. {
  218923. for (int i = 0; i < numVisuals; ++i)
  218924. {
  218925. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218926. if (pictVisualFormat != 0
  218927. && pictVisualFormat->type == PictTypeDirect
  218928. && pictVisualFormat->direct.alphaMask)
  218929. {
  218930. visual = xvinfos[i].visual;
  218931. matchedDepth = 32;
  218932. break;
  218933. }
  218934. }
  218935. XFree (xvinfos);
  218936. }
  218937. }
  218938. }
  218939. #endif
  218940. if (visual == 0)
  218941. {
  218942. visual = findVisualWithDepth (32);
  218943. if (visual != 0)
  218944. matchedDepth = 32;
  218945. }
  218946. }
  218947. #endif
  218948. }
  218949. if (visual == 0 && desiredDepth >= 24)
  218950. {
  218951. visual = findVisualWithDepth (24);
  218952. if (visual != 0)
  218953. matchedDepth = 24;
  218954. }
  218955. if (visual == 0 && desiredDepth >= 16)
  218956. {
  218957. visual = findVisualWithDepth (16);
  218958. if (visual != 0)
  218959. matchedDepth = 16;
  218960. }
  218961. return visual;
  218962. }
  218963. }
  218964. class XBitmapImage : public Image::SharedImage
  218965. {
  218966. public:
  218967. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218968. const bool clearImage, const int imageDepth_, Visual* visual)
  218969. : Image::SharedImage (format_, w, h),
  218970. imageDepth (imageDepth_),
  218971. gc (None)
  218972. {
  218973. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218974. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218975. lineStride = ((w * pixelStride + 3) & ~3);
  218976. ScopedXLock xlock;
  218977. #if JUCE_USE_XSHM
  218978. usingXShm = false;
  218979. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218980. {
  218981. zerostruct (segmentInfo);
  218982. segmentInfo.shmid = -1;
  218983. segmentInfo.shmaddr = (char *) -1;
  218984. segmentInfo.readOnly = False;
  218985. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218986. if (xImage != 0)
  218987. {
  218988. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218989. xImage->bytes_per_line * xImage->height,
  218990. IPC_CREAT | 0777)) >= 0)
  218991. {
  218992. if (segmentInfo.shmid != -1)
  218993. {
  218994. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218995. if (segmentInfo.shmaddr != (void*) -1)
  218996. {
  218997. segmentInfo.readOnly = False;
  218998. xImage->data = segmentInfo.shmaddr;
  218999. imageData = (uint8*) segmentInfo.shmaddr;
  219000. if (XShmAttach (display, &segmentInfo) != 0)
  219001. usingXShm = true;
  219002. else
  219003. jassertfalse;
  219004. }
  219005. else
  219006. {
  219007. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219008. }
  219009. }
  219010. }
  219011. }
  219012. }
  219013. if (! usingXShm)
  219014. #endif
  219015. {
  219016. imageDataAllocated.malloc (lineStride * h);
  219017. imageData = imageDataAllocated;
  219018. if (format_ == Image::ARGB && clearImage)
  219019. zeromem (imageData, h * lineStride);
  219020. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219021. xImage->width = w;
  219022. xImage->height = h;
  219023. xImage->xoffset = 0;
  219024. xImage->format = ZPixmap;
  219025. xImage->data = (char*) imageData;
  219026. xImage->byte_order = ImageByteOrder (display);
  219027. xImage->bitmap_unit = BitmapUnit (display);
  219028. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219029. xImage->bitmap_pad = 32;
  219030. xImage->depth = pixelStride * 8;
  219031. xImage->bytes_per_line = lineStride;
  219032. xImage->bits_per_pixel = pixelStride * 8;
  219033. xImage->red_mask = 0x00FF0000;
  219034. xImage->green_mask = 0x0000FF00;
  219035. xImage->blue_mask = 0x000000FF;
  219036. if (imageDepth == 16)
  219037. {
  219038. const int pixelStride = 2;
  219039. const int lineStride = ((w * pixelStride + 3) & ~3);
  219040. imageData16Bit.malloc (lineStride * h);
  219041. xImage->data = imageData16Bit;
  219042. xImage->bitmap_pad = 16;
  219043. xImage->depth = pixelStride * 8;
  219044. xImage->bytes_per_line = lineStride;
  219045. xImage->bits_per_pixel = pixelStride * 8;
  219046. xImage->red_mask = visual->red_mask;
  219047. xImage->green_mask = visual->green_mask;
  219048. xImage->blue_mask = visual->blue_mask;
  219049. }
  219050. if (! XInitImage (xImage))
  219051. jassertfalse;
  219052. }
  219053. }
  219054. ~XBitmapImage()
  219055. {
  219056. ScopedXLock xlock;
  219057. if (gc != None)
  219058. XFreeGC (display, gc);
  219059. #if JUCE_USE_XSHM
  219060. if (usingXShm)
  219061. {
  219062. XShmDetach (display, &segmentInfo);
  219063. XFlush (display);
  219064. XDestroyImage (xImage);
  219065. shmdt (segmentInfo.shmaddr);
  219066. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219067. }
  219068. else
  219069. #endif
  219070. {
  219071. xImage->data = 0;
  219072. XDestroyImage (xImage);
  219073. }
  219074. }
  219075. Image::ImageType getType() const { return Image::NativeImage; }
  219076. LowLevelGraphicsContext* createLowLevelContext()
  219077. {
  219078. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219079. }
  219080. SharedImage* clone()
  219081. {
  219082. jassertfalse;
  219083. return 0;
  219084. }
  219085. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219086. {
  219087. ScopedXLock xlock;
  219088. if (gc == None)
  219089. {
  219090. XGCValues gcvalues;
  219091. gcvalues.foreground = None;
  219092. gcvalues.background = None;
  219093. gcvalues.function = GXcopy;
  219094. gcvalues.plane_mask = AllPlanes;
  219095. gcvalues.clip_mask = None;
  219096. gcvalues.graphics_exposures = False;
  219097. gc = XCreateGC (display, window,
  219098. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219099. &gcvalues);
  219100. }
  219101. if (imageDepth == 16)
  219102. {
  219103. const uint32 rMask = xImage->red_mask;
  219104. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219105. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219106. const uint32 gMask = xImage->green_mask;
  219107. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219108. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219109. const uint32 bMask = xImage->blue_mask;
  219110. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219111. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219112. const Image::BitmapData srcData (Image (this), false);
  219113. for (int y = sy; y < sy + dh; ++y)
  219114. {
  219115. const uint8* p = srcData.getPixelPointer (sx, y);
  219116. for (int x = sx; x < sx + dw; ++x)
  219117. {
  219118. const PixelRGB* const pixel = (const PixelRGB*) p;
  219119. p += srcData.pixelStride;
  219120. XPutPixel (xImage, x, y,
  219121. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219122. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219123. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219124. }
  219125. }
  219126. }
  219127. // blit results to screen.
  219128. #if JUCE_USE_XSHM
  219129. if (usingXShm)
  219130. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219131. else
  219132. #endif
  219133. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219134. }
  219135. private:
  219136. XImage* xImage;
  219137. const int imageDepth;
  219138. HeapBlock <uint8> imageDataAllocated;
  219139. HeapBlock <char> imageData16Bit;
  219140. GC gc;
  219141. #if JUCE_USE_XSHM
  219142. XShmSegmentInfo segmentInfo;
  219143. bool usingXShm;
  219144. #endif
  219145. static int getShiftNeeded (const uint32 mask) throw()
  219146. {
  219147. for (int i = 32; --i >= 0;)
  219148. if (((mask >> i) & 1) != 0)
  219149. return i - 7;
  219150. jassertfalse;
  219151. return 0;
  219152. }
  219153. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219154. };
  219155. namespace PixmapHelpers
  219156. {
  219157. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219158. {
  219159. ScopedXLock xlock;
  219160. const int width = image.getWidth();
  219161. const int height = image.getHeight();
  219162. HeapBlock <uint32> colour (width * height);
  219163. int index = 0;
  219164. for (int y = 0; y < height; ++y)
  219165. for (int x = 0; x < width; ++x)
  219166. colour[index++] = image.getPixelAt (x, y).getARGB();
  219167. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219168. 0, reinterpret_cast<char*> (colour.getData()),
  219169. width, height, 32, 0);
  219170. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219171. width, height, 24);
  219172. GC gc = XCreateGC (display, pixmap, 0, 0);
  219173. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219174. XFreeGC (display, gc);
  219175. return pixmap;
  219176. }
  219177. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219178. {
  219179. ScopedXLock xlock;
  219180. const int width = image.getWidth();
  219181. const int height = image.getHeight();
  219182. const int stride = (width + 7) >> 3;
  219183. HeapBlock <char> mask;
  219184. mask.calloc (stride * height);
  219185. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219186. for (int y = 0; y < height; ++y)
  219187. {
  219188. for (int x = 0; x < width; ++x)
  219189. {
  219190. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219191. const int offset = y * stride + (x >> 3);
  219192. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219193. mask[offset] |= bit;
  219194. }
  219195. }
  219196. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219197. mask.getData(), width, height, 1, 0, 1);
  219198. }
  219199. }
  219200. class LinuxComponentPeer : public ComponentPeer
  219201. {
  219202. public:
  219203. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219204. : ComponentPeer (component, windowStyleFlags),
  219205. windowH (0),
  219206. parentWindow (0),
  219207. wx (0),
  219208. wy (0),
  219209. ww (0),
  219210. wh (0),
  219211. fullScreen (false),
  219212. mapped (false),
  219213. visual (0),
  219214. depth (0)
  219215. {
  219216. // it's dangerous to create a window on a thread other than the message thread..
  219217. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219218. repainter = new LinuxRepaintManager (this);
  219219. createWindow();
  219220. setTitle (component->getName());
  219221. }
  219222. ~LinuxComponentPeer()
  219223. {
  219224. // it's dangerous to delete a window on a thread other than the message thread..
  219225. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219226. deleteIconPixmaps();
  219227. destroyWindow();
  219228. windowH = 0;
  219229. }
  219230. void* getNativeHandle() const
  219231. {
  219232. return (void*) windowH;
  219233. }
  219234. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219235. {
  219236. XPointer peer = 0;
  219237. ScopedXLock xlock;
  219238. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219239. {
  219240. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219241. peer = 0;
  219242. }
  219243. return (LinuxComponentPeer*) peer;
  219244. }
  219245. void setVisible (bool shouldBeVisible)
  219246. {
  219247. ScopedXLock xlock;
  219248. if (shouldBeVisible)
  219249. XMapWindow (display, windowH);
  219250. else
  219251. XUnmapWindow (display, windowH);
  219252. }
  219253. void setTitle (const String& title)
  219254. {
  219255. XTextProperty nameProperty;
  219256. char* strings[] = { const_cast <char*> (title.toUTF8().getAddress()) };
  219257. ScopedXLock xlock;
  219258. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219259. {
  219260. XSetWMName (display, windowH, &nameProperty);
  219261. XSetWMIconName (display, windowH, &nameProperty);
  219262. XFree (nameProperty.value);
  219263. }
  219264. }
  219265. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219266. {
  219267. fullScreen = isNowFullScreen;
  219268. if (windowH != 0)
  219269. {
  219270. WeakReference<Component> deletionChecker (component);
  219271. wx = x;
  219272. wy = y;
  219273. ww = jmax (1, w);
  219274. wh = jmax (1, h);
  219275. ScopedXLock xlock;
  219276. // Make sure the Window manager does what we want
  219277. XSizeHints* hints = XAllocSizeHints();
  219278. hints->flags = USSize | USPosition;
  219279. hints->width = ww;
  219280. hints->height = wh;
  219281. hints->x = wx;
  219282. hints->y = wy;
  219283. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219284. {
  219285. hints->min_width = hints->max_width = hints->width;
  219286. hints->min_height = hints->max_height = hints->height;
  219287. hints->flags |= PMinSize | PMaxSize;
  219288. }
  219289. XSetWMNormalHints (display, windowH, hints);
  219290. XFree (hints);
  219291. XMoveResizeWindow (display, windowH,
  219292. wx - windowBorder.getLeft(),
  219293. wy - windowBorder.getTop(), ww, wh);
  219294. if (deletionChecker != 0)
  219295. {
  219296. updateBorderSize();
  219297. handleMovedOrResized();
  219298. }
  219299. }
  219300. }
  219301. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219302. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219303. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219304. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219305. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219306. {
  219307. return relativePosition + getScreenPosition();
  219308. }
  219309. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219310. {
  219311. return screenPosition - getScreenPosition();
  219312. }
  219313. void setAlpha (float newAlpha)
  219314. {
  219315. //xxx todo!
  219316. }
  219317. void setMinimised (bool shouldBeMinimised)
  219318. {
  219319. if (shouldBeMinimised)
  219320. {
  219321. Window root = RootWindow (display, DefaultScreen (display));
  219322. XClientMessageEvent clientMsg;
  219323. clientMsg.display = display;
  219324. clientMsg.window = windowH;
  219325. clientMsg.type = ClientMessage;
  219326. clientMsg.format = 32;
  219327. clientMsg.message_type = Atoms::ChangeState;
  219328. clientMsg.data.l[0] = IconicState;
  219329. ScopedXLock xlock;
  219330. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219331. }
  219332. else
  219333. {
  219334. setVisible (true);
  219335. }
  219336. }
  219337. bool isMinimised() const
  219338. {
  219339. bool minimised = false;
  219340. unsigned char* stateProp;
  219341. unsigned long nitems, bytesLeft;
  219342. Atom actualType;
  219343. int actualFormat;
  219344. ScopedXLock xlock;
  219345. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219346. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219347. &stateProp) == Success
  219348. && actualType == Atoms::State
  219349. && actualFormat == 32
  219350. && nitems > 0)
  219351. {
  219352. if (((unsigned long*) stateProp)[0] == IconicState)
  219353. minimised = true;
  219354. XFree (stateProp);
  219355. }
  219356. return minimised;
  219357. }
  219358. void setFullScreen (const bool shouldBeFullScreen)
  219359. {
  219360. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219361. setMinimised (false);
  219362. if (fullScreen != shouldBeFullScreen)
  219363. {
  219364. if (shouldBeFullScreen)
  219365. r = Desktop::getInstance().getMainMonitorArea();
  219366. if (! r.isEmpty())
  219367. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219368. getComponent()->repaint();
  219369. }
  219370. }
  219371. bool isFullScreen() const
  219372. {
  219373. return fullScreen;
  219374. }
  219375. bool isChildWindowOf (Window possibleParent) const
  219376. {
  219377. Window* windowList = 0;
  219378. uint32 windowListSize = 0;
  219379. Window parent, root;
  219380. ScopedXLock xlock;
  219381. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219382. {
  219383. if (windowList != 0)
  219384. XFree (windowList);
  219385. return parent == possibleParent;
  219386. }
  219387. return false;
  219388. }
  219389. bool isFrontWindow() const
  219390. {
  219391. Window* windowList = 0;
  219392. uint32 windowListSize = 0;
  219393. bool result = false;
  219394. ScopedXLock xlock;
  219395. Window parent, root = RootWindow (display, DefaultScreen (display));
  219396. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219397. {
  219398. for (int i = windowListSize; --i >= 0;)
  219399. {
  219400. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219401. if (peer != 0)
  219402. {
  219403. result = (peer == this);
  219404. break;
  219405. }
  219406. }
  219407. }
  219408. if (windowList != 0)
  219409. XFree (windowList);
  219410. return result;
  219411. }
  219412. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219413. {
  219414. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219415. return false;
  219416. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219417. {
  219418. Component* const c = Desktop::getInstance().getComponent (i);
  219419. if (c == getComponent())
  219420. break;
  219421. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219422. return false;
  219423. }
  219424. if (trueIfInAChildWindow)
  219425. return true;
  219426. ::Window root, child;
  219427. unsigned int bw, depth;
  219428. int wx, wy, w, h;
  219429. ScopedXLock xlock;
  219430. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219431. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219432. &bw, &depth))
  219433. {
  219434. return false;
  219435. }
  219436. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219437. return false;
  219438. return child == None;
  219439. }
  219440. const BorderSize<int> getFrameSize() const
  219441. {
  219442. return BorderSize<int>();
  219443. }
  219444. bool setAlwaysOnTop (bool alwaysOnTop)
  219445. {
  219446. return false;
  219447. }
  219448. void toFront (bool makeActive)
  219449. {
  219450. if (makeActive)
  219451. {
  219452. setVisible (true);
  219453. grabFocus();
  219454. }
  219455. XEvent ev;
  219456. ev.xclient.type = ClientMessage;
  219457. ev.xclient.serial = 0;
  219458. ev.xclient.send_event = True;
  219459. ev.xclient.message_type = Atoms::ActiveWin;
  219460. ev.xclient.window = windowH;
  219461. ev.xclient.format = 32;
  219462. ev.xclient.data.l[0] = 2;
  219463. ev.xclient.data.l[1] = CurrentTime;
  219464. ev.xclient.data.l[2] = 0;
  219465. ev.xclient.data.l[3] = 0;
  219466. ev.xclient.data.l[4] = 0;
  219467. {
  219468. ScopedXLock xlock;
  219469. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219470. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219471. XWindowAttributes attr;
  219472. XGetWindowAttributes (display, windowH, &attr);
  219473. if (component->isAlwaysOnTop())
  219474. XRaiseWindow (display, windowH);
  219475. XSync (display, False);
  219476. }
  219477. handleBroughtToFront();
  219478. }
  219479. void toBehind (ComponentPeer* other)
  219480. {
  219481. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219482. jassert (otherPeer != 0); // wrong type of window?
  219483. if (otherPeer != 0)
  219484. {
  219485. setMinimised (false);
  219486. Window newStack[] = { otherPeer->windowH, windowH };
  219487. ScopedXLock xlock;
  219488. XRestackWindows (display, newStack, 2);
  219489. }
  219490. }
  219491. bool isFocused() const
  219492. {
  219493. int revert = 0;
  219494. Window focusedWindow = 0;
  219495. ScopedXLock xlock;
  219496. XGetInputFocus (display, &focusedWindow, &revert);
  219497. return focusedWindow == windowH;
  219498. }
  219499. void grabFocus()
  219500. {
  219501. XWindowAttributes atts;
  219502. ScopedXLock xlock;
  219503. if (windowH != 0
  219504. && XGetWindowAttributes (display, windowH, &atts)
  219505. && atts.map_state == IsViewable
  219506. && ! isFocused())
  219507. {
  219508. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219509. isActiveApplication = true;
  219510. }
  219511. }
  219512. void textInputRequired (const Point<int>&)
  219513. {
  219514. }
  219515. void repaint (const Rectangle<int>& area)
  219516. {
  219517. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219518. }
  219519. void performAnyPendingRepaintsNow()
  219520. {
  219521. repainter->performAnyPendingRepaintsNow();
  219522. }
  219523. void setIcon (const Image& newIcon)
  219524. {
  219525. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219526. HeapBlock <unsigned long> data (dataSize);
  219527. int index = 0;
  219528. data[index++] = newIcon.getWidth();
  219529. data[index++] = newIcon.getHeight();
  219530. for (int y = 0; y < newIcon.getHeight(); ++y)
  219531. for (int x = 0; x < newIcon.getWidth(); ++x)
  219532. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219533. ScopedXLock xlock;
  219534. XChangeProperty (display, windowH,
  219535. XInternAtom (display, "_NET_WM_ICON", False),
  219536. XA_CARDINAL, 32, PropModeReplace,
  219537. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219538. deleteIconPixmaps();
  219539. XWMHints* wmHints = XGetWMHints (display, windowH);
  219540. if (wmHints == 0)
  219541. wmHints = XAllocWMHints();
  219542. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219543. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  219544. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  219545. XSetWMHints (display, windowH, wmHints);
  219546. XFree (wmHints);
  219547. XSync (display, False);
  219548. }
  219549. void deleteIconPixmaps()
  219550. {
  219551. ScopedXLock xlock;
  219552. XWMHints* wmHints = XGetWMHints (display, windowH);
  219553. if (wmHints != 0)
  219554. {
  219555. if ((wmHints->flags & IconPixmapHint) != 0)
  219556. {
  219557. wmHints->flags &= ~IconPixmapHint;
  219558. XFreePixmap (display, wmHints->icon_pixmap);
  219559. }
  219560. if ((wmHints->flags & IconMaskHint) != 0)
  219561. {
  219562. wmHints->flags &= ~IconMaskHint;
  219563. XFreePixmap (display, wmHints->icon_mask);
  219564. }
  219565. XSetWMHints (display, windowH, wmHints);
  219566. XFree (wmHints);
  219567. }
  219568. }
  219569. void handleWindowMessage (XEvent* event)
  219570. {
  219571. switch (event->xany.type)
  219572. {
  219573. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  219574. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  219575. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  219576. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  219577. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  219578. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  219579. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  219580. case FocusIn: handleFocusInEvent(); break;
  219581. case FocusOut: handleFocusOutEvent(); break;
  219582. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  219583. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  219584. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  219585. case SelectionNotify: handleDragAndDropSelection (event); break;
  219586. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  219587. case ReparentNotify: handleReparentNotifyEvent(); break;
  219588. case GravityNotify: handleGravityNotify(); break;
  219589. case CirculateNotify:
  219590. case CreateNotify:
  219591. case DestroyNotify:
  219592. // Think we can ignore these
  219593. break;
  219594. case MapNotify:
  219595. mapped = true;
  219596. handleBroughtToFront();
  219597. break;
  219598. case UnmapNotify:
  219599. mapped = false;
  219600. break;
  219601. case SelectionClear:
  219602. case SelectionRequest:
  219603. break;
  219604. default:
  219605. #if JUCE_USE_XSHM
  219606. {
  219607. ScopedXLock xlock;
  219608. if (event->xany.type == XShmGetEventBase (display))
  219609. repainter->notifyPaintCompleted();
  219610. }
  219611. #endif
  219612. break;
  219613. }
  219614. }
  219615. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  219616. {
  219617. char utf8 [64] = { 0 };
  219618. juce_wchar unicodeChar = 0;
  219619. int keyCode = 0;
  219620. bool keyDownChange = false;
  219621. KeySym sym;
  219622. {
  219623. ScopedXLock xlock;
  219624. updateKeyStates (keyEvent->keycode, true);
  219625. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219626. ::setlocale (LC_ALL, "");
  219627. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219628. ::setlocale (LC_ALL, oldLocale);
  219629. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219630. keyCode = (int) unicodeChar;
  219631. if (keyCode < 0x20)
  219632. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219633. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219634. }
  219635. const ModifierKeys oldMods (currentModifiers);
  219636. bool keyPressed = false;
  219637. if ((sym & 0xff00) == 0xff00)
  219638. {
  219639. switch (sym) // Translate keypad
  219640. {
  219641. case XK_KP_Divide: keyCode = XK_slash; break;
  219642. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  219643. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  219644. case XK_KP_Add: keyCode = XK_plus; break;
  219645. case XK_KP_Enter: keyCode = XK_Return; break;
  219646. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  219647. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  219648. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  219649. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  219650. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  219651. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  219652. case XK_KP_5: keyCode = XK_5; break;
  219653. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  219654. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  219655. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  219656. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  219657. default: break;
  219658. }
  219659. switch (sym)
  219660. {
  219661. case XK_Left:
  219662. case XK_Right:
  219663. case XK_Up:
  219664. case XK_Down:
  219665. case XK_Page_Up:
  219666. case XK_Page_Down:
  219667. case XK_End:
  219668. case XK_Home:
  219669. case XK_Delete:
  219670. case XK_Insert:
  219671. keyPressed = true;
  219672. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219673. break;
  219674. case XK_Tab:
  219675. case XK_Return:
  219676. case XK_Escape:
  219677. case XK_BackSpace:
  219678. keyPressed = true;
  219679. keyCode &= 0xff;
  219680. break;
  219681. default:
  219682. if (sym >= XK_F1 && sym <= XK_F16)
  219683. {
  219684. keyPressed = true;
  219685. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219686. }
  219687. break;
  219688. }
  219689. }
  219690. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219691. keyPressed = true;
  219692. if (oldMods != currentModifiers)
  219693. handleModifierKeysChange();
  219694. if (keyDownChange)
  219695. handleKeyUpOrDown (true);
  219696. if (keyPressed)
  219697. handleKeyPress (keyCode, unicodeChar);
  219698. }
  219699. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  219700. {
  219701. updateKeyStates (keyEvent->keycode, false);
  219702. KeySym sym;
  219703. {
  219704. ScopedXLock xlock;
  219705. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219706. }
  219707. const ModifierKeys oldMods (currentModifiers);
  219708. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219709. if (oldMods != currentModifiers)
  219710. handleModifierKeysChange();
  219711. if (keyDownChange)
  219712. handleKeyUpOrDown (false);
  219713. }
  219714. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  219715. {
  219716. updateKeyModifiers (buttonPressEvent->state);
  219717. bool buttonMsg = false;
  219718. const int map = pointerMap [buttonPressEvent->button - Button1];
  219719. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219720. {
  219721. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219722. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219723. }
  219724. if (map == Keys::LeftButton)
  219725. {
  219726. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219727. buttonMsg = true;
  219728. }
  219729. else if (map == Keys::RightButton)
  219730. {
  219731. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219732. buttonMsg = true;
  219733. }
  219734. else if (map == Keys::MiddleButton)
  219735. {
  219736. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219737. buttonMsg = true;
  219738. }
  219739. if (buttonMsg)
  219740. {
  219741. toFront (true);
  219742. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219743. getEventTime (buttonPressEvent->time));
  219744. }
  219745. clearLastMousePos();
  219746. }
  219747. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  219748. {
  219749. updateKeyModifiers (buttonRelEvent->state);
  219750. const int map = pointerMap [buttonRelEvent->button - Button1];
  219751. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219752. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219753. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219754. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219755. getEventTime (buttonRelEvent->time));
  219756. clearLastMousePos();
  219757. }
  219758. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  219759. {
  219760. updateKeyModifiers (movedEvent->state);
  219761. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  219762. if (lastMousePos != mousePos)
  219763. {
  219764. lastMousePos = mousePos;
  219765. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219766. {
  219767. Window wRoot = 0, wParent = 0;
  219768. {
  219769. ScopedXLock xlock;
  219770. unsigned int numChildren;
  219771. Window* wChild = 0;
  219772. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219773. }
  219774. if (wParent != 0
  219775. && wParent != windowH
  219776. && wParent != wRoot)
  219777. {
  219778. parentWindow = wParent;
  219779. updateBounds();
  219780. }
  219781. else
  219782. {
  219783. parentWindow = 0;
  219784. }
  219785. }
  219786. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219787. }
  219788. }
  219789. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  219790. {
  219791. clearLastMousePos();
  219792. if (! currentModifiers.isAnyMouseButtonDown())
  219793. {
  219794. updateKeyModifiers (enterEvent->state);
  219795. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219796. }
  219797. }
  219798. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  219799. {
  219800. // Suppress the normal leave if we've got a pointer grab, or if
  219801. // it's a bogus one caused by clicking a mouse button when running
  219802. // in a Window manager
  219803. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219804. || leaveEvent->mode == NotifyUngrab)
  219805. {
  219806. updateKeyModifiers (leaveEvent->state);
  219807. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219808. }
  219809. }
  219810. void handleFocusInEvent()
  219811. {
  219812. isActiveApplication = true;
  219813. if (isFocused())
  219814. handleFocusGain();
  219815. }
  219816. void handleFocusOutEvent()
  219817. {
  219818. isActiveApplication = false;
  219819. if (! isFocused())
  219820. handleFocusLoss();
  219821. }
  219822. void handleExposeEvent (XExposeEvent* exposeEvent)
  219823. {
  219824. // Batch together all pending expose events
  219825. XEvent nextEvent;
  219826. ScopedXLock xlock;
  219827. if (exposeEvent->window != windowH)
  219828. {
  219829. Window child;
  219830. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219831. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219832. &child);
  219833. }
  219834. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219835. exposeEvent->width, exposeEvent->height));
  219836. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219837. {
  219838. XPeekEvent (display, (XEvent*) &nextEvent);
  219839. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  219840. break;
  219841. XNextEvent (display, (XEvent*) &nextEvent);
  219842. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219843. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219844. nextExposeEvent->width, nextExposeEvent->height));
  219845. }
  219846. }
  219847. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  219848. {
  219849. updateBounds();
  219850. updateBorderSize();
  219851. handleMovedOrResized();
  219852. // if the native title bar is dragged, need to tell any active menus, etc.
  219853. if ((styleFlags & windowHasTitleBar) != 0
  219854. && component->isCurrentlyBlockedByAnotherModalComponent())
  219855. {
  219856. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219857. if (currentModalComp != 0)
  219858. currentModalComp->inputAttemptWhenModal();
  219859. }
  219860. if (confEvent->window == windowH
  219861. && confEvent->above != 0
  219862. && isFrontWindow())
  219863. {
  219864. handleBroughtToFront();
  219865. }
  219866. }
  219867. void handleReparentNotifyEvent()
  219868. {
  219869. parentWindow = 0;
  219870. Window wRoot = 0;
  219871. Window* wChild = 0;
  219872. unsigned int numChildren;
  219873. {
  219874. ScopedXLock xlock;
  219875. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219876. }
  219877. if (parentWindow == windowH || parentWindow == wRoot)
  219878. parentWindow = 0;
  219879. handleGravityNotify();
  219880. }
  219881. void handleGravityNotify()
  219882. {
  219883. updateBounds();
  219884. updateBorderSize();
  219885. handleMovedOrResized();
  219886. }
  219887. void handleMappingNotify (XMappingEvent* const mappingEvent)
  219888. {
  219889. if (mappingEvent->request != MappingPointer)
  219890. {
  219891. // Deal with modifier/keyboard mapping
  219892. ScopedXLock xlock;
  219893. XRefreshKeyboardMapping (mappingEvent);
  219894. updateModifierMappings();
  219895. }
  219896. }
  219897. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  219898. {
  219899. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219900. {
  219901. const Atom atom = (Atom) clientMsg->data.l[0];
  219902. if (atom == Atoms::ProtocolList [Atoms::PING])
  219903. {
  219904. Window root = RootWindow (display, DefaultScreen (display));
  219905. clientMsg->window = root;
  219906. XSendEvent (display, root, False, NoEventMask, event);
  219907. XFlush (display);
  219908. }
  219909. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219910. {
  219911. XWindowAttributes atts;
  219912. ScopedXLock xlock;
  219913. if (clientMsg->window != 0
  219914. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219915. {
  219916. if (atts.map_state == IsViewable)
  219917. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219918. }
  219919. }
  219920. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219921. {
  219922. handleUserClosingWindow();
  219923. }
  219924. }
  219925. else if (clientMsg->message_type == Atoms::XdndEnter)
  219926. {
  219927. handleDragAndDropEnter (clientMsg);
  219928. }
  219929. else if (clientMsg->message_type == Atoms::XdndLeave)
  219930. {
  219931. resetDragAndDrop();
  219932. }
  219933. else if (clientMsg->message_type == Atoms::XdndPosition)
  219934. {
  219935. handleDragAndDropPosition (clientMsg);
  219936. }
  219937. else if (clientMsg->message_type == Atoms::XdndDrop)
  219938. {
  219939. handleDragAndDropDrop (clientMsg);
  219940. }
  219941. else if (clientMsg->message_type == Atoms::XdndStatus)
  219942. {
  219943. handleDragAndDropStatus (clientMsg);
  219944. }
  219945. else if (clientMsg->message_type == Atoms::XdndFinished)
  219946. {
  219947. resetDragAndDrop();
  219948. }
  219949. }
  219950. void showMouseCursor (Cursor cursor) throw()
  219951. {
  219952. ScopedXLock xlock;
  219953. XDefineCursor (display, windowH, cursor);
  219954. }
  219955. void setTaskBarIcon (const Image& image)
  219956. {
  219957. ScopedXLock xlock;
  219958. taskbarImage = image;
  219959. Screen* const screen = XDefaultScreenOfDisplay (display);
  219960. const int screenNumber = XScreenNumberOfScreen (screen);
  219961. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219962. screenAtom << screenNumber;
  219963. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219964. XGrabServer (display);
  219965. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219966. if (managerWin != None)
  219967. XSelectInput (display, managerWin, StructureNotifyMask);
  219968. XUngrabServer (display);
  219969. XFlush (display);
  219970. if (managerWin != None)
  219971. {
  219972. XEvent ev;
  219973. zerostruct (ev);
  219974. ev.xclient.type = ClientMessage;
  219975. ev.xclient.window = managerWin;
  219976. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219977. ev.xclient.format = 32;
  219978. ev.xclient.data.l[0] = CurrentTime;
  219979. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219980. ev.xclient.data.l[2] = windowH;
  219981. ev.xclient.data.l[3] = 0;
  219982. ev.xclient.data.l[4] = 0;
  219983. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219984. XSync (display, False);
  219985. }
  219986. // For older KDE's ...
  219987. long atomData = 1;
  219988. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219989. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219990. // For more recent KDE's...
  219991. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219992. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219993. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219994. XSizeHints* hints = XAllocSizeHints();
  219995. hints->flags = PMinSize;
  219996. hints->min_width = 22;
  219997. hints->min_height = 22;
  219998. XSetWMNormalHints (display, windowH, hints);
  219999. XFree (hints);
  220000. }
  220001. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220002. bool dontRepaint;
  220003. static ModifierKeys currentModifiers;
  220004. static bool isActiveApplication;
  220005. private:
  220006. class LinuxRepaintManager : public Timer
  220007. {
  220008. public:
  220009. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220010. : peer (peer_),
  220011. lastTimeImageUsed (0)
  220012. {
  220013. #if JUCE_USE_XSHM
  220014. shmCompletedDrawing = true;
  220015. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220016. if (useARGBImagesForRendering)
  220017. {
  220018. ScopedXLock xlock;
  220019. XShmSegmentInfo segmentinfo;
  220020. XImage* const testImage
  220021. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220022. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220023. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220024. XDestroyImage (testImage);
  220025. }
  220026. #endif
  220027. }
  220028. void timerCallback()
  220029. {
  220030. #if JUCE_USE_XSHM
  220031. if (! shmCompletedDrawing)
  220032. return;
  220033. #endif
  220034. if (! regionsNeedingRepaint.isEmpty())
  220035. {
  220036. stopTimer();
  220037. performAnyPendingRepaintsNow();
  220038. }
  220039. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220040. {
  220041. stopTimer();
  220042. image = Image::null;
  220043. }
  220044. }
  220045. void repaint (const Rectangle<int>& area)
  220046. {
  220047. if (! isTimerRunning())
  220048. startTimer (repaintTimerPeriod);
  220049. regionsNeedingRepaint.add (area);
  220050. }
  220051. void performAnyPendingRepaintsNow()
  220052. {
  220053. #if JUCE_USE_XSHM
  220054. if (! shmCompletedDrawing)
  220055. {
  220056. startTimer (repaintTimerPeriod);
  220057. return;
  220058. }
  220059. #endif
  220060. peer->clearMaskedRegion();
  220061. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220062. regionsNeedingRepaint.clear();
  220063. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220064. if (! totalArea.isEmpty())
  220065. {
  220066. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220067. || image.getHeight() < totalArea.getHeight())
  220068. {
  220069. #if JUCE_USE_XSHM
  220070. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220071. : Image::RGB,
  220072. #else
  220073. image = Image (new XBitmapImage (Image::RGB,
  220074. #endif
  220075. (totalArea.getWidth() + 31) & ~31,
  220076. (totalArea.getHeight() + 31) & ~31,
  220077. false, peer->depth, peer->visual));
  220078. }
  220079. startTimer (repaintTimerPeriod);
  220080. RectangleList adjustedList (originalRepaintRegion);
  220081. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220082. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220083. if (peer->depth == 32)
  220084. {
  220085. RectangleList::Iterator i (originalRepaintRegion);
  220086. while (i.next())
  220087. image.clear (*i.getRectangle() - totalArea.getPosition());
  220088. }
  220089. peer->handlePaint (context);
  220090. if (! peer->maskedRegion.isEmpty())
  220091. originalRepaintRegion.subtract (peer->maskedRegion);
  220092. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220093. {
  220094. #if JUCE_USE_XSHM
  220095. shmCompletedDrawing = false;
  220096. #endif
  220097. const Rectangle<int>& r = *i.getRectangle();
  220098. static_cast<XBitmapImage*> (image.getSharedImage())
  220099. ->blitToWindow (peer->windowH,
  220100. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220101. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220102. }
  220103. }
  220104. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220105. startTimer (repaintTimerPeriod);
  220106. }
  220107. #if JUCE_USE_XSHM
  220108. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220109. #endif
  220110. private:
  220111. enum { repaintTimerPeriod = 1000 / 100 };
  220112. LinuxComponentPeer* const peer;
  220113. Image image;
  220114. uint32 lastTimeImageUsed;
  220115. RectangleList regionsNeedingRepaint;
  220116. #if JUCE_USE_XSHM
  220117. bool useARGBImagesForRendering, shmCompletedDrawing;
  220118. #endif
  220119. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220120. };
  220121. ScopedPointer <LinuxRepaintManager> repainter;
  220122. friend class LinuxRepaintManager;
  220123. Window windowH, parentWindow;
  220124. int wx, wy, ww, wh;
  220125. Image taskbarImage;
  220126. bool fullScreen, mapped;
  220127. Visual* visual;
  220128. int depth;
  220129. BorderSize<int> windowBorder;
  220130. struct MotifWmHints
  220131. {
  220132. unsigned long flags;
  220133. unsigned long functions;
  220134. unsigned long decorations;
  220135. long input_mode;
  220136. unsigned long status;
  220137. };
  220138. static void updateKeyStates (const int keycode, const bool press) throw()
  220139. {
  220140. const int keybyte = keycode >> 3;
  220141. const int keybit = (1 << (keycode & 7));
  220142. if (press)
  220143. Keys::keyStates [keybyte] |= keybit;
  220144. else
  220145. Keys::keyStates [keybyte] &= ~keybit;
  220146. }
  220147. static void updateKeyModifiers (const int status) throw()
  220148. {
  220149. int keyMods = 0;
  220150. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220151. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220152. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220153. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220154. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220155. Keys::capsLock = ((status & LockMask) != 0);
  220156. }
  220157. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220158. {
  220159. int modifier = 0;
  220160. bool isModifier = true;
  220161. switch (sym)
  220162. {
  220163. case XK_Shift_L:
  220164. case XK_Shift_R:
  220165. modifier = ModifierKeys::shiftModifier;
  220166. break;
  220167. case XK_Control_L:
  220168. case XK_Control_R:
  220169. modifier = ModifierKeys::ctrlModifier;
  220170. break;
  220171. case XK_Alt_L:
  220172. case XK_Alt_R:
  220173. modifier = ModifierKeys::altModifier;
  220174. break;
  220175. case XK_Num_Lock:
  220176. if (press)
  220177. Keys::numLock = ! Keys::numLock;
  220178. break;
  220179. case XK_Caps_Lock:
  220180. if (press)
  220181. Keys::capsLock = ! Keys::capsLock;
  220182. break;
  220183. case XK_Scroll_Lock:
  220184. break;
  220185. default:
  220186. isModifier = false;
  220187. break;
  220188. }
  220189. if (modifier != 0)
  220190. {
  220191. if (press)
  220192. currentModifiers = currentModifiers.withFlags (modifier);
  220193. else
  220194. currentModifiers = currentModifiers.withoutFlags (modifier);
  220195. }
  220196. return isModifier;
  220197. }
  220198. // Alt and Num lock are not defined by standard X
  220199. // modifier constants: check what they're mapped to
  220200. static void updateModifierMappings() throw()
  220201. {
  220202. ScopedXLock xlock;
  220203. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220204. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220205. Keys::AltMask = 0;
  220206. Keys::NumLockMask = 0;
  220207. XModifierKeymap* mapping = XGetModifierMapping (display);
  220208. if (mapping)
  220209. {
  220210. for (int i = 0; i < 8; i++)
  220211. {
  220212. if (mapping->modifiermap [i << 1] == altLeftCode)
  220213. Keys::AltMask = 1 << i;
  220214. else if (mapping->modifiermap [i << 1] == numLockCode)
  220215. Keys::NumLockMask = 1 << i;
  220216. }
  220217. XFreeModifiermap (mapping);
  220218. }
  220219. }
  220220. void removeWindowDecorations (Window wndH)
  220221. {
  220222. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220223. if (hints != None)
  220224. {
  220225. MotifWmHints motifHints;
  220226. zerostruct (motifHints);
  220227. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220228. motifHints.decorations = 0;
  220229. ScopedXLock xlock;
  220230. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220231. (unsigned char*) &motifHints, 4);
  220232. }
  220233. hints = XInternAtom (display, "_WIN_HINTS", True);
  220234. if (hints != None)
  220235. {
  220236. long gnomeHints = 0;
  220237. ScopedXLock xlock;
  220238. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220239. (unsigned char*) &gnomeHints, 1);
  220240. }
  220241. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220242. if (hints != None)
  220243. {
  220244. long kwmHints = 2; /*KDE_tinyDecoration*/
  220245. ScopedXLock xlock;
  220246. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220247. (unsigned char*) &kwmHints, 1);
  220248. }
  220249. }
  220250. void addWindowButtons (Window wndH)
  220251. {
  220252. ScopedXLock xlock;
  220253. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220254. if (hints != None)
  220255. {
  220256. MotifWmHints motifHints;
  220257. zerostruct (motifHints);
  220258. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220259. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220260. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220261. if ((styleFlags & windowHasCloseButton) != 0)
  220262. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220263. if ((styleFlags & windowHasMinimiseButton) != 0)
  220264. {
  220265. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220266. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220267. }
  220268. if ((styleFlags & windowHasMaximiseButton) != 0)
  220269. {
  220270. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220271. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220272. }
  220273. if ((styleFlags & windowIsResizable) != 0)
  220274. {
  220275. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220276. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220277. }
  220278. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220279. }
  220280. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220281. if (hints != None)
  220282. {
  220283. int netHints [6];
  220284. int num = 0;
  220285. if ((styleFlags & windowIsResizable) != 0)
  220286. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220287. if ((styleFlags & windowHasMaximiseButton) != 0)
  220288. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220289. if ((styleFlags & windowHasMinimiseButton) != 0)
  220290. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220291. if ((styleFlags & windowHasCloseButton) != 0)
  220292. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220293. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220294. }
  220295. }
  220296. void setWindowType()
  220297. {
  220298. int netHints [2];
  220299. int numHints = 0;
  220300. if ((styleFlags & windowIsTemporary) != 0
  220301. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220302. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220303. else
  220304. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220305. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220306. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220307. (unsigned char*) &netHints, numHints);
  220308. numHints = 0;
  220309. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220310. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220311. if (component->isAlwaysOnTop())
  220312. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220313. if (numHints > 0)
  220314. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220315. (unsigned char*) &netHints, numHints);
  220316. }
  220317. void createWindow()
  220318. {
  220319. ScopedXLock xlock;
  220320. Atoms::initialiseAtoms();
  220321. resetDragAndDrop();
  220322. // Get defaults for various properties
  220323. const int screen = DefaultScreen (display);
  220324. Window root = RootWindow (display, screen);
  220325. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220326. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220327. if (visual == 0)
  220328. {
  220329. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220330. Process::terminate();
  220331. }
  220332. // Create and install a colormap suitable fr our visual
  220333. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220334. XInstallColormap (display, colormap);
  220335. // Set up the window attributes
  220336. XSetWindowAttributes swa;
  220337. swa.border_pixel = 0;
  220338. swa.background_pixmap = None;
  220339. swa.colormap = colormap;
  220340. swa.event_mask = getAllEventsMask();
  220341. windowH = XCreateWindow (display, root,
  220342. 0, 0, 1, 1,
  220343. 0, depth, InputOutput, visual,
  220344. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220345. &swa);
  220346. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220347. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220348. GrabModeAsync, GrabModeAsync, None, None);
  220349. // Set the window context to identify the window handle object
  220350. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220351. {
  220352. // Failed
  220353. jassertfalse;
  220354. Logger::outputDebugString ("Failed to create context information for window.\n");
  220355. XDestroyWindow (display, windowH);
  220356. windowH = 0;
  220357. return;
  220358. }
  220359. // Set window manager hints
  220360. XWMHints* wmHints = XAllocWMHints();
  220361. wmHints->flags = InputHint | StateHint;
  220362. wmHints->input = True; // Locally active input model
  220363. wmHints->initial_state = NormalState;
  220364. XSetWMHints (display, windowH, wmHints);
  220365. XFree (wmHints);
  220366. // Set the window type
  220367. setWindowType();
  220368. // Define decoration
  220369. if ((styleFlags & windowHasTitleBar) == 0)
  220370. removeWindowDecorations (windowH);
  220371. else
  220372. addWindowButtons (windowH);
  220373. setTitle (getComponent()->getName());
  220374. // Associate the PID, allowing to be shut down when something goes wrong
  220375. unsigned long pid = getpid();
  220376. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220377. (unsigned char*) &pid, 1);
  220378. // Set window manager protocols
  220379. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220380. (unsigned char*) Atoms::ProtocolList, 2);
  220381. // Set drag and drop flags
  220382. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220383. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220384. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220385. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220386. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220387. (const unsigned char*) "", 0);
  220388. unsigned long dndVersion = Atoms::DndVersion;
  220389. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220390. (const unsigned char*) &dndVersion, 1);
  220391. // Initialise the pointer and keyboard mapping
  220392. // This is not the same as the logical pointer mapping the X server uses:
  220393. // we don't mess with this.
  220394. static bool mappingInitialised = false;
  220395. if (! mappingInitialised)
  220396. {
  220397. mappingInitialised = true;
  220398. const int numButtons = XGetPointerMapping (display, 0, 0);
  220399. if (numButtons == 2)
  220400. {
  220401. pointerMap[0] = Keys::LeftButton;
  220402. pointerMap[1] = Keys::RightButton;
  220403. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220404. }
  220405. else if (numButtons >= 3)
  220406. {
  220407. pointerMap[0] = Keys::LeftButton;
  220408. pointerMap[1] = Keys::MiddleButton;
  220409. pointerMap[2] = Keys::RightButton;
  220410. if (numButtons >= 5)
  220411. {
  220412. pointerMap[3] = Keys::WheelUp;
  220413. pointerMap[4] = Keys::WheelDown;
  220414. }
  220415. }
  220416. updateModifierMappings();
  220417. }
  220418. }
  220419. void destroyWindow()
  220420. {
  220421. ScopedXLock xlock;
  220422. XPointer handlePointer;
  220423. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220424. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220425. XDestroyWindow (display, windowH);
  220426. // Wait for it to complete and then remove any events for this
  220427. // window from the event queue.
  220428. XSync (display, false);
  220429. XEvent event;
  220430. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220431. {}
  220432. }
  220433. static int getAllEventsMask() throw()
  220434. {
  220435. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220436. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220437. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220438. }
  220439. static int64 getEventTime (::Time t)
  220440. {
  220441. static int64 eventTimeOffset = 0x12345678;
  220442. const int64 thisMessageTime = t;
  220443. if (eventTimeOffset == 0x12345678)
  220444. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220445. return eventTimeOffset + thisMessageTime;
  220446. }
  220447. void updateBorderSize()
  220448. {
  220449. if ((styleFlags & windowHasTitleBar) == 0)
  220450. {
  220451. windowBorder = BorderSize<int> (0);
  220452. }
  220453. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220454. {
  220455. ScopedXLock xlock;
  220456. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220457. if (hints != None)
  220458. {
  220459. unsigned char* data = 0;
  220460. unsigned long nitems, bytesLeft;
  220461. Atom actualType;
  220462. int actualFormat;
  220463. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220464. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220465. &data) == Success)
  220466. {
  220467. const unsigned long* const sizes = (const unsigned long*) data;
  220468. if (actualFormat == 32)
  220469. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  220470. (int) sizes[3], (int) sizes[1]);
  220471. XFree (data);
  220472. }
  220473. }
  220474. }
  220475. }
  220476. void updateBounds()
  220477. {
  220478. jassert (windowH != 0);
  220479. if (windowH != 0)
  220480. {
  220481. Window root, child;
  220482. unsigned int bw, depth;
  220483. ScopedXLock xlock;
  220484. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220485. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220486. &bw, &depth))
  220487. {
  220488. wx = wy = ww = wh = 0;
  220489. }
  220490. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220491. {
  220492. wx = wy = 0;
  220493. }
  220494. }
  220495. }
  220496. void resetDragAndDrop()
  220497. {
  220498. dragAndDropFiles.clear();
  220499. lastDropPos = Point<int> (-1, -1);
  220500. dragAndDropCurrentMimeType = 0;
  220501. dragAndDropSourceWindow = 0;
  220502. srcMimeTypeAtomList.clear();
  220503. }
  220504. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220505. {
  220506. msg.type = ClientMessage;
  220507. msg.display = display;
  220508. msg.window = dragAndDropSourceWindow;
  220509. msg.format = 32;
  220510. msg.data.l[0] = windowH;
  220511. ScopedXLock xlock;
  220512. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220513. }
  220514. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220515. {
  220516. XClientMessageEvent msg;
  220517. zerostruct (msg);
  220518. msg.message_type = Atoms::XdndStatus;
  220519. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220520. msg.data.l[4] = dropAction;
  220521. sendDragAndDropMessage (msg);
  220522. }
  220523. void sendDragAndDropLeave()
  220524. {
  220525. XClientMessageEvent msg;
  220526. zerostruct (msg);
  220527. msg.message_type = Atoms::XdndLeave;
  220528. sendDragAndDropMessage (msg);
  220529. }
  220530. void sendDragAndDropFinish()
  220531. {
  220532. XClientMessageEvent msg;
  220533. zerostruct (msg);
  220534. msg.message_type = Atoms::XdndFinished;
  220535. sendDragAndDropMessage (msg);
  220536. }
  220537. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220538. {
  220539. if ((clientMsg->data.l[1] & 1) == 0)
  220540. {
  220541. sendDragAndDropLeave();
  220542. if (dragAndDropFiles.size() > 0)
  220543. handleFileDragExit (dragAndDropFiles);
  220544. dragAndDropFiles.clear();
  220545. }
  220546. }
  220547. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220548. {
  220549. if (dragAndDropSourceWindow == 0)
  220550. return;
  220551. dragAndDropSourceWindow = clientMsg->data.l[0];
  220552. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220553. (int) clientMsg->data.l[2] & 0xffff);
  220554. dropPos -= getScreenPosition();
  220555. if (lastDropPos != dropPos)
  220556. {
  220557. lastDropPos = dropPos;
  220558. dragAndDropTimestamp = clientMsg->data.l[3];
  220559. Atom targetAction = Atoms::XdndActionCopy;
  220560. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220561. {
  220562. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220563. {
  220564. targetAction = Atoms::allowedActions[i];
  220565. break;
  220566. }
  220567. }
  220568. sendDragAndDropStatus (true, targetAction);
  220569. if (dragAndDropFiles.size() == 0)
  220570. updateDraggedFileList (clientMsg);
  220571. if (dragAndDropFiles.size() > 0)
  220572. handleFileDragMove (dragAndDropFiles, dropPos);
  220573. }
  220574. }
  220575. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220576. {
  220577. if (dragAndDropFiles.size() == 0)
  220578. updateDraggedFileList (clientMsg);
  220579. const StringArray files (dragAndDropFiles);
  220580. const Point<int> lastPos (lastDropPos);
  220581. sendDragAndDropFinish();
  220582. resetDragAndDrop();
  220583. if (files.size() > 0)
  220584. handleFileDragDrop (files, lastPos);
  220585. }
  220586. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220587. {
  220588. dragAndDropFiles.clear();
  220589. srcMimeTypeAtomList.clear();
  220590. dragAndDropCurrentMimeType = 0;
  220591. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220592. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220593. {
  220594. dragAndDropSourceWindow = 0;
  220595. return;
  220596. }
  220597. dragAndDropSourceWindow = clientMsg->data.l[0];
  220598. if ((clientMsg->data.l[1] & 1) != 0)
  220599. {
  220600. Atom actual;
  220601. int format;
  220602. unsigned long count = 0, remaining = 0;
  220603. unsigned char* data = 0;
  220604. ScopedXLock xlock;
  220605. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220606. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220607. &count, &remaining, &data);
  220608. if (data != 0)
  220609. {
  220610. if (actual == XA_ATOM && format == 32 && count != 0)
  220611. {
  220612. const unsigned long* const types = (const unsigned long*) data;
  220613. for (unsigned int i = 0; i < count; ++i)
  220614. if (types[i] != None)
  220615. srcMimeTypeAtomList.add (types[i]);
  220616. }
  220617. XFree (data);
  220618. }
  220619. }
  220620. if (srcMimeTypeAtomList.size() == 0)
  220621. {
  220622. for (int i = 2; i < 5; ++i)
  220623. if (clientMsg->data.l[i] != None)
  220624. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220625. if (srcMimeTypeAtomList.size() == 0)
  220626. {
  220627. dragAndDropSourceWindow = 0;
  220628. return;
  220629. }
  220630. }
  220631. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220632. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220633. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220634. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220635. handleDragAndDropPosition (clientMsg);
  220636. }
  220637. void handleDragAndDropSelection (const XEvent* const evt)
  220638. {
  220639. dragAndDropFiles.clear();
  220640. if (evt->xselection.property != 0)
  220641. {
  220642. StringArray lines;
  220643. {
  220644. MemoryBlock dropData;
  220645. for (;;)
  220646. {
  220647. Atom actual;
  220648. uint8* data = 0;
  220649. unsigned long count = 0, remaining = 0;
  220650. int format = 0;
  220651. ScopedXLock xlock;
  220652. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220653. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220654. &format, &count, &remaining, &data) == Success)
  220655. {
  220656. dropData.append (data, count * format / 8);
  220657. XFree (data);
  220658. if (remaining == 0)
  220659. break;
  220660. }
  220661. else
  220662. {
  220663. XFree (data);
  220664. break;
  220665. }
  220666. }
  220667. lines.addLines (dropData.toString());
  220668. }
  220669. for (int i = 0; i < lines.size(); ++i)
  220670. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220671. dragAndDropFiles.trim();
  220672. dragAndDropFiles.removeEmptyStrings();
  220673. }
  220674. }
  220675. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220676. {
  220677. dragAndDropFiles.clear();
  220678. if (dragAndDropSourceWindow != None
  220679. && dragAndDropCurrentMimeType != 0)
  220680. {
  220681. dragAndDropTimestamp = clientMsg->data.l[2];
  220682. ScopedXLock xlock;
  220683. XConvertSelection (display,
  220684. Atoms::XdndSelection,
  220685. dragAndDropCurrentMimeType,
  220686. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220687. windowH,
  220688. dragAndDropTimestamp);
  220689. }
  220690. }
  220691. StringArray dragAndDropFiles;
  220692. int dragAndDropTimestamp;
  220693. Point<int> lastDropPos;
  220694. Atom dragAndDropCurrentMimeType;
  220695. Window dragAndDropSourceWindow;
  220696. Array <Atom> srcMimeTypeAtomList;
  220697. static int pointerMap[5];
  220698. static Point<int> lastMousePos;
  220699. static void clearLastMousePos() throw()
  220700. {
  220701. lastMousePos = Point<int> (0x100000, 0x100000);
  220702. }
  220703. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  220704. };
  220705. ModifierKeys LinuxComponentPeer::currentModifiers;
  220706. bool LinuxComponentPeer::isActiveApplication = false;
  220707. int LinuxComponentPeer::pointerMap[5];
  220708. Point<int> LinuxComponentPeer::lastMousePos;
  220709. bool Process::isForegroundProcess()
  220710. {
  220711. return LinuxComponentPeer::isActiveApplication;
  220712. }
  220713. void ModifierKeys::updateCurrentModifiers() throw()
  220714. {
  220715. currentModifiers = LinuxComponentPeer::currentModifiers;
  220716. }
  220717. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220718. {
  220719. Window root, child;
  220720. int x, y, winx, winy;
  220721. unsigned int mask;
  220722. int mouseMods = 0;
  220723. ScopedXLock xlock;
  220724. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220725. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220726. {
  220727. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220728. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220729. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220730. }
  220731. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220732. return LinuxComponentPeer::currentModifiers;
  220733. }
  220734. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220735. {
  220736. if (enableOrDisable)
  220737. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220738. }
  220739. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220740. {
  220741. return new LinuxComponentPeer (this, styleFlags);
  220742. }
  220743. // (this callback is hooked up in the messaging code)
  220744. void juce_windowMessageReceive (XEvent* event)
  220745. {
  220746. if (event->xany.window != None)
  220747. {
  220748. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220749. if (ComponentPeer::isValidPeer (peer))
  220750. peer->handleWindowMessage (event);
  220751. }
  220752. else
  220753. {
  220754. switch (event->xany.type)
  220755. {
  220756. case KeymapNotify:
  220757. {
  220758. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220759. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220760. break;
  220761. }
  220762. default:
  220763. break;
  220764. }
  220765. }
  220766. }
  220767. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220768. {
  220769. if (display == 0)
  220770. return;
  220771. #if JUCE_USE_XINERAMA
  220772. int major_opcode, first_event, first_error;
  220773. ScopedXLock xlock;
  220774. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220775. {
  220776. typedef Bool (*tXineramaIsActive) (Display*);
  220777. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220778. static tXineramaIsActive xXineramaIsActive = 0;
  220779. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220780. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220781. {
  220782. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220783. if (h == 0)
  220784. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220785. if (h != 0)
  220786. {
  220787. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220788. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220789. }
  220790. }
  220791. if (xXineramaIsActive != 0
  220792. && xXineramaQueryScreens != 0
  220793. && xXineramaIsActive (display))
  220794. {
  220795. int numMonitors = 0;
  220796. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220797. if (screens != 0)
  220798. {
  220799. for (int i = numMonitors; --i >= 0;)
  220800. {
  220801. int index = screens[i].screen_number;
  220802. if (index >= 0)
  220803. {
  220804. while (monitorCoords.size() < index)
  220805. monitorCoords.add (Rectangle<int>());
  220806. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220807. screens[i].y_org,
  220808. screens[i].width,
  220809. screens[i].height));
  220810. }
  220811. }
  220812. XFree (screens);
  220813. }
  220814. }
  220815. }
  220816. if (monitorCoords.size() == 0)
  220817. #endif
  220818. {
  220819. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220820. if (hints != None)
  220821. {
  220822. const int numMonitors = ScreenCount (display);
  220823. for (int i = 0; i < numMonitors; ++i)
  220824. {
  220825. Window root = RootWindow (display, i);
  220826. unsigned long nitems, bytesLeft;
  220827. Atom actualType;
  220828. int actualFormat;
  220829. unsigned char* data = 0;
  220830. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220831. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220832. &data) == Success)
  220833. {
  220834. const long* const position = (const long*) data;
  220835. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220836. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220837. position[2], position[3]));
  220838. XFree (data);
  220839. }
  220840. }
  220841. }
  220842. if (monitorCoords.size() == 0)
  220843. {
  220844. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220845. DisplayHeight (display, DefaultScreen (display))));
  220846. }
  220847. }
  220848. }
  220849. void Desktop::createMouseInputSources()
  220850. {
  220851. mouseSources.add (new MouseInputSource (0, true));
  220852. }
  220853. bool Desktop::canUseSemiTransparentWindows() throw()
  220854. {
  220855. int matchedDepth = 0;
  220856. const int desiredDepth = 32;
  220857. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220858. && (matchedDepth == desiredDepth);
  220859. }
  220860. const Point<int> MouseInputSource::getCurrentMousePosition()
  220861. {
  220862. Window root, child;
  220863. int x, y, winx, winy;
  220864. unsigned int mask;
  220865. ScopedXLock xlock;
  220866. if (XQueryPointer (display,
  220867. RootWindow (display, DefaultScreen (display)),
  220868. &root, &child,
  220869. &x, &y, &winx, &winy, &mask) == False)
  220870. {
  220871. // Pointer not on the default screen
  220872. x = y = -1;
  220873. }
  220874. return Point<int> (x, y);
  220875. }
  220876. void Desktop::setMousePosition (const Point<int>& newPosition)
  220877. {
  220878. ScopedXLock xlock;
  220879. Window root = RootWindow (display, DefaultScreen (display));
  220880. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220881. }
  220882. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  220883. {
  220884. return upright;
  220885. }
  220886. static bool screenSaverAllowed = true;
  220887. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220888. {
  220889. if (screenSaverAllowed != isEnabled)
  220890. {
  220891. screenSaverAllowed = isEnabled;
  220892. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220893. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220894. if (xScreenSaverSuspend == 0)
  220895. {
  220896. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220897. if (h != 0)
  220898. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220899. }
  220900. ScopedXLock xlock;
  220901. if (xScreenSaverSuspend != 0)
  220902. xScreenSaverSuspend (display, ! isEnabled);
  220903. }
  220904. }
  220905. bool Desktop::isScreenSaverEnabled()
  220906. {
  220907. return screenSaverAllowed;
  220908. }
  220909. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220910. {
  220911. ScopedXLock xlock;
  220912. const unsigned int imageW = image.getWidth();
  220913. const unsigned int imageH = image.getHeight();
  220914. #if JUCE_USE_XCURSOR
  220915. {
  220916. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220917. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220918. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220919. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220920. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220921. static tXcursorImageCreate xXcursorImageCreate = 0;
  220922. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220923. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220924. static bool hasBeenLoaded = false;
  220925. if (! hasBeenLoaded)
  220926. {
  220927. hasBeenLoaded = true;
  220928. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220929. if (h != 0)
  220930. {
  220931. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220932. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220933. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220934. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220935. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220936. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220937. || ! xXcursorSupportsARGB (display))
  220938. xXcursorSupportsARGB = 0;
  220939. }
  220940. }
  220941. if (xXcursorSupportsARGB != 0)
  220942. {
  220943. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220944. if (xcImage != 0)
  220945. {
  220946. xcImage->xhot = hotspotX;
  220947. xcImage->yhot = hotspotY;
  220948. XcursorPixel* dest = xcImage->pixels;
  220949. for (int y = 0; y < (int) imageH; ++y)
  220950. for (int x = 0; x < (int) imageW; ++x)
  220951. *dest++ = image.getPixelAt (x, y).getARGB();
  220952. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220953. xXcursorImageDestroy (xcImage);
  220954. if (result != 0)
  220955. return result;
  220956. }
  220957. }
  220958. }
  220959. #endif
  220960. Window root = RootWindow (display, DefaultScreen (display));
  220961. unsigned int cursorW, cursorH;
  220962. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220963. return 0;
  220964. Image im (Image::ARGB, cursorW, cursorH, true);
  220965. {
  220966. Graphics g (im);
  220967. if (imageW > cursorW || imageH > cursorH)
  220968. {
  220969. hotspotX = (hotspotX * cursorW) / imageW;
  220970. hotspotY = (hotspotY * cursorH) / imageH;
  220971. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220972. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220973. false);
  220974. }
  220975. else
  220976. {
  220977. g.drawImageAt (image, 0, 0);
  220978. }
  220979. }
  220980. const int stride = (cursorW + 7) >> 3;
  220981. HeapBlock <char> maskPlane, sourcePlane;
  220982. maskPlane.calloc (stride * cursorH);
  220983. sourcePlane.calloc (stride * cursorH);
  220984. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220985. for (int y = cursorH; --y >= 0;)
  220986. {
  220987. for (int x = cursorW; --x >= 0;)
  220988. {
  220989. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220990. const int offset = y * stride + (x >> 3);
  220991. const Colour c (im.getPixelAt (x, y));
  220992. if (c.getAlpha() >= 128)
  220993. maskPlane[offset] |= mask;
  220994. if (c.getBrightness() >= 0.5f)
  220995. sourcePlane[offset] |= mask;
  220996. }
  220997. }
  220998. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220999. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221000. XColor white, black;
  221001. black.red = black.green = black.blue = 0;
  221002. white.red = white.green = white.blue = 0xffff;
  221003. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221004. XFreePixmap (display, sourcePixmap);
  221005. XFreePixmap (display, maskPixmap);
  221006. return result;
  221007. }
  221008. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221009. {
  221010. ScopedXLock xlock;
  221011. if (cursorHandle != 0)
  221012. XFreeCursor (display, (Cursor) cursorHandle);
  221013. }
  221014. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221015. {
  221016. unsigned int shape;
  221017. switch (type)
  221018. {
  221019. case NormalCursor: return None; // Use parent cursor
  221020. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221021. case WaitCursor: shape = XC_watch; break;
  221022. case IBeamCursor: shape = XC_xterm; break;
  221023. case PointingHandCursor: shape = XC_hand2; break;
  221024. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221025. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221026. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221027. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221028. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221029. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221030. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221031. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221032. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221033. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221034. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221035. case CrosshairCursor: shape = XC_crosshair; break;
  221036. case DraggingHandCursor:
  221037. {
  221038. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221039. 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,
  221040. 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 };
  221041. const int dragHandDataSize = 99;
  221042. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221043. }
  221044. case CopyingCursor:
  221045. {
  221046. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221047. 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,
  221048. 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,
  221049. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221050. const int copyCursorSize = 119;
  221051. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221052. }
  221053. default:
  221054. jassertfalse;
  221055. return None;
  221056. }
  221057. ScopedXLock xlock;
  221058. return (void*) XCreateFontCursor (display, shape);
  221059. }
  221060. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221061. {
  221062. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221063. if (lp != 0)
  221064. lp->showMouseCursor ((Cursor) getHandle());
  221065. }
  221066. void MouseCursor::showInAllWindows() const
  221067. {
  221068. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221069. showInWindow (ComponentPeer::getPeer (i));
  221070. }
  221071. const Image juce_createIconForFile (const File& file)
  221072. {
  221073. return Image::null;
  221074. }
  221075. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221076. {
  221077. return createSoftwareImage (format, width, height, clearImage);
  221078. }
  221079. #if JUCE_OPENGL
  221080. class WindowedGLContext : public OpenGLContext
  221081. {
  221082. public:
  221083. WindowedGLContext (Component* const component,
  221084. const OpenGLPixelFormat& pixelFormat_,
  221085. GLXContext sharedContext)
  221086. : renderContext (0),
  221087. embeddedWindow (0),
  221088. pixelFormat (pixelFormat_),
  221089. swapInterval (0)
  221090. {
  221091. jassert (component != 0);
  221092. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221093. if (peer == 0)
  221094. return;
  221095. ScopedXLock xlock;
  221096. XSync (display, False);
  221097. GLint attribs [64];
  221098. int n = 0;
  221099. attribs[n++] = GLX_RGBA;
  221100. attribs[n++] = GLX_DOUBLEBUFFER;
  221101. attribs[n++] = GLX_RED_SIZE;
  221102. attribs[n++] = pixelFormat.redBits;
  221103. attribs[n++] = GLX_GREEN_SIZE;
  221104. attribs[n++] = pixelFormat.greenBits;
  221105. attribs[n++] = GLX_BLUE_SIZE;
  221106. attribs[n++] = pixelFormat.blueBits;
  221107. attribs[n++] = GLX_ALPHA_SIZE;
  221108. attribs[n++] = pixelFormat.alphaBits;
  221109. attribs[n++] = GLX_DEPTH_SIZE;
  221110. attribs[n++] = pixelFormat.depthBufferBits;
  221111. attribs[n++] = GLX_STENCIL_SIZE;
  221112. attribs[n++] = pixelFormat.stencilBufferBits;
  221113. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221114. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221115. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221116. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221117. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221118. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221119. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221120. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221121. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221122. attribs[n++] = None;
  221123. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221124. if (bestVisual == 0)
  221125. return;
  221126. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221127. Window windowH = (Window) peer->getNativeHandle();
  221128. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221129. XSetWindowAttributes swa;
  221130. swa.colormap = colourMap;
  221131. swa.border_pixel = 0;
  221132. swa.event_mask = ExposureMask | StructureNotifyMask;
  221133. embeddedWindow = XCreateWindow (display, windowH,
  221134. 0, 0, 1, 1, 0,
  221135. bestVisual->depth,
  221136. InputOutput,
  221137. bestVisual->visual,
  221138. CWBorderPixel | CWColormap | CWEventMask,
  221139. &swa);
  221140. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221141. XMapWindow (display, embeddedWindow);
  221142. XFreeColormap (display, colourMap);
  221143. XFree (bestVisual);
  221144. XSync (display, False);
  221145. }
  221146. ~WindowedGLContext()
  221147. {
  221148. ScopedXLock xlock;
  221149. deleteContext();
  221150. XUnmapWindow (display, embeddedWindow);
  221151. XDestroyWindow (display, embeddedWindow);
  221152. }
  221153. void deleteContext()
  221154. {
  221155. makeInactive();
  221156. if (renderContext != 0)
  221157. {
  221158. ScopedXLock xlock;
  221159. glXDestroyContext (display, renderContext);
  221160. renderContext = 0;
  221161. }
  221162. }
  221163. bool makeActive() const throw()
  221164. {
  221165. jassert (renderContext != 0);
  221166. ScopedXLock xlock;
  221167. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221168. && XSync (display, False);
  221169. }
  221170. bool makeInactive() const throw()
  221171. {
  221172. ScopedXLock xlock;
  221173. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221174. }
  221175. bool isActive() const throw()
  221176. {
  221177. ScopedXLock xlock;
  221178. return glXGetCurrentContext() == renderContext;
  221179. }
  221180. const OpenGLPixelFormat getPixelFormat() const
  221181. {
  221182. return pixelFormat;
  221183. }
  221184. void* getRawContext() const throw()
  221185. {
  221186. return renderContext;
  221187. }
  221188. void updateWindowPosition (int x, int y, int w, int h, int)
  221189. {
  221190. ScopedXLock xlock;
  221191. XMoveResizeWindow (display, embeddedWindow,
  221192. x, y, jmax (1, w), jmax (1, h));
  221193. }
  221194. void swapBuffers()
  221195. {
  221196. ScopedXLock xlock;
  221197. glXSwapBuffers (display, embeddedWindow);
  221198. }
  221199. bool setSwapInterval (const int numFramesPerSwap)
  221200. {
  221201. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221202. if (GLXSwapIntervalSGI != 0)
  221203. {
  221204. swapInterval = numFramesPerSwap;
  221205. GLXSwapIntervalSGI (numFramesPerSwap);
  221206. return true;
  221207. }
  221208. return false;
  221209. }
  221210. int getSwapInterval() const
  221211. {
  221212. return swapInterval;
  221213. }
  221214. void repaint()
  221215. {
  221216. }
  221217. GLXContext renderContext;
  221218. private:
  221219. Window embeddedWindow;
  221220. OpenGLPixelFormat pixelFormat;
  221221. int swapInterval;
  221222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221223. };
  221224. OpenGLContext* OpenGLComponent::createContext()
  221225. {
  221226. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221227. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221228. return (c->renderContext != 0) ? c.release() : 0;
  221229. }
  221230. void juce_glViewport (const int w, const int h)
  221231. {
  221232. glViewport (0, 0, w, h);
  221233. }
  221234. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221235. OwnedArray <OpenGLPixelFormat>& results)
  221236. {
  221237. results.add (new OpenGLPixelFormat()); // xxx
  221238. }
  221239. #endif
  221240. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221241. {
  221242. jassertfalse; // not implemented!
  221243. return false;
  221244. }
  221245. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221246. {
  221247. jassertfalse; // not implemented!
  221248. return false;
  221249. }
  221250. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221251. {
  221252. if (! isOnDesktop ())
  221253. addToDesktop (0);
  221254. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221255. if (wp != 0)
  221256. {
  221257. wp->setTaskBarIcon (newImage);
  221258. setVisible (true);
  221259. toFront (false);
  221260. repaint();
  221261. }
  221262. }
  221263. void SystemTrayIconComponent::paint (Graphics& g)
  221264. {
  221265. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221266. if (wp != 0)
  221267. {
  221268. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221269. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221270. false);
  221271. }
  221272. }
  221273. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221274. {
  221275. // xxx not yet implemented!
  221276. }
  221277. void PlatformUtilities::beep()
  221278. {
  221279. std::cout << "\a" << std::flush;
  221280. }
  221281. bool AlertWindow::showNativeDialogBox (const String& title,
  221282. const String& bodyText,
  221283. bool isOkCancel)
  221284. {
  221285. // use a non-native one for the time being..
  221286. if (isOkCancel)
  221287. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221288. else
  221289. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221290. return true;
  221291. }
  221292. const int KeyPress::spaceKey = XK_space & 0xff;
  221293. const int KeyPress::returnKey = XK_Return & 0xff;
  221294. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221295. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221296. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221297. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221298. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221299. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221300. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221301. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221302. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221303. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221304. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221305. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221306. const int KeyPress::tabKey = XK_Tab & 0xff;
  221307. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221308. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221309. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221310. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221311. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221312. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221313. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221314. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221315. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221316. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221317. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221318. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221319. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221320. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221321. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221322. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221323. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221324. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221325. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221326. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221327. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221328. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221329. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221330. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221331. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221332. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221333. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221334. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221335. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221336. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221337. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221338. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221339. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221340. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221341. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221342. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221343. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221344. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221345. #endif
  221346. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221347. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221348. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221349. // compiled on its own).
  221350. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221351. namespace
  221352. {
  221353. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221354. {
  221355. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221356. snd_pcm_hw_params_t* hwParams;
  221357. snd_pcm_hw_params_alloca (&hwParams);
  221358. for (int i = 0; ratesToTry[i] != 0; ++i)
  221359. {
  221360. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221361. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221362. {
  221363. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221364. }
  221365. }
  221366. }
  221367. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221368. {
  221369. snd_pcm_hw_params_t *params;
  221370. snd_pcm_hw_params_alloca (&params);
  221371. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221372. {
  221373. snd_pcm_hw_params_get_channels_min (params, minChans);
  221374. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221375. }
  221376. }
  221377. void getDeviceProperties (const String& deviceID,
  221378. unsigned int& minChansOut,
  221379. unsigned int& maxChansOut,
  221380. unsigned int& minChansIn,
  221381. unsigned int& maxChansIn,
  221382. Array <int>& rates)
  221383. {
  221384. if (deviceID.isEmpty())
  221385. return;
  221386. snd_ctl_t* handle;
  221387. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221388. {
  221389. snd_pcm_info_t* info;
  221390. snd_pcm_info_alloca (&info);
  221391. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221392. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221393. snd_pcm_info_set_subdevice (info, 0);
  221394. if (snd_ctl_pcm_info (handle, info) >= 0)
  221395. {
  221396. snd_pcm_t* pcmHandle;
  221397. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221398. {
  221399. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221400. getDeviceSampleRates (pcmHandle, rates);
  221401. snd_pcm_close (pcmHandle);
  221402. }
  221403. }
  221404. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221405. if (snd_ctl_pcm_info (handle, info) >= 0)
  221406. {
  221407. snd_pcm_t* pcmHandle;
  221408. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221409. {
  221410. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221411. if (rates.size() == 0)
  221412. getDeviceSampleRates (pcmHandle, rates);
  221413. snd_pcm_close (pcmHandle);
  221414. }
  221415. }
  221416. snd_ctl_close (handle);
  221417. }
  221418. }
  221419. }
  221420. class ALSADevice
  221421. {
  221422. public:
  221423. ALSADevice (const String& deviceID, bool forInput)
  221424. : handle (0),
  221425. bitDepth (16),
  221426. numChannelsRunning (0),
  221427. latency (0),
  221428. isInput (forInput),
  221429. isInterleaved (true)
  221430. {
  221431. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221432. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221433. SND_PCM_ASYNC));
  221434. }
  221435. ~ALSADevice()
  221436. {
  221437. if (handle != 0)
  221438. snd_pcm_close (handle);
  221439. }
  221440. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221441. {
  221442. if (handle == 0)
  221443. return false;
  221444. snd_pcm_hw_params_t* hwParams;
  221445. snd_pcm_hw_params_alloca (&hwParams);
  221446. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221447. return false;
  221448. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221449. isInterleaved = false;
  221450. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221451. isInterleaved = true;
  221452. else
  221453. {
  221454. jassertfalse;
  221455. return false;
  221456. }
  221457. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221458. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221459. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221460. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221461. SND_PCM_FORMAT_S32_BE, 32,
  221462. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221463. SND_PCM_FORMAT_S24_3BE, 24,
  221464. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221465. SND_PCM_FORMAT_S16_BE, 16 };
  221466. bitDepth = 0;
  221467. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221468. {
  221469. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221470. {
  221471. bitDepth = formatsToTry [i + 1] & 255;
  221472. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221473. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221474. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221475. break;
  221476. }
  221477. }
  221478. if (bitDepth == 0)
  221479. {
  221480. error = "device doesn't support a compatible PCM format";
  221481. DBG ("ALSA error: " + error + "\n");
  221482. return false;
  221483. }
  221484. int dir = 0;
  221485. unsigned int periods = 4;
  221486. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221487. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221488. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221489. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221490. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221491. || failed (snd_pcm_hw_params (handle, hwParams)))
  221492. {
  221493. return false;
  221494. }
  221495. snd_pcm_uframes_t frames = 0;
  221496. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221497. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221498. latency = 0;
  221499. else
  221500. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221501. snd_pcm_sw_params_t* swParams;
  221502. snd_pcm_sw_params_alloca (&swParams);
  221503. snd_pcm_uframes_t boundary;
  221504. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221505. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221506. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221507. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221508. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221509. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221510. || failed (snd_pcm_sw_params (handle, swParams)))
  221511. {
  221512. return false;
  221513. }
  221514. #if 0
  221515. // enable this to dump the config of the devices that get opened
  221516. snd_output_t* out;
  221517. snd_output_stdio_attach (&out, stderr, 0);
  221518. snd_pcm_hw_params_dump (hwParams, out);
  221519. snd_pcm_sw_params_dump (swParams, out);
  221520. #endif
  221521. numChannelsRunning = numChannels;
  221522. return true;
  221523. }
  221524. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221525. {
  221526. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221527. float** const data = outputChannelBuffer.getArrayOfChannels();
  221528. snd_pcm_sframes_t numDone = 0;
  221529. if (isInterleaved)
  221530. {
  221531. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221532. for (int i = 0; i < numChannelsRunning; ++i)
  221533. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  221534. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  221535. }
  221536. else
  221537. {
  221538. for (int i = 0; i < numChannelsRunning; ++i)
  221539. converter->convertSamples (data[i], data[i], numSamples);
  221540. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  221541. }
  221542. if (failed (numDone))
  221543. {
  221544. if (numDone == -EPIPE)
  221545. {
  221546. if (failed (snd_pcm_prepare (handle)))
  221547. return false;
  221548. }
  221549. else if (numDone != -ESTRPIPE)
  221550. return false;
  221551. }
  221552. return true;
  221553. }
  221554. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221555. {
  221556. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221557. float** const data = inputChannelBuffer.getArrayOfChannels();
  221558. if (isInterleaved)
  221559. {
  221560. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221561. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  221562. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  221563. if (failed (num))
  221564. {
  221565. if (num == -EPIPE)
  221566. {
  221567. if (failed (snd_pcm_prepare (handle)))
  221568. return false;
  221569. }
  221570. else if (num != -ESTRPIPE)
  221571. return false;
  221572. }
  221573. for (int i = 0; i < numChannelsRunning; ++i)
  221574. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  221575. }
  221576. else
  221577. {
  221578. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221579. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221580. return false;
  221581. for (int i = 0; i < numChannelsRunning; ++i)
  221582. converter->convertSamples (data[i], data[i], numSamples);
  221583. }
  221584. return true;
  221585. }
  221586. snd_pcm_t* handle;
  221587. String error;
  221588. int bitDepth, numChannelsRunning, latency;
  221589. private:
  221590. const bool isInput;
  221591. bool isInterleaved;
  221592. MemoryBlock scratch;
  221593. ScopedPointer<AudioData::Converter> converter;
  221594. template <class SampleType>
  221595. struct ConverterHelper
  221596. {
  221597. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  221598. {
  221599. if (forInput)
  221600. {
  221601. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  221602. if (isLittleEndian)
  221603. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221604. else
  221605. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221606. }
  221607. else
  221608. {
  221609. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  221610. if (isLittleEndian)
  221611. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221612. else
  221613. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221614. }
  221615. }
  221616. };
  221617. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  221618. {
  221619. switch (bitDepth)
  221620. {
  221621. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221622. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221623. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  221624. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221625. default: jassertfalse; break; // unsupported format!
  221626. }
  221627. return 0;
  221628. }
  221629. bool failed (const int errorNum)
  221630. {
  221631. if (errorNum >= 0)
  221632. return false;
  221633. error = snd_strerror (errorNum);
  221634. DBG ("ALSA error: " + error + "\n");
  221635. return true;
  221636. }
  221637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  221638. };
  221639. class ALSAThread : public Thread
  221640. {
  221641. public:
  221642. ALSAThread (const String& inputId_,
  221643. const String& outputId_)
  221644. : Thread ("Juce ALSA"),
  221645. sampleRate (0),
  221646. bufferSize (0),
  221647. outputLatency (0),
  221648. inputLatency (0),
  221649. callback (0),
  221650. inputId (inputId_),
  221651. outputId (outputId_),
  221652. numCallbacks (0),
  221653. inputChannelBuffer (1, 1),
  221654. outputChannelBuffer (1, 1)
  221655. {
  221656. initialiseRatesAndChannels();
  221657. }
  221658. ~ALSAThread()
  221659. {
  221660. close();
  221661. }
  221662. void open (BigInteger inputChannels,
  221663. BigInteger outputChannels,
  221664. const double sampleRate_,
  221665. const int bufferSize_)
  221666. {
  221667. close();
  221668. error = String::empty;
  221669. sampleRate = sampleRate_;
  221670. bufferSize = bufferSize_;
  221671. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221672. inputChannelBuffer.clear();
  221673. inputChannelDataForCallback.clear();
  221674. currentInputChans.clear();
  221675. if (inputChannels.getHighestBit() >= 0)
  221676. {
  221677. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221678. {
  221679. if (inputChannels[i])
  221680. {
  221681. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221682. currentInputChans.setBit (i);
  221683. }
  221684. }
  221685. }
  221686. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221687. outputChannelBuffer.clear();
  221688. outputChannelDataForCallback.clear();
  221689. currentOutputChans.clear();
  221690. if (outputChannels.getHighestBit() >= 0)
  221691. {
  221692. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221693. {
  221694. if (outputChannels[i])
  221695. {
  221696. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221697. currentOutputChans.setBit (i);
  221698. }
  221699. }
  221700. }
  221701. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221702. {
  221703. outputDevice = new ALSADevice (outputId, false);
  221704. if (outputDevice->error.isNotEmpty())
  221705. {
  221706. error = outputDevice->error;
  221707. outputDevice = 0;
  221708. return;
  221709. }
  221710. currentOutputChans.setRange (0, minChansOut, true);
  221711. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221712. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221713. bufferSize))
  221714. {
  221715. error = outputDevice->error;
  221716. outputDevice = 0;
  221717. return;
  221718. }
  221719. outputLatency = outputDevice->latency;
  221720. }
  221721. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221722. {
  221723. inputDevice = new ALSADevice (inputId, true);
  221724. if (inputDevice->error.isNotEmpty())
  221725. {
  221726. error = inputDevice->error;
  221727. inputDevice = 0;
  221728. return;
  221729. }
  221730. currentInputChans.setRange (0, minChansIn, true);
  221731. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221732. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221733. bufferSize))
  221734. {
  221735. error = inputDevice->error;
  221736. inputDevice = 0;
  221737. return;
  221738. }
  221739. inputLatency = inputDevice->latency;
  221740. }
  221741. if (outputDevice == 0 && inputDevice == 0)
  221742. {
  221743. error = "no channels";
  221744. return;
  221745. }
  221746. if (outputDevice != 0 && inputDevice != 0)
  221747. {
  221748. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221749. }
  221750. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221751. return;
  221752. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221753. return;
  221754. startThread (9);
  221755. int count = 1000;
  221756. while (numCallbacks == 0)
  221757. {
  221758. sleep (5);
  221759. if (--count < 0 || ! isThreadRunning())
  221760. {
  221761. error = "device didn't start";
  221762. break;
  221763. }
  221764. }
  221765. }
  221766. void close()
  221767. {
  221768. stopThread (6000);
  221769. inputDevice = 0;
  221770. outputDevice = 0;
  221771. inputChannelBuffer.setSize (1, 1);
  221772. outputChannelBuffer.setSize (1, 1);
  221773. numCallbacks = 0;
  221774. }
  221775. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221776. {
  221777. const ScopedLock sl (callbackLock);
  221778. callback = newCallback;
  221779. }
  221780. void run()
  221781. {
  221782. while (! threadShouldExit())
  221783. {
  221784. if (inputDevice != 0)
  221785. {
  221786. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  221787. {
  221788. DBG ("ALSA: read failure");
  221789. break;
  221790. }
  221791. }
  221792. if (threadShouldExit())
  221793. break;
  221794. {
  221795. const ScopedLock sl (callbackLock);
  221796. ++numCallbacks;
  221797. if (callback != 0)
  221798. {
  221799. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221800. inputChannelDataForCallback.size(),
  221801. outputChannelDataForCallback.getRawDataPointer(),
  221802. outputChannelDataForCallback.size(),
  221803. bufferSize);
  221804. }
  221805. else
  221806. {
  221807. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221808. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221809. }
  221810. }
  221811. if (outputDevice != 0)
  221812. {
  221813. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221814. if (threadShouldExit())
  221815. break;
  221816. failed (snd_pcm_avail_update (outputDevice->handle));
  221817. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  221818. {
  221819. DBG ("ALSA: write failure");
  221820. break;
  221821. }
  221822. }
  221823. }
  221824. }
  221825. int getBitDepth() const throw()
  221826. {
  221827. if (outputDevice != 0)
  221828. return outputDevice->bitDepth;
  221829. if (inputDevice != 0)
  221830. return inputDevice->bitDepth;
  221831. return 16;
  221832. }
  221833. String error;
  221834. double sampleRate;
  221835. int bufferSize, outputLatency, inputLatency;
  221836. BigInteger currentInputChans, currentOutputChans;
  221837. Array <int> sampleRates;
  221838. StringArray channelNamesOut, channelNamesIn;
  221839. AudioIODeviceCallback* callback;
  221840. private:
  221841. const String inputId, outputId;
  221842. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221843. int numCallbacks;
  221844. CriticalSection callbackLock;
  221845. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221846. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221847. unsigned int minChansOut, maxChansOut;
  221848. unsigned int minChansIn, maxChansIn;
  221849. bool failed (const int errorNum)
  221850. {
  221851. if (errorNum >= 0)
  221852. return false;
  221853. error = snd_strerror (errorNum);
  221854. DBG ("ALSA error: " + error + "\n");
  221855. return true;
  221856. }
  221857. void initialiseRatesAndChannels()
  221858. {
  221859. sampleRates.clear();
  221860. channelNamesOut.clear();
  221861. channelNamesIn.clear();
  221862. minChansOut = 0;
  221863. maxChansOut = 0;
  221864. minChansIn = 0;
  221865. maxChansIn = 0;
  221866. unsigned int dummy = 0;
  221867. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221868. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221869. unsigned int i;
  221870. for (i = 0; i < maxChansOut; ++i)
  221871. channelNamesOut.add ("channel " + String ((int) i + 1));
  221872. for (i = 0; i < maxChansIn; ++i)
  221873. channelNamesIn.add ("channel " + String ((int) i + 1));
  221874. }
  221875. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  221876. };
  221877. class ALSAAudioIODevice : public AudioIODevice
  221878. {
  221879. public:
  221880. ALSAAudioIODevice (const String& deviceName,
  221881. const String& inputId_,
  221882. const String& outputId_)
  221883. : AudioIODevice (deviceName, "ALSA"),
  221884. inputId (inputId_),
  221885. outputId (outputId_),
  221886. isOpen_ (false),
  221887. isStarted (false),
  221888. internal (inputId_, outputId_)
  221889. {
  221890. }
  221891. ~ALSAAudioIODevice()
  221892. {
  221893. }
  221894. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  221895. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  221896. int getNumSampleRates() { return internal.sampleRates.size(); }
  221897. double getSampleRate (int index) { return internal.sampleRates [index]; }
  221898. int getDefaultBufferSize() { return 512; }
  221899. int getNumBufferSizesAvailable() { return 50; }
  221900. int getBufferSizeSamples (int index)
  221901. {
  221902. int n = 16;
  221903. for (int i = 0; i < index; ++i)
  221904. n += n < 64 ? 16
  221905. : (n < 512 ? 32
  221906. : (n < 1024 ? 64
  221907. : (n < 2048 ? 128 : 256)));
  221908. return n;
  221909. }
  221910. const String open (const BigInteger& inputChannels,
  221911. const BigInteger& outputChannels,
  221912. double sampleRate,
  221913. int bufferSizeSamples)
  221914. {
  221915. close();
  221916. if (bufferSizeSamples <= 0)
  221917. bufferSizeSamples = getDefaultBufferSize();
  221918. if (sampleRate <= 0)
  221919. {
  221920. for (int i = 0; i < getNumSampleRates(); ++i)
  221921. {
  221922. if (getSampleRate (i) >= 44100)
  221923. {
  221924. sampleRate = getSampleRate (i);
  221925. break;
  221926. }
  221927. }
  221928. }
  221929. internal.open (inputChannels, outputChannels,
  221930. sampleRate, bufferSizeSamples);
  221931. isOpen_ = internal.error.isEmpty();
  221932. return internal.error;
  221933. }
  221934. void close()
  221935. {
  221936. stop();
  221937. internal.close();
  221938. isOpen_ = false;
  221939. }
  221940. bool isOpen() { return isOpen_; }
  221941. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  221942. const String getLastError() { return internal.error; }
  221943. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  221944. double getCurrentSampleRate() { return internal.sampleRate; }
  221945. int getCurrentBitDepth() { return internal.getBitDepth(); }
  221946. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  221947. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  221948. int getOutputLatencyInSamples() { return internal.outputLatency; }
  221949. int getInputLatencyInSamples() { return internal.inputLatency; }
  221950. void start (AudioIODeviceCallback* callback)
  221951. {
  221952. if (! isOpen_)
  221953. callback = 0;
  221954. if (callback != 0)
  221955. callback->audioDeviceAboutToStart (this);
  221956. internal.setCallback (callback);
  221957. isStarted = (callback != 0);
  221958. }
  221959. void stop()
  221960. {
  221961. AudioIODeviceCallback* const oldCallback = internal.callback;
  221962. start (0);
  221963. if (oldCallback != 0)
  221964. oldCallback->audioDeviceStopped();
  221965. }
  221966. String inputId, outputId;
  221967. private:
  221968. bool isOpen_, isStarted;
  221969. ALSAThread internal;
  221970. };
  221971. class ALSAAudioIODeviceType : public AudioIODeviceType
  221972. {
  221973. public:
  221974. ALSAAudioIODeviceType()
  221975. : AudioIODeviceType ("ALSA"),
  221976. hasScanned (false)
  221977. {
  221978. }
  221979. ~ALSAAudioIODeviceType()
  221980. {
  221981. }
  221982. void scanForDevices()
  221983. {
  221984. if (hasScanned)
  221985. return;
  221986. hasScanned = true;
  221987. inputNames.clear();
  221988. inputIds.clear();
  221989. outputNames.clear();
  221990. outputIds.clear();
  221991. /* void** hints = 0;
  221992. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  221993. {
  221994. for (void** hint = hints; *hint != 0; ++hint)
  221995. {
  221996. const String name (getHint (*hint, "NAME"));
  221997. if (name.isNotEmpty())
  221998. {
  221999. const String ioid (getHint (*hint, "IOID"));
  222000. String desc (getHint (*hint, "DESC"));
  222001. if (desc.isEmpty())
  222002. desc = name;
  222003. desc = desc.replaceCharacters ("\n\r", " ");
  222004. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222005. if (ioid.isEmpty() || ioid == "Input")
  222006. {
  222007. inputNames.add (desc);
  222008. inputIds.add (name);
  222009. }
  222010. if (ioid.isEmpty() || ioid == "Output")
  222011. {
  222012. outputNames.add (desc);
  222013. outputIds.add (name);
  222014. }
  222015. }
  222016. }
  222017. snd_device_name_free_hint (hints);
  222018. }
  222019. */
  222020. snd_ctl_t* handle = 0;
  222021. snd_ctl_card_info_t* info = 0;
  222022. snd_ctl_card_info_alloca (&info);
  222023. int cardNum = -1;
  222024. while (outputIds.size() + inputIds.size() <= 32)
  222025. {
  222026. snd_card_next (&cardNum);
  222027. if (cardNum < 0)
  222028. break;
  222029. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222030. {
  222031. if (snd_ctl_card_info (handle, info) >= 0)
  222032. {
  222033. String cardId (snd_ctl_card_info_get_id (info));
  222034. if (cardId.removeCharacters ("0123456789").isEmpty())
  222035. cardId = String (cardNum);
  222036. int device = -1;
  222037. for (;;)
  222038. {
  222039. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222040. break;
  222041. String id, name;
  222042. id << "hw:" << cardId << ',' << device;
  222043. bool isInput, isOutput;
  222044. if (testDevice (id, isInput, isOutput))
  222045. {
  222046. name << snd_ctl_card_info_get_name (info);
  222047. if (name.isEmpty())
  222048. name = id;
  222049. if (isInput)
  222050. {
  222051. inputNames.add (name);
  222052. inputIds.add (id);
  222053. }
  222054. if (isOutput)
  222055. {
  222056. outputNames.add (name);
  222057. outputIds.add (id);
  222058. }
  222059. }
  222060. }
  222061. }
  222062. snd_ctl_close (handle);
  222063. }
  222064. }
  222065. inputNames.appendNumbersToDuplicates (false, true);
  222066. outputNames.appendNumbersToDuplicates (false, true);
  222067. }
  222068. const StringArray getDeviceNames (bool wantInputNames) const
  222069. {
  222070. jassert (hasScanned); // need to call scanForDevices() before doing this
  222071. return wantInputNames ? inputNames : outputNames;
  222072. }
  222073. int getDefaultDeviceIndex (bool forInput) const
  222074. {
  222075. jassert (hasScanned); // need to call scanForDevices() before doing this
  222076. return 0;
  222077. }
  222078. bool hasSeparateInputsAndOutputs() const { return true; }
  222079. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222080. {
  222081. jassert (hasScanned); // need to call scanForDevices() before doing this
  222082. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222083. if (d == 0)
  222084. return -1;
  222085. return asInput ? inputIds.indexOf (d->inputId)
  222086. : outputIds.indexOf (d->outputId);
  222087. }
  222088. AudioIODevice* createDevice (const String& outputDeviceName,
  222089. const String& inputDeviceName)
  222090. {
  222091. jassert (hasScanned); // need to call scanForDevices() before doing this
  222092. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222093. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222094. String deviceName (outputIndex >= 0 ? outputDeviceName
  222095. : inputDeviceName);
  222096. if (inputIndex >= 0 || outputIndex >= 0)
  222097. return new ALSAAudioIODevice (deviceName,
  222098. inputIds [inputIndex],
  222099. outputIds [outputIndex]);
  222100. return 0;
  222101. }
  222102. private:
  222103. StringArray inputNames, outputNames, inputIds, outputIds;
  222104. bool hasScanned;
  222105. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222106. {
  222107. unsigned int minChansOut = 0, maxChansOut = 0;
  222108. unsigned int minChansIn = 0, maxChansIn = 0;
  222109. Array <int> rates;
  222110. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222111. DBG ("ALSA device: " + id
  222112. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222113. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222114. + " rates=" + String (rates.size()));
  222115. isInput = maxChansIn > 0;
  222116. isOutput = maxChansOut > 0;
  222117. return (isInput || isOutput) && rates.size() > 0;
  222118. }
  222119. /*static const String getHint (void* hint, const char* type)
  222120. {
  222121. char* const n = snd_device_name_get_hint (hint, type);
  222122. const String s ((const char*) n);
  222123. free (n);
  222124. return s;
  222125. }*/
  222126. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222127. };
  222128. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222129. {
  222130. return new ALSAAudioIODeviceType();
  222131. }
  222132. #endif
  222133. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222134. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222135. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222136. // compiled on its own).
  222137. #ifdef JUCE_INCLUDED_FILE
  222138. #if JUCE_JACK
  222139. static void* juce_libjack_handle = 0;
  222140. void* juce_load_jack_function (const char* const name)
  222141. {
  222142. if (juce_libjack_handle == 0)
  222143. return 0;
  222144. return dlsym (juce_libjack_handle, name);
  222145. }
  222146. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222147. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222148. return_type fn_name argument_types { \
  222149. static fn_name##_ptr_t fn = 0; \
  222150. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222151. if (fn) return (*fn)arguments; \
  222152. else return 0; \
  222153. }
  222154. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222155. typedef void (*fn_name##_ptr_t)argument_types; \
  222156. void fn_name argument_types { \
  222157. static fn_name##_ptr_t fn = 0; \
  222158. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222159. if (fn) (*fn)arguments; \
  222160. }
  222161. 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));
  222162. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222163. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222164. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222165. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222166. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222167. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222168. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222169. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222170. 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));
  222171. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222172. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222173. 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));
  222174. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222175. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222176. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222177. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222178. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222179. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222180. #if JUCE_DEBUG
  222181. #define JACK_LOGGING_ENABLED 1
  222182. #endif
  222183. #if JACK_LOGGING_ENABLED
  222184. namespace
  222185. {
  222186. void jack_Log (const String& s)
  222187. {
  222188. std::cerr << s << std::endl;
  222189. }
  222190. void dumpJackErrorMessage (const jack_status_t status)
  222191. {
  222192. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222193. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222194. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222195. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222196. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222197. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222198. }
  222199. }
  222200. #else
  222201. #define dumpJackErrorMessage(a) {}
  222202. #define jack_Log(...) {}
  222203. #endif
  222204. #ifndef JUCE_JACK_CLIENT_NAME
  222205. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222206. #endif
  222207. class JackAudioIODevice : public AudioIODevice
  222208. {
  222209. public:
  222210. JackAudioIODevice (const String& deviceName,
  222211. const String& inputId_,
  222212. const String& outputId_)
  222213. : AudioIODevice (deviceName, "JACK"),
  222214. inputId (inputId_),
  222215. outputId (outputId_),
  222216. isOpen_ (false),
  222217. callback (0),
  222218. totalNumberOfInputChannels (0),
  222219. totalNumberOfOutputChannels (0)
  222220. {
  222221. jassert (deviceName.isNotEmpty());
  222222. jack_status_t status;
  222223. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222224. if (client == 0)
  222225. {
  222226. dumpJackErrorMessage (status);
  222227. }
  222228. else
  222229. {
  222230. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222231. // open input ports
  222232. const StringArray inputChannels (getInputChannelNames());
  222233. for (int i = 0; i < inputChannels.size(); i++)
  222234. {
  222235. String inputName;
  222236. inputName << "in_" << ++totalNumberOfInputChannels;
  222237. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222238. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222239. }
  222240. // open output ports
  222241. const StringArray outputChannels (getOutputChannelNames());
  222242. for (int i = 0; i < outputChannels.size (); i++)
  222243. {
  222244. String outputName;
  222245. outputName << "out_" << ++totalNumberOfOutputChannels;
  222246. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222247. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222248. }
  222249. inChans.calloc (totalNumberOfInputChannels + 2);
  222250. outChans.calloc (totalNumberOfOutputChannels + 2);
  222251. }
  222252. }
  222253. ~JackAudioIODevice()
  222254. {
  222255. close();
  222256. if (client != 0)
  222257. {
  222258. JUCE_NAMESPACE::jack_client_close (client);
  222259. client = 0;
  222260. }
  222261. }
  222262. const StringArray getChannelNames (bool forInput) const
  222263. {
  222264. StringArray names;
  222265. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222266. forInput ? JackPortIsInput : JackPortIsOutput);
  222267. if (ports != 0)
  222268. {
  222269. int j = 0;
  222270. while (ports[j] != 0)
  222271. {
  222272. const String portName (ports [j++]);
  222273. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222274. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222275. }
  222276. free (ports);
  222277. }
  222278. return names;
  222279. }
  222280. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222281. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222282. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222283. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222284. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222285. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222286. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222287. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222288. double sampleRate, int bufferSizeSamples)
  222289. {
  222290. if (client == 0)
  222291. {
  222292. lastError = "No JACK client running";
  222293. return lastError;
  222294. }
  222295. lastError = String::empty;
  222296. close();
  222297. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222298. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222299. JUCE_NAMESPACE::jack_activate (client);
  222300. isOpen_ = true;
  222301. if (! inputChannels.isZero())
  222302. {
  222303. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222304. if (ports != 0)
  222305. {
  222306. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222307. for (int i = 0; i < numInputChannels; ++i)
  222308. {
  222309. const String portName (ports[i]);
  222310. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222311. {
  222312. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222313. if (error != 0)
  222314. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222315. }
  222316. }
  222317. free (ports);
  222318. }
  222319. }
  222320. if (! outputChannels.isZero())
  222321. {
  222322. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222323. if (ports != 0)
  222324. {
  222325. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222326. for (int i = 0; i < numOutputChannels; ++i)
  222327. {
  222328. const String portName (ports[i]);
  222329. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222330. {
  222331. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222332. if (error != 0)
  222333. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222334. }
  222335. }
  222336. free (ports);
  222337. }
  222338. }
  222339. return lastError;
  222340. }
  222341. void close()
  222342. {
  222343. stop();
  222344. if (client != 0)
  222345. {
  222346. JUCE_NAMESPACE::jack_deactivate (client);
  222347. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222348. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222349. }
  222350. isOpen_ = false;
  222351. }
  222352. void start (AudioIODeviceCallback* newCallback)
  222353. {
  222354. if (isOpen_ && newCallback != callback)
  222355. {
  222356. if (newCallback != 0)
  222357. newCallback->audioDeviceAboutToStart (this);
  222358. AudioIODeviceCallback* const oldCallback = callback;
  222359. {
  222360. const ScopedLock sl (callbackLock);
  222361. callback = newCallback;
  222362. }
  222363. if (oldCallback != 0)
  222364. oldCallback->audioDeviceStopped();
  222365. }
  222366. }
  222367. void stop()
  222368. {
  222369. start (0);
  222370. }
  222371. bool isOpen() { return isOpen_; }
  222372. bool isPlaying() { return callback != 0; }
  222373. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222374. double getCurrentSampleRate() { return getSampleRate (0); }
  222375. int getCurrentBitDepth() { return 32; }
  222376. const String getLastError() { return lastError; }
  222377. const BigInteger getActiveOutputChannels() const
  222378. {
  222379. BigInteger outputBits;
  222380. for (int i = 0; i < outputPorts.size(); i++)
  222381. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222382. outputBits.setBit (i);
  222383. return outputBits;
  222384. }
  222385. const BigInteger getActiveInputChannels() const
  222386. {
  222387. BigInteger inputBits;
  222388. for (int i = 0; i < inputPorts.size(); i++)
  222389. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222390. inputBits.setBit (i);
  222391. return inputBits;
  222392. }
  222393. int getOutputLatencyInSamples()
  222394. {
  222395. int latency = 0;
  222396. for (int i = 0; i < outputPorts.size(); i++)
  222397. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222398. return latency;
  222399. }
  222400. int getInputLatencyInSamples()
  222401. {
  222402. int latency = 0;
  222403. for (int i = 0; i < inputPorts.size(); i++)
  222404. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222405. return latency;
  222406. }
  222407. String inputId, outputId;
  222408. private:
  222409. void process (const int numSamples)
  222410. {
  222411. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222412. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222413. {
  222414. jack_default_audio_sample_t* in
  222415. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222416. if (in != 0)
  222417. inChans [numActiveInChans++] = (float*) in;
  222418. }
  222419. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222420. {
  222421. jack_default_audio_sample_t* out
  222422. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222423. if (out != 0)
  222424. outChans [numActiveOutChans++] = (float*) out;
  222425. }
  222426. const ScopedLock sl (callbackLock);
  222427. if (callback != 0)
  222428. {
  222429. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222430. outChans, numActiveOutChans, numSamples);
  222431. }
  222432. else
  222433. {
  222434. for (i = 0; i < numActiveOutChans; ++i)
  222435. zeromem (outChans[i], sizeof (float) * numSamples);
  222436. }
  222437. }
  222438. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222439. {
  222440. if (callbackArgument != 0)
  222441. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222442. return 0;
  222443. }
  222444. static void threadInitCallback (void* callbackArgument)
  222445. {
  222446. jack_Log ("JackAudioIODevice::initialise");
  222447. }
  222448. static void shutdownCallback (void* callbackArgument)
  222449. {
  222450. jack_Log ("JackAudioIODevice::shutdown");
  222451. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222452. if (device != 0)
  222453. {
  222454. device->client = 0;
  222455. device->close();
  222456. }
  222457. }
  222458. static void errorCallback (const char* msg)
  222459. {
  222460. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222461. }
  222462. bool isOpen_;
  222463. jack_client_t* client;
  222464. String lastError;
  222465. AudioIODeviceCallback* callback;
  222466. CriticalSection callbackLock;
  222467. HeapBlock <float*> inChans, outChans;
  222468. int totalNumberOfInputChannels;
  222469. int totalNumberOfOutputChannels;
  222470. Array<void*> inputPorts, outputPorts;
  222471. };
  222472. class JackAudioIODeviceType : public AudioIODeviceType
  222473. {
  222474. public:
  222475. JackAudioIODeviceType()
  222476. : AudioIODeviceType ("JACK"),
  222477. hasScanned (false)
  222478. {
  222479. }
  222480. ~JackAudioIODeviceType()
  222481. {
  222482. }
  222483. void scanForDevices()
  222484. {
  222485. hasScanned = true;
  222486. inputNames.clear();
  222487. inputIds.clear();
  222488. outputNames.clear();
  222489. outputIds.clear();
  222490. if (juce_libjack_handle == 0)
  222491. {
  222492. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222493. if (juce_libjack_handle == 0)
  222494. return;
  222495. }
  222496. // open a dummy client
  222497. jack_status_t status;
  222498. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222499. if (client == 0)
  222500. {
  222501. dumpJackErrorMessage (status);
  222502. }
  222503. else
  222504. {
  222505. // scan for output devices
  222506. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222507. if (ports != 0)
  222508. {
  222509. int j = 0;
  222510. while (ports[j] != 0)
  222511. {
  222512. String clientName (ports[j]);
  222513. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222514. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222515. && ! inputNames.contains (clientName))
  222516. {
  222517. inputNames.add (clientName);
  222518. inputIds.add (ports [j]);
  222519. }
  222520. ++j;
  222521. }
  222522. free (ports);
  222523. }
  222524. // scan for input devices
  222525. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222526. if (ports != 0)
  222527. {
  222528. int j = 0;
  222529. while (ports[j] != 0)
  222530. {
  222531. String clientName (ports[j]);
  222532. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222533. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222534. && ! outputNames.contains (clientName))
  222535. {
  222536. outputNames.add (clientName);
  222537. outputIds.add (ports [j]);
  222538. }
  222539. ++j;
  222540. }
  222541. free (ports);
  222542. }
  222543. JUCE_NAMESPACE::jack_client_close (client);
  222544. }
  222545. }
  222546. const StringArray getDeviceNames (bool wantInputNames) const
  222547. {
  222548. jassert (hasScanned); // need to call scanForDevices() before doing this
  222549. return wantInputNames ? inputNames : outputNames;
  222550. }
  222551. int getDefaultDeviceIndex (bool forInput) const
  222552. {
  222553. jassert (hasScanned); // need to call scanForDevices() before doing this
  222554. return 0;
  222555. }
  222556. bool hasSeparateInputsAndOutputs() const { return true; }
  222557. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222558. {
  222559. jassert (hasScanned); // need to call scanForDevices() before doing this
  222560. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222561. if (d == 0)
  222562. return -1;
  222563. return asInput ? inputIds.indexOf (d->inputId)
  222564. : outputIds.indexOf (d->outputId);
  222565. }
  222566. AudioIODevice* createDevice (const String& outputDeviceName,
  222567. const String& inputDeviceName)
  222568. {
  222569. jassert (hasScanned); // need to call scanForDevices() before doing this
  222570. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222571. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222572. if (inputIndex >= 0 || outputIndex >= 0)
  222573. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222574. : inputDeviceName,
  222575. inputIds [inputIndex],
  222576. outputIds [outputIndex]);
  222577. return 0;
  222578. }
  222579. private:
  222580. StringArray inputNames, outputNames, inputIds, outputIds;
  222581. bool hasScanned;
  222582. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  222583. };
  222584. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222585. {
  222586. return new JackAudioIODeviceType();
  222587. }
  222588. #else // if JACK is turned off..
  222589. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222590. #endif
  222591. #endif
  222592. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222593. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222594. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222595. // compiled on its own).
  222596. #if JUCE_INCLUDED_FILE
  222597. #if JUCE_ALSA
  222598. namespace
  222599. {
  222600. snd_seq_t* iterateMidiDevices (const bool forInput,
  222601. StringArray& deviceNamesFound,
  222602. const int deviceIndexToOpen)
  222603. {
  222604. snd_seq_t* returnedHandle = 0;
  222605. snd_seq_t* seqHandle;
  222606. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222607. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222608. {
  222609. snd_seq_system_info_t* systemInfo;
  222610. snd_seq_client_info_t* clientInfo;
  222611. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222612. {
  222613. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222614. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222615. {
  222616. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222617. while (--numClients >= 0 && returnedHandle == 0)
  222618. {
  222619. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222620. {
  222621. snd_seq_port_info_t* portInfo;
  222622. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222623. {
  222624. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222625. const int client = snd_seq_client_info_get_client (clientInfo);
  222626. snd_seq_port_info_set_client (portInfo, client);
  222627. snd_seq_port_info_set_port (portInfo, -1);
  222628. while (--numPorts >= 0)
  222629. {
  222630. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222631. && (snd_seq_port_info_get_capability (portInfo)
  222632. & (forInput ? SND_SEQ_PORT_CAP_READ
  222633. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222634. {
  222635. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222636. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222637. {
  222638. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222639. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222640. if (sourcePort != -1)
  222641. {
  222642. snd_seq_set_client_name (seqHandle,
  222643. forInput ? "Juce Midi Input"
  222644. : "Juce Midi Output");
  222645. const int portId
  222646. = snd_seq_create_simple_port (seqHandle,
  222647. forInput ? "Juce Midi In Port"
  222648. : "Juce Midi Out Port",
  222649. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222650. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222651. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222652. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222653. returnedHandle = seqHandle;
  222654. }
  222655. }
  222656. }
  222657. }
  222658. snd_seq_port_info_free (portInfo);
  222659. }
  222660. }
  222661. }
  222662. snd_seq_client_info_free (clientInfo);
  222663. }
  222664. snd_seq_system_info_free (systemInfo);
  222665. }
  222666. if (returnedHandle == 0)
  222667. snd_seq_close (seqHandle);
  222668. }
  222669. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222670. return returnedHandle;
  222671. }
  222672. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  222673. {
  222674. snd_seq_t* seqHandle = 0;
  222675. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222676. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222677. {
  222678. snd_seq_set_client_name (seqHandle,
  222679. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222680. const int portId
  222681. = snd_seq_create_simple_port (seqHandle,
  222682. forInput ? "in"
  222683. : "out",
  222684. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222685. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222686. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222687. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222688. if (portId < 0)
  222689. {
  222690. snd_seq_close (seqHandle);
  222691. seqHandle = 0;
  222692. }
  222693. }
  222694. return seqHandle;
  222695. }
  222696. }
  222697. class MidiOutputDevice
  222698. {
  222699. public:
  222700. MidiOutputDevice (MidiOutput* const midiOutput_,
  222701. snd_seq_t* const seqHandle_)
  222702. :
  222703. midiOutput (midiOutput_),
  222704. seqHandle (seqHandle_),
  222705. maxEventSize (16 * 1024)
  222706. {
  222707. jassert (seqHandle != 0 && midiOutput != 0);
  222708. snd_midi_event_new (maxEventSize, &midiParser);
  222709. }
  222710. ~MidiOutputDevice()
  222711. {
  222712. snd_midi_event_free (midiParser);
  222713. snd_seq_close (seqHandle);
  222714. }
  222715. void sendMessageNow (const MidiMessage& message)
  222716. {
  222717. if (message.getRawDataSize() > maxEventSize)
  222718. {
  222719. maxEventSize = message.getRawDataSize();
  222720. snd_midi_event_free (midiParser);
  222721. snd_midi_event_new (maxEventSize, &midiParser);
  222722. }
  222723. snd_seq_event_t event;
  222724. snd_seq_ev_clear (&event);
  222725. snd_midi_event_encode (midiParser,
  222726. message.getRawData(),
  222727. message.getRawDataSize(),
  222728. &event);
  222729. snd_midi_event_reset_encode (midiParser);
  222730. snd_seq_ev_set_source (&event, 0);
  222731. snd_seq_ev_set_subs (&event);
  222732. snd_seq_ev_set_direct (&event);
  222733. snd_seq_event_output (seqHandle, &event);
  222734. snd_seq_drain_output (seqHandle);
  222735. }
  222736. private:
  222737. MidiOutput* const midiOutput;
  222738. snd_seq_t* const seqHandle;
  222739. snd_midi_event_t* midiParser;
  222740. int maxEventSize;
  222741. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  222742. };
  222743. const StringArray MidiOutput::getDevices()
  222744. {
  222745. StringArray devices;
  222746. iterateMidiDevices (false, devices, -1);
  222747. return devices;
  222748. }
  222749. int MidiOutput::getDefaultDeviceIndex()
  222750. {
  222751. return 0;
  222752. }
  222753. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222754. {
  222755. MidiOutput* newDevice = 0;
  222756. StringArray devices;
  222757. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  222758. if (handle != 0)
  222759. {
  222760. newDevice = new MidiOutput();
  222761. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222762. }
  222763. return newDevice;
  222764. }
  222765. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222766. {
  222767. MidiOutput* newDevice = 0;
  222768. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  222769. if (handle != 0)
  222770. {
  222771. newDevice = new MidiOutput();
  222772. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222773. }
  222774. return newDevice;
  222775. }
  222776. MidiOutput::~MidiOutput()
  222777. {
  222778. delete static_cast <MidiOutputDevice*> (internal);
  222779. }
  222780. void MidiOutput::reset()
  222781. {
  222782. }
  222783. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222784. {
  222785. return false;
  222786. }
  222787. void MidiOutput::setVolume (float leftVol, float rightVol)
  222788. {
  222789. }
  222790. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222791. {
  222792. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  222793. }
  222794. class MidiInputThread : public Thread
  222795. {
  222796. public:
  222797. MidiInputThread (MidiInput* const midiInput_,
  222798. snd_seq_t* const seqHandle_,
  222799. MidiInputCallback* const callback_)
  222800. : Thread ("Juce MIDI Input"),
  222801. midiInput (midiInput_),
  222802. seqHandle (seqHandle_),
  222803. callback (callback_)
  222804. {
  222805. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222806. }
  222807. ~MidiInputThread()
  222808. {
  222809. snd_seq_close (seqHandle);
  222810. }
  222811. void run()
  222812. {
  222813. const int maxEventSize = 16 * 1024;
  222814. snd_midi_event_t* midiParser;
  222815. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222816. {
  222817. HeapBlock <uint8> buffer (maxEventSize);
  222818. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222819. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222820. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222821. while (! threadShouldExit())
  222822. {
  222823. if (poll (pfd, numPfds, 500) > 0)
  222824. {
  222825. snd_seq_event_t* inputEvent = 0;
  222826. snd_seq_nonblock (seqHandle, 1);
  222827. do
  222828. {
  222829. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222830. {
  222831. // xxx what about SYSEXes that are too big for the buffer?
  222832. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222833. snd_midi_event_reset_decode (midiParser);
  222834. if (numBytes > 0)
  222835. {
  222836. const MidiMessage message ((const uint8*) buffer,
  222837. numBytes,
  222838. Time::getMillisecondCounter() * 0.001);
  222839. callback->handleIncomingMidiMessage (midiInput, message);
  222840. }
  222841. snd_seq_free_event (inputEvent);
  222842. }
  222843. }
  222844. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222845. snd_seq_free_event (inputEvent);
  222846. }
  222847. }
  222848. snd_midi_event_free (midiParser);
  222849. }
  222850. };
  222851. private:
  222852. MidiInput* const midiInput;
  222853. snd_seq_t* const seqHandle;
  222854. MidiInputCallback* const callback;
  222855. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  222856. };
  222857. MidiInput::MidiInput (const String& name_)
  222858. : name (name_),
  222859. internal (0)
  222860. {
  222861. }
  222862. MidiInput::~MidiInput()
  222863. {
  222864. stop();
  222865. delete static_cast <MidiInputThread*> (internal);
  222866. }
  222867. void MidiInput::start()
  222868. {
  222869. static_cast <MidiInputThread*> (internal)->startThread();
  222870. }
  222871. void MidiInput::stop()
  222872. {
  222873. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  222874. }
  222875. int MidiInput::getDefaultDeviceIndex()
  222876. {
  222877. return 0;
  222878. }
  222879. const StringArray MidiInput::getDevices()
  222880. {
  222881. StringArray devices;
  222882. iterateMidiDevices (true, devices, -1);
  222883. return devices;
  222884. }
  222885. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222886. {
  222887. MidiInput* newDevice = 0;
  222888. StringArray devices;
  222889. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  222890. if (handle != 0)
  222891. {
  222892. newDevice = new MidiInput (devices [deviceIndex]);
  222893. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222894. }
  222895. return newDevice;
  222896. }
  222897. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222898. {
  222899. MidiInput* newDevice = 0;
  222900. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  222901. if (handle != 0)
  222902. {
  222903. newDevice = new MidiInput (deviceName);
  222904. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222905. }
  222906. return newDevice;
  222907. }
  222908. #else
  222909. // (These are just stub functions if ALSA is unavailable...)
  222910. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222911. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222912. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222913. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222914. MidiOutput::~MidiOutput() {}
  222915. void MidiOutput::reset() {}
  222916. bool MidiOutput::getVolume (float&, float&) { return false; }
  222917. void MidiOutput::setVolume (float, float) {}
  222918. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222919. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222920. MidiInput::~MidiInput() {}
  222921. void MidiInput::start() {}
  222922. void MidiInput::stop() {}
  222923. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222924. const StringArray MidiInput::getDevices() { return StringArray(); }
  222925. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222926. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222927. #endif
  222928. #endif
  222929. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222930. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222931. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222932. // compiled on its own).
  222933. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222934. AudioCDReader::AudioCDReader()
  222935. : AudioFormatReader (0, "CD Audio")
  222936. {
  222937. }
  222938. const StringArray AudioCDReader::getAvailableCDNames()
  222939. {
  222940. StringArray names;
  222941. return names;
  222942. }
  222943. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222944. {
  222945. return 0;
  222946. }
  222947. AudioCDReader::~AudioCDReader()
  222948. {
  222949. }
  222950. void AudioCDReader::refreshTrackLengths()
  222951. {
  222952. }
  222953. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222954. int64 startSampleInFile, int numSamples)
  222955. {
  222956. return false;
  222957. }
  222958. bool AudioCDReader::isCDStillPresent() const
  222959. {
  222960. return false;
  222961. }
  222962. bool AudioCDReader::isTrackAudio (int trackNum) const
  222963. {
  222964. return false;
  222965. }
  222966. void AudioCDReader::enableIndexScanning (bool b)
  222967. {
  222968. }
  222969. int AudioCDReader::getLastIndex() const
  222970. {
  222971. return 0;
  222972. }
  222973. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222974. {
  222975. return Array<int>();
  222976. }
  222977. #endif
  222978. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222979. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222980. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222981. // compiled on its own).
  222982. #if JUCE_INCLUDED_FILE
  222983. void FileChooser::showPlatformDialog (Array<File>& results,
  222984. const String& title,
  222985. const File& file,
  222986. const String& filters,
  222987. bool isDirectory,
  222988. bool selectsFiles,
  222989. bool isSave,
  222990. bool warnAboutOverwritingExistingFiles,
  222991. bool selectMultipleFiles,
  222992. FilePreviewComponent* previewComponent)
  222993. {
  222994. const String separator (":");
  222995. String command ("zenity --file-selection");
  222996. if (title.isNotEmpty())
  222997. command << " --title=\"" << title << "\"";
  222998. if (file != File::nonexistent)
  222999. command << " --filename=\"" << file.getFullPathName () << "\"";
  223000. if (isDirectory)
  223001. command << " --directory";
  223002. if (isSave)
  223003. command << " --save";
  223004. if (selectMultipleFiles)
  223005. command << " --multiple --separator=\"" << separator << "\"";
  223006. command << " 2>&1";
  223007. MemoryOutputStream result;
  223008. int status = -1;
  223009. FILE* stream = popen (command.toUTF8(), "r");
  223010. if (stream != 0)
  223011. {
  223012. for (;;)
  223013. {
  223014. char buffer [1024];
  223015. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223016. if (bytesRead <= 0)
  223017. break;
  223018. result.write (buffer, bytesRead);
  223019. }
  223020. status = pclose (stream);
  223021. }
  223022. if (status == 0)
  223023. {
  223024. StringArray tokens;
  223025. if (selectMultipleFiles)
  223026. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223027. else
  223028. tokens.add (result.toUTF8());
  223029. for (int i = 0; i < tokens.size(); i++)
  223030. results.add (File (tokens[i]));
  223031. return;
  223032. }
  223033. //xxx ain't got one!
  223034. jassertfalse;
  223035. }
  223036. #endif
  223037. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223038. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223039. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223040. // compiled on its own).
  223041. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223042. /*
  223043. Sorry.. This class isn't implemented on Linux!
  223044. */
  223045. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223046. : browser (0),
  223047. blankPageShown (false),
  223048. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223049. {
  223050. setOpaque (true);
  223051. }
  223052. WebBrowserComponent::~WebBrowserComponent()
  223053. {
  223054. }
  223055. void WebBrowserComponent::goToURL (const String& url,
  223056. const StringArray* headers,
  223057. const MemoryBlock* postData)
  223058. {
  223059. lastURL = url;
  223060. lastHeaders.clear();
  223061. if (headers != 0)
  223062. lastHeaders = *headers;
  223063. lastPostData.setSize (0);
  223064. if (postData != 0)
  223065. lastPostData = *postData;
  223066. blankPageShown = false;
  223067. }
  223068. void WebBrowserComponent::stop()
  223069. {
  223070. }
  223071. void WebBrowserComponent::goBack()
  223072. {
  223073. lastURL = String::empty;
  223074. blankPageShown = false;
  223075. }
  223076. void WebBrowserComponent::goForward()
  223077. {
  223078. lastURL = String::empty;
  223079. }
  223080. void WebBrowserComponent::refresh()
  223081. {
  223082. }
  223083. void WebBrowserComponent::paint (Graphics& g)
  223084. {
  223085. g.fillAll (Colours::white);
  223086. }
  223087. void WebBrowserComponent::checkWindowAssociation()
  223088. {
  223089. }
  223090. void WebBrowserComponent::reloadLastURL()
  223091. {
  223092. if (lastURL.isNotEmpty())
  223093. {
  223094. goToURL (lastURL, &lastHeaders, &lastPostData);
  223095. lastURL = String::empty;
  223096. }
  223097. }
  223098. void WebBrowserComponent::parentHierarchyChanged()
  223099. {
  223100. checkWindowAssociation();
  223101. }
  223102. void WebBrowserComponent::resized()
  223103. {
  223104. }
  223105. void WebBrowserComponent::visibilityChanged()
  223106. {
  223107. checkWindowAssociation();
  223108. }
  223109. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223110. {
  223111. return true;
  223112. }
  223113. #endif
  223114. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223115. #endif
  223116. END_JUCE_NAMESPACE
  223117. #endif
  223118. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223119. #elif JUCE_MAC || JUCE_IOS
  223120. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223121. /*
  223122. This file wraps together all the mac-specific code, so that
  223123. we can include all the native headers just once, and compile all our
  223124. platform-specific stuff in one big lump, keeping it out of the way of
  223125. the rest of the codebase.
  223126. */
  223127. #if JUCE_MAC || JUCE_IOS
  223128. #undef JUCE_BUILD_NATIVE
  223129. #define JUCE_BUILD_NATIVE 1
  223130. BEGIN_JUCE_NAMESPACE
  223131. #undef Point
  223132. namespace
  223133. {
  223134. template <class RectType>
  223135. const Rectangle<int> convertToRectInt (const RectType& r)
  223136. {
  223137. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223138. }
  223139. template <class RectType>
  223140. const Rectangle<float> convertToRectFloat (const RectType& r)
  223141. {
  223142. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223143. }
  223144. template <class RectType>
  223145. CGRect convertToCGRect (const RectType& r)
  223146. {
  223147. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223148. }
  223149. }
  223150. class MessageQueue
  223151. {
  223152. public:
  223153. MessageQueue()
  223154. {
  223155. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223156. runLoop = CFRunLoopGetMain();
  223157. #else
  223158. runLoop = CFRunLoopGetCurrent();
  223159. #endif
  223160. CFRunLoopSourceContext sourceContext;
  223161. zerostruct (sourceContext);
  223162. sourceContext.info = this;
  223163. sourceContext.perform = runLoopSourceCallback;
  223164. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223165. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223166. }
  223167. ~MessageQueue()
  223168. {
  223169. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223170. CFRunLoopSourceInvalidate (runLoopSource);
  223171. CFRelease (runLoopSource);
  223172. }
  223173. void post (Message* const message)
  223174. {
  223175. messages.add (message);
  223176. CFRunLoopSourceSignal (runLoopSource);
  223177. CFRunLoopWakeUp (runLoop);
  223178. }
  223179. private:
  223180. ReferenceCountedArray <Message, CriticalSection> messages;
  223181. CriticalSection lock;
  223182. CFRunLoopRef runLoop;
  223183. CFRunLoopSourceRef runLoopSource;
  223184. bool deliverNextMessage()
  223185. {
  223186. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223187. if (nextMessage == 0)
  223188. return false;
  223189. const ScopedAutoReleasePool pool;
  223190. MessageManager::getInstance()->deliverMessage (nextMessage);
  223191. return true;
  223192. }
  223193. void runLoopCallback()
  223194. {
  223195. for (int i = 4; --i >= 0;)
  223196. if (! deliverNextMessage())
  223197. return;
  223198. CFRunLoopSourceSignal (runLoopSource);
  223199. CFRunLoopWakeUp (runLoop);
  223200. }
  223201. static void runLoopSourceCallback (void* info)
  223202. {
  223203. static_cast <MessageQueue*> (info)->runLoopCallback();
  223204. }
  223205. };
  223206. #define JUCE_INCLUDED_FILE 1
  223207. // Now include the actual code files..
  223208. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223209. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223210. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223211. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223212. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223213. actually calling into a similarly named class in the other module's address space.
  223214. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223215. have unique names, and should avoid this problem.
  223216. If you're using the amalgamated version, you can just set this macro to something unique before
  223217. you include juce_amalgamated.cpp.
  223218. */
  223219. #ifndef JUCE_ObjCExtraSuffix
  223220. #define JUCE_ObjCExtraSuffix 3
  223221. #endif
  223222. #ifndef DOXYGEN
  223223. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223224. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223225. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223226. #endif
  223227. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223228. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223229. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223230. // compiled on its own).
  223231. #if JUCE_INCLUDED_FILE
  223232. namespace
  223233. {
  223234. const String nsStringToJuce (NSString* s)
  223235. {
  223236. return String::fromUTF8 ([s UTF8String]);
  223237. }
  223238. NSString* juceStringToNS (const String& s)
  223239. {
  223240. return [NSString stringWithUTF8String: s.toUTF8()];
  223241. }
  223242. const String convertUTF16ToString (const UniChar* utf16)
  223243. {
  223244. String s;
  223245. while (*utf16 != 0)
  223246. s += (juce_wchar) *utf16++;
  223247. return s;
  223248. }
  223249. }
  223250. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223251. {
  223252. String result;
  223253. if (cfString != 0)
  223254. {
  223255. CFRange range = { 0, CFStringGetLength (cfString) };
  223256. HeapBlock <UniChar> u (range.length + 1);
  223257. CFStringGetCharacters (cfString, range, u);
  223258. u[range.length] = 0;
  223259. result = convertUTF16ToString (u);
  223260. }
  223261. return result;
  223262. }
  223263. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223264. {
  223265. const int len = s.length();
  223266. HeapBlock <UniChar> temp (len + 2);
  223267. for (int i = 0; i <= len; ++i)
  223268. temp[i] = s[i];
  223269. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223270. }
  223271. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223272. {
  223273. #if JUCE_IOS
  223274. const ScopedAutoReleasePool pool;
  223275. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223276. #else
  223277. UnicodeMapping map;
  223278. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223279. kUnicodeNoSubset,
  223280. kTextEncodingDefaultFormat);
  223281. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223282. kUnicodeCanonicalCompVariant,
  223283. kTextEncodingDefaultFormat);
  223284. map.mappingVersion = kUnicodeUseLatestMapping;
  223285. UnicodeToTextInfo conversionInfo = 0;
  223286. String result;
  223287. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223288. {
  223289. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (s.getCharPointer());
  223290. HeapBlock <char> tempOut;
  223291. tempOut.calloc (bytesNeeded + 4);
  223292. ByteCount bytesRead = 0;
  223293. ByteCount outputBufferSize = 0;
  223294. if (ConvertFromUnicodeToText (conversionInfo,
  223295. bytesNeeded, (ConstUniCharArrayPtr) s.toUTF16().getAddress(),
  223296. kUnicodeDefaultDirectionMask,
  223297. 0, 0, 0, 0,
  223298. bytesNeeded, &bytesRead,
  223299. &outputBufferSize, tempOut) == noErr)
  223300. {
  223301. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223302. CharPointer_UTF32 dest (result.getCharPointer());
  223303. dest.writeAll (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  223304. }
  223305. DisposeUnicodeToTextInfo (&conversionInfo);
  223306. }
  223307. return result;
  223308. #endif
  223309. }
  223310. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223311. void SystemClipboard::copyTextToClipboard (const String& text)
  223312. {
  223313. #if JUCE_IOS
  223314. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223315. forPasteboardType: @"public.text"];
  223316. #else
  223317. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223318. owner: nil];
  223319. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223320. forType: NSStringPboardType];
  223321. #endif
  223322. }
  223323. const String SystemClipboard::getTextFromClipboard()
  223324. {
  223325. #if JUCE_IOS
  223326. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223327. #else
  223328. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223329. #endif
  223330. return text == 0 ? String::empty
  223331. : nsStringToJuce (text);
  223332. }
  223333. #endif
  223334. #endif
  223335. /*** End of inlined file: juce_mac_Strings.mm ***/
  223336. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223337. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223338. // compiled on its own).
  223339. #if JUCE_INCLUDED_FILE
  223340. namespace SystemStatsHelpers
  223341. {
  223342. static int64 highResTimerFrequency = 0;
  223343. static double highResTimerToMillisecRatio = 0;
  223344. #if JUCE_INTEL
  223345. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223346. {
  223347. uint32 la = a, lb = b, lc = c, ld = d;
  223348. asm ("mov %%ebx, %%esi \n\t"
  223349. "cpuid \n\t"
  223350. "xchg %%esi, %%ebx"
  223351. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223352. #if JUCE_64BIT
  223353. , "b" (lb), "c" (lc), "d" (ld)
  223354. #endif
  223355. );
  223356. a = la; b = lb; c = lc; d = ld;
  223357. }
  223358. #endif
  223359. }
  223360. void SystemStats::initialiseStats()
  223361. {
  223362. using namespace SystemStatsHelpers;
  223363. static bool initialised = false;
  223364. if (! initialised)
  223365. {
  223366. initialised = true;
  223367. #if JUCE_MAC
  223368. [NSApplication sharedApplication];
  223369. #endif
  223370. #if JUCE_INTEL
  223371. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223372. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223373. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223374. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223375. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223376. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223377. #else
  223378. cpuFlags.hasMMX = false;
  223379. cpuFlags.hasSSE = false;
  223380. cpuFlags.hasSSE2 = false;
  223381. cpuFlags.has3DNow = false;
  223382. #endif
  223383. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223384. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223385. #else
  223386. cpuFlags.numCpus = (int) MPProcessors();
  223387. #endif
  223388. mach_timebase_info_data_t timebase;
  223389. (void) mach_timebase_info (&timebase);
  223390. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223391. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223392. String s (SystemStats::getJUCEVersion());
  223393. rlimit lim;
  223394. getrlimit (RLIMIT_NOFILE, &lim);
  223395. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223396. setrlimit (RLIMIT_NOFILE, &lim);
  223397. }
  223398. }
  223399. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223400. {
  223401. return MacOSX;
  223402. }
  223403. const String SystemStats::getOperatingSystemName()
  223404. {
  223405. return "Mac OS X";
  223406. }
  223407. #if ! JUCE_IOS
  223408. int PlatformUtilities::getOSXMinorVersionNumber()
  223409. {
  223410. SInt32 versionMinor = 0;
  223411. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223412. (void) err;
  223413. jassert (err == noErr);
  223414. return (int) versionMinor;
  223415. }
  223416. #endif
  223417. bool SystemStats::isOperatingSystem64Bit()
  223418. {
  223419. #if JUCE_IOS
  223420. return false;
  223421. #elif JUCE_64BIT
  223422. return true;
  223423. #else
  223424. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223425. #endif
  223426. }
  223427. int SystemStats::getMemorySizeInMegabytes()
  223428. {
  223429. uint64 mem = 0;
  223430. size_t memSize = sizeof (mem);
  223431. int mib[] = { CTL_HW, HW_MEMSIZE };
  223432. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223433. return (int) (mem / (1024 * 1024));
  223434. }
  223435. const String SystemStats::getCpuVendor()
  223436. {
  223437. #if JUCE_INTEL
  223438. uint32 dummy = 0;
  223439. uint32 vendor[4];
  223440. zerostruct (vendor);
  223441. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223442. return String (reinterpret_cast <const char*> (vendor), 12);
  223443. #else
  223444. return String::empty;
  223445. #endif
  223446. }
  223447. int SystemStats::getCpuSpeedInMegaherz()
  223448. {
  223449. uint64 speedHz = 0;
  223450. size_t speedSize = sizeof (speedHz);
  223451. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223452. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223453. #if JUCE_BIG_ENDIAN
  223454. if (speedSize == 4)
  223455. speedHz >>= 32;
  223456. #endif
  223457. return (int) (speedHz / 1000000);
  223458. }
  223459. const String SystemStats::getLogonName()
  223460. {
  223461. return nsStringToJuce (NSUserName());
  223462. }
  223463. const String SystemStats::getFullUserName()
  223464. {
  223465. return nsStringToJuce (NSFullUserName());
  223466. }
  223467. uint32 juce_millisecondsSinceStartup() throw()
  223468. {
  223469. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223470. }
  223471. double Time::getMillisecondCounterHiRes() throw()
  223472. {
  223473. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223474. }
  223475. int64 Time::getHighResolutionTicks() throw()
  223476. {
  223477. return (int64) mach_absolute_time();
  223478. }
  223479. int64 Time::getHighResolutionTicksPerSecond() throw()
  223480. {
  223481. return SystemStatsHelpers::highResTimerFrequency;
  223482. }
  223483. bool Time::setSystemTimeToThisTime() const
  223484. {
  223485. jassertfalse;
  223486. return false;
  223487. }
  223488. int SystemStats::getPageSize()
  223489. {
  223490. return (int) NSPageSize();
  223491. }
  223492. void PlatformUtilities::fpuReset()
  223493. {
  223494. }
  223495. #endif
  223496. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223497. /*** Start of inlined file: juce_mac_Network.mm ***/
  223498. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223499. // compiled on its own).
  223500. #if JUCE_INCLUDED_FILE
  223501. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223502. {
  223503. ifaddrs* addrs = 0;
  223504. if (getifaddrs (&addrs) == 0)
  223505. {
  223506. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223507. {
  223508. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223509. if (sto->ss_family == AF_LINK)
  223510. {
  223511. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223512. #ifndef IFT_ETHER
  223513. #define IFT_ETHER 6
  223514. #endif
  223515. if (sadd->sdl_type == IFT_ETHER)
  223516. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  223517. }
  223518. }
  223519. freeifaddrs (addrs);
  223520. }
  223521. }
  223522. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223523. const String& emailSubject,
  223524. const String& bodyText,
  223525. const StringArray& filesToAttach)
  223526. {
  223527. #if JUCE_IOS
  223528. //xxx probably need to use MFMailComposeViewController
  223529. jassertfalse;
  223530. return false;
  223531. #else
  223532. const ScopedAutoReleasePool pool;
  223533. String script;
  223534. script << "tell application \"Mail\"\r\n"
  223535. "set newMessage to make new outgoing message with properties {subject:\""
  223536. << emailSubject.replace ("\"", "\\\"")
  223537. << "\", content:\""
  223538. << bodyText.replace ("\"", "\\\"")
  223539. << "\" & return & return}\r\n"
  223540. "tell newMessage\r\n"
  223541. "set visible to true\r\n"
  223542. "set sender to \"sdfsdfsdfewf\"\r\n"
  223543. "make new to recipient at end of to recipients with properties {address:\""
  223544. << targetEmailAddress
  223545. << "\"}\r\n";
  223546. for (int i = 0; i < filesToAttach.size(); ++i)
  223547. {
  223548. script << "tell content\r\n"
  223549. "make new attachment with properties {file name:\""
  223550. << filesToAttach[i].replace ("\"", "\\\"")
  223551. << "\"} at after the last paragraph\r\n"
  223552. "end tell\r\n";
  223553. }
  223554. script << "end tell\r\n"
  223555. "end tell\r\n";
  223556. NSAppleScript* s = [[NSAppleScript alloc]
  223557. initWithSource: juceStringToNS (script)];
  223558. NSDictionary* error = 0;
  223559. const bool ok = [s executeAndReturnError: &error] != nil;
  223560. [s release];
  223561. return ok;
  223562. #endif
  223563. }
  223564. END_JUCE_NAMESPACE
  223565. using namespace JUCE_NAMESPACE;
  223566. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223567. @interface JuceURLConnection : NSObject
  223568. {
  223569. @public
  223570. NSURLRequest* request;
  223571. NSURLConnection* connection;
  223572. NSMutableData* data;
  223573. Thread* runLoopThread;
  223574. bool initialised, hasFailed, hasFinished;
  223575. int position;
  223576. int64 contentLength;
  223577. NSDictionary* headers;
  223578. NSLock* dataLock;
  223579. }
  223580. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223581. - (void) dealloc;
  223582. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223583. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223584. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223585. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223586. - (BOOL) isOpen;
  223587. - (int) read: (char*) dest numBytes: (int) num;
  223588. - (int) readPosition;
  223589. - (void) stop;
  223590. - (void) createConnection;
  223591. @end
  223592. class JuceURLConnectionMessageThread : public Thread
  223593. {
  223594. public:
  223595. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223596. : Thread ("http connection"),
  223597. owner (owner_)
  223598. {
  223599. }
  223600. ~JuceURLConnectionMessageThread()
  223601. {
  223602. stopThread (10000);
  223603. }
  223604. void run()
  223605. {
  223606. [owner createConnection];
  223607. while (! threadShouldExit())
  223608. {
  223609. const ScopedAutoReleasePool pool;
  223610. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223611. }
  223612. }
  223613. private:
  223614. JuceURLConnection* owner;
  223615. };
  223616. @implementation JuceURLConnection
  223617. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223618. withCallback: (URL::OpenStreamProgressCallback*) callback
  223619. withContext: (void*) context;
  223620. {
  223621. [super init];
  223622. request = req;
  223623. [request retain];
  223624. data = [[NSMutableData data] retain];
  223625. dataLock = [[NSLock alloc] init];
  223626. connection = 0;
  223627. initialised = false;
  223628. hasFailed = false;
  223629. hasFinished = false;
  223630. contentLength = -1;
  223631. headers = 0;
  223632. runLoopThread = new JuceURLConnectionMessageThread (self);
  223633. runLoopThread->startThread();
  223634. while (runLoopThread->isThreadRunning() && ! initialised)
  223635. {
  223636. if (callback != 0)
  223637. callback (context, -1, (int) [[request HTTPBody] length]);
  223638. Thread::sleep (1);
  223639. }
  223640. return self;
  223641. }
  223642. - (void) dealloc
  223643. {
  223644. [self stop];
  223645. deleteAndZero (runLoopThread);
  223646. [connection release];
  223647. [data release];
  223648. [dataLock release];
  223649. [request release];
  223650. [headers release];
  223651. [super dealloc];
  223652. }
  223653. - (void) createConnection
  223654. {
  223655. NSUInteger oldRetainCount = [self retainCount];
  223656. connection = [[NSURLConnection alloc] initWithRequest: request
  223657. delegate: self];
  223658. if (oldRetainCount == [self retainCount])
  223659. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223660. if (connection == nil)
  223661. runLoopThread->signalThreadShouldExit();
  223662. }
  223663. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223664. {
  223665. (void) conn;
  223666. [dataLock lock];
  223667. [data setLength: 0];
  223668. [dataLock unlock];
  223669. initialised = true;
  223670. contentLength = [response expectedContentLength];
  223671. [headers release];
  223672. headers = 0;
  223673. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223674. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223675. }
  223676. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223677. {
  223678. (void) conn;
  223679. DBG (nsStringToJuce ([error description]));
  223680. hasFailed = true;
  223681. initialised = true;
  223682. if (runLoopThread != 0)
  223683. runLoopThread->signalThreadShouldExit();
  223684. }
  223685. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223686. {
  223687. (void) conn;
  223688. [dataLock lock];
  223689. [data appendData: newData];
  223690. [dataLock unlock];
  223691. initialised = true;
  223692. }
  223693. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223694. {
  223695. (void) conn;
  223696. hasFinished = true;
  223697. initialised = true;
  223698. if (runLoopThread != 0)
  223699. runLoopThread->signalThreadShouldExit();
  223700. }
  223701. - (BOOL) isOpen
  223702. {
  223703. return connection != 0 && ! hasFailed;
  223704. }
  223705. - (int) readPosition
  223706. {
  223707. return position;
  223708. }
  223709. - (int) read: (char*) dest numBytes: (int) numNeeded
  223710. {
  223711. int numDone = 0;
  223712. while (numNeeded > 0)
  223713. {
  223714. int available = jmin (numNeeded, (int) [data length]);
  223715. if (available > 0)
  223716. {
  223717. [dataLock lock];
  223718. [data getBytes: dest length: available];
  223719. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223720. [dataLock unlock];
  223721. numDone += available;
  223722. numNeeded -= available;
  223723. dest += available;
  223724. }
  223725. else
  223726. {
  223727. if (hasFailed || hasFinished)
  223728. break;
  223729. Thread::sleep (1);
  223730. }
  223731. }
  223732. position += numDone;
  223733. return numDone;
  223734. }
  223735. - (void) stop
  223736. {
  223737. [connection cancel];
  223738. if (runLoopThread != 0)
  223739. runLoopThread->stopThread (10000);
  223740. }
  223741. @end
  223742. BEGIN_JUCE_NAMESPACE
  223743. class WebInputStream : public InputStream
  223744. {
  223745. public:
  223746. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  223747. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223748. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  223749. : connection (nil),
  223750. address (address_), headers (headers_), postData (postData_), position (0),
  223751. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  223752. {
  223753. JUCE_AUTORELEASEPOOL
  223754. connection = createConnection (progressCallback, progressCallbackContext);
  223755. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  223756. {
  223757. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  223758. NSString* key;
  223759. while ((key = [enumerator nextObject]) != nil)
  223760. responseHeaders->set (nsStringToJuce (key),
  223761. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  223762. }
  223763. }
  223764. ~WebInputStream()
  223765. {
  223766. close();
  223767. }
  223768. bool isError() const { return connection == nil; }
  223769. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  223770. bool isExhausted() { return finished; }
  223771. int64 getPosition() { return position; }
  223772. int read (void* buffer, int bytesToRead)
  223773. {
  223774. if (finished || isError())
  223775. {
  223776. return 0;
  223777. }
  223778. else
  223779. {
  223780. JUCE_AUTORELEASEPOOL
  223781. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  223782. position += bytesRead;
  223783. if (bytesRead == 0)
  223784. finished = true;
  223785. return bytesRead;
  223786. }
  223787. }
  223788. bool setPosition (int64 wantedPos)
  223789. {
  223790. if (wantedPos != position)
  223791. {
  223792. finished = false;
  223793. if (wantedPos < position)
  223794. {
  223795. close();
  223796. position = 0;
  223797. connection = createConnection (0, 0);
  223798. }
  223799. skipNextBytes (wantedPos - position);
  223800. }
  223801. return true;
  223802. }
  223803. private:
  223804. JuceURLConnection* connection;
  223805. String address, headers;
  223806. MemoryBlock postData;
  223807. int64 position;
  223808. bool finished;
  223809. const bool isPost;
  223810. const int timeOutMs;
  223811. void close()
  223812. {
  223813. [connection stop];
  223814. [connection release];
  223815. connection = nil;
  223816. }
  223817. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  223818. void* progressCallbackContext)
  223819. {
  223820. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  223821. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223822. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223823. if (req == nil)
  223824. return 0;
  223825. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223826. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223827. StringArray headerLines;
  223828. headerLines.addLines (headers);
  223829. headerLines.removeEmptyStrings (true);
  223830. for (int i = 0; i < headerLines.size(); ++i)
  223831. {
  223832. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223833. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223834. if (key.isNotEmpty() && value.isNotEmpty())
  223835. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223836. }
  223837. if (isPost && postData.getSize() > 0)
  223838. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223839. length: postData.getSize()]];
  223840. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223841. withCallback: progressCallback
  223842. withContext: progressCallbackContext];
  223843. if ([s isOpen])
  223844. return s;
  223845. [s release];
  223846. return 0;
  223847. }
  223848. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  223849. };
  223850. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  223851. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223852. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  223853. {
  223854. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  223855. progressCallback, progressCallbackContext,
  223856. headers, timeOutMs, responseHeaders));
  223857. return wi->isError() ? 0 : wi.release();
  223858. }
  223859. #endif
  223860. /*** End of inlined file: juce_mac_Network.mm ***/
  223861. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223862. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223863. // compiled on its own).
  223864. #if JUCE_INCLUDED_FILE
  223865. struct NamedPipeInternal
  223866. {
  223867. String pipeInName, pipeOutName;
  223868. int pipeIn, pipeOut;
  223869. bool volatile createdPipe, blocked, stopReadOperation;
  223870. static void signalHandler (int) {}
  223871. };
  223872. void NamedPipe::cancelPendingReads()
  223873. {
  223874. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  223875. {
  223876. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223877. intern->stopReadOperation = true;
  223878. char buffer [1] = { 0 };
  223879. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223880. (void) bytesWritten;
  223881. int timeout = 2000;
  223882. while (intern->blocked && --timeout >= 0)
  223883. Thread::sleep (2);
  223884. intern->stopReadOperation = false;
  223885. }
  223886. }
  223887. void NamedPipe::close()
  223888. {
  223889. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223890. if (intern != 0)
  223891. {
  223892. internal = 0;
  223893. if (intern->pipeIn != -1)
  223894. ::close (intern->pipeIn);
  223895. if (intern->pipeOut != -1)
  223896. ::close (intern->pipeOut);
  223897. if (intern->createdPipe)
  223898. {
  223899. unlink (intern->pipeInName.toUTF8());
  223900. unlink (intern->pipeOutName.toUTF8());
  223901. }
  223902. delete intern;
  223903. }
  223904. }
  223905. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223906. {
  223907. close();
  223908. NamedPipeInternal* const intern = new NamedPipeInternal();
  223909. internal = intern;
  223910. intern->createdPipe = createPipe;
  223911. intern->blocked = false;
  223912. intern->stopReadOperation = false;
  223913. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223914. siginterrupt (SIGPIPE, 1);
  223915. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223916. intern->pipeInName = pipePath + "_in";
  223917. intern->pipeOutName = pipePath + "_out";
  223918. intern->pipeIn = -1;
  223919. intern->pipeOut = -1;
  223920. if (createPipe)
  223921. {
  223922. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223923. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223924. {
  223925. delete intern;
  223926. internal = 0;
  223927. return false;
  223928. }
  223929. }
  223930. return true;
  223931. }
  223932. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223933. {
  223934. int bytesRead = -1;
  223935. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223936. if (intern != 0)
  223937. {
  223938. intern->blocked = true;
  223939. if (intern->pipeIn == -1)
  223940. {
  223941. if (intern->createdPipe)
  223942. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223943. else
  223944. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223945. if (intern->pipeIn == -1)
  223946. {
  223947. intern->blocked = false;
  223948. return -1;
  223949. }
  223950. }
  223951. bytesRead = 0;
  223952. char* p = static_cast<char*> (destBuffer);
  223953. while (bytesRead < maxBytesToRead)
  223954. {
  223955. const int bytesThisTime = maxBytesToRead - bytesRead;
  223956. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223957. if (numRead <= 0 || intern->stopReadOperation)
  223958. {
  223959. bytesRead = -1;
  223960. break;
  223961. }
  223962. bytesRead += numRead;
  223963. p += bytesRead;
  223964. }
  223965. intern->blocked = false;
  223966. }
  223967. return bytesRead;
  223968. }
  223969. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223970. {
  223971. int bytesWritten = -1;
  223972. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223973. if (intern != 0)
  223974. {
  223975. if (intern->pipeOut == -1)
  223976. {
  223977. if (intern->createdPipe)
  223978. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223979. else
  223980. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223981. if (intern->pipeOut == -1)
  223982. {
  223983. return -1;
  223984. }
  223985. }
  223986. const char* p = static_cast<const char*> (sourceBuffer);
  223987. bytesWritten = 0;
  223988. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223989. while (bytesWritten < numBytesToWrite
  223990. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223991. {
  223992. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223993. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223994. if (numWritten <= 0)
  223995. {
  223996. bytesWritten = -1;
  223997. break;
  223998. }
  223999. bytesWritten += numWritten;
  224000. p += bytesWritten;
  224001. }
  224002. }
  224003. return bytesWritten;
  224004. }
  224005. #endif
  224006. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224007. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224008. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224009. // compiled on its own).
  224010. #if JUCE_INCLUDED_FILE
  224011. /*
  224012. Note that a lot of methods that you'd expect to find in this file actually
  224013. live in juce_posix_SharedCode.h!
  224014. */
  224015. bool Process::isForegroundProcess()
  224016. {
  224017. #if JUCE_MAC
  224018. return [NSApp isActive];
  224019. #else
  224020. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224021. #endif
  224022. }
  224023. void Process::raisePrivilege()
  224024. {
  224025. jassertfalse;
  224026. }
  224027. void Process::lowerPrivilege()
  224028. {
  224029. jassertfalse;
  224030. }
  224031. void Process::terminate()
  224032. {
  224033. exit (0);
  224034. }
  224035. void Process::setPriority (ProcessPriority)
  224036. {
  224037. // xxx
  224038. }
  224039. #endif
  224040. /*** End of inlined file: juce_mac_Threads.mm ***/
  224041. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224042. /*
  224043. This file contains posix routines that are common to both the Linux and Mac builds.
  224044. It gets included directly in the cpp files for these platforms.
  224045. */
  224046. CriticalSection::CriticalSection() throw()
  224047. {
  224048. pthread_mutexattr_t atts;
  224049. pthread_mutexattr_init (&atts);
  224050. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224051. #if ! JUCE_ANDROID
  224052. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224053. #endif
  224054. pthread_mutex_init (&internal, &atts);
  224055. }
  224056. CriticalSection::~CriticalSection() throw()
  224057. {
  224058. pthread_mutex_destroy (&internal);
  224059. }
  224060. void CriticalSection::enter() const throw()
  224061. {
  224062. pthread_mutex_lock (&internal);
  224063. }
  224064. bool CriticalSection::tryEnter() const throw()
  224065. {
  224066. return pthread_mutex_trylock (&internal) == 0;
  224067. }
  224068. void CriticalSection::exit() const throw()
  224069. {
  224070. pthread_mutex_unlock (&internal);
  224071. }
  224072. class WaitableEventImpl
  224073. {
  224074. public:
  224075. WaitableEventImpl (const bool manualReset_)
  224076. : triggered (false),
  224077. manualReset (manualReset_)
  224078. {
  224079. pthread_cond_init (&condition, 0);
  224080. pthread_mutexattr_t atts;
  224081. pthread_mutexattr_init (&atts);
  224082. #if ! JUCE_ANDROID
  224083. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224084. #endif
  224085. pthread_mutex_init (&mutex, &atts);
  224086. }
  224087. ~WaitableEventImpl()
  224088. {
  224089. pthread_cond_destroy (&condition);
  224090. pthread_mutex_destroy (&mutex);
  224091. }
  224092. bool wait (const int timeOutMillisecs) throw()
  224093. {
  224094. pthread_mutex_lock (&mutex);
  224095. if (! triggered)
  224096. {
  224097. if (timeOutMillisecs < 0)
  224098. {
  224099. do
  224100. {
  224101. pthread_cond_wait (&condition, &mutex);
  224102. }
  224103. while (! triggered);
  224104. }
  224105. else
  224106. {
  224107. struct timeval now;
  224108. gettimeofday (&now, 0);
  224109. struct timespec time;
  224110. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224111. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224112. if (time.tv_nsec >= 1000000000)
  224113. {
  224114. time.tv_nsec -= 1000000000;
  224115. time.tv_sec++;
  224116. }
  224117. do
  224118. {
  224119. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224120. {
  224121. pthread_mutex_unlock (&mutex);
  224122. return false;
  224123. }
  224124. }
  224125. while (! triggered);
  224126. }
  224127. }
  224128. if (! manualReset)
  224129. triggered = false;
  224130. pthread_mutex_unlock (&mutex);
  224131. return true;
  224132. }
  224133. void signal() throw()
  224134. {
  224135. pthread_mutex_lock (&mutex);
  224136. triggered = true;
  224137. pthread_cond_broadcast (&condition);
  224138. pthread_mutex_unlock (&mutex);
  224139. }
  224140. void reset() throw()
  224141. {
  224142. pthread_mutex_lock (&mutex);
  224143. triggered = false;
  224144. pthread_mutex_unlock (&mutex);
  224145. }
  224146. private:
  224147. pthread_cond_t condition;
  224148. pthread_mutex_t mutex;
  224149. bool triggered;
  224150. const bool manualReset;
  224151. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224152. };
  224153. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224154. : internal (new WaitableEventImpl (manualReset))
  224155. {
  224156. }
  224157. WaitableEvent::~WaitableEvent() throw()
  224158. {
  224159. delete static_cast <WaitableEventImpl*> (internal);
  224160. }
  224161. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224162. {
  224163. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224164. }
  224165. void WaitableEvent::signal() const throw()
  224166. {
  224167. static_cast <WaitableEventImpl*> (internal)->signal();
  224168. }
  224169. void WaitableEvent::reset() const throw()
  224170. {
  224171. static_cast <WaitableEventImpl*> (internal)->reset();
  224172. }
  224173. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224174. {
  224175. struct timespec time;
  224176. time.tv_sec = millisecs / 1000;
  224177. time.tv_nsec = (millisecs % 1000) * 1000000;
  224178. nanosleep (&time, 0);
  224179. }
  224180. const juce_wchar File::separator = '/';
  224181. const String File::separatorString ("/");
  224182. const File File::getCurrentWorkingDirectory()
  224183. {
  224184. HeapBlock<char> heapBuffer;
  224185. char localBuffer [1024];
  224186. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224187. int bufferSize = 4096;
  224188. while (cwd == 0 && errno == ERANGE)
  224189. {
  224190. heapBuffer.malloc (bufferSize);
  224191. cwd = getcwd (heapBuffer, bufferSize - 1);
  224192. bufferSize += 1024;
  224193. }
  224194. return File (String::fromUTF8 (cwd));
  224195. }
  224196. bool File::setAsCurrentWorkingDirectory() const
  224197. {
  224198. return chdir (getFullPathName().toUTF8()) == 0;
  224199. }
  224200. namespace
  224201. {
  224202. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224203. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224204. #else
  224205. typedef struct stat juce_statStruct;
  224206. #endif
  224207. bool juce_stat (const String& fileName, juce_statStruct& info)
  224208. {
  224209. return fileName.isNotEmpty()
  224210. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224211. && (stat64 (fileName.toUTF8(), &info) == 0);
  224212. #else
  224213. && (stat (fileName.toUTF8(), &info) == 0);
  224214. #endif
  224215. }
  224216. // if this file doesn't exist, find a parent of it that does..
  224217. bool juce_doStatFS (File f, struct statfs& result)
  224218. {
  224219. for (int i = 5; --i >= 0;)
  224220. {
  224221. if (f.exists())
  224222. break;
  224223. f = f.getParentDirectory();
  224224. }
  224225. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224226. }
  224227. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224228. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224229. {
  224230. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224231. {
  224232. juce_statStruct info;
  224233. const bool statOk = juce_stat (path, info);
  224234. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224235. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224236. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224237. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224238. }
  224239. if (isReadOnly != 0)
  224240. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224241. }
  224242. }
  224243. bool File::isDirectory() const
  224244. {
  224245. juce_statStruct info;
  224246. return fullPath.isEmpty()
  224247. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224248. }
  224249. bool File::exists() const
  224250. {
  224251. juce_statStruct info;
  224252. return fullPath.isNotEmpty()
  224253. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224254. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224255. #else
  224256. && (lstat (fullPath.toUTF8(), &info) == 0);
  224257. #endif
  224258. }
  224259. bool File::existsAsFile() const
  224260. {
  224261. return exists() && ! isDirectory();
  224262. }
  224263. int64 File::getSize() const
  224264. {
  224265. juce_statStruct info;
  224266. return juce_stat (fullPath, info) ? info.st_size : 0;
  224267. }
  224268. bool File::hasWriteAccess() const
  224269. {
  224270. if (exists())
  224271. return access (fullPath.toUTF8(), W_OK) == 0;
  224272. if ((! isDirectory()) && fullPath.containsChar (separator))
  224273. return getParentDirectory().hasWriteAccess();
  224274. return false;
  224275. }
  224276. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224277. {
  224278. juce_statStruct info;
  224279. if (! juce_stat (fullPath, info))
  224280. return false;
  224281. info.st_mode &= 0777; // Just permissions
  224282. if (shouldBeReadOnly)
  224283. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224284. else
  224285. // Give everybody write permission?
  224286. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224287. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224288. }
  224289. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224290. {
  224291. modificationTime = 0;
  224292. accessTime = 0;
  224293. creationTime = 0;
  224294. juce_statStruct info;
  224295. if (juce_stat (fullPath, info))
  224296. {
  224297. modificationTime = (int64) info.st_mtime * 1000;
  224298. accessTime = (int64) info.st_atime * 1000;
  224299. creationTime = (int64) info.st_ctime * 1000;
  224300. }
  224301. }
  224302. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224303. {
  224304. juce_statStruct info;
  224305. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  224306. {
  224307. struct utimbuf times;
  224308. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  224309. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  224310. return utime (fullPath.toUTF8(), &times) == 0;
  224311. }
  224312. return false;
  224313. }
  224314. bool File::deleteFile() const
  224315. {
  224316. if (! exists())
  224317. return true;
  224318. if (isDirectory())
  224319. return rmdir (fullPath.toUTF8()) == 0;
  224320. return remove (fullPath.toUTF8()) == 0;
  224321. }
  224322. bool File::moveInternal (const File& dest) const
  224323. {
  224324. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224325. return true;
  224326. if (hasWriteAccess() && copyInternal (dest))
  224327. {
  224328. if (deleteFile())
  224329. return true;
  224330. dest.deleteFile();
  224331. }
  224332. return false;
  224333. }
  224334. void File::createDirectoryInternal (const String& fileName) const
  224335. {
  224336. mkdir (fileName.toUTF8(), 0777);
  224337. }
  224338. int64 juce_fileSetPosition (void* handle, int64 pos)
  224339. {
  224340. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224341. return pos;
  224342. return -1;
  224343. }
  224344. void FileInputStream::openHandle()
  224345. {
  224346. totalSize = file.getSize();
  224347. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224348. if (f != -1)
  224349. fileHandle = (void*) f;
  224350. }
  224351. void FileInputStream::closeHandle()
  224352. {
  224353. if (fileHandle != 0)
  224354. {
  224355. close ((int) (pointer_sized_int) fileHandle);
  224356. fileHandle = 0;
  224357. }
  224358. }
  224359. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224360. {
  224361. if (fileHandle != 0)
  224362. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224363. return 0;
  224364. }
  224365. void FileOutputStream::openHandle()
  224366. {
  224367. if (file.exists())
  224368. {
  224369. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224370. if (f != -1)
  224371. {
  224372. currentPosition = lseek (f, 0, SEEK_END);
  224373. if (currentPosition >= 0)
  224374. fileHandle = (void*) f;
  224375. else
  224376. close (f);
  224377. }
  224378. }
  224379. else
  224380. {
  224381. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224382. if (f != -1)
  224383. fileHandle = (void*) f;
  224384. }
  224385. }
  224386. void FileOutputStream::closeHandle()
  224387. {
  224388. if (fileHandle != 0)
  224389. {
  224390. close ((int) (pointer_sized_int) fileHandle);
  224391. fileHandle = 0;
  224392. }
  224393. }
  224394. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224395. {
  224396. if (fileHandle != 0)
  224397. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224398. return 0;
  224399. }
  224400. void FileOutputStream::flushInternal()
  224401. {
  224402. if (fileHandle != 0)
  224403. fsync ((int) (pointer_sized_int) fileHandle);
  224404. }
  224405. const File juce_getExecutableFile()
  224406. {
  224407. #if JUCE_ANDROID
  224408. // TODO
  224409. return File::nonexistent;
  224410. #else
  224411. Dl_info exeInfo;
  224412. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  224413. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224414. #endif
  224415. }
  224416. int64 File::getBytesFreeOnVolume() const
  224417. {
  224418. struct statfs buf;
  224419. if (juce_doStatFS (*this, buf))
  224420. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224421. return 0;
  224422. }
  224423. int64 File::getVolumeTotalSize() const
  224424. {
  224425. struct statfs buf;
  224426. if (juce_doStatFS (*this, buf))
  224427. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224428. return 0;
  224429. }
  224430. const String File::getVolumeLabel() const
  224431. {
  224432. #if JUCE_MAC
  224433. struct VolAttrBuf
  224434. {
  224435. u_int32_t length;
  224436. attrreference_t mountPointRef;
  224437. char mountPointSpace [MAXPATHLEN];
  224438. } attrBuf;
  224439. struct attrlist attrList;
  224440. zerostruct (attrList);
  224441. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224442. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224443. File f (*this);
  224444. for (;;)
  224445. {
  224446. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224447. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224448. (int) attrBuf.mountPointRef.attr_length);
  224449. const File parent (f.getParentDirectory());
  224450. if (f == parent)
  224451. break;
  224452. f = parent;
  224453. }
  224454. #endif
  224455. return String::empty;
  224456. }
  224457. int File::getVolumeSerialNumber() const
  224458. {
  224459. int result = 0;
  224460. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  224461. char info [512];
  224462. #ifndef HDIO_GET_IDENTITY
  224463. #define HDIO_GET_IDENTITY 0x030d
  224464. #endif
  224465. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  224466. {
  224467. DBG (String (info + 20, 20));
  224468. result = String (info + 20, 20).trim().getIntValue();
  224469. }
  224470. close (fd);*/
  224471. return result;
  224472. }
  224473. void juce_runSystemCommand (const String& command)
  224474. {
  224475. int result = system (command.toUTF8());
  224476. (void) result;
  224477. }
  224478. const String juce_getOutputFromCommand (const String& command)
  224479. {
  224480. // slight bodge here, as we just pipe the output into a temp file and read it...
  224481. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224482. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224483. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224484. String result (tempFile.loadFileAsString());
  224485. tempFile.deleteFile();
  224486. return result;
  224487. }
  224488. class InterProcessLock::Pimpl
  224489. {
  224490. public:
  224491. Pimpl (const String& name, const int timeOutMillisecs)
  224492. : handle (0), refCount (1)
  224493. {
  224494. #if JUCE_MAC
  224495. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224496. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224497. #else
  224498. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224499. #endif
  224500. temp.create();
  224501. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224502. if (handle != 0)
  224503. {
  224504. struct flock fl;
  224505. zerostruct (fl);
  224506. fl.l_whence = SEEK_SET;
  224507. fl.l_type = F_WRLCK;
  224508. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224509. for (;;)
  224510. {
  224511. const int result = fcntl (handle, F_SETLK, &fl);
  224512. if (result >= 0)
  224513. return;
  224514. if (errno != EINTR)
  224515. {
  224516. if (timeOutMillisecs == 0
  224517. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224518. break;
  224519. Thread::sleep (10);
  224520. }
  224521. }
  224522. }
  224523. closeFile();
  224524. }
  224525. ~Pimpl()
  224526. {
  224527. closeFile();
  224528. }
  224529. void closeFile()
  224530. {
  224531. if (handle != 0)
  224532. {
  224533. struct flock fl;
  224534. zerostruct (fl);
  224535. fl.l_whence = SEEK_SET;
  224536. fl.l_type = F_UNLCK;
  224537. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224538. {}
  224539. close (handle);
  224540. handle = 0;
  224541. }
  224542. }
  224543. int handle, refCount;
  224544. };
  224545. InterProcessLock::InterProcessLock (const String& name_)
  224546. : name (name_)
  224547. {
  224548. }
  224549. InterProcessLock::~InterProcessLock()
  224550. {
  224551. }
  224552. bool InterProcessLock::enter (const int timeOutMillisecs)
  224553. {
  224554. const ScopedLock sl (lock);
  224555. if (pimpl == 0)
  224556. {
  224557. pimpl = new Pimpl (name, timeOutMillisecs);
  224558. if (pimpl->handle == 0)
  224559. pimpl = 0;
  224560. }
  224561. else
  224562. {
  224563. pimpl->refCount++;
  224564. }
  224565. return pimpl != 0;
  224566. }
  224567. void InterProcessLock::exit()
  224568. {
  224569. const ScopedLock sl (lock);
  224570. // Trying to release the lock too many times!
  224571. jassert (pimpl != 0);
  224572. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224573. pimpl = 0;
  224574. }
  224575. void JUCE_API juce_threadEntryPoint (void*);
  224576. void* threadEntryProc (void* userData)
  224577. {
  224578. JUCE_AUTORELEASEPOOL
  224579. juce_threadEntryPoint (userData);
  224580. return 0;
  224581. }
  224582. void Thread::launchThread()
  224583. {
  224584. threadHandle_ = 0;
  224585. pthread_t handle = 0;
  224586. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  224587. {
  224588. pthread_detach (handle);
  224589. threadHandle_ = (void*) handle;
  224590. threadId_ = (ThreadID) threadHandle_;
  224591. }
  224592. }
  224593. void Thread::closeThreadHandle()
  224594. {
  224595. threadId_ = 0;
  224596. threadHandle_ = 0;
  224597. }
  224598. void Thread::killThread()
  224599. {
  224600. if (threadHandle_ != 0)
  224601. {
  224602. #if JUCE_ANDROID
  224603. jassertfalse; // pthread_cancel not available!
  224604. #else
  224605. pthread_cancel ((pthread_t) threadHandle_);
  224606. #endif
  224607. }
  224608. }
  224609. void Thread::setCurrentThreadName (const String& /*name*/)
  224610. {
  224611. }
  224612. bool Thread::setThreadPriority (void* handle, int priority)
  224613. {
  224614. struct sched_param param;
  224615. int policy;
  224616. priority = jlimit (0, 10, priority);
  224617. if (handle == 0)
  224618. handle = (void*) pthread_self();
  224619. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  224620. return false;
  224621. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  224622. const int minPriority = sched_get_priority_min (policy);
  224623. const int maxPriority = sched_get_priority_max (policy);
  224624. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  224625. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  224626. }
  224627. Thread::ThreadID Thread::getCurrentThreadId()
  224628. {
  224629. return (ThreadID) pthread_self();
  224630. }
  224631. void Thread::yield()
  224632. {
  224633. sched_yield();
  224634. }
  224635. /* Remove this macro if you're having problems compiling the cpu affinity
  224636. calls (the API for these has changed about quite a bit in various Linux
  224637. versions, and a lot of distros seem to ship with obsolete versions)
  224638. */
  224639. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  224640. #define SUPPORT_AFFINITIES 1
  224641. #endif
  224642. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  224643. {
  224644. #if SUPPORT_AFFINITIES
  224645. cpu_set_t affinity;
  224646. CPU_ZERO (&affinity);
  224647. for (int i = 0; i < 32; ++i)
  224648. if ((affinityMask & (1 << i)) != 0)
  224649. CPU_SET (i, &affinity);
  224650. /*
  224651. N.B. If this line causes a compile error, then you've probably not got the latest
  224652. version of glibc installed.
  224653. If you don't want to update your copy of glibc and don't care about cpu affinities,
  224654. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  224655. */
  224656. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  224657. sched_yield();
  224658. #else
  224659. /* affinities aren't supported because either the appropriate header files weren't found,
  224660. or the SUPPORT_AFFINITIES macro was turned off
  224661. */
  224662. jassertfalse;
  224663. (void) affinityMask;
  224664. #endif
  224665. }
  224666. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224667. /*** Start of inlined file: juce_mac_Files.mm ***/
  224668. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224669. // compiled on its own).
  224670. #if JUCE_INCLUDED_FILE
  224671. /*
  224672. Note that a lot of methods that you'd expect to find in this file actually
  224673. live in juce_posix_SharedCode.h!
  224674. */
  224675. bool File::copyInternal (const File& dest) const
  224676. {
  224677. const ScopedAutoReleasePool pool;
  224678. NSFileManager* fm = [NSFileManager defaultManager];
  224679. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224680. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224681. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224682. toPath: juceStringToNS (dest.getFullPathName())
  224683. error: nil];
  224684. #else
  224685. && [fm copyPath: juceStringToNS (fullPath)
  224686. toPath: juceStringToNS (dest.getFullPathName())
  224687. handler: nil];
  224688. #endif
  224689. }
  224690. void File::findFileSystemRoots (Array<File>& destArray)
  224691. {
  224692. destArray.add (File ("/"));
  224693. }
  224694. namespace FileHelpers
  224695. {
  224696. bool isFileOnDriveType (const File& f, const char* const* types)
  224697. {
  224698. struct statfs buf;
  224699. if (juce_doStatFS (f, buf))
  224700. {
  224701. const String type (buf.f_fstypename);
  224702. while (*types != 0)
  224703. if (type.equalsIgnoreCase (*types++))
  224704. return true;
  224705. }
  224706. return false;
  224707. }
  224708. bool isHiddenFile (const String& path)
  224709. {
  224710. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  224711. const ScopedAutoReleasePool pool;
  224712. NSNumber* hidden = nil;
  224713. NSError* err = nil;
  224714. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  224715. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  224716. && [hidden boolValue];
  224717. #else
  224718. #if JUCE_IOS
  224719. return File (path).getFileName().startsWithChar ('.');
  224720. #else
  224721. FSRef ref;
  224722. LSItemInfoRecord info;
  224723. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8().getAddress(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  224724. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  224725. && (info.flags & kLSItemInfoIsInvisible) != 0;
  224726. #endif
  224727. #endif
  224728. }
  224729. #if JUCE_IOS
  224730. const String getIOSSystemLocation (NSSearchPathDirectory type)
  224731. {
  224732. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  224733. objectAtIndex: 0]);
  224734. }
  224735. #endif
  224736. bool launchExecutable (const String& pathAndArguments)
  224737. {
  224738. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224739. const int cpid = fork();
  224740. if (cpid == 0)
  224741. {
  224742. // Child process
  224743. if (execve (argv[0], (char**) argv, 0) < 0)
  224744. exit (0);
  224745. }
  224746. else
  224747. {
  224748. if (cpid < 0)
  224749. return false;
  224750. }
  224751. return true;
  224752. }
  224753. }
  224754. bool File::isOnCDRomDrive() const
  224755. {
  224756. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224757. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  224758. }
  224759. bool File::isOnHardDisk() const
  224760. {
  224761. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224762. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  224763. }
  224764. bool File::isOnRemovableDrive() const
  224765. {
  224766. #if JUCE_IOS
  224767. return false; // xxx is this possible?
  224768. #else
  224769. const ScopedAutoReleasePool pool;
  224770. BOOL removable = false;
  224771. [[NSWorkspace sharedWorkspace]
  224772. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224773. isRemovable: &removable
  224774. isWritable: nil
  224775. isUnmountable: nil
  224776. description: nil
  224777. type: nil];
  224778. return removable;
  224779. #endif
  224780. }
  224781. bool File::isHidden() const
  224782. {
  224783. return FileHelpers::isHiddenFile (getFullPathName());
  224784. }
  224785. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224786. const File File::getSpecialLocation (const SpecialLocationType type)
  224787. {
  224788. const ScopedAutoReleasePool pool;
  224789. String resultPath;
  224790. switch (type)
  224791. {
  224792. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  224793. #if JUCE_IOS
  224794. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  224795. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  224796. case tempDirectory:
  224797. {
  224798. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  224799. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  224800. tmp.createDirectory();
  224801. return tmp.getFullPathName();
  224802. }
  224803. #else
  224804. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  224805. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  224806. case tempDirectory:
  224807. {
  224808. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224809. tmp.createDirectory();
  224810. return tmp.getFullPathName();
  224811. }
  224812. #endif
  224813. case userMusicDirectory: resultPath = "~/Music"; break;
  224814. case userMoviesDirectory: resultPath = "~/Movies"; break;
  224815. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  224816. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  224817. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  224818. case invokedExecutableFile:
  224819. if (juce_Argv0 != 0)
  224820. return File (String::fromUTF8 (juce_Argv0));
  224821. // deliberate fall-through...
  224822. case currentExecutableFile:
  224823. return juce_getExecutableFile();
  224824. case currentApplicationFile:
  224825. {
  224826. const File exe (juce_getExecutableFile());
  224827. const File parent (exe.getParentDirectory());
  224828. #if JUCE_IOS
  224829. return parent;
  224830. #else
  224831. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224832. ? parent.getParentDirectory().getParentDirectory()
  224833. : exe;
  224834. #endif
  224835. }
  224836. case hostApplicationPath:
  224837. {
  224838. unsigned int size = 8192;
  224839. HeapBlock<char> buffer;
  224840. buffer.calloc (size + 8);
  224841. _NSGetExecutablePath (buffer.getData(), &size);
  224842. return String::fromUTF8 (buffer, size);
  224843. }
  224844. default:
  224845. jassertfalse; // unknown type?
  224846. break;
  224847. }
  224848. if (resultPath.isNotEmpty())
  224849. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224850. return File::nonexistent;
  224851. }
  224852. const String File::getVersion() const
  224853. {
  224854. const ScopedAutoReleasePool pool;
  224855. String result;
  224856. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224857. if (bundle != 0)
  224858. {
  224859. NSDictionary* info = [bundle infoDictionary];
  224860. if (info != 0)
  224861. {
  224862. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224863. if (name != nil)
  224864. result = nsStringToJuce (name);
  224865. }
  224866. }
  224867. return result;
  224868. }
  224869. const File File::getLinkedTarget() const
  224870. {
  224871. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224872. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224873. #else
  224874. // (the cast here avoids a deprecation warning)
  224875. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224876. #endif
  224877. if (dest != nil)
  224878. return File (nsStringToJuce (dest));
  224879. return *this;
  224880. }
  224881. bool File::moveToTrash() const
  224882. {
  224883. if (! exists())
  224884. return true;
  224885. #if JUCE_IOS
  224886. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224887. #else
  224888. const ScopedAutoReleasePool pool;
  224889. NSString* p = juceStringToNS (getFullPathName());
  224890. return [[NSWorkspace sharedWorkspace]
  224891. performFileOperation: NSWorkspaceRecycleOperation
  224892. source: [p stringByDeletingLastPathComponent]
  224893. destination: @""
  224894. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224895. tag: nil ];
  224896. #endif
  224897. }
  224898. class DirectoryIterator::NativeIterator::Pimpl
  224899. {
  224900. public:
  224901. Pimpl (const File& directory, const String& wildCard_)
  224902. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224903. wildCard (wildCard_),
  224904. enumerator (0)
  224905. {
  224906. const ScopedAutoReleasePool pool;
  224907. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224908. wildcardUTF8 = wildCard.toUTF8();
  224909. }
  224910. ~Pimpl()
  224911. {
  224912. [enumerator release];
  224913. }
  224914. bool next (String& filenameFound,
  224915. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224916. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224917. {
  224918. const ScopedAutoReleasePool pool;
  224919. for (;;)
  224920. {
  224921. NSString* file;
  224922. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224923. return false;
  224924. [enumerator skipDescendents];
  224925. filenameFound = nsStringToJuce (file);
  224926. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224927. continue;
  224928. const String path (parentDir + filenameFound);
  224929. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  224930. if (isHidden != 0)
  224931. *isHidden = FileHelpers::isHiddenFile (path);
  224932. return true;
  224933. }
  224934. }
  224935. private:
  224936. String parentDir, wildCard;
  224937. const char* wildcardUTF8;
  224938. NSDirectoryEnumerator* enumerator;
  224939. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  224940. };
  224941. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224942. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224943. {
  224944. }
  224945. DirectoryIterator::NativeIterator::~NativeIterator()
  224946. {
  224947. }
  224948. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224949. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224950. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224951. {
  224952. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224953. }
  224954. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224955. {
  224956. #if JUCE_IOS
  224957. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224958. #else
  224959. const ScopedAutoReleasePool pool;
  224960. if (parameters.isEmpty())
  224961. {
  224962. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224963. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224964. }
  224965. bool ok = false;
  224966. if (PlatformUtilities::isBundle (fileName))
  224967. {
  224968. NSMutableArray* urls = [NSMutableArray array];
  224969. StringArray docs;
  224970. docs.addTokens (parameters, true);
  224971. for (int i = 0; i < docs.size(); ++i)
  224972. [urls addObject: juceStringToNS (docs[i])];
  224973. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224974. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224975. options: 0
  224976. additionalEventParamDescriptor: nil
  224977. launchIdentifiers: nil];
  224978. }
  224979. else if (File (fileName).exists())
  224980. {
  224981. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  224982. }
  224983. return ok;
  224984. #endif
  224985. }
  224986. void File::revealToUser() const
  224987. {
  224988. #if ! JUCE_IOS
  224989. if (exists())
  224990. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224991. else if (getParentDirectory().exists())
  224992. getParentDirectory().revealToUser();
  224993. #endif
  224994. }
  224995. #if ! JUCE_IOS
  224996. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224997. {
  224998. return FSPathMakeRef (reinterpret_cast <const UInt8*> (path.toUTF8().getAddress()), destFSRef, 0) == noErr;
  224999. }
  225000. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225001. {
  225002. char path [2048];
  225003. zerostruct (path);
  225004. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225005. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225006. return String::empty;
  225007. }
  225008. #endif
  225009. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225010. {
  225011. const ScopedAutoReleasePool pool;
  225012. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225013. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225014. #else
  225015. // (the cast here avoids a deprecation warning)
  225016. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225017. #endif
  225018. return [fileDict fileHFSTypeCode];
  225019. }
  225020. bool PlatformUtilities::isBundle (const String& filename)
  225021. {
  225022. #if JUCE_IOS
  225023. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225024. #else
  225025. const ScopedAutoReleasePool pool;
  225026. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225027. #endif
  225028. }
  225029. #endif
  225030. /*** End of inlined file: juce_mac_Files.mm ***/
  225031. #if JUCE_IOS
  225032. /*** Start of inlined file: juce_ios_MiscUtilities.mm ***/
  225033. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225034. // compiled on its own).
  225035. #if JUCE_INCLUDED_FILE
  225036. END_JUCE_NAMESPACE
  225037. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225038. {
  225039. }
  225040. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225041. - (void) applicationWillTerminate: (UIApplication*) application;
  225042. @end
  225043. @implementation JuceAppStartupDelegate
  225044. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225045. {
  225046. initialiseJuce_GUI();
  225047. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225048. exit (0);
  225049. }
  225050. - (void) applicationWillTerminate: (UIApplication*) application
  225051. {
  225052. JUCEApplication::appWillTerminateByForce();
  225053. }
  225054. @end
  225055. BEGIN_JUCE_NAMESPACE
  225056. int juce_iOSMain (int argc, const char* argv[])
  225057. {
  225058. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225059. }
  225060. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225061. {
  225062. pool = [[NSAutoreleasePool alloc] init];
  225063. }
  225064. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225065. {
  225066. [((NSAutoreleasePool*) pool) release];
  225067. }
  225068. void PlatformUtilities::beep()
  225069. {
  225070. //xxx
  225071. //AudioServicesPlaySystemSound ();
  225072. }
  225073. void PlatformUtilities::addItemToDock (const File& file)
  225074. {
  225075. }
  225076. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225077. END_JUCE_NAMESPACE
  225078. @interface JuceAlertBoxDelegate : NSObject
  225079. {
  225080. @public
  225081. bool clickedOk;
  225082. }
  225083. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225084. @end
  225085. @implementation JuceAlertBoxDelegate
  225086. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225087. {
  225088. clickedOk = (buttonIndex == 0);
  225089. alertView.hidden = true;
  225090. }
  225091. @end
  225092. BEGIN_JUCE_NAMESPACE
  225093. // (This function is used directly by other bits of code)
  225094. bool juce_iPhoneShowModalAlert (const String& title,
  225095. const String& bodyText,
  225096. NSString* okButtonText,
  225097. NSString* cancelButtonText)
  225098. {
  225099. const ScopedAutoReleasePool pool;
  225100. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225101. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225102. message: juceStringToNS (bodyText)
  225103. delegate: callback
  225104. cancelButtonTitle: okButtonText
  225105. otherButtonTitles: cancelButtonText, nil];
  225106. [alert retain];
  225107. [alert show];
  225108. while (! alert.hidden && alert.superview != nil)
  225109. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225110. const bool result = callback->clickedOk;
  225111. [alert release];
  225112. [callback release];
  225113. return result;
  225114. }
  225115. bool AlertWindow::showNativeDialogBox (const String& title,
  225116. const String& bodyText,
  225117. bool isOkCancel)
  225118. {
  225119. return juce_iPhoneShowModalAlert (title, bodyText,
  225120. @"OK",
  225121. isOkCancel ? @"Cancel" : nil);
  225122. }
  225123. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225124. {
  225125. jassertfalse; // no such thing on the iphone!
  225126. return false;
  225127. }
  225128. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225129. {
  225130. jassertfalse; // no such thing on the iphone!
  225131. return false;
  225132. }
  225133. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225134. {
  225135. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225136. }
  225137. bool Desktop::isScreenSaverEnabled()
  225138. {
  225139. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225140. }
  225141. #endif
  225142. #endif
  225143. /*** End of inlined file: juce_ios_MiscUtilities.mm ***/
  225144. #else
  225145. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225146. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225147. // compiled on its own).
  225148. #if JUCE_INCLUDED_FILE
  225149. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225150. {
  225151. pool = [[NSAutoreleasePool alloc] init];
  225152. }
  225153. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225154. {
  225155. [((NSAutoreleasePool*) pool) release];
  225156. }
  225157. void PlatformUtilities::beep()
  225158. {
  225159. NSBeep();
  225160. }
  225161. void PlatformUtilities::addItemToDock (const File& file)
  225162. {
  225163. // check that it's not already there...
  225164. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225165. .containsIgnoreCase (file.getFullPathName()))
  225166. {
  225167. 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>"
  225168. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225169. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225170. }
  225171. }
  225172. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225173. bool AlertWindow::showNativeDialogBox (const String& title,
  225174. const String& bodyText,
  225175. bool isOkCancel)
  225176. {
  225177. const ScopedAutoReleasePool pool;
  225178. return NSRunAlertPanel (juceStringToNS (title),
  225179. juceStringToNS (bodyText),
  225180. @"Ok",
  225181. isOkCancel ? @"Cancel" : nil,
  225182. nil) == NSAlertDefaultReturn;
  225183. }
  225184. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225185. {
  225186. if (files.size() == 0)
  225187. return false;
  225188. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225189. if (draggingSource == 0)
  225190. {
  225191. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225192. return false;
  225193. }
  225194. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225195. if (sourceComp == 0)
  225196. {
  225197. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225198. return false;
  225199. }
  225200. const ScopedAutoReleasePool pool;
  225201. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225202. if (view == 0)
  225203. return false;
  225204. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225205. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225206. owner: nil];
  225207. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225208. for (int i = 0; i < files.size(); ++i)
  225209. [filesArray addObject: juceStringToNS (files[i])];
  225210. [pboard setPropertyList: filesArray
  225211. forType: NSFilenamesPboardType];
  225212. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225213. fromView: nil];
  225214. dragPosition.x -= 16;
  225215. dragPosition.y -= 16;
  225216. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225217. at: dragPosition
  225218. offset: NSMakeSize (0, 0)
  225219. event: [[view window] currentEvent]
  225220. pasteboard: pboard
  225221. source: view
  225222. slideBack: YES];
  225223. return true;
  225224. }
  225225. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225226. {
  225227. jassertfalse; // not implemented!
  225228. return false;
  225229. }
  225230. bool Desktop::canUseSemiTransparentWindows() throw()
  225231. {
  225232. return true;
  225233. }
  225234. const Point<int> MouseInputSource::getCurrentMousePosition()
  225235. {
  225236. const ScopedAutoReleasePool pool;
  225237. const NSPoint p ([NSEvent mouseLocation]);
  225238. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225239. }
  225240. void Desktop::setMousePosition (const Point<int>& newPosition)
  225241. {
  225242. // this rubbish needs to be done around the warp call, to avoid causing a
  225243. // bizarre glitch..
  225244. CGAssociateMouseAndMouseCursorPosition (false);
  225245. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225246. CGAssociateMouseAndMouseCursorPosition (true);
  225247. }
  225248. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225249. {
  225250. return upright;
  225251. }
  225252. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225253. class ScreenSaverDefeater : public Timer,
  225254. public DeletedAtShutdown
  225255. {
  225256. public:
  225257. ScreenSaverDefeater()
  225258. {
  225259. startTimer (10000);
  225260. timerCallback();
  225261. }
  225262. ~ScreenSaverDefeater() {}
  225263. void timerCallback()
  225264. {
  225265. if (Process::isForegroundProcess())
  225266. UpdateSystemActivity (UsrActivity);
  225267. }
  225268. };
  225269. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225270. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225271. {
  225272. if (isEnabled)
  225273. deleteAndZero (screenSaverDefeater);
  225274. else if (screenSaverDefeater == 0)
  225275. screenSaverDefeater = new ScreenSaverDefeater();
  225276. }
  225277. bool Desktop::isScreenSaverEnabled()
  225278. {
  225279. return screenSaverDefeater == 0;
  225280. }
  225281. #else
  225282. static IOPMAssertionID screenSaverDisablerID = 0;
  225283. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225284. {
  225285. if (isEnabled)
  225286. {
  225287. if (screenSaverDisablerID != 0)
  225288. {
  225289. IOPMAssertionRelease (screenSaverDisablerID);
  225290. screenSaverDisablerID = 0;
  225291. }
  225292. }
  225293. else
  225294. {
  225295. if (screenSaverDisablerID == 0)
  225296. {
  225297. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225298. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225299. CFSTR ("Juce"), &screenSaverDisablerID);
  225300. #else
  225301. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225302. &screenSaverDisablerID);
  225303. #endif
  225304. }
  225305. }
  225306. }
  225307. bool Desktop::isScreenSaverEnabled()
  225308. {
  225309. return screenSaverDisablerID == 0;
  225310. }
  225311. #endif
  225312. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225313. {
  225314. const ScopedAutoReleasePool pool;
  225315. monitorCoords.clear();
  225316. NSArray* screens = [NSScreen screens];
  225317. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225318. for (unsigned int i = 0; i < [screens count]; ++i)
  225319. {
  225320. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225321. NSRect r = clipToWorkArea ? [s visibleFrame]
  225322. : [s frame];
  225323. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225324. monitorCoords.add (convertToRectInt (r));
  225325. }
  225326. jassert (monitorCoords.size() > 0);
  225327. }
  225328. #endif
  225329. #endif
  225330. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225331. #endif
  225332. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225333. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225334. // compiled on its own).
  225335. #if JUCE_INCLUDED_FILE
  225336. void Logger::outputDebugString (const String& text)
  225337. {
  225338. std::cerr << text << std::endl;
  225339. }
  225340. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225341. {
  225342. static char testResult = 0;
  225343. if (testResult == 0)
  225344. {
  225345. struct kinfo_proc info;
  225346. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225347. size_t sz = sizeof (info);
  225348. sysctl (m, 4, &info, &sz, 0, 0);
  225349. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225350. }
  225351. return testResult > 0;
  225352. }
  225353. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225354. {
  225355. return juce_isRunningUnderDebugger();
  225356. }
  225357. #endif
  225358. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225359. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225360. #if JUCE_IOS
  225361. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225362. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225363. // compiled on its own).
  225364. #if JUCE_INCLUDED_FILE
  225365. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225366. #define SUPPORT_10_4_FONTS 1
  225367. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225368. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225369. #define SUPPORT_ONLY_10_4_FONTS 1
  225370. #endif
  225371. END_JUCE_NAMESPACE
  225372. @interface NSFont (PrivateHack)
  225373. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225374. @end
  225375. BEGIN_JUCE_NAMESPACE
  225376. #endif
  225377. class MacTypeface : public Typeface
  225378. {
  225379. public:
  225380. MacTypeface (const Font& font)
  225381. : Typeface (font.getTypefaceName())
  225382. {
  225383. const ScopedAutoReleasePool pool;
  225384. renderingTransform = CGAffineTransformIdentity;
  225385. bool needsItalicTransform = false;
  225386. #if JUCE_IOS
  225387. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225388. if (font.isItalic() || font.isBold())
  225389. {
  225390. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225391. for (NSString* i in familyFonts)
  225392. {
  225393. const String fn (nsStringToJuce (i));
  225394. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225395. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225396. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225397. || afterDash.containsIgnoreCase ("italic")
  225398. || fn.endsWithIgnoreCase ("oblique")
  225399. || fn.endsWithIgnoreCase ("italic");
  225400. if (probablyBold == font.isBold()
  225401. && probablyItalic == font.isItalic())
  225402. {
  225403. fontName = i;
  225404. needsItalicTransform = false;
  225405. break;
  225406. }
  225407. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225408. {
  225409. fontName = i;
  225410. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225411. }
  225412. }
  225413. if (needsItalicTransform)
  225414. renderingTransform.c = 0.15f;
  225415. }
  225416. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225417. const int ascender = abs (CGFontGetAscent (fontRef));
  225418. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225419. ascent = ascender / totalHeight;
  225420. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225421. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225422. #else
  225423. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225424. if (font.isItalic())
  225425. {
  225426. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225427. toHaveTrait: NSItalicFontMask];
  225428. if (newFont == nsFont)
  225429. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225430. nsFont = newFont;
  225431. }
  225432. if (font.isBold())
  225433. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225434. [nsFont retain];
  225435. ascent = std::abs ((float) [nsFont ascender]);
  225436. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225437. ascent /= totalSize;
  225438. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225439. if (needsItalicTransform)
  225440. {
  225441. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225442. renderingTransform.c = 0.15f;
  225443. }
  225444. #if SUPPORT_ONLY_10_4_FONTS
  225445. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225446. if (atsFont == 0)
  225447. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225448. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225449. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225450. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225451. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225452. #else
  225453. #if SUPPORT_10_4_FONTS
  225454. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225455. {
  225456. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225457. if (atsFont == 0)
  225458. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225459. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225460. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225461. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225462. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225463. }
  225464. else
  225465. #endif
  225466. {
  225467. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225468. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225469. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225470. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225471. }
  225472. #endif
  225473. #endif
  225474. }
  225475. ~MacTypeface()
  225476. {
  225477. #if ! JUCE_IOS
  225478. [nsFont release];
  225479. #endif
  225480. if (fontRef != 0)
  225481. CGFontRelease (fontRef);
  225482. }
  225483. float getAscent() const
  225484. {
  225485. return ascent;
  225486. }
  225487. float getDescent() const
  225488. {
  225489. return 1.0f - ascent;
  225490. }
  225491. float getStringWidth (const String& text)
  225492. {
  225493. if (fontRef == 0 || text.isEmpty())
  225494. return 0;
  225495. const int length = text.length();
  225496. HeapBlock <CGGlyph> glyphs;
  225497. createGlyphsForString (text.getCharPointer(), length, glyphs);
  225498. float x = 0;
  225499. #if SUPPORT_ONLY_10_4_FONTS
  225500. HeapBlock <NSSize> advances (length);
  225501. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225502. for (int i = 0; i < length; ++i)
  225503. x += advances[i].width;
  225504. #else
  225505. #if SUPPORT_10_4_FONTS
  225506. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225507. {
  225508. HeapBlock <NSSize> advances (length);
  225509. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225510. for (int i = 0; i < length; ++i)
  225511. x += advances[i].width;
  225512. }
  225513. else
  225514. #endif
  225515. {
  225516. HeapBlock <int> advances (length);
  225517. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225518. for (int i = 0; i < length; ++i)
  225519. x += advances[i];
  225520. }
  225521. #endif
  225522. return x * unitsToHeightScaleFactor;
  225523. }
  225524. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225525. {
  225526. xOffsets.add (0);
  225527. if (fontRef == 0 || text.isEmpty())
  225528. return;
  225529. const int length = text.length();
  225530. HeapBlock <CGGlyph> glyphs;
  225531. createGlyphsForString (text.getCharPointer(), length, glyphs);
  225532. #if SUPPORT_ONLY_10_4_FONTS
  225533. HeapBlock <NSSize> advances (length);
  225534. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225535. int x = 0;
  225536. for (int i = 0; i < length; ++i)
  225537. {
  225538. x += advances[i].width;
  225539. xOffsets.add (x * unitsToHeightScaleFactor);
  225540. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225541. }
  225542. #else
  225543. #if SUPPORT_10_4_FONTS
  225544. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225545. {
  225546. HeapBlock <NSSize> advances (length);
  225547. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225548. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225549. float x = 0;
  225550. for (int i = 0; i < length; ++i)
  225551. {
  225552. x += advances[i].width;
  225553. xOffsets.add (x * unitsToHeightScaleFactor);
  225554. resultGlyphs.add (nsGlyphs[i]);
  225555. }
  225556. }
  225557. else
  225558. #endif
  225559. {
  225560. HeapBlock <int> advances (length);
  225561. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225562. {
  225563. int x = 0;
  225564. for (int i = 0; i < length; ++i)
  225565. {
  225566. x += advances [i];
  225567. xOffsets.add (x * unitsToHeightScaleFactor);
  225568. resultGlyphs.add (glyphs[i]);
  225569. }
  225570. }
  225571. }
  225572. #endif
  225573. }
  225574. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225575. {
  225576. #if JUCE_IOS
  225577. return false;
  225578. #else
  225579. if (nsFont == 0)
  225580. return false;
  225581. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225582. jassert (path.isEmpty());
  225583. const ScopedAutoReleasePool pool;
  225584. NSBezierPath* bez = [NSBezierPath bezierPath];
  225585. [bez moveToPoint: NSMakePoint (0, 0)];
  225586. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225587. inFont: nsFont];
  225588. for (int i = 0; i < [bez elementCount]; ++i)
  225589. {
  225590. NSPoint p[3];
  225591. switch ([bez elementAtIndex: i associatedPoints: p])
  225592. {
  225593. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  225594. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  225595. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  225596. (float) p[1].x, (float) -p[1].y,
  225597. (float) p[2].x, (float) -p[2].y); break;
  225598. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  225599. default: jassertfalse; break;
  225600. }
  225601. }
  225602. path.applyTransform (pathTransform);
  225603. return true;
  225604. #endif
  225605. }
  225606. CGFontRef fontRef;
  225607. float fontHeightToCGSizeFactor;
  225608. CGAffineTransform renderingTransform;
  225609. private:
  225610. float ascent, unitsToHeightScaleFactor;
  225611. #if JUCE_IOS
  225612. #else
  225613. NSFont* nsFont;
  225614. AffineTransform pathTransform;
  225615. #endif
  225616. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  225617. {
  225618. #if SUPPORT_10_4_FONTS
  225619. #if ! SUPPORT_ONLY_10_4_FONTS
  225620. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225621. #endif
  225622. {
  225623. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225624. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225625. for (int i = 0; i < length; ++i)
  225626. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  225627. return;
  225628. }
  225629. #endif
  225630. #if ! SUPPORT_ONLY_10_4_FONTS
  225631. if (charToGlyphMapper == 0)
  225632. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225633. glyphs.malloc (length);
  225634. for (int i = 0; i < length; ++i)
  225635. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  225636. #endif
  225637. }
  225638. #if ! SUPPORT_ONLY_10_4_FONTS
  225639. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225640. class CharToGlyphMapper
  225641. {
  225642. public:
  225643. CharToGlyphMapper (CGFontRef fontRef)
  225644. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225645. idRangeOffset (0), glyphIndexes (0)
  225646. {
  225647. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225648. if (cmapTable != 0)
  225649. {
  225650. const int numSubtables = getValue16 (cmapTable, 2);
  225651. for (int i = 0; i < numSubtables; ++i)
  225652. {
  225653. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225654. {
  225655. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225656. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225657. {
  225658. const int length = getValue16 (cmapTable, offset + 2);
  225659. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225660. segCount = segCountX2 / 2;
  225661. const int endCodeOffset = offset + 14;
  225662. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225663. const int idDeltaOffset = startCodeOffset + segCountX2;
  225664. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225665. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225666. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225667. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225668. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225669. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225670. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225671. }
  225672. break;
  225673. }
  225674. }
  225675. CFRelease (cmapTable);
  225676. }
  225677. }
  225678. ~CharToGlyphMapper()
  225679. {
  225680. if (endCode != 0)
  225681. {
  225682. CFRelease (endCode);
  225683. CFRelease (startCode);
  225684. CFRelease (idDelta);
  225685. CFRelease (idRangeOffset);
  225686. CFRelease (glyphIndexes);
  225687. }
  225688. }
  225689. int getGlyphForCharacter (const juce_wchar c) const
  225690. {
  225691. for (int i = 0; i < segCount; ++i)
  225692. {
  225693. if (getValue16 (endCode, i * 2) >= c)
  225694. {
  225695. const int start = getValue16 (startCode, i * 2);
  225696. if (start > c)
  225697. break;
  225698. const int delta = getValue16 (idDelta, i * 2);
  225699. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225700. if (rangeOffset == 0)
  225701. return delta + c;
  225702. else
  225703. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225704. }
  225705. }
  225706. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225707. return jmax (-1, (int) c - 29);
  225708. }
  225709. private:
  225710. int segCount;
  225711. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225712. static uint16 getValue16 (CFDataRef data, const int index)
  225713. {
  225714. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225715. }
  225716. static uint32 getValue32 (CFDataRef data, const int index)
  225717. {
  225718. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225719. }
  225720. };
  225721. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225722. #endif
  225723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  225724. };
  225725. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225726. {
  225727. return new MacTypeface (font);
  225728. }
  225729. const StringArray Font::findAllTypefaceNames()
  225730. {
  225731. StringArray names;
  225732. const ScopedAutoReleasePool pool;
  225733. #if JUCE_IOS
  225734. NSArray* fonts = [UIFont familyNames];
  225735. #else
  225736. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225737. #endif
  225738. for (unsigned int i = 0; i < [fonts count]; ++i)
  225739. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225740. names.sort (true);
  225741. return names;
  225742. }
  225743. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  225744. {
  225745. #if JUCE_IOS
  225746. defaultSans = "Helvetica";
  225747. defaultSerif = "Times New Roman";
  225748. defaultFixed = "Courier New";
  225749. #else
  225750. defaultSans = "Lucida Grande";
  225751. defaultSerif = "Times New Roman";
  225752. defaultFixed = "Monaco";
  225753. #endif
  225754. defaultFallback = "Arial Unicode MS";
  225755. }
  225756. #endif
  225757. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225758. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225759. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225760. // compiled on its own).
  225761. #if JUCE_INCLUDED_FILE
  225762. class CoreGraphicsImage : public Image::SharedImage
  225763. {
  225764. public:
  225765. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225766. : Image::SharedImage (format_, width_, height_)
  225767. {
  225768. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225769. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225770. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225771. imageData = imageDataAllocated;
  225772. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225773. : CGColorSpaceCreateDeviceRGB();
  225774. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225775. colourSpace, getCGImageFlags (format_));
  225776. CGColorSpaceRelease (colourSpace);
  225777. }
  225778. ~CoreGraphicsImage()
  225779. {
  225780. CGContextRelease (context);
  225781. }
  225782. Image::ImageType getType() const { return Image::NativeImage; }
  225783. LowLevelGraphicsContext* createLowLevelContext();
  225784. SharedImage* clone()
  225785. {
  225786. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225787. memcpy (im->imageData, imageData, lineStride * height);
  225788. return im;
  225789. }
  225790. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  225791. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  225792. {
  225793. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225794. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225795. {
  225796. return CGBitmapContextCreateImage (nativeImage->context);
  225797. }
  225798. else
  225799. {
  225800. const Image::BitmapData srcData (juceImage, false);
  225801. CGDataProviderRef provider;
  225802. if (mustOutliveSource)
  225803. {
  225804. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  225805. provider = CGDataProviderCreateWithCFData (data);
  225806. CFRelease (data);
  225807. }
  225808. else
  225809. {
  225810. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225811. }
  225812. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225813. 8, srcData.pixelStride * 8, srcData.lineStride,
  225814. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225815. 0, true, kCGRenderingIntentDefault);
  225816. CGDataProviderRelease (provider);
  225817. return imageRef;
  225818. }
  225819. }
  225820. #if JUCE_MAC
  225821. static NSImage* createNSImage (const Image& image)
  225822. {
  225823. const ScopedAutoReleasePool pool;
  225824. NSImage* im = [[NSImage alloc] init];
  225825. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225826. [im lockFocus];
  225827. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225828. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  225829. CGColorSpaceRelease (colourSpace);
  225830. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225831. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225832. CGImageRelease (imageRef);
  225833. [im unlockFocus];
  225834. return im;
  225835. }
  225836. #endif
  225837. CGContextRef context;
  225838. HeapBlock<uint8> imageDataAllocated;
  225839. private:
  225840. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225841. {
  225842. #if JUCE_BIG_ENDIAN
  225843. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225844. #else
  225845. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225846. #endif
  225847. }
  225848. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  225849. };
  225850. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225851. {
  225852. #if USE_COREGRAPHICS_RENDERING
  225853. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225854. #else
  225855. return createSoftwareImage (format, width, height, clearImage);
  225856. #endif
  225857. }
  225858. class CoreGraphicsContext : public LowLevelGraphicsContext
  225859. {
  225860. public:
  225861. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225862. : context (context_),
  225863. flipHeight (flipHeight_),
  225864. lastClipRectIsValid (false),
  225865. state (new SavedState()),
  225866. numGradientLookupEntries (0)
  225867. {
  225868. CGContextRetain (context);
  225869. CGContextSaveGState(context);
  225870. CGContextSetShouldSmoothFonts (context, true);
  225871. CGContextSetShouldAntialias (context, true);
  225872. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225873. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225874. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225875. gradientCallbacks.version = 0;
  225876. gradientCallbacks.evaluate = gradientCallback;
  225877. gradientCallbacks.releaseInfo = 0;
  225878. setFont (Font());
  225879. }
  225880. ~CoreGraphicsContext()
  225881. {
  225882. CGContextRestoreGState (context);
  225883. CGContextRelease (context);
  225884. CGColorSpaceRelease (rgbColourSpace);
  225885. CGColorSpaceRelease (greyColourSpace);
  225886. }
  225887. bool isVectorDevice() const { return false; }
  225888. void setOrigin (int x, int y)
  225889. {
  225890. CGContextTranslateCTM (context, x, -y);
  225891. if (lastClipRectIsValid)
  225892. lastClipRect.translate (-x, -y);
  225893. }
  225894. void addTransform (const AffineTransform& transform)
  225895. {
  225896. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  225897. .translated (0, flipHeight)
  225898. .followedBy (transform)
  225899. .translated (0, -flipHeight)
  225900. .scaled (1.0f, -1.0f));
  225901. lastClipRectIsValid = false;
  225902. }
  225903. float getScaleFactor()
  225904. {
  225905. CGAffineTransform t = CGContextGetCTM (context);
  225906. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  225907. }
  225908. bool clipToRectangle (const Rectangle<int>& r)
  225909. {
  225910. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225911. if (lastClipRectIsValid)
  225912. {
  225913. // This is actually incorrect, because the actual clip region may be complex, and
  225914. // clipping its bounds to a rect may not be right... But, removing this shortcut
  225915. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  225916. // when calculating the resultant clip bounds, and makes the same mistake!
  225917. lastClipRect = lastClipRect.getIntersection (r);
  225918. return ! lastClipRect.isEmpty();
  225919. }
  225920. return ! isClipEmpty();
  225921. }
  225922. bool clipToRectangleList (const RectangleList& clipRegion)
  225923. {
  225924. if (clipRegion.isEmpty())
  225925. {
  225926. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225927. lastClipRectIsValid = true;
  225928. lastClipRect = Rectangle<int>();
  225929. return false;
  225930. }
  225931. else
  225932. {
  225933. const int numRects = clipRegion.getNumRectangles();
  225934. HeapBlock <CGRect> rects (numRects);
  225935. for (int i = 0; i < numRects; ++i)
  225936. {
  225937. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225938. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225939. }
  225940. CGContextClipToRects (context, rects, numRects);
  225941. lastClipRectIsValid = false;
  225942. return ! isClipEmpty();
  225943. }
  225944. }
  225945. void excludeClipRectangle (const Rectangle<int>& r)
  225946. {
  225947. RectangleList remaining (getClipBounds());
  225948. remaining.subtract (r);
  225949. clipToRectangleList (remaining);
  225950. lastClipRectIsValid = false;
  225951. }
  225952. void clipToPath (const Path& path, const AffineTransform& transform)
  225953. {
  225954. createPath (path, transform);
  225955. CGContextClip (context);
  225956. lastClipRectIsValid = false;
  225957. }
  225958. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  225959. {
  225960. if (! transform.isSingularity())
  225961. {
  225962. Image singleChannelImage (sourceImage);
  225963. if (sourceImage.getFormat() != Image::SingleChannel)
  225964. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225965. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  225966. flip();
  225967. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  225968. applyTransform (t);
  225969. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  225970. CGContextClipToMask (context, r, image);
  225971. applyTransform (t.inverted());
  225972. flip();
  225973. CGImageRelease (image);
  225974. lastClipRectIsValid = false;
  225975. }
  225976. }
  225977. bool clipRegionIntersects (const Rectangle<int>& r)
  225978. {
  225979. return getClipBounds().intersects (r);
  225980. }
  225981. const Rectangle<int> getClipBounds() const
  225982. {
  225983. if (! lastClipRectIsValid)
  225984. {
  225985. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225986. lastClipRectIsValid = true;
  225987. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225988. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225989. roundToInt (bounds.size.width),
  225990. roundToInt (bounds.size.height));
  225991. }
  225992. return lastClipRect;
  225993. }
  225994. bool isClipEmpty() const
  225995. {
  225996. return getClipBounds().isEmpty();
  225997. }
  225998. void saveState()
  225999. {
  226000. CGContextSaveGState (context);
  226001. stateStack.add (new SavedState (*state));
  226002. }
  226003. void restoreState()
  226004. {
  226005. CGContextRestoreGState (context);
  226006. SavedState* const top = stateStack.getLast();
  226007. if (top != 0)
  226008. {
  226009. state = top;
  226010. stateStack.removeLast (1, false);
  226011. lastClipRectIsValid = false;
  226012. }
  226013. else
  226014. {
  226015. jassertfalse; // trying to pop with an empty stack!
  226016. }
  226017. }
  226018. void beginTransparencyLayer (float opacity)
  226019. {
  226020. saveState();
  226021. CGContextSetAlpha (context, opacity);
  226022. CGContextBeginTransparencyLayer (context, 0);
  226023. }
  226024. void endTransparencyLayer()
  226025. {
  226026. CGContextEndTransparencyLayer (context);
  226027. restoreState();
  226028. }
  226029. void setFill (const FillType& fillType)
  226030. {
  226031. state->fillType = fillType;
  226032. if (fillType.isColour())
  226033. {
  226034. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226035. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226036. CGContextSetAlpha (context, 1.0f);
  226037. }
  226038. }
  226039. void setOpacity (float newOpacity)
  226040. {
  226041. state->fillType.setOpacity (newOpacity);
  226042. setFill (state->fillType);
  226043. }
  226044. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226045. {
  226046. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226047. ? kCGInterpolationLow
  226048. : kCGInterpolationHigh);
  226049. }
  226050. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226051. {
  226052. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226053. }
  226054. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226055. {
  226056. if (replaceExistingContents)
  226057. {
  226058. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226059. CGContextClearRect (context, cgRect);
  226060. #else
  226061. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226062. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226063. CGContextClearRect (context, cgRect);
  226064. else
  226065. #endif
  226066. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226067. #endif
  226068. fillCGRect (cgRect, false);
  226069. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226070. }
  226071. else
  226072. {
  226073. if (state->fillType.isColour())
  226074. {
  226075. CGContextFillRect (context, cgRect);
  226076. }
  226077. else if (state->fillType.isGradient())
  226078. {
  226079. CGContextSaveGState (context);
  226080. CGContextClipToRect (context, cgRect);
  226081. drawGradient();
  226082. CGContextRestoreGState (context);
  226083. }
  226084. else
  226085. {
  226086. CGContextSaveGState (context);
  226087. CGContextClipToRect (context, cgRect);
  226088. drawImage (state->fillType.image, state->fillType.transform, true);
  226089. CGContextRestoreGState (context);
  226090. }
  226091. }
  226092. }
  226093. void fillPath (const Path& path, const AffineTransform& transform)
  226094. {
  226095. CGContextSaveGState (context);
  226096. if (state->fillType.isColour())
  226097. {
  226098. flip();
  226099. applyTransform (transform);
  226100. createPath (path);
  226101. if (path.isUsingNonZeroWinding())
  226102. CGContextFillPath (context);
  226103. else
  226104. CGContextEOFillPath (context);
  226105. }
  226106. else
  226107. {
  226108. createPath (path, transform);
  226109. if (path.isUsingNonZeroWinding())
  226110. CGContextClip (context);
  226111. else
  226112. CGContextEOClip (context);
  226113. if (state->fillType.isGradient())
  226114. drawGradient();
  226115. else
  226116. drawImage (state->fillType.image, state->fillType.transform, true);
  226117. }
  226118. CGContextRestoreGState (context);
  226119. }
  226120. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226121. {
  226122. const int iw = sourceImage.getWidth();
  226123. const int ih = sourceImage.getHeight();
  226124. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  226125. CGContextSaveGState (context);
  226126. CGContextSetAlpha (context, state->fillType.getOpacity());
  226127. flip();
  226128. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226129. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226130. if (fillEntireClipAsTiles)
  226131. {
  226132. #if JUCE_IOS
  226133. CGContextDrawTiledImage (context, imageRect, image);
  226134. #else
  226135. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226136. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226137. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226138. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226139. CGContextDrawTiledImage (context, imageRect, image);
  226140. else
  226141. #endif
  226142. {
  226143. // Fallback to manually doing a tiled fill on 10.4
  226144. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226145. int x = 0, y = 0;
  226146. while (x > clip.origin.x) x -= iw;
  226147. while (y > clip.origin.y) y -= ih;
  226148. const int right = (int) (clip.origin.x + clip.size.width);
  226149. const int bottom = (int) (clip.origin.y + clip.size.height);
  226150. while (y < bottom)
  226151. {
  226152. for (int x2 = x; x2 < right; x2 += iw)
  226153. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226154. y += ih;
  226155. }
  226156. }
  226157. #endif
  226158. }
  226159. else
  226160. {
  226161. CGContextDrawImage (context, imageRect, image);
  226162. }
  226163. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226164. CGContextRestoreGState (context);
  226165. }
  226166. void drawLine (const Line<float>& line)
  226167. {
  226168. if (state->fillType.isColour())
  226169. {
  226170. CGContextSetLineCap (context, kCGLineCapSquare);
  226171. CGContextSetLineWidth (context, 1.0f);
  226172. CGContextSetRGBStrokeColor (context,
  226173. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226174. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226175. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226176. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226177. CGContextStrokeLineSegments (context, cgLine, 1);
  226178. }
  226179. else
  226180. {
  226181. Path p;
  226182. p.addLineSegment (line, 1.0f);
  226183. fillPath (p, AffineTransform::identity);
  226184. }
  226185. }
  226186. void drawVerticalLine (const int x, float top, float bottom)
  226187. {
  226188. if (state->fillType.isColour())
  226189. {
  226190. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226191. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226192. #else
  226193. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226194. // the x co-ord slightly to trick it..
  226195. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226196. #endif
  226197. }
  226198. else
  226199. {
  226200. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226201. }
  226202. }
  226203. void drawHorizontalLine (const int y, float left, float right)
  226204. {
  226205. if (state->fillType.isColour())
  226206. {
  226207. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226208. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226209. #else
  226210. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226211. // the x co-ord slightly to trick it..
  226212. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226213. #endif
  226214. }
  226215. else
  226216. {
  226217. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226218. }
  226219. }
  226220. void setFont (const Font& newFont)
  226221. {
  226222. if (state->font != newFont)
  226223. {
  226224. state->fontRef = 0;
  226225. state->font = newFont;
  226226. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226227. if (mf != 0)
  226228. {
  226229. state->fontRef = mf->fontRef;
  226230. CGContextSetFont (context, state->fontRef);
  226231. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226232. state->fontTransform = mf->renderingTransform;
  226233. state->fontTransform.a *= state->font.getHorizontalScale();
  226234. CGContextSetTextMatrix (context, state->fontTransform);
  226235. }
  226236. }
  226237. }
  226238. const Font getFont()
  226239. {
  226240. return state->font;
  226241. }
  226242. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226243. {
  226244. if (state->fontRef != 0 && state->fillType.isColour())
  226245. {
  226246. if (transform.isOnlyTranslation())
  226247. {
  226248. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226249. CGGlyph g = glyphNumber;
  226250. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226251. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226252. }
  226253. else
  226254. {
  226255. CGContextSaveGState (context);
  226256. flip();
  226257. applyTransform (transform);
  226258. CGAffineTransform t = state->fontTransform;
  226259. t.d = -t.d;
  226260. CGContextSetTextMatrix (context, t);
  226261. CGGlyph g = glyphNumber;
  226262. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226263. CGContextRestoreGState (context);
  226264. }
  226265. }
  226266. else
  226267. {
  226268. Path p;
  226269. Font& f = state->font;
  226270. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226271. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226272. .followedBy (transform));
  226273. }
  226274. }
  226275. private:
  226276. CGContextRef context;
  226277. const CGFloat flipHeight;
  226278. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226279. CGFunctionCallbacks gradientCallbacks;
  226280. mutable Rectangle<int> lastClipRect;
  226281. mutable bool lastClipRectIsValid;
  226282. struct SavedState
  226283. {
  226284. SavedState()
  226285. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226286. {
  226287. }
  226288. SavedState (const SavedState& other)
  226289. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226290. fontTransform (other.fontTransform)
  226291. {
  226292. }
  226293. FillType fillType;
  226294. Font font;
  226295. CGFontRef fontRef;
  226296. CGAffineTransform fontTransform;
  226297. };
  226298. ScopedPointer <SavedState> state;
  226299. OwnedArray <SavedState> stateStack;
  226300. HeapBlock <PixelARGB> gradientLookupTable;
  226301. int numGradientLookupEntries;
  226302. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226303. {
  226304. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226305. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226306. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226307. colour.unpremultiply();
  226308. outData[0] = colour.getRed() / 255.0f;
  226309. outData[1] = colour.getGreen() / 255.0f;
  226310. outData[2] = colour.getBlue() / 255.0f;
  226311. outData[3] = colour.getAlpha() / 255.0f;
  226312. }
  226313. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226314. {
  226315. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226316. CGShadingRef result = 0;
  226317. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226318. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226319. if (gradient.isRadial)
  226320. {
  226321. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226322. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226323. function, true, true);
  226324. }
  226325. else
  226326. {
  226327. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226328. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226329. function, true, true);
  226330. }
  226331. CGFunctionRelease (function);
  226332. return result;
  226333. }
  226334. void drawGradient()
  226335. {
  226336. flip();
  226337. applyTransform (state->fillType.transform);
  226338. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226339. // you draw a gradient with high quality interp enabled).
  226340. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226341. CGContextSetAlpha (context, state->fillType.getOpacity());
  226342. CGContextDrawShading (context, shading);
  226343. CGShadingRelease (shading);
  226344. }
  226345. void createPath (const Path& path) const
  226346. {
  226347. CGContextBeginPath (context);
  226348. Path::Iterator i (path);
  226349. while (i.next())
  226350. {
  226351. switch (i.elementType)
  226352. {
  226353. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226354. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226355. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226356. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226357. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226358. default: jassertfalse; break;
  226359. }
  226360. }
  226361. }
  226362. void createPath (const Path& path, const AffineTransform& transform) const
  226363. {
  226364. CGContextBeginPath (context);
  226365. Path::Iterator i (path);
  226366. while (i.next())
  226367. {
  226368. switch (i.elementType)
  226369. {
  226370. case Path::Iterator::startNewSubPath:
  226371. transform.transformPoint (i.x1, i.y1);
  226372. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226373. break;
  226374. case Path::Iterator::lineTo:
  226375. transform.transformPoint (i.x1, i.y1);
  226376. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226377. break;
  226378. case Path::Iterator::quadraticTo:
  226379. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226380. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226381. break;
  226382. case Path::Iterator::cubicTo:
  226383. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226384. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226385. break;
  226386. case Path::Iterator::closePath:
  226387. CGContextClosePath (context); break;
  226388. default:
  226389. jassertfalse;
  226390. break;
  226391. }
  226392. }
  226393. }
  226394. void flip() const
  226395. {
  226396. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226397. }
  226398. void applyTransform (const AffineTransform& transform) const
  226399. {
  226400. CGAffineTransform t;
  226401. t.a = transform.mat00;
  226402. t.b = transform.mat10;
  226403. t.c = transform.mat01;
  226404. t.d = transform.mat11;
  226405. t.tx = transform.mat02;
  226406. t.ty = transform.mat12;
  226407. CGContextConcatCTM (context, t);
  226408. }
  226409. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226410. };
  226411. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226412. {
  226413. return new CoreGraphicsContext (context, height);
  226414. }
  226415. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226416. const Image juce_loadWithCoreImage (InputStream& input)
  226417. {
  226418. MemoryBlock data;
  226419. input.readIntoMemoryBlock (data, -1);
  226420. #if JUCE_IOS
  226421. JUCE_AUTORELEASEPOOL
  226422. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226423. length: data.getSize()
  226424. freeWhenDone: NO]];
  226425. if (image != nil)
  226426. {
  226427. CGImageRef loadedImage = image.CGImage;
  226428. #else
  226429. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226430. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226431. CGDataProviderRelease (provider);
  226432. if (imageSource != 0)
  226433. {
  226434. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226435. CFRelease (imageSource);
  226436. #endif
  226437. if (loadedImage != 0)
  226438. {
  226439. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226440. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226441. && alphaInfo != kCGImageAlphaNoneSkipLast
  226442. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226443. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226444. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226445. hasAlphaChan, Image::NativeImage);
  226446. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226447. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226448. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226449. CGContextFlush (cgImage->context);
  226450. #if ! JUCE_IOS
  226451. CFRelease (loadedImage);
  226452. #endif
  226453. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226454. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226455. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226456. return image;
  226457. }
  226458. }
  226459. return Image::null;
  226460. }
  226461. #endif
  226462. #endif
  226463. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226464. /*** Start of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  226465. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226466. // compiled on its own).
  226467. #if JUCE_INCLUDED_FILE
  226468. class UIViewComponentPeer;
  226469. END_JUCE_NAMESPACE
  226470. #define JuceUIView MakeObjCClassName(JuceUIView)
  226471. @interface JuceUIView : UIView <UITextViewDelegate>
  226472. {
  226473. @public
  226474. UIViewComponentPeer* owner;
  226475. UITextView* hiddenTextView;
  226476. }
  226477. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226478. - (void) dealloc;
  226479. - (void) drawRect: (CGRect) r;
  226480. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226481. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226482. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226483. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226484. - (BOOL) becomeFirstResponder;
  226485. - (BOOL) resignFirstResponder;
  226486. - (BOOL) canBecomeFirstResponder;
  226487. - (void) asyncRepaint: (id) rect;
  226488. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226489. @end
  226490. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226491. @interface JuceUIViewController : UIViewController
  226492. {
  226493. }
  226494. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226495. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226496. @end
  226497. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226498. @interface JuceUIWindow : UIWindow
  226499. {
  226500. @private
  226501. UIViewComponentPeer* owner;
  226502. bool isZooming;
  226503. }
  226504. - (void) setOwner: (UIViewComponentPeer*) owner;
  226505. - (void) becomeKeyWindow;
  226506. @end
  226507. BEGIN_JUCE_NAMESPACE
  226508. class UIViewComponentPeer : public ComponentPeer,
  226509. public FocusChangeListener
  226510. {
  226511. public:
  226512. UIViewComponentPeer (Component* const component,
  226513. const int windowStyleFlags,
  226514. UIView* viewToAttachTo);
  226515. ~UIViewComponentPeer();
  226516. void* getNativeHandle() const;
  226517. void setVisible (bool shouldBeVisible);
  226518. void setTitle (const String& title);
  226519. void setPosition (int x, int y);
  226520. void setSize (int w, int h);
  226521. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226522. const Rectangle<int> getBounds() const;
  226523. const Rectangle<int> getBounds (const bool global) const;
  226524. const Point<int> getScreenPosition() const;
  226525. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226526. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226527. void setAlpha (float newAlpha);
  226528. void setMinimised (bool shouldBeMinimised);
  226529. bool isMinimised() const;
  226530. void setFullScreen (bool shouldBeFullScreen);
  226531. bool isFullScreen() const;
  226532. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226533. const BorderSize<int> getFrameSize() const;
  226534. bool setAlwaysOnTop (bool alwaysOnTop);
  226535. void toFront (bool makeActiveWindow);
  226536. void toBehind (ComponentPeer* other);
  226537. void setIcon (const Image& newIcon);
  226538. virtual void drawRect (CGRect r);
  226539. virtual bool canBecomeKeyWindow();
  226540. virtual bool windowShouldClose();
  226541. virtual void redirectMovedOrResized();
  226542. virtual CGRect constrainRect (CGRect r);
  226543. virtual void viewFocusGain();
  226544. virtual void viewFocusLoss();
  226545. bool isFocused() const;
  226546. void grabFocus();
  226547. void textInputRequired (const Point<int>& position);
  226548. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226549. void updateHiddenTextContent (TextInputTarget* target);
  226550. void globalFocusChanged (Component*);
  226551. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226552. virtual void displayRotated();
  226553. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226554. void repaint (const Rectangle<int>& area);
  226555. void performAnyPendingRepaintsNow();
  226556. UIWindow* window;
  226557. JuceUIView* view;
  226558. JuceUIViewController* controller;
  226559. bool isSharedWindow, fullScreen, insideDrawRect;
  226560. static ModifierKeys currentModifiers;
  226561. static int64 getMouseTime (UIEvent* e)
  226562. {
  226563. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226564. + (int64) ([e timestamp] * 1000.0);
  226565. }
  226566. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  226567. {
  226568. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226569. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226570. {
  226571. case UIInterfaceOrientationPortrait:
  226572. return r;
  226573. case UIInterfaceOrientationPortraitUpsideDown:
  226574. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226575. r.getWidth(), r.getHeight());
  226576. case UIInterfaceOrientationLandscapeLeft:
  226577. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  226578. r.getHeight(), r.getWidth());
  226579. case UIInterfaceOrientationLandscapeRight:
  226580. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  226581. r.getHeight(), r.getWidth());
  226582. default: jassertfalse; // unknown orientation!
  226583. }
  226584. return r;
  226585. }
  226586. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  226587. {
  226588. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226589. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226590. {
  226591. case UIInterfaceOrientationPortrait:
  226592. return r;
  226593. case UIInterfaceOrientationPortraitUpsideDown:
  226594. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226595. r.getWidth(), r.getHeight());
  226596. case UIInterfaceOrientationLandscapeLeft:
  226597. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  226598. r.getHeight(), r.getWidth());
  226599. case UIInterfaceOrientationLandscapeRight:
  226600. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  226601. r.getHeight(), r.getWidth());
  226602. default: jassertfalse; // unknown orientation!
  226603. }
  226604. return r;
  226605. }
  226606. Array <UITouch*> currentTouches;
  226607. private:
  226608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  226609. };
  226610. END_JUCE_NAMESPACE
  226611. @implementation JuceUIViewController
  226612. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  226613. {
  226614. JuceUIView* juceView = (JuceUIView*) [self view];
  226615. jassert (juceView != 0 && juceView->owner != 0);
  226616. return juceView->owner->shouldRotate (interfaceOrientation);
  226617. }
  226618. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  226619. {
  226620. JuceUIView* juceView = (JuceUIView*) [self view];
  226621. jassert (juceView != 0 && juceView->owner != 0);
  226622. juceView->owner->displayRotated();
  226623. }
  226624. @end
  226625. @implementation JuceUIView
  226626. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  226627. withFrame: (CGRect) frame
  226628. {
  226629. [super initWithFrame: frame];
  226630. owner = owner_;
  226631. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  226632. [self addSubview: hiddenTextView];
  226633. hiddenTextView.delegate = self;
  226634. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  226635. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  226636. return self;
  226637. }
  226638. - (void) dealloc
  226639. {
  226640. [hiddenTextView removeFromSuperview];
  226641. [hiddenTextView release];
  226642. [super dealloc];
  226643. }
  226644. - (void) drawRect: (CGRect) r
  226645. {
  226646. if (owner != 0)
  226647. owner->drawRect (r);
  226648. }
  226649. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  226650. {
  226651. return false;
  226652. }
  226653. ModifierKeys UIViewComponentPeer::currentModifiers;
  226654. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  226655. {
  226656. return UIViewComponentPeer::currentModifiers;
  226657. }
  226658. void ModifierKeys::updateCurrentModifiers() throw()
  226659. {
  226660. currentModifiers = UIViewComponentPeer::currentModifiers;
  226661. }
  226662. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  226663. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226664. {
  226665. if (owner != 0)
  226666. owner->handleTouches (event, true, false, false);
  226667. }
  226668. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226669. {
  226670. if (owner != 0)
  226671. owner->handleTouches (event, false, false, false);
  226672. }
  226673. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226674. {
  226675. if (owner != 0)
  226676. owner->handleTouches (event, false, true, false);
  226677. }
  226678. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226679. {
  226680. if (owner != 0)
  226681. owner->handleTouches (event, false, true, true);
  226682. [self touchesEnded: touches withEvent: event];
  226683. }
  226684. - (BOOL) becomeFirstResponder
  226685. {
  226686. if (owner != 0)
  226687. owner->viewFocusGain();
  226688. return true;
  226689. }
  226690. - (BOOL) resignFirstResponder
  226691. {
  226692. if (owner != 0)
  226693. owner->viewFocusLoss();
  226694. return true;
  226695. }
  226696. - (BOOL) canBecomeFirstResponder
  226697. {
  226698. return owner != 0 && owner->canBecomeKeyWindow();
  226699. }
  226700. - (void) asyncRepaint: (id) rect
  226701. {
  226702. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226703. [self setNeedsDisplayInRect: *r];
  226704. }
  226705. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226706. {
  226707. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226708. nsStringToJuce (text));
  226709. }
  226710. @end
  226711. @implementation JuceUIWindow
  226712. - (void) setOwner: (UIViewComponentPeer*) owner_
  226713. {
  226714. owner = owner_;
  226715. isZooming = false;
  226716. }
  226717. - (void) becomeKeyWindow
  226718. {
  226719. [super becomeKeyWindow];
  226720. if (owner != 0)
  226721. owner->grabFocus();
  226722. }
  226723. @end
  226724. BEGIN_JUCE_NAMESPACE
  226725. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226726. const int windowStyleFlags,
  226727. UIView* viewToAttachTo)
  226728. : ComponentPeer (component, windowStyleFlags),
  226729. window (0),
  226730. view (0), controller (0),
  226731. isSharedWindow (viewToAttachTo != 0),
  226732. fullScreen (false),
  226733. insideDrawRect (false)
  226734. {
  226735. CGRect r = convertToCGRect (component->getLocalBounds());
  226736. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226737. if (isSharedWindow)
  226738. {
  226739. window = [viewToAttachTo window];
  226740. [viewToAttachTo addSubview: view];
  226741. setVisible (component->isVisible());
  226742. }
  226743. else
  226744. {
  226745. controller = [[JuceUIViewController alloc] init];
  226746. controller.view = view;
  226747. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  226748. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226749. window = [[JuceUIWindow alloc] init];
  226750. window.frame = r;
  226751. window.opaque = component->isOpaque();
  226752. view.opaque = component->isOpaque();
  226753. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226754. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226755. [((JuceUIWindow*) window) setOwner: this];
  226756. if (component->isAlwaysOnTop())
  226757. window.windowLevel = UIWindowLevelAlert;
  226758. [window addSubview: view];
  226759. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226760. view.hidden = ! component->isVisible();
  226761. window.hidden = ! component->isVisible();
  226762. view.multipleTouchEnabled = YES;
  226763. }
  226764. setTitle (component->getName());
  226765. Desktop::getInstance().addFocusChangeListener (this);
  226766. }
  226767. UIViewComponentPeer::~UIViewComponentPeer()
  226768. {
  226769. Desktop::getInstance().removeFocusChangeListener (this);
  226770. view->owner = 0;
  226771. [view removeFromSuperview];
  226772. [view release];
  226773. [controller release];
  226774. if (! isSharedWindow)
  226775. {
  226776. [((JuceUIWindow*) window) setOwner: 0];
  226777. [window release];
  226778. }
  226779. }
  226780. void* UIViewComponentPeer::getNativeHandle() const
  226781. {
  226782. return view;
  226783. }
  226784. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226785. {
  226786. view.hidden = ! shouldBeVisible;
  226787. if (! isSharedWindow)
  226788. window.hidden = ! shouldBeVisible;
  226789. }
  226790. void UIViewComponentPeer::setTitle (const String& title)
  226791. {
  226792. // xxx is this possible?
  226793. }
  226794. void UIViewComponentPeer::setPosition (int x, int y)
  226795. {
  226796. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226797. }
  226798. void UIViewComponentPeer::setSize (int w, int h)
  226799. {
  226800. setBounds (component->getX(), component->getY(), w, h, false);
  226801. }
  226802. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226803. {
  226804. fullScreen = isNowFullScreen;
  226805. w = jmax (0, w);
  226806. h = jmax (0, h);
  226807. if (isSharedWindow)
  226808. {
  226809. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  226810. if ([view frame].size.width != r.size.width
  226811. || [view frame].size.height != r.size.height)
  226812. [view setNeedsDisplay];
  226813. view.frame = r;
  226814. }
  226815. else
  226816. {
  226817. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  226818. window.frame = convertToCGRect (bounds);
  226819. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  226820. handleMovedOrResized();
  226821. }
  226822. }
  226823. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226824. {
  226825. CGRect r = [view frame];
  226826. if (global && [view window] != 0)
  226827. {
  226828. r = [view convertRect: r toView: nil];
  226829. CGRect wr = [[view window] frame];
  226830. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  226831. r.origin.x = windowBounds.getX();
  226832. r.origin.y = windowBounds.getY();
  226833. }
  226834. return convertToRectInt (r);
  226835. }
  226836. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226837. {
  226838. return getBounds (! isSharedWindow);
  226839. }
  226840. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226841. {
  226842. return getBounds (true).getPosition();
  226843. }
  226844. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  226845. {
  226846. return relativePosition + getScreenPosition();
  226847. }
  226848. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  226849. {
  226850. return screenPosition - getScreenPosition();
  226851. }
  226852. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226853. {
  226854. if (constrainer != 0)
  226855. {
  226856. CGRect current = [window frame];
  226857. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226858. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226859. Rectangle<int> pos (convertToRectInt (r));
  226860. Rectangle<int> original (convertToRectInt (current));
  226861. constrainer->checkBounds (pos, original,
  226862. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226863. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226864. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226865. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226866. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226867. r.origin.x = pos.getX();
  226868. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226869. r.size.width = pos.getWidth();
  226870. r.size.height = pos.getHeight();
  226871. }
  226872. return r;
  226873. }
  226874. void UIViewComponentPeer::setAlpha (float newAlpha)
  226875. {
  226876. [[view window] setAlpha: (CGFloat) newAlpha];
  226877. }
  226878. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226879. {
  226880. }
  226881. bool UIViewComponentPeer::isMinimised() const
  226882. {
  226883. return false;
  226884. }
  226885. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226886. {
  226887. if (! isSharedWindow)
  226888. {
  226889. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  226890. : lastNonFullscreenBounds);
  226891. if ((! shouldBeFullScreen) && r.isEmpty())
  226892. r = getBounds();
  226893. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226894. if (! r.isEmpty())
  226895. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226896. component->repaint();
  226897. }
  226898. }
  226899. bool UIViewComponentPeer::isFullScreen() const
  226900. {
  226901. return fullScreen;
  226902. }
  226903. namespace
  226904. {
  226905. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  226906. {
  226907. switch (interfaceOrientation)
  226908. {
  226909. case UIInterfaceOrientationPortrait: return Desktop::upright;
  226910. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  226911. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  226912. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  226913. default: jassertfalse; // unknown orientation!
  226914. }
  226915. return Desktop::upright;
  226916. }
  226917. }
  226918. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  226919. {
  226920. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  226921. }
  226922. void UIViewComponentPeer::displayRotated()
  226923. {
  226924. const Rectangle<int> oldArea (component->getBounds());
  226925. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  226926. Desktop::getInstance().refreshMonitorSizes();
  226927. if (fullScreen)
  226928. {
  226929. fullScreen = false;
  226930. setFullScreen (true);
  226931. }
  226932. else
  226933. {
  226934. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  226935. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  226936. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  226937. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  226938. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  226939. setBounds ((int) (l * newDesktop.getWidth()),
  226940. (int) (t * newDesktop.getHeight()),
  226941. (int) ((r - l) * newDesktop.getWidth()),
  226942. (int) ((b - t) * newDesktop.getHeight()),
  226943. false);
  226944. }
  226945. }
  226946. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226947. {
  226948. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  226949. && isPositiveAndBelow (position.getY(), component->getHeight())))
  226950. return false;
  226951. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  226952. withEvent: nil];
  226953. if (trueIfInAChildWindow)
  226954. return v != nil;
  226955. return v == view;
  226956. }
  226957. const BorderSize<int> UIViewComponentPeer::getFrameSize() const
  226958. {
  226959. return BorderSize<int>();
  226960. }
  226961. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226962. {
  226963. if (! isSharedWindow)
  226964. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226965. return true;
  226966. }
  226967. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226968. {
  226969. if (isSharedWindow)
  226970. [[view superview] bringSubviewToFront: view];
  226971. if (window != 0 && component->isVisible())
  226972. [window makeKeyAndVisible];
  226973. }
  226974. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226975. {
  226976. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226977. jassert (otherPeer != 0); // wrong type of window?
  226978. if (otherPeer != 0)
  226979. {
  226980. if (isSharedWindow)
  226981. {
  226982. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  226983. }
  226984. else
  226985. {
  226986. jassertfalse; // don't know how to do this
  226987. }
  226988. }
  226989. }
  226990. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226991. {
  226992. // to do..
  226993. }
  226994. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226995. {
  226996. NSArray* touches = [[event touchesForView: view] allObjects];
  226997. for (unsigned int i = 0; i < [touches count]; ++i)
  226998. {
  226999. UITouch* touch = [touches objectAtIndex: i];
  227000. CGPoint p = [touch locationInView: view];
  227001. const Point<int> pos ((int) p.x, (int) p.y);
  227002. juce_lastMousePos = pos + getScreenPosition();
  227003. const int64 time = getMouseTime (event);
  227004. int touchIndex = currentTouches.indexOf (touch);
  227005. if (touchIndex < 0)
  227006. {
  227007. touchIndex = currentTouches.size();
  227008. currentTouches.add (touch);
  227009. }
  227010. if (isDown)
  227011. {
  227012. currentModifiers = currentModifiers.withoutMouseButtons();
  227013. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227014. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227015. }
  227016. else if (isUp)
  227017. {
  227018. currentModifiers = currentModifiers.withoutMouseButtons();
  227019. currentTouches.remove (touchIndex);
  227020. }
  227021. if (isCancel)
  227022. currentTouches.clear();
  227023. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227024. }
  227025. }
  227026. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227027. void UIViewComponentPeer::viewFocusGain()
  227028. {
  227029. if (currentlyFocusedPeer != this)
  227030. {
  227031. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227032. currentlyFocusedPeer->handleFocusLoss();
  227033. currentlyFocusedPeer = this;
  227034. handleFocusGain();
  227035. }
  227036. }
  227037. void UIViewComponentPeer::viewFocusLoss()
  227038. {
  227039. if (currentlyFocusedPeer == this)
  227040. {
  227041. currentlyFocusedPeer = 0;
  227042. handleFocusLoss();
  227043. }
  227044. }
  227045. void juce_HandleProcessFocusChange()
  227046. {
  227047. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227048. {
  227049. if (Process::isForegroundProcess())
  227050. {
  227051. currentlyFocusedPeer->handleFocusGain();
  227052. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227053. }
  227054. else
  227055. {
  227056. currentlyFocusedPeer->handleFocusLoss();
  227057. // turn kiosk mode off if we lose focus..
  227058. Desktop::getInstance().setKioskModeComponent (0);
  227059. }
  227060. }
  227061. }
  227062. bool UIViewComponentPeer::isFocused() const
  227063. {
  227064. return isSharedWindow ? this == currentlyFocusedPeer
  227065. : (window != 0 && [window isKeyWindow]);
  227066. }
  227067. void UIViewComponentPeer::grabFocus()
  227068. {
  227069. if (window != 0)
  227070. {
  227071. [window makeKeyWindow];
  227072. viewFocusGain();
  227073. }
  227074. }
  227075. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227076. {
  227077. }
  227078. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227079. {
  227080. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227081. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227082. }
  227083. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227084. {
  227085. TextInputTarget* const target = findCurrentTextInputTarget();
  227086. if (target != 0)
  227087. {
  227088. const Range<int> currentSelection (target->getHighlightedRegion());
  227089. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227090. if (currentSelection.isEmpty())
  227091. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227092. target->insertTextAtCaret (text);
  227093. updateHiddenTextContent (target);
  227094. }
  227095. return NO;
  227096. }
  227097. void UIViewComponentPeer::globalFocusChanged (Component*)
  227098. {
  227099. TextInputTarget* const target = findCurrentTextInputTarget();
  227100. if (target != 0)
  227101. {
  227102. Component* comp = dynamic_cast<Component*> (target);
  227103. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227104. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227105. updateHiddenTextContent (target);
  227106. [view->hiddenTextView becomeFirstResponder];
  227107. }
  227108. else
  227109. {
  227110. [view->hiddenTextView resignFirstResponder];
  227111. }
  227112. }
  227113. void UIViewComponentPeer::drawRect (CGRect r)
  227114. {
  227115. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227116. return;
  227117. CGContextRef cg = UIGraphicsGetCurrentContext();
  227118. if (! component->isOpaque())
  227119. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227120. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227121. CoreGraphicsContext g (cg, view.bounds.size.height);
  227122. insideDrawRect = true;
  227123. handlePaint (g);
  227124. insideDrawRect = false;
  227125. }
  227126. bool UIViewComponentPeer::canBecomeKeyWindow()
  227127. {
  227128. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227129. }
  227130. bool UIViewComponentPeer::windowShouldClose()
  227131. {
  227132. if (! isValidPeer (this))
  227133. return YES;
  227134. handleUserClosingWindow();
  227135. return NO;
  227136. }
  227137. void UIViewComponentPeer::redirectMovedOrResized()
  227138. {
  227139. handleMovedOrResized();
  227140. }
  227141. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227142. {
  227143. }
  227144. class AsyncRepaintMessage : public CallbackMessage
  227145. {
  227146. public:
  227147. UIViewComponentPeer* const peer;
  227148. const Rectangle<int> rect;
  227149. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227150. : peer (peer_), rect (rect_)
  227151. {
  227152. }
  227153. void messageCallback()
  227154. {
  227155. if (ComponentPeer::isValidPeer (peer))
  227156. peer->repaint (rect);
  227157. }
  227158. };
  227159. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227160. {
  227161. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227162. {
  227163. (new AsyncRepaintMessage (this, area))->post();
  227164. }
  227165. else
  227166. {
  227167. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227168. }
  227169. }
  227170. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227171. {
  227172. }
  227173. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227174. {
  227175. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227176. }
  227177. const Image juce_createIconForFile (const File& file)
  227178. {
  227179. return Image::null;
  227180. }
  227181. void Desktop::createMouseInputSources()
  227182. {
  227183. for (int i = 0; i < 10; ++i)
  227184. mouseSources.add (new MouseInputSource (i, false));
  227185. }
  227186. bool Desktop::canUseSemiTransparentWindows() throw()
  227187. {
  227188. return true;
  227189. }
  227190. const Point<int> MouseInputSource::getCurrentMousePosition()
  227191. {
  227192. return juce_lastMousePos;
  227193. }
  227194. void Desktop::setMousePosition (const Point<int>&)
  227195. {
  227196. }
  227197. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227198. {
  227199. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227200. }
  227201. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227202. {
  227203. const ScopedAutoReleasePool pool;
  227204. monitorCoords.clear();
  227205. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227206. : [[UIScreen mainScreen] bounds];
  227207. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227208. }
  227209. const int KeyPress::spaceKey = ' ';
  227210. const int KeyPress::returnKey = 0x0d;
  227211. const int KeyPress::escapeKey = 0x1b;
  227212. const int KeyPress::backspaceKey = 0x7f;
  227213. const int KeyPress::leftKey = 0x1000;
  227214. const int KeyPress::rightKey = 0x1001;
  227215. const int KeyPress::upKey = 0x1002;
  227216. const int KeyPress::downKey = 0x1003;
  227217. const int KeyPress::pageUpKey = 0x1004;
  227218. const int KeyPress::pageDownKey = 0x1005;
  227219. const int KeyPress::endKey = 0x1006;
  227220. const int KeyPress::homeKey = 0x1007;
  227221. const int KeyPress::deleteKey = 0x1008;
  227222. const int KeyPress::insertKey = -1;
  227223. const int KeyPress::tabKey = 9;
  227224. const int KeyPress::F1Key = 0x2001;
  227225. const int KeyPress::F2Key = 0x2002;
  227226. const int KeyPress::F3Key = 0x2003;
  227227. const int KeyPress::F4Key = 0x2004;
  227228. const int KeyPress::F5Key = 0x2005;
  227229. const int KeyPress::F6Key = 0x2006;
  227230. const int KeyPress::F7Key = 0x2007;
  227231. const int KeyPress::F8Key = 0x2008;
  227232. const int KeyPress::F9Key = 0x2009;
  227233. const int KeyPress::F10Key = 0x200a;
  227234. const int KeyPress::F11Key = 0x200b;
  227235. const int KeyPress::F12Key = 0x200c;
  227236. const int KeyPress::F13Key = 0x200d;
  227237. const int KeyPress::F14Key = 0x200e;
  227238. const int KeyPress::F15Key = 0x200f;
  227239. const int KeyPress::F16Key = 0x2010;
  227240. const int KeyPress::numberPad0 = 0x30020;
  227241. const int KeyPress::numberPad1 = 0x30021;
  227242. const int KeyPress::numberPad2 = 0x30022;
  227243. const int KeyPress::numberPad3 = 0x30023;
  227244. const int KeyPress::numberPad4 = 0x30024;
  227245. const int KeyPress::numberPad5 = 0x30025;
  227246. const int KeyPress::numberPad6 = 0x30026;
  227247. const int KeyPress::numberPad7 = 0x30027;
  227248. const int KeyPress::numberPad8 = 0x30028;
  227249. const int KeyPress::numberPad9 = 0x30029;
  227250. const int KeyPress::numberPadAdd = 0x3002a;
  227251. const int KeyPress::numberPadSubtract = 0x3002b;
  227252. const int KeyPress::numberPadMultiply = 0x3002c;
  227253. const int KeyPress::numberPadDivide = 0x3002d;
  227254. const int KeyPress::numberPadSeparator = 0x3002e;
  227255. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227256. const int KeyPress::numberPadEquals = 0x30030;
  227257. const int KeyPress::numberPadDelete = 0x30031;
  227258. const int KeyPress::playKey = 0x30000;
  227259. const int KeyPress::stopKey = 0x30001;
  227260. const int KeyPress::fastForwardKey = 0x30002;
  227261. const int KeyPress::rewindKey = 0x30003;
  227262. #endif
  227263. /*** End of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  227264. /*** Start of inlined file: juce_ios_MessageManager.mm ***/
  227265. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227266. // compiled on its own).
  227267. #if JUCE_INCLUDED_FILE
  227268. struct CallbackMessagePayload
  227269. {
  227270. MessageCallbackFunction* function;
  227271. void* parameter;
  227272. void* volatile result;
  227273. bool volatile hasBeenExecuted;
  227274. };
  227275. END_JUCE_NAMESPACE
  227276. @interface JuceCustomMessageHandler : NSObject
  227277. {
  227278. }
  227279. - (void) performCallback: (id) info;
  227280. @end
  227281. @implementation JuceCustomMessageHandler
  227282. - (void) performCallback: (id) info
  227283. {
  227284. if ([info isKindOfClass: [NSData class]])
  227285. {
  227286. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227287. if (pl != 0)
  227288. {
  227289. pl->result = (*pl->function) (pl->parameter);
  227290. pl->hasBeenExecuted = true;
  227291. }
  227292. }
  227293. else
  227294. {
  227295. jassertfalse; // should never get here!
  227296. }
  227297. }
  227298. @end
  227299. BEGIN_JUCE_NAMESPACE
  227300. void MessageManager::runDispatchLoop()
  227301. {
  227302. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227303. runDispatchLoopUntil (-1);
  227304. }
  227305. void MessageManager::stopDispatchLoop()
  227306. {
  227307. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227308. exit (0); // iPhone apps get no mercy..
  227309. }
  227310. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227311. {
  227312. const ScopedAutoReleasePool pool;
  227313. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227314. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227315. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227316. while (! quitMessagePosted)
  227317. {
  227318. const ScopedAutoReleasePool pool;
  227319. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227320. beforeDate: endDate];
  227321. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227322. break;
  227323. }
  227324. return ! quitMessagePosted;
  227325. }
  227326. struct MessageDispatchSystem
  227327. {
  227328. MessageDispatchSystem()
  227329. : juceCustomMessageHandler (0)
  227330. {
  227331. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227332. }
  227333. ~MessageDispatchSystem()
  227334. {
  227335. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227336. [juceCustomMessageHandler release];
  227337. }
  227338. JuceCustomMessageHandler* juceCustomMessageHandler;
  227339. MessageQueue messageQueue;
  227340. };
  227341. static MessageDispatchSystem* dispatcher = 0;
  227342. void MessageManager::doPlatformSpecificInitialisation()
  227343. {
  227344. if (dispatcher == 0)
  227345. dispatcher = new MessageDispatchSystem();
  227346. }
  227347. void MessageManager::doPlatformSpecificShutdown()
  227348. {
  227349. deleteAndZero (dispatcher);
  227350. }
  227351. bool juce_postMessageToSystemQueue (Message* message)
  227352. {
  227353. if (dispatcher != 0)
  227354. dispatcher->messageQueue.post (message);
  227355. return true;
  227356. }
  227357. void MessageManager::broadcastMessage (const String& value)
  227358. {
  227359. }
  227360. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227361. {
  227362. if (isThisTheMessageThread())
  227363. {
  227364. return (*callback) (data);
  227365. }
  227366. else
  227367. {
  227368. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227369. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227370. // deadlock because the message manager is blocked from running, so can never
  227371. // call your function..
  227372. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227373. const ScopedAutoReleasePool pool;
  227374. CallbackMessagePayload cmp;
  227375. cmp.function = callback;
  227376. cmp.parameter = data;
  227377. cmp.result = 0;
  227378. cmp.hasBeenExecuted = false;
  227379. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227380. withObject: [NSData dataWithBytesNoCopy: &cmp
  227381. length: sizeof (cmp)
  227382. freeWhenDone: NO]
  227383. waitUntilDone: YES];
  227384. return cmp.result;
  227385. }
  227386. }
  227387. #endif
  227388. /*** End of inlined file: juce_ios_MessageManager.mm ***/
  227389. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227390. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227391. // compiled on its own).
  227392. #if JUCE_INCLUDED_FILE
  227393. #if JUCE_MAC
  227394. END_JUCE_NAMESPACE
  227395. using namespace JUCE_NAMESPACE;
  227396. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227397. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227398. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227399. #else
  227400. @interface JuceFileChooserDelegate : NSObject
  227401. #endif
  227402. {
  227403. StringArray* filters;
  227404. }
  227405. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227406. - (void) dealloc;
  227407. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227408. @end
  227409. @implementation JuceFileChooserDelegate
  227410. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227411. {
  227412. [super init];
  227413. filters = filters_;
  227414. return self;
  227415. }
  227416. - (void) dealloc
  227417. {
  227418. delete filters;
  227419. [super dealloc];
  227420. }
  227421. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227422. {
  227423. (void) sender;
  227424. const File f (nsStringToJuce (filename));
  227425. for (int i = filters->size(); --i >= 0;)
  227426. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227427. return true;
  227428. return f.isDirectory();
  227429. }
  227430. @end
  227431. BEGIN_JUCE_NAMESPACE
  227432. void FileChooser::showPlatformDialog (Array<File>& results,
  227433. const String& title,
  227434. const File& currentFileOrDirectory,
  227435. const String& filter,
  227436. bool selectsDirectory,
  227437. bool selectsFiles,
  227438. bool isSaveDialogue,
  227439. bool /*warnAboutOverwritingExistingFiles*/,
  227440. bool selectMultipleFiles,
  227441. FilePreviewComponent* /*extraInfoComponent*/)
  227442. {
  227443. const ScopedAutoReleasePool pool;
  227444. StringArray* filters = new StringArray();
  227445. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227446. filters->trim();
  227447. filters->removeEmptyStrings();
  227448. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227449. [delegate autorelease];
  227450. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227451. : [NSOpenPanel openPanel];
  227452. [panel setTitle: juceStringToNS (title)];
  227453. if (! isSaveDialogue)
  227454. {
  227455. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227456. [openPanel setCanChooseDirectories: selectsDirectory];
  227457. [openPanel setCanChooseFiles: selectsFiles];
  227458. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227459. }
  227460. [panel setDelegate: delegate];
  227461. if (isSaveDialogue || selectsDirectory)
  227462. [panel setCanCreateDirectories: YES];
  227463. String directory, filename;
  227464. if (currentFileOrDirectory.isDirectory())
  227465. {
  227466. directory = currentFileOrDirectory.getFullPathName();
  227467. }
  227468. else
  227469. {
  227470. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227471. filename = currentFileOrDirectory.getFileName();
  227472. }
  227473. if ([panel runModalForDirectory: juceStringToNS (directory)
  227474. file: juceStringToNS (filename)]
  227475. == NSOKButton)
  227476. {
  227477. if (isSaveDialogue)
  227478. {
  227479. results.add (File (nsStringToJuce ([panel filename])));
  227480. }
  227481. else
  227482. {
  227483. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227484. NSArray* urls = [openPanel filenames];
  227485. for (unsigned int i = 0; i < [urls count]; ++i)
  227486. {
  227487. NSString* f = [urls objectAtIndex: i];
  227488. results.add (File (nsStringToJuce (f)));
  227489. }
  227490. }
  227491. }
  227492. [panel setDelegate: nil];
  227493. }
  227494. #else
  227495. void FileChooser::showPlatformDialog (Array<File>& results,
  227496. const String& title,
  227497. const File& currentFileOrDirectory,
  227498. const String& filter,
  227499. bool selectsDirectory,
  227500. bool selectsFiles,
  227501. bool isSaveDialogue,
  227502. bool warnAboutOverwritingExistingFiles,
  227503. bool selectMultipleFiles,
  227504. FilePreviewComponent* extraInfoComponent)
  227505. {
  227506. const ScopedAutoReleasePool pool;
  227507. jassertfalse; //xxx to do
  227508. }
  227509. #endif
  227510. #endif
  227511. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227512. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227513. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227514. // compiled on its own).
  227515. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227516. #if JUCE_MAC
  227517. END_JUCE_NAMESPACE
  227518. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227519. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227520. {
  227521. CriticalSection* contextLock;
  227522. bool needsUpdate;
  227523. }
  227524. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227525. - (bool) makeActive;
  227526. - (void) makeInactive;
  227527. - (void) reshape;
  227528. @end
  227529. @implementation ThreadSafeNSOpenGLView
  227530. - (id) initWithFrame: (NSRect) frameRect
  227531. pixelFormat: (NSOpenGLPixelFormat*) format
  227532. {
  227533. contextLock = new CriticalSection();
  227534. self = [super initWithFrame: frameRect pixelFormat: format];
  227535. if (self != nil)
  227536. [[NSNotificationCenter defaultCenter] addObserver: self
  227537. selector: @selector (_surfaceNeedsUpdate:)
  227538. name: NSViewGlobalFrameDidChangeNotification
  227539. object: self];
  227540. return self;
  227541. }
  227542. - (void) dealloc
  227543. {
  227544. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227545. delete contextLock;
  227546. [super dealloc];
  227547. }
  227548. - (bool) makeActive
  227549. {
  227550. const ScopedLock sl (*contextLock);
  227551. if ([self openGLContext] == 0)
  227552. return false;
  227553. [[self openGLContext] makeCurrentContext];
  227554. if (needsUpdate)
  227555. {
  227556. [super update];
  227557. needsUpdate = false;
  227558. }
  227559. return true;
  227560. }
  227561. - (void) makeInactive
  227562. {
  227563. const ScopedLock sl (*contextLock);
  227564. [NSOpenGLContext clearCurrentContext];
  227565. }
  227566. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  227567. {
  227568. (void) notification;
  227569. const ScopedLock sl (*contextLock);
  227570. needsUpdate = true;
  227571. }
  227572. - (void) update
  227573. {
  227574. const ScopedLock sl (*contextLock);
  227575. needsUpdate = true;
  227576. }
  227577. - (void) reshape
  227578. {
  227579. const ScopedLock sl (*contextLock);
  227580. needsUpdate = true;
  227581. }
  227582. @end
  227583. BEGIN_JUCE_NAMESPACE
  227584. class WindowedGLContext : public OpenGLContext
  227585. {
  227586. public:
  227587. WindowedGLContext (Component& component,
  227588. const OpenGLPixelFormat& pixelFormat_,
  227589. NSOpenGLContext* sharedContext)
  227590. : renderContext (0),
  227591. pixelFormat (pixelFormat_)
  227592. {
  227593. NSOpenGLPixelFormatAttribute attribs [64];
  227594. int n = 0;
  227595. attribs[n++] = NSOpenGLPFADoubleBuffer;
  227596. attribs[n++] = NSOpenGLPFAAccelerated;
  227597. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  227598. attribs[n++] = NSOpenGLPFAColorSize;
  227599. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  227600. pixelFormat.greenBits,
  227601. pixelFormat.blueBits);
  227602. attribs[n++] = NSOpenGLPFAAlphaSize;
  227603. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  227604. attribs[n++] = NSOpenGLPFADepthSize;
  227605. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  227606. attribs[n++] = NSOpenGLPFAStencilSize;
  227607. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  227608. attribs[n++] = NSOpenGLPFAAccumSize;
  227609. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  227610. pixelFormat.accumulationBufferGreenBits,
  227611. pixelFormat.accumulationBufferBlueBits,
  227612. pixelFormat.accumulationBufferAlphaBits);
  227613. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  227614. attribs[n++] = NSOpenGLPFASampleBuffers;
  227615. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  227616. attribs[n++] = NSOpenGLPFAClosestPolicy;
  227617. attribs[n++] = NSOpenGLPFANoRecovery;
  227618. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  227619. NSOpenGLPixelFormat* format
  227620. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  227621. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227622. pixelFormat: format];
  227623. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  227624. shareContext: sharedContext] autorelease];
  227625. const GLint swapInterval = 1;
  227626. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  227627. [view setOpenGLContext: renderContext];
  227628. [format release];
  227629. viewHolder = new NSViewComponentInternal (view, component);
  227630. }
  227631. ~WindowedGLContext()
  227632. {
  227633. deleteContext();
  227634. viewHolder = 0;
  227635. }
  227636. void deleteContext()
  227637. {
  227638. makeInactive();
  227639. [renderContext clearDrawable];
  227640. [renderContext setView: nil];
  227641. [view setOpenGLContext: nil];
  227642. renderContext = nil;
  227643. }
  227644. bool makeActive() const throw()
  227645. {
  227646. jassert (renderContext != 0);
  227647. if ([renderContext view] != view)
  227648. [renderContext setView: view];
  227649. [view makeActive];
  227650. return isActive();
  227651. }
  227652. bool makeInactive() const throw()
  227653. {
  227654. [view makeInactive];
  227655. return true;
  227656. }
  227657. bool isActive() const throw()
  227658. {
  227659. return [NSOpenGLContext currentContext] == renderContext;
  227660. }
  227661. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227662. void* getRawContext() const throw() { return renderContext; }
  227663. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  227664. {
  227665. }
  227666. void swapBuffers()
  227667. {
  227668. [renderContext flushBuffer];
  227669. }
  227670. bool setSwapInterval (const int numFramesPerSwap)
  227671. {
  227672. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227673. forParameter: NSOpenGLCPSwapInterval];
  227674. return true;
  227675. }
  227676. int getSwapInterval() const
  227677. {
  227678. GLint numFrames = 0;
  227679. [renderContext getValues: &numFrames
  227680. forParameter: NSOpenGLCPSwapInterval];
  227681. return numFrames;
  227682. }
  227683. void repaint()
  227684. {
  227685. // we need to invalidate the juce view that holds this gl view, to make it
  227686. // cause a repaint callback
  227687. NSView* v = (NSView*) viewHolder->view;
  227688. NSRect r = [v frame];
  227689. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227690. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227691. // repaint message, thus never causing our paint() callback, and never repainting
  227692. // the comp. So invalidating just a little bit around the edge helps..
  227693. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227694. }
  227695. void* getNativeWindowHandle() const { return viewHolder->view; }
  227696. NSOpenGLContext* renderContext;
  227697. ThreadSafeNSOpenGLView* view;
  227698. private:
  227699. OpenGLPixelFormat pixelFormat;
  227700. ScopedPointer <NSViewComponentInternal> viewHolder;
  227701. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  227702. };
  227703. OpenGLContext* OpenGLComponent::createContext()
  227704. {
  227705. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  227706. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227707. return (c->renderContext != 0) ? c.release() : 0;
  227708. }
  227709. void* OpenGLComponent::getNativeWindowHandle() const
  227710. {
  227711. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227712. : 0;
  227713. }
  227714. void juce_glViewport (const int w, const int h)
  227715. {
  227716. glViewport (0, 0, w, h);
  227717. }
  227718. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227719. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227720. {
  227721. /* GLint attribs [64];
  227722. int n = 0;
  227723. attribs[n++] = AGL_RGBA;
  227724. attribs[n++] = AGL_DOUBLEBUFFER;
  227725. attribs[n++] = AGL_ACCELERATED;
  227726. attribs[n++] = AGL_NO_RECOVERY;
  227727. attribs[n++] = AGL_NONE;
  227728. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227729. while (p != 0)
  227730. {
  227731. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227732. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227733. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227734. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227735. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227736. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227737. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227738. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227739. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227740. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227741. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227742. results.add (pf);
  227743. p = aglNextPixelFormat (p);
  227744. }*/
  227745. //jassertfalse // can't see how you do this in cocoa!
  227746. }
  227747. #else
  227748. END_JUCE_NAMESPACE
  227749. @interface JuceGLView : UIView
  227750. {
  227751. }
  227752. + (Class) layerClass;
  227753. @end
  227754. @implementation JuceGLView
  227755. + (Class) layerClass
  227756. {
  227757. return [CAEAGLLayer class];
  227758. }
  227759. @end
  227760. BEGIN_JUCE_NAMESPACE
  227761. class GLESContext : public OpenGLContext
  227762. {
  227763. public:
  227764. GLESContext (UIViewComponentPeer* peer,
  227765. Component* const component_,
  227766. const OpenGLPixelFormat& pixelFormat_,
  227767. const GLESContext* const sharedContext,
  227768. NSUInteger apiType)
  227769. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227770. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227771. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227772. {
  227773. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227774. view.opaque = YES;
  227775. view.hidden = NO;
  227776. view.backgroundColor = [UIColor blackColor];
  227777. view.userInteractionEnabled = NO;
  227778. glLayer = (CAEAGLLayer*) [view layer];
  227779. [peer->view addSubview: view];
  227780. if (sharedContext != 0)
  227781. context = [[EAGLContext alloc] initWithAPI: apiType
  227782. sharegroup: [sharedContext->context sharegroup]];
  227783. else
  227784. context = [[EAGLContext alloc] initWithAPI: apiType];
  227785. createGLBuffers();
  227786. }
  227787. ~GLESContext()
  227788. {
  227789. deleteContext();
  227790. [view removeFromSuperview];
  227791. [view release];
  227792. freeGLBuffers();
  227793. }
  227794. void deleteContext()
  227795. {
  227796. makeInactive();
  227797. [context release];
  227798. context = nil;
  227799. }
  227800. bool makeActive() const throw()
  227801. {
  227802. jassert (context != 0);
  227803. [EAGLContext setCurrentContext: context];
  227804. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227805. return true;
  227806. }
  227807. void swapBuffers()
  227808. {
  227809. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227810. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227811. }
  227812. bool makeInactive() const throw()
  227813. {
  227814. return [EAGLContext setCurrentContext: nil];
  227815. }
  227816. bool isActive() const throw()
  227817. {
  227818. return [EAGLContext currentContext] == context;
  227819. }
  227820. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227821. void* getRawContext() const throw() { return glLayer; }
  227822. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227823. {
  227824. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227825. if (lastWidth != w || lastHeight != h)
  227826. {
  227827. lastWidth = w;
  227828. lastHeight = h;
  227829. freeGLBuffers();
  227830. createGLBuffers();
  227831. }
  227832. }
  227833. bool setSwapInterval (const int numFramesPerSwap)
  227834. {
  227835. numFrames = numFramesPerSwap;
  227836. return true;
  227837. }
  227838. int getSwapInterval() const
  227839. {
  227840. return numFrames;
  227841. }
  227842. void repaint()
  227843. {
  227844. }
  227845. void createGLBuffers()
  227846. {
  227847. makeActive();
  227848. glGenFramebuffersOES (1, &frameBufferHandle);
  227849. glGenRenderbuffersOES (1, &colorBufferHandle);
  227850. glGenRenderbuffersOES (1, &depthBufferHandle);
  227851. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227852. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227853. GLint width, height;
  227854. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227855. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227856. if (useDepthBuffer)
  227857. {
  227858. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227859. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227860. }
  227861. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227862. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227863. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227864. if (useDepthBuffer)
  227865. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227866. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227867. }
  227868. void freeGLBuffers()
  227869. {
  227870. if (frameBufferHandle != 0)
  227871. {
  227872. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227873. frameBufferHandle = 0;
  227874. }
  227875. if (colorBufferHandle != 0)
  227876. {
  227877. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227878. colorBufferHandle = 0;
  227879. }
  227880. if (depthBufferHandle != 0)
  227881. {
  227882. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227883. depthBufferHandle = 0;
  227884. }
  227885. }
  227886. private:
  227887. WeakReference<Component> component;
  227888. OpenGLPixelFormat pixelFormat;
  227889. JuceGLView* view;
  227890. CAEAGLLayer* glLayer;
  227891. EAGLContext* context;
  227892. bool useDepthBuffer;
  227893. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227894. int numFrames;
  227895. int lastWidth, lastHeight;
  227896. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  227897. };
  227898. OpenGLContext* OpenGLComponent::createContext()
  227899. {
  227900. ScopedAutoReleasePool pool;
  227901. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227902. if (peer != 0)
  227903. return new GLESContext (peer, this, preferredPixelFormat,
  227904. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227905. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227906. return 0;
  227907. }
  227908. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227909. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227910. {
  227911. }
  227912. void juce_glViewport (const int w, const int h)
  227913. {
  227914. glViewport (0, 0, w, h);
  227915. }
  227916. #endif
  227917. #endif
  227918. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227919. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227920. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227921. // compiled on its own).
  227922. #if JUCE_INCLUDED_FILE
  227923. #if JUCE_MAC
  227924. namespace MouseCursorHelpers
  227925. {
  227926. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227927. {
  227928. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227929. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227930. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227931. [im release];
  227932. return c;
  227933. }
  227934. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227935. {
  227936. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227937. BufferedInputStream buf (fileStream, 4096);
  227938. PNGImageFormat pngFormat;
  227939. Image im (pngFormat.decodeImage (buf));
  227940. if (im.isValid())
  227941. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227942. jassertfalse;
  227943. return 0;
  227944. }
  227945. }
  227946. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227947. {
  227948. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227949. }
  227950. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227951. {
  227952. const ScopedAutoReleasePool pool;
  227953. NSCursor* c = 0;
  227954. switch (type)
  227955. {
  227956. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227957. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227958. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227959. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227960. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227961. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227962. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227963. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227964. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227965. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227966. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227967. case UpDownResizeCursor:
  227968. case TopEdgeResizeCursor:
  227969. case BottomEdgeResizeCursor:
  227970. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227971. case TopLeftCornerResizeCursor:
  227972. case BottomRightCornerResizeCursor:
  227973. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227974. case TopRightCornerResizeCursor:
  227975. case BottomLeftCornerResizeCursor:
  227976. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227977. case UpDownLeftRightResizeCursor:
  227978. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227979. default:
  227980. jassertfalse;
  227981. break;
  227982. }
  227983. [c retain];
  227984. return c;
  227985. }
  227986. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227987. {
  227988. [((NSCursor*) cursorHandle) release];
  227989. }
  227990. void MouseCursor::showInAllWindows() const
  227991. {
  227992. showInWindow (0);
  227993. }
  227994. void MouseCursor::showInWindow (ComponentPeer*) const
  227995. {
  227996. NSCursor* c = (NSCursor*) getHandle();
  227997. if (c == 0)
  227998. c = [NSCursor arrowCursor];
  227999. [c set];
  228000. }
  228001. #else
  228002. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228003. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228004. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228005. void MouseCursor::showInAllWindows() const {}
  228006. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228007. #endif
  228008. #endif
  228009. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228010. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228011. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228012. // compiled on its own).
  228013. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228014. #if JUCE_MAC
  228015. END_JUCE_NAMESPACE
  228016. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228017. @interface DownloadClickDetector : NSObject
  228018. {
  228019. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228020. }
  228021. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228022. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228023. request: (NSURLRequest*) request
  228024. frame: (WebFrame*) frame
  228025. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228026. @end
  228027. @implementation DownloadClickDetector
  228028. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228029. {
  228030. [super init];
  228031. ownerComponent = ownerComponent_;
  228032. return self;
  228033. }
  228034. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228035. request: (NSURLRequest*) request
  228036. frame: (WebFrame*) frame
  228037. decisionListener: (id <WebPolicyDecisionListener>) listener
  228038. {
  228039. (void) sender;
  228040. (void) request;
  228041. (void) frame;
  228042. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228043. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228044. [listener use];
  228045. else
  228046. [listener ignore];
  228047. }
  228048. @end
  228049. BEGIN_JUCE_NAMESPACE
  228050. class WebBrowserComponentInternal : public NSViewComponent
  228051. {
  228052. public:
  228053. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228054. {
  228055. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228056. frameName: @""
  228057. groupName: @""];
  228058. setView (webView);
  228059. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228060. [webView setPolicyDelegate: clickListener];
  228061. }
  228062. ~WebBrowserComponentInternal()
  228063. {
  228064. [webView setPolicyDelegate: nil];
  228065. [clickListener release];
  228066. setView (0);
  228067. }
  228068. void goToURL (const String& url,
  228069. const StringArray* headers,
  228070. const MemoryBlock* postData)
  228071. {
  228072. NSMutableURLRequest* r
  228073. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228074. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228075. timeoutInterval: 30.0];
  228076. if (postData != 0 && postData->getSize() > 0)
  228077. {
  228078. [r setHTTPMethod: @"POST"];
  228079. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228080. length: postData->getSize()]];
  228081. }
  228082. if (headers != 0)
  228083. {
  228084. for (int i = 0; i < headers->size(); ++i)
  228085. {
  228086. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228087. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228088. [r setValue: juceStringToNS (headerValue)
  228089. forHTTPHeaderField: juceStringToNS (headerName)];
  228090. }
  228091. }
  228092. stop();
  228093. [[webView mainFrame] loadRequest: r];
  228094. }
  228095. void goBack()
  228096. {
  228097. [webView goBack];
  228098. }
  228099. void goForward()
  228100. {
  228101. [webView goForward];
  228102. }
  228103. void stop()
  228104. {
  228105. [webView stopLoading: nil];
  228106. }
  228107. void refresh()
  228108. {
  228109. [webView reload: nil];
  228110. }
  228111. void mouseMove (const MouseEvent&)
  228112. {
  228113. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228114. // them work is to push them via this non-public method..
  228115. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228116. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228117. }
  228118. private:
  228119. WebView* webView;
  228120. DownloadClickDetector* clickListener;
  228121. };
  228122. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228123. : browser (0),
  228124. blankPageShown (false),
  228125. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228126. {
  228127. setOpaque (true);
  228128. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228129. }
  228130. WebBrowserComponent::~WebBrowserComponent()
  228131. {
  228132. deleteAndZero (browser);
  228133. }
  228134. void WebBrowserComponent::goToURL (const String& url,
  228135. const StringArray* headers,
  228136. const MemoryBlock* postData)
  228137. {
  228138. lastURL = url;
  228139. lastHeaders.clear();
  228140. if (headers != 0)
  228141. lastHeaders = *headers;
  228142. lastPostData.setSize (0);
  228143. if (postData != 0)
  228144. lastPostData = *postData;
  228145. blankPageShown = false;
  228146. browser->goToURL (url, headers, postData);
  228147. }
  228148. void WebBrowserComponent::stop()
  228149. {
  228150. browser->stop();
  228151. }
  228152. void WebBrowserComponent::goBack()
  228153. {
  228154. lastURL = String::empty;
  228155. blankPageShown = false;
  228156. browser->goBack();
  228157. }
  228158. void WebBrowserComponent::goForward()
  228159. {
  228160. lastURL = String::empty;
  228161. browser->goForward();
  228162. }
  228163. void WebBrowserComponent::refresh()
  228164. {
  228165. browser->refresh();
  228166. }
  228167. void WebBrowserComponent::paint (Graphics&)
  228168. {
  228169. }
  228170. void WebBrowserComponent::checkWindowAssociation()
  228171. {
  228172. if (isShowing())
  228173. {
  228174. if (blankPageShown)
  228175. goBack();
  228176. }
  228177. else
  228178. {
  228179. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228180. {
  228181. // when the component becomes invisible, some stuff like flash
  228182. // carries on playing audio, so we need to force it onto a blank
  228183. // page to avoid this, (and send it back when it's made visible again).
  228184. blankPageShown = true;
  228185. browser->goToURL ("about:blank", 0, 0);
  228186. }
  228187. }
  228188. }
  228189. void WebBrowserComponent::reloadLastURL()
  228190. {
  228191. if (lastURL.isNotEmpty())
  228192. {
  228193. goToURL (lastURL, &lastHeaders, &lastPostData);
  228194. lastURL = String::empty;
  228195. }
  228196. }
  228197. void WebBrowserComponent::parentHierarchyChanged()
  228198. {
  228199. checkWindowAssociation();
  228200. }
  228201. void WebBrowserComponent::resized()
  228202. {
  228203. browser->setSize (getWidth(), getHeight());
  228204. }
  228205. void WebBrowserComponent::visibilityChanged()
  228206. {
  228207. checkWindowAssociation();
  228208. }
  228209. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228210. {
  228211. return true;
  228212. }
  228213. #else
  228214. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228215. {
  228216. }
  228217. WebBrowserComponent::~WebBrowserComponent()
  228218. {
  228219. }
  228220. void WebBrowserComponent::goToURL (const String& url,
  228221. const StringArray* headers,
  228222. const MemoryBlock* postData)
  228223. {
  228224. }
  228225. void WebBrowserComponent::stop()
  228226. {
  228227. }
  228228. void WebBrowserComponent::goBack()
  228229. {
  228230. }
  228231. void WebBrowserComponent::goForward()
  228232. {
  228233. }
  228234. void WebBrowserComponent::refresh()
  228235. {
  228236. }
  228237. void WebBrowserComponent::paint (Graphics& g)
  228238. {
  228239. }
  228240. void WebBrowserComponent::checkWindowAssociation()
  228241. {
  228242. }
  228243. void WebBrowserComponent::reloadLastURL()
  228244. {
  228245. }
  228246. void WebBrowserComponent::parentHierarchyChanged()
  228247. {
  228248. }
  228249. void WebBrowserComponent::resized()
  228250. {
  228251. }
  228252. void WebBrowserComponent::visibilityChanged()
  228253. {
  228254. }
  228255. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228256. {
  228257. return true;
  228258. }
  228259. #endif
  228260. #endif
  228261. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228262. /*** Start of inlined file: juce_ios_Audio.cpp ***/
  228263. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228264. // compiled on its own).
  228265. #if JUCE_INCLUDED_FILE
  228266. class IPhoneAudioIODevice : public AudioIODevice
  228267. {
  228268. public:
  228269. IPhoneAudioIODevice (const String& deviceName)
  228270. : AudioIODevice (deviceName, "Audio"),
  228271. actualBufferSize (0),
  228272. isRunning (false),
  228273. audioUnit (0),
  228274. callback (0),
  228275. floatData (1, 2)
  228276. {
  228277. numInputChannels = 2;
  228278. numOutputChannels = 2;
  228279. preferredBufferSize = 0;
  228280. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228281. updateDeviceInfo();
  228282. }
  228283. ~IPhoneAudioIODevice()
  228284. {
  228285. close();
  228286. }
  228287. const StringArray getOutputChannelNames()
  228288. {
  228289. StringArray s;
  228290. s.add ("Left");
  228291. s.add ("Right");
  228292. return s;
  228293. }
  228294. const StringArray getInputChannelNames()
  228295. {
  228296. StringArray s;
  228297. if (audioInputIsAvailable)
  228298. {
  228299. s.add ("Left");
  228300. s.add ("Right");
  228301. }
  228302. return s;
  228303. }
  228304. int getNumSampleRates()
  228305. {
  228306. return 1;
  228307. }
  228308. double getSampleRate (int index)
  228309. {
  228310. return sampleRate;
  228311. }
  228312. int getNumBufferSizesAvailable()
  228313. {
  228314. return 1;
  228315. }
  228316. int getBufferSizeSamples (int index)
  228317. {
  228318. return getDefaultBufferSize();
  228319. }
  228320. int getDefaultBufferSize()
  228321. {
  228322. return 1024;
  228323. }
  228324. const String open (const BigInteger& inputChannels,
  228325. const BigInteger& outputChannels,
  228326. double sampleRate,
  228327. int bufferSize)
  228328. {
  228329. close();
  228330. lastError = String::empty;
  228331. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228332. // xxx set up channel mapping
  228333. activeOutputChans = outputChannels;
  228334. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228335. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228336. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228337. activeInputChans = inputChannels;
  228338. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228339. numInputChannels = activeInputChans.countNumberOfSetBits();
  228340. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228341. AudioSessionSetActive (true);
  228342. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228343. : kAudioSessionCategory_MediaPlayback;
  228344. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228345. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228346. fixAudioRouteIfSetToReceiver();
  228347. updateDeviceInfo();
  228348. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228349. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228350. actualBufferSize = preferredBufferSize;
  228351. prepareFloatBuffers();
  228352. isRunning = true;
  228353. propertyChanged (0, 0, 0); // creates and starts the AU
  228354. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228355. return lastError;
  228356. }
  228357. void close()
  228358. {
  228359. if (isRunning)
  228360. {
  228361. isRunning = false;
  228362. AudioSessionSetActive (false);
  228363. if (audioUnit != 0)
  228364. {
  228365. AudioComponentInstanceDispose (audioUnit);
  228366. audioUnit = 0;
  228367. }
  228368. }
  228369. }
  228370. bool isOpen()
  228371. {
  228372. return isRunning;
  228373. }
  228374. int getCurrentBufferSizeSamples()
  228375. {
  228376. return actualBufferSize;
  228377. }
  228378. double getCurrentSampleRate()
  228379. {
  228380. return sampleRate;
  228381. }
  228382. int getCurrentBitDepth()
  228383. {
  228384. return 16;
  228385. }
  228386. const BigInteger getActiveOutputChannels() const
  228387. {
  228388. return activeOutputChans;
  228389. }
  228390. const BigInteger getActiveInputChannels() const
  228391. {
  228392. return activeInputChans;
  228393. }
  228394. int getOutputLatencyInSamples()
  228395. {
  228396. return 0; //xxx
  228397. }
  228398. int getInputLatencyInSamples()
  228399. {
  228400. return 0; //xxx
  228401. }
  228402. void start (AudioIODeviceCallback* callback_)
  228403. {
  228404. if (isRunning && callback != callback_)
  228405. {
  228406. if (callback_ != 0)
  228407. callback_->audioDeviceAboutToStart (this);
  228408. const ScopedLock sl (callbackLock);
  228409. callback = callback_;
  228410. }
  228411. }
  228412. void stop()
  228413. {
  228414. if (isRunning)
  228415. {
  228416. AudioIODeviceCallback* lastCallback;
  228417. {
  228418. const ScopedLock sl (callbackLock);
  228419. lastCallback = callback;
  228420. callback = 0;
  228421. }
  228422. if (lastCallback != 0)
  228423. lastCallback->audioDeviceStopped();
  228424. }
  228425. }
  228426. bool isPlaying()
  228427. {
  228428. return isRunning && callback != 0;
  228429. }
  228430. const String getLastError()
  228431. {
  228432. return lastError;
  228433. }
  228434. private:
  228435. CriticalSection callbackLock;
  228436. Float64 sampleRate;
  228437. int numInputChannels, numOutputChannels;
  228438. int preferredBufferSize;
  228439. int actualBufferSize;
  228440. bool isRunning;
  228441. String lastError;
  228442. AudioStreamBasicDescription format;
  228443. AudioUnit audioUnit;
  228444. UInt32 audioInputIsAvailable;
  228445. AudioIODeviceCallback* callback;
  228446. BigInteger activeOutputChans, activeInputChans;
  228447. AudioSampleBuffer floatData;
  228448. float* inputChannels[3];
  228449. float* outputChannels[3];
  228450. bool monoInputChannelNumber, monoOutputChannelNumber;
  228451. void prepareFloatBuffers()
  228452. {
  228453. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228454. zerostruct (inputChannels);
  228455. zerostruct (outputChannels);
  228456. for (int i = 0; i < numInputChannels; ++i)
  228457. inputChannels[i] = floatData.getSampleData (i);
  228458. for (int i = 0; i < numOutputChannels; ++i)
  228459. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228460. }
  228461. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228462. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228463. {
  228464. OSStatus err = noErr;
  228465. if (audioInputIsAvailable)
  228466. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228467. const ScopedLock sl (callbackLock);
  228468. if (callback != 0)
  228469. {
  228470. if (audioInputIsAvailable && numInputChannels > 0)
  228471. {
  228472. short* shortData = (short*) ioData->mBuffers[0].mData;
  228473. if (numInputChannels >= 2)
  228474. {
  228475. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228476. {
  228477. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228478. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228479. }
  228480. }
  228481. else
  228482. {
  228483. if (monoInputChannelNumber > 0)
  228484. ++shortData;
  228485. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228486. {
  228487. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228488. ++shortData;
  228489. }
  228490. }
  228491. }
  228492. else
  228493. {
  228494. for (int i = numInputChannels; --i >= 0;)
  228495. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228496. }
  228497. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228498. outputChannels, numOutputChannels,
  228499. (int) inNumberFrames);
  228500. short* shortData = (short*) ioData->mBuffers[0].mData;
  228501. int n = 0;
  228502. if (numOutputChannels >= 2)
  228503. {
  228504. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228505. {
  228506. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228507. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228508. }
  228509. }
  228510. else if (numOutputChannels == 1)
  228511. {
  228512. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228513. {
  228514. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228515. shortData [n++] = s;
  228516. shortData [n++] = s;
  228517. }
  228518. }
  228519. else
  228520. {
  228521. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228522. }
  228523. }
  228524. else
  228525. {
  228526. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228527. }
  228528. return err;
  228529. }
  228530. void updateDeviceInfo()
  228531. {
  228532. UInt32 size = sizeof (sampleRate);
  228533. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228534. size = sizeof (audioInputIsAvailable);
  228535. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228536. }
  228537. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228538. {
  228539. if (! isRunning)
  228540. return;
  228541. if (inPropertyValue != 0)
  228542. {
  228543. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228544. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228545. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228546. SInt32 routeChangeReason;
  228547. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228548. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228549. fixAudioRouteIfSetToReceiver();
  228550. }
  228551. updateDeviceInfo();
  228552. createAudioUnit();
  228553. AudioSessionSetActive (true);
  228554. if (audioUnit != 0)
  228555. {
  228556. UInt32 formatSize = sizeof (format);
  228557. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  228558. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228559. UInt32 bufferDurationSize = sizeof (bufferDuration);
  228560. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  228561. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  228562. AudioOutputUnitStart (audioUnit);
  228563. }
  228564. }
  228565. void interruptionListener (UInt32 inInterruption)
  228566. {
  228567. /*if (inInterruption == kAudioSessionBeginInterruption)
  228568. {
  228569. isRunning = false;
  228570. AudioOutputUnitStop (audioUnit);
  228571. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  228572. "This could have been interrupted by another application or by unplugging a headset",
  228573. @"Resume",
  228574. @"Cancel"))
  228575. {
  228576. isRunning = true;
  228577. propertyChanged (0, 0, 0);
  228578. }
  228579. }*/
  228580. if (inInterruption == kAudioSessionEndInterruption)
  228581. {
  228582. isRunning = true;
  228583. AudioSessionSetActive (true);
  228584. AudioOutputUnitStart (audioUnit);
  228585. }
  228586. }
  228587. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228588. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228589. {
  228590. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  228591. }
  228592. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228593. {
  228594. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  228595. }
  228596. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  228597. {
  228598. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  228599. }
  228600. void resetFormat (const int numChannels)
  228601. {
  228602. memset (&format, 0, sizeof (format));
  228603. format.mFormatID = kAudioFormatLinearPCM;
  228604. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  228605. format.mBitsPerChannel = 8 * sizeof (short);
  228606. format.mChannelsPerFrame = 2;
  228607. format.mFramesPerPacket = 1;
  228608. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  228609. }
  228610. bool createAudioUnit()
  228611. {
  228612. if (audioUnit != 0)
  228613. {
  228614. AudioComponentInstanceDispose (audioUnit);
  228615. audioUnit = 0;
  228616. }
  228617. resetFormat (2);
  228618. AudioComponentDescription desc;
  228619. desc.componentType = kAudioUnitType_Output;
  228620. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  228621. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  228622. desc.componentFlags = 0;
  228623. desc.componentFlagsMask = 0;
  228624. AudioComponent comp = AudioComponentFindNext (0, &desc);
  228625. AudioComponentInstanceNew (comp, &audioUnit);
  228626. if (audioUnit == 0)
  228627. return false;
  228628. const UInt32 one = 1;
  228629. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  228630. AudioChannelLayout layout;
  228631. layout.mChannelBitmap = 0;
  228632. layout.mNumberChannelDescriptions = 0;
  228633. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  228634. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  228635. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  228636. AURenderCallbackStruct inputProc;
  228637. inputProc.inputProc = processStatic;
  228638. inputProc.inputProcRefCon = this;
  228639. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  228640. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  228641. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  228642. AudioUnitInitialize (audioUnit);
  228643. return true;
  228644. }
  228645. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  228646. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  228647. static void fixAudioRouteIfSetToReceiver()
  228648. {
  228649. CFStringRef audioRoute = 0;
  228650. UInt32 propertySize = sizeof (audioRoute);
  228651. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  228652. {
  228653. NSString* route = (NSString*) audioRoute;
  228654. //DBG ("audio route: " + nsStringToJuce (route));
  228655. if ([route hasPrefix: @"Receiver"])
  228656. {
  228657. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  228658. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228659. }
  228660. CFRelease (audioRoute);
  228661. }
  228662. }
  228663. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  228664. };
  228665. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228666. {
  228667. public:
  228668. IPhoneAudioIODeviceType()
  228669. : AudioIODeviceType ("iPhone Audio")
  228670. {
  228671. }
  228672. void scanForDevices()
  228673. {
  228674. }
  228675. const StringArray getDeviceNames (bool wantInputNames) const
  228676. {
  228677. StringArray s;
  228678. s.add ("iPhone Audio");
  228679. return s;
  228680. }
  228681. int getDefaultDeviceIndex (bool forInput) const
  228682. {
  228683. return 0;
  228684. }
  228685. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228686. {
  228687. return device != 0 ? 0 : -1;
  228688. }
  228689. bool hasSeparateInputsAndOutputs() const { return false; }
  228690. AudioIODevice* createDevice (const String& outputDeviceName,
  228691. const String& inputDeviceName)
  228692. {
  228693. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228694. {
  228695. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228696. : inputDeviceName);
  228697. }
  228698. return 0;
  228699. }
  228700. private:
  228701. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  228702. };
  228703. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228704. {
  228705. return new IPhoneAudioIODeviceType();
  228706. }
  228707. #endif
  228708. /*** End of inlined file: juce_ios_Audio.cpp ***/
  228709. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228710. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228711. // compiled on its own).
  228712. #if JUCE_INCLUDED_FILE
  228713. #if JUCE_MAC
  228714. namespace CoreMidiHelpers
  228715. {
  228716. bool logError (const OSStatus err, const int lineNum)
  228717. {
  228718. if (err == noErr)
  228719. return true;
  228720. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228721. jassertfalse;
  228722. return false;
  228723. }
  228724. #undef CHECK_ERROR
  228725. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  228726. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228727. {
  228728. String result;
  228729. CFStringRef str = 0;
  228730. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228731. if (str != 0)
  228732. {
  228733. result = PlatformUtilities::cfStringToJuceString (str);
  228734. CFRelease (str);
  228735. str = 0;
  228736. }
  228737. MIDIEntityRef entity = 0;
  228738. MIDIEndpointGetEntity (endpoint, &entity);
  228739. if (entity == 0)
  228740. return result; // probably virtual
  228741. if (result.isEmpty())
  228742. {
  228743. // endpoint name has zero length - try the entity
  228744. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228745. if (str != 0)
  228746. {
  228747. result += PlatformUtilities::cfStringToJuceString (str);
  228748. CFRelease (str);
  228749. str = 0;
  228750. }
  228751. }
  228752. // now consider the device's name
  228753. MIDIDeviceRef device = 0;
  228754. MIDIEntityGetDevice (entity, &device);
  228755. if (device == 0)
  228756. return result;
  228757. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228758. if (str != 0)
  228759. {
  228760. const String s (PlatformUtilities::cfStringToJuceString (str));
  228761. CFRelease (str);
  228762. // if an external device has only one entity, throw away
  228763. // the endpoint name and just use the device name
  228764. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228765. {
  228766. result = s;
  228767. }
  228768. else if (! result.startsWithIgnoreCase (s))
  228769. {
  228770. // prepend the device name to the entity name
  228771. result = (s + " " + result).trimEnd();
  228772. }
  228773. }
  228774. return result;
  228775. }
  228776. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228777. {
  228778. String result;
  228779. // Does the endpoint have connections?
  228780. CFDataRef connections = 0;
  228781. int numConnections = 0;
  228782. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228783. if (connections != 0)
  228784. {
  228785. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228786. if (numConnections > 0)
  228787. {
  228788. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228789. for (int i = 0; i < numConnections; ++i, ++pid)
  228790. {
  228791. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228792. MIDIObjectRef connObject;
  228793. MIDIObjectType connObjectType;
  228794. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228795. if (err == noErr)
  228796. {
  228797. String s;
  228798. if (connObjectType == kMIDIObjectType_ExternalSource
  228799. || connObjectType == kMIDIObjectType_ExternalDestination)
  228800. {
  228801. // Connected to an external device's endpoint (10.3 and later).
  228802. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228803. }
  228804. else
  228805. {
  228806. // Connected to an external device (10.2) (or something else, catch-all)
  228807. CFStringRef str = 0;
  228808. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228809. if (str != 0)
  228810. {
  228811. s = PlatformUtilities::cfStringToJuceString (str);
  228812. CFRelease (str);
  228813. }
  228814. }
  228815. if (s.isNotEmpty())
  228816. {
  228817. if (result.isNotEmpty())
  228818. result += ", ";
  228819. result += s;
  228820. }
  228821. }
  228822. }
  228823. }
  228824. CFRelease (connections);
  228825. }
  228826. if (result.isNotEmpty())
  228827. return result;
  228828. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228829. return getEndpointName (endpoint, false);
  228830. }
  228831. MIDIClientRef getGlobalMidiClient()
  228832. {
  228833. static MIDIClientRef globalMidiClient = 0;
  228834. if (globalMidiClient == 0)
  228835. {
  228836. String name ("JUCE");
  228837. if (JUCEApplication::getInstance() != 0)
  228838. name = JUCEApplication::getInstance()->getApplicationName();
  228839. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228840. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228841. CFRelease (appName);
  228842. }
  228843. return globalMidiClient;
  228844. }
  228845. class MidiPortAndEndpoint
  228846. {
  228847. public:
  228848. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228849. : port (port_), endPoint (endPoint_)
  228850. {
  228851. }
  228852. ~MidiPortAndEndpoint()
  228853. {
  228854. if (port != 0)
  228855. MIDIPortDispose (port);
  228856. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228857. MIDIEndpointDispose (endPoint);
  228858. }
  228859. void send (const MIDIPacketList* const packets)
  228860. {
  228861. if (port != 0)
  228862. MIDISend (port, endPoint, packets);
  228863. else
  228864. MIDIReceived (endPoint, packets);
  228865. }
  228866. MIDIPortRef port;
  228867. MIDIEndpointRef endPoint;
  228868. };
  228869. class MidiPortAndCallback;
  228870. CriticalSection callbackLock;
  228871. Array<MidiPortAndCallback*> activeCallbacks;
  228872. class MidiPortAndCallback
  228873. {
  228874. public:
  228875. MidiPortAndCallback (MidiInputCallback& callback_)
  228876. : input (0), active (false), callback (callback_), concatenator (2048)
  228877. {
  228878. }
  228879. ~MidiPortAndCallback()
  228880. {
  228881. active = false;
  228882. {
  228883. const ScopedLock sl (callbackLock);
  228884. activeCallbacks.removeValue (this);
  228885. }
  228886. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  228887. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  228888. }
  228889. void handlePackets (const MIDIPacketList* const pktlist)
  228890. {
  228891. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  228892. const ScopedLock sl (callbackLock);
  228893. if (activeCallbacks.contains (this) && active)
  228894. {
  228895. const MIDIPacket* packet = &pktlist->packet[0];
  228896. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228897. {
  228898. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  228899. input, callback);
  228900. packet = MIDIPacketNext (packet);
  228901. }
  228902. }
  228903. }
  228904. MidiInput* input;
  228905. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  228906. volatile bool active;
  228907. private:
  228908. MidiInputCallback& callback;
  228909. MidiDataConcatenator concatenator;
  228910. };
  228911. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  228912. {
  228913. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  228914. }
  228915. }
  228916. const StringArray MidiOutput::getDevices()
  228917. {
  228918. StringArray s;
  228919. const ItemCount num = MIDIGetNumberOfDestinations();
  228920. for (ItemCount i = 0; i < num; ++i)
  228921. {
  228922. MIDIEndpointRef dest = MIDIGetDestination (i);
  228923. if (dest != 0)
  228924. {
  228925. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  228926. if (name.isEmpty())
  228927. name = "<error>";
  228928. s.add (name);
  228929. }
  228930. else
  228931. {
  228932. s.add ("<error>");
  228933. }
  228934. }
  228935. return s;
  228936. }
  228937. int MidiOutput::getDefaultDeviceIndex()
  228938. {
  228939. return 0;
  228940. }
  228941. MidiOutput* MidiOutput::openDevice (int index)
  228942. {
  228943. MidiOutput* mo = 0;
  228944. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  228945. {
  228946. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228947. CFStringRef pname;
  228948. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228949. {
  228950. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228951. MIDIPortRef port;
  228952. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  228953. {
  228954. mo = new MidiOutput();
  228955. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  228956. }
  228957. CFRelease (pname);
  228958. }
  228959. }
  228960. return mo;
  228961. }
  228962. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228963. {
  228964. MidiOutput* mo = 0;
  228965. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228966. MIDIEndpointRef endPoint;
  228967. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228968. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  228969. {
  228970. mo = new MidiOutput();
  228971. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  228972. }
  228973. CFRelease (name);
  228974. return mo;
  228975. }
  228976. MidiOutput::~MidiOutput()
  228977. {
  228978. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  228979. }
  228980. void MidiOutput::reset()
  228981. {
  228982. }
  228983. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228984. {
  228985. return false;
  228986. }
  228987. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228988. {
  228989. }
  228990. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228991. {
  228992. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  228993. if (message.isSysEx())
  228994. {
  228995. const int maxPacketSize = 256;
  228996. int pos = 0, bytesLeft = message.getRawDataSize();
  228997. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228998. HeapBlock <MIDIPacketList> packets;
  228999. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229000. packets->numPackets = numPackets;
  229001. MIDIPacket* p = packets->packet;
  229002. for (int i = 0; i < numPackets; ++i)
  229003. {
  229004. p->timeStamp = AudioGetCurrentHostTime();
  229005. p->length = jmin (maxPacketSize, bytesLeft);
  229006. memcpy (p->data, message.getRawData() + pos, p->length);
  229007. pos += p->length;
  229008. bytesLeft -= p->length;
  229009. p = MIDIPacketNext (p);
  229010. }
  229011. mpe->send (packets);
  229012. }
  229013. else
  229014. {
  229015. MIDIPacketList packets;
  229016. packets.numPackets = 1;
  229017. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229018. packets.packet[0].length = message.getRawDataSize();
  229019. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229020. mpe->send (&packets);
  229021. }
  229022. }
  229023. const StringArray MidiInput::getDevices()
  229024. {
  229025. StringArray s;
  229026. const ItemCount num = MIDIGetNumberOfSources();
  229027. for (ItemCount i = 0; i < num; ++i)
  229028. {
  229029. MIDIEndpointRef source = MIDIGetSource (i);
  229030. if (source != 0)
  229031. {
  229032. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229033. if (name.isEmpty())
  229034. name = "<error>";
  229035. s.add (name);
  229036. }
  229037. else
  229038. {
  229039. s.add ("<error>");
  229040. }
  229041. }
  229042. return s;
  229043. }
  229044. int MidiInput::getDefaultDeviceIndex()
  229045. {
  229046. return 0;
  229047. }
  229048. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229049. {
  229050. jassert (callback != 0);
  229051. using namespace CoreMidiHelpers;
  229052. MidiInput* newInput = 0;
  229053. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229054. {
  229055. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229056. if (endPoint != 0)
  229057. {
  229058. CFStringRef name;
  229059. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229060. {
  229061. MIDIClientRef client = getGlobalMidiClient();
  229062. if (client != 0)
  229063. {
  229064. MIDIPortRef port;
  229065. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229066. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229067. {
  229068. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229069. {
  229070. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229071. newInput = new MidiInput (getDevices() [index]);
  229072. mpc->input = newInput;
  229073. newInput->internal = mpc;
  229074. const ScopedLock sl (callbackLock);
  229075. activeCallbacks.add (mpc.release());
  229076. }
  229077. else
  229078. {
  229079. CHECK_ERROR (MIDIPortDispose (port));
  229080. }
  229081. }
  229082. }
  229083. }
  229084. CFRelease (name);
  229085. }
  229086. }
  229087. return newInput;
  229088. }
  229089. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229090. {
  229091. jassert (callback != 0);
  229092. using namespace CoreMidiHelpers;
  229093. MidiInput* mi = 0;
  229094. MIDIClientRef client = getGlobalMidiClient();
  229095. if (client != 0)
  229096. {
  229097. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229098. mpc->active = false;
  229099. MIDIEndpointRef endPoint;
  229100. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229101. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229102. {
  229103. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229104. mi = new MidiInput (deviceName);
  229105. mpc->input = mi;
  229106. mi->internal = mpc;
  229107. const ScopedLock sl (callbackLock);
  229108. activeCallbacks.add (mpc.release());
  229109. }
  229110. CFRelease (name);
  229111. }
  229112. return mi;
  229113. }
  229114. MidiInput::MidiInput (const String& name_)
  229115. : name (name_)
  229116. {
  229117. }
  229118. MidiInput::~MidiInput()
  229119. {
  229120. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229121. }
  229122. void MidiInput::start()
  229123. {
  229124. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229125. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229126. }
  229127. void MidiInput::stop()
  229128. {
  229129. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229130. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229131. }
  229132. #undef CHECK_ERROR
  229133. #else // Stubs for iOS...
  229134. MidiOutput::~MidiOutput() {}
  229135. void MidiOutput::reset() {}
  229136. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229137. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229138. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229139. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229140. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229141. const StringArray MidiInput::getDevices() { return StringArray(); }
  229142. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229143. #endif
  229144. #endif
  229145. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229146. #else
  229147. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229148. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229149. // compiled on its own).
  229150. #if JUCE_INCLUDED_FILE
  229151. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229152. #define SUPPORT_10_4_FONTS 1
  229153. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229154. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229155. #define SUPPORT_ONLY_10_4_FONTS 1
  229156. #endif
  229157. END_JUCE_NAMESPACE
  229158. @interface NSFont (PrivateHack)
  229159. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229160. @end
  229161. BEGIN_JUCE_NAMESPACE
  229162. #endif
  229163. class MacTypeface : public Typeface
  229164. {
  229165. public:
  229166. MacTypeface (const Font& font)
  229167. : Typeface (font.getTypefaceName())
  229168. {
  229169. const ScopedAutoReleasePool pool;
  229170. renderingTransform = CGAffineTransformIdentity;
  229171. bool needsItalicTransform = false;
  229172. #if JUCE_IOS
  229173. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229174. if (font.isItalic() || font.isBold())
  229175. {
  229176. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229177. for (NSString* i in familyFonts)
  229178. {
  229179. const String fn (nsStringToJuce (i));
  229180. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229181. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229182. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229183. || afterDash.containsIgnoreCase ("italic")
  229184. || fn.endsWithIgnoreCase ("oblique")
  229185. || fn.endsWithIgnoreCase ("italic");
  229186. if (probablyBold == font.isBold()
  229187. && probablyItalic == font.isItalic())
  229188. {
  229189. fontName = i;
  229190. needsItalicTransform = false;
  229191. break;
  229192. }
  229193. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229194. {
  229195. fontName = i;
  229196. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229197. }
  229198. }
  229199. if (needsItalicTransform)
  229200. renderingTransform.c = 0.15f;
  229201. }
  229202. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229203. const int ascender = abs (CGFontGetAscent (fontRef));
  229204. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229205. ascent = ascender / totalHeight;
  229206. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229207. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229208. #else
  229209. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229210. if (font.isItalic())
  229211. {
  229212. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229213. toHaveTrait: NSItalicFontMask];
  229214. if (newFont == nsFont)
  229215. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229216. nsFont = newFont;
  229217. }
  229218. if (font.isBold())
  229219. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229220. [nsFont retain];
  229221. ascent = std::abs ((float) [nsFont ascender]);
  229222. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229223. ascent /= totalSize;
  229224. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229225. if (needsItalicTransform)
  229226. {
  229227. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229228. renderingTransform.c = 0.15f;
  229229. }
  229230. #if SUPPORT_ONLY_10_4_FONTS
  229231. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229232. if (atsFont == 0)
  229233. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229234. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229235. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229236. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229237. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229238. #else
  229239. #if SUPPORT_10_4_FONTS
  229240. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229241. {
  229242. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229243. if (atsFont == 0)
  229244. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229245. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229246. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229247. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229248. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229249. }
  229250. else
  229251. #endif
  229252. {
  229253. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229254. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229255. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229256. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229257. }
  229258. #endif
  229259. #endif
  229260. }
  229261. ~MacTypeface()
  229262. {
  229263. #if ! JUCE_IOS
  229264. [nsFont release];
  229265. #endif
  229266. if (fontRef != 0)
  229267. CGFontRelease (fontRef);
  229268. }
  229269. float getAscent() const
  229270. {
  229271. return ascent;
  229272. }
  229273. float getDescent() const
  229274. {
  229275. return 1.0f - ascent;
  229276. }
  229277. float getStringWidth (const String& text)
  229278. {
  229279. if (fontRef == 0 || text.isEmpty())
  229280. return 0;
  229281. const int length = text.length();
  229282. HeapBlock <CGGlyph> glyphs;
  229283. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229284. float x = 0;
  229285. #if SUPPORT_ONLY_10_4_FONTS
  229286. HeapBlock <NSSize> advances (length);
  229287. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229288. for (int i = 0; i < length; ++i)
  229289. x += advances[i].width;
  229290. #else
  229291. #if SUPPORT_10_4_FONTS
  229292. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229293. {
  229294. HeapBlock <NSSize> advances (length);
  229295. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229296. for (int i = 0; i < length; ++i)
  229297. x += advances[i].width;
  229298. }
  229299. else
  229300. #endif
  229301. {
  229302. HeapBlock <int> advances (length);
  229303. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229304. for (int i = 0; i < length; ++i)
  229305. x += advances[i];
  229306. }
  229307. #endif
  229308. return x * unitsToHeightScaleFactor;
  229309. }
  229310. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229311. {
  229312. xOffsets.add (0);
  229313. if (fontRef == 0 || text.isEmpty())
  229314. return;
  229315. const int length = text.length();
  229316. HeapBlock <CGGlyph> glyphs;
  229317. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229318. #if SUPPORT_ONLY_10_4_FONTS
  229319. HeapBlock <NSSize> advances (length);
  229320. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229321. int x = 0;
  229322. for (int i = 0; i < length; ++i)
  229323. {
  229324. x += advances[i].width;
  229325. xOffsets.add (x * unitsToHeightScaleFactor);
  229326. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229327. }
  229328. #else
  229329. #if SUPPORT_10_4_FONTS
  229330. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229331. {
  229332. HeapBlock <NSSize> advances (length);
  229333. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229334. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229335. float x = 0;
  229336. for (int i = 0; i < length; ++i)
  229337. {
  229338. x += advances[i].width;
  229339. xOffsets.add (x * unitsToHeightScaleFactor);
  229340. resultGlyphs.add (nsGlyphs[i]);
  229341. }
  229342. }
  229343. else
  229344. #endif
  229345. {
  229346. HeapBlock <int> advances (length);
  229347. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229348. {
  229349. int x = 0;
  229350. for (int i = 0; i < length; ++i)
  229351. {
  229352. x += advances [i];
  229353. xOffsets.add (x * unitsToHeightScaleFactor);
  229354. resultGlyphs.add (glyphs[i]);
  229355. }
  229356. }
  229357. }
  229358. #endif
  229359. }
  229360. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229361. {
  229362. #if JUCE_IOS
  229363. return false;
  229364. #else
  229365. if (nsFont == 0)
  229366. return false;
  229367. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229368. jassert (path.isEmpty());
  229369. const ScopedAutoReleasePool pool;
  229370. NSBezierPath* bez = [NSBezierPath bezierPath];
  229371. [bez moveToPoint: NSMakePoint (0, 0)];
  229372. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229373. inFont: nsFont];
  229374. for (int i = 0; i < [bez elementCount]; ++i)
  229375. {
  229376. NSPoint p[3];
  229377. switch ([bez elementAtIndex: i associatedPoints: p])
  229378. {
  229379. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229380. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229381. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229382. (float) p[1].x, (float) -p[1].y,
  229383. (float) p[2].x, (float) -p[2].y); break;
  229384. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229385. default: jassertfalse; break;
  229386. }
  229387. }
  229388. path.applyTransform (pathTransform);
  229389. return true;
  229390. #endif
  229391. }
  229392. CGFontRef fontRef;
  229393. float fontHeightToCGSizeFactor;
  229394. CGAffineTransform renderingTransform;
  229395. private:
  229396. float ascent, unitsToHeightScaleFactor;
  229397. #if JUCE_IOS
  229398. #else
  229399. NSFont* nsFont;
  229400. AffineTransform pathTransform;
  229401. #endif
  229402. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  229403. {
  229404. #if SUPPORT_10_4_FONTS
  229405. #if ! SUPPORT_ONLY_10_4_FONTS
  229406. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229407. #endif
  229408. {
  229409. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229410. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229411. for (int i = 0; i < length; ++i)
  229412. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  229413. return;
  229414. }
  229415. #endif
  229416. #if ! SUPPORT_ONLY_10_4_FONTS
  229417. if (charToGlyphMapper == 0)
  229418. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229419. glyphs.malloc (length);
  229420. for (int i = 0; i < length; ++i)
  229421. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  229422. #endif
  229423. }
  229424. #if ! SUPPORT_ONLY_10_4_FONTS
  229425. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229426. class CharToGlyphMapper
  229427. {
  229428. public:
  229429. CharToGlyphMapper (CGFontRef fontRef)
  229430. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229431. idRangeOffset (0), glyphIndexes (0)
  229432. {
  229433. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229434. if (cmapTable != 0)
  229435. {
  229436. const int numSubtables = getValue16 (cmapTable, 2);
  229437. for (int i = 0; i < numSubtables; ++i)
  229438. {
  229439. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229440. {
  229441. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229442. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229443. {
  229444. const int length = getValue16 (cmapTable, offset + 2);
  229445. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229446. segCount = segCountX2 / 2;
  229447. const int endCodeOffset = offset + 14;
  229448. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229449. const int idDeltaOffset = startCodeOffset + segCountX2;
  229450. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229451. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229452. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229453. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229454. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229455. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229456. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229457. }
  229458. break;
  229459. }
  229460. }
  229461. CFRelease (cmapTable);
  229462. }
  229463. }
  229464. ~CharToGlyphMapper()
  229465. {
  229466. if (endCode != 0)
  229467. {
  229468. CFRelease (endCode);
  229469. CFRelease (startCode);
  229470. CFRelease (idDelta);
  229471. CFRelease (idRangeOffset);
  229472. CFRelease (glyphIndexes);
  229473. }
  229474. }
  229475. int getGlyphForCharacter (const juce_wchar c) const
  229476. {
  229477. for (int i = 0; i < segCount; ++i)
  229478. {
  229479. if (getValue16 (endCode, i * 2) >= c)
  229480. {
  229481. const int start = getValue16 (startCode, i * 2);
  229482. if (start > c)
  229483. break;
  229484. const int delta = getValue16 (idDelta, i * 2);
  229485. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229486. if (rangeOffset == 0)
  229487. return delta + c;
  229488. else
  229489. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229490. }
  229491. }
  229492. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229493. return jmax (-1, (int) c - 29);
  229494. }
  229495. private:
  229496. int segCount;
  229497. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229498. static uint16 getValue16 (CFDataRef data, const int index)
  229499. {
  229500. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229501. }
  229502. static uint32 getValue32 (CFDataRef data, const int index)
  229503. {
  229504. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229505. }
  229506. };
  229507. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229508. #endif
  229509. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229510. };
  229511. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229512. {
  229513. return new MacTypeface (font);
  229514. }
  229515. const StringArray Font::findAllTypefaceNames()
  229516. {
  229517. StringArray names;
  229518. const ScopedAutoReleasePool pool;
  229519. #if JUCE_IOS
  229520. NSArray* fonts = [UIFont familyNames];
  229521. #else
  229522. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229523. #endif
  229524. for (unsigned int i = 0; i < [fonts count]; ++i)
  229525. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229526. names.sort (true);
  229527. return names;
  229528. }
  229529. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229530. {
  229531. #if JUCE_IOS
  229532. defaultSans = "Helvetica";
  229533. defaultSerif = "Times New Roman";
  229534. defaultFixed = "Courier New";
  229535. #else
  229536. defaultSans = "Lucida Grande";
  229537. defaultSerif = "Times New Roman";
  229538. defaultFixed = "Monaco";
  229539. #endif
  229540. defaultFallback = "Arial Unicode MS";
  229541. }
  229542. #endif
  229543. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229544. // (must go before juce_mac_CoreGraphicsContext.mm)
  229545. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229546. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229547. // compiled on its own).
  229548. #if JUCE_INCLUDED_FILE
  229549. class CoreGraphicsImage : public Image::SharedImage
  229550. {
  229551. public:
  229552. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229553. : Image::SharedImage (format_, width_, height_)
  229554. {
  229555. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229556. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229557. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229558. imageData = imageDataAllocated;
  229559. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229560. : CGColorSpaceCreateDeviceRGB();
  229561. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229562. colourSpace, getCGImageFlags (format_));
  229563. CGColorSpaceRelease (colourSpace);
  229564. }
  229565. ~CoreGraphicsImage()
  229566. {
  229567. CGContextRelease (context);
  229568. }
  229569. Image::ImageType getType() const { return Image::NativeImage; }
  229570. LowLevelGraphicsContext* createLowLevelContext();
  229571. SharedImage* clone()
  229572. {
  229573. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229574. memcpy (im->imageData, imageData, lineStride * height);
  229575. return im;
  229576. }
  229577. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  229578. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  229579. {
  229580. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229581. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229582. {
  229583. return CGBitmapContextCreateImage (nativeImage->context);
  229584. }
  229585. else
  229586. {
  229587. const Image::BitmapData srcData (juceImage, false);
  229588. CGDataProviderRef provider;
  229589. if (mustOutliveSource)
  229590. {
  229591. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  229592. provider = CGDataProviderCreateWithCFData (data);
  229593. CFRelease (data);
  229594. }
  229595. else
  229596. {
  229597. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229598. }
  229599. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229600. 8, srcData.pixelStride * 8, srcData.lineStride,
  229601. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229602. 0, true, kCGRenderingIntentDefault);
  229603. CGDataProviderRelease (provider);
  229604. return imageRef;
  229605. }
  229606. }
  229607. #if JUCE_MAC
  229608. static NSImage* createNSImage (const Image& image)
  229609. {
  229610. const ScopedAutoReleasePool pool;
  229611. NSImage* im = [[NSImage alloc] init];
  229612. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229613. [im lockFocus];
  229614. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229615. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  229616. CGColorSpaceRelease (colourSpace);
  229617. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229618. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229619. CGImageRelease (imageRef);
  229620. [im unlockFocus];
  229621. return im;
  229622. }
  229623. #endif
  229624. CGContextRef context;
  229625. HeapBlock<uint8> imageDataAllocated;
  229626. private:
  229627. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229628. {
  229629. #if JUCE_BIG_ENDIAN
  229630. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229631. #else
  229632. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229633. #endif
  229634. }
  229635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  229636. };
  229637. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229638. {
  229639. #if USE_COREGRAPHICS_RENDERING
  229640. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229641. #else
  229642. return createSoftwareImage (format, width, height, clearImage);
  229643. #endif
  229644. }
  229645. class CoreGraphicsContext : public LowLevelGraphicsContext
  229646. {
  229647. public:
  229648. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229649. : context (context_),
  229650. flipHeight (flipHeight_),
  229651. lastClipRectIsValid (false),
  229652. state (new SavedState()),
  229653. numGradientLookupEntries (0)
  229654. {
  229655. CGContextRetain (context);
  229656. CGContextSaveGState(context);
  229657. CGContextSetShouldSmoothFonts (context, true);
  229658. CGContextSetShouldAntialias (context, true);
  229659. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229660. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229661. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229662. gradientCallbacks.version = 0;
  229663. gradientCallbacks.evaluate = gradientCallback;
  229664. gradientCallbacks.releaseInfo = 0;
  229665. setFont (Font());
  229666. }
  229667. ~CoreGraphicsContext()
  229668. {
  229669. CGContextRestoreGState (context);
  229670. CGContextRelease (context);
  229671. CGColorSpaceRelease (rgbColourSpace);
  229672. CGColorSpaceRelease (greyColourSpace);
  229673. }
  229674. bool isVectorDevice() const { return false; }
  229675. void setOrigin (int x, int y)
  229676. {
  229677. CGContextTranslateCTM (context, x, -y);
  229678. if (lastClipRectIsValid)
  229679. lastClipRect.translate (-x, -y);
  229680. }
  229681. void addTransform (const AffineTransform& transform)
  229682. {
  229683. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  229684. .translated (0, flipHeight)
  229685. .followedBy (transform)
  229686. .translated (0, -flipHeight)
  229687. .scaled (1.0f, -1.0f));
  229688. lastClipRectIsValid = false;
  229689. }
  229690. float getScaleFactor()
  229691. {
  229692. CGAffineTransform t = CGContextGetCTM (context);
  229693. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  229694. }
  229695. bool clipToRectangle (const Rectangle<int>& r)
  229696. {
  229697. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229698. if (lastClipRectIsValid)
  229699. {
  229700. // This is actually incorrect, because the actual clip region may be complex, and
  229701. // clipping its bounds to a rect may not be right... But, removing this shortcut
  229702. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  229703. // when calculating the resultant clip bounds, and makes the same mistake!
  229704. lastClipRect = lastClipRect.getIntersection (r);
  229705. return ! lastClipRect.isEmpty();
  229706. }
  229707. return ! isClipEmpty();
  229708. }
  229709. bool clipToRectangleList (const RectangleList& clipRegion)
  229710. {
  229711. if (clipRegion.isEmpty())
  229712. {
  229713. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229714. lastClipRectIsValid = true;
  229715. lastClipRect = Rectangle<int>();
  229716. return false;
  229717. }
  229718. else
  229719. {
  229720. const int numRects = clipRegion.getNumRectangles();
  229721. HeapBlock <CGRect> rects (numRects);
  229722. for (int i = 0; i < numRects; ++i)
  229723. {
  229724. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229725. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229726. }
  229727. CGContextClipToRects (context, rects, numRects);
  229728. lastClipRectIsValid = false;
  229729. return ! isClipEmpty();
  229730. }
  229731. }
  229732. void excludeClipRectangle (const Rectangle<int>& r)
  229733. {
  229734. RectangleList remaining (getClipBounds());
  229735. remaining.subtract (r);
  229736. clipToRectangleList (remaining);
  229737. lastClipRectIsValid = false;
  229738. }
  229739. void clipToPath (const Path& path, const AffineTransform& transform)
  229740. {
  229741. createPath (path, transform);
  229742. CGContextClip (context);
  229743. lastClipRectIsValid = false;
  229744. }
  229745. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229746. {
  229747. if (! transform.isSingularity())
  229748. {
  229749. Image singleChannelImage (sourceImage);
  229750. if (sourceImage.getFormat() != Image::SingleChannel)
  229751. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229752. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  229753. flip();
  229754. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229755. applyTransform (t);
  229756. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229757. CGContextClipToMask (context, r, image);
  229758. applyTransform (t.inverted());
  229759. flip();
  229760. CGImageRelease (image);
  229761. lastClipRectIsValid = false;
  229762. }
  229763. }
  229764. bool clipRegionIntersects (const Rectangle<int>& r)
  229765. {
  229766. return getClipBounds().intersects (r);
  229767. }
  229768. const Rectangle<int> getClipBounds() const
  229769. {
  229770. if (! lastClipRectIsValid)
  229771. {
  229772. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229773. lastClipRectIsValid = true;
  229774. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229775. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229776. roundToInt (bounds.size.width),
  229777. roundToInt (bounds.size.height));
  229778. }
  229779. return lastClipRect;
  229780. }
  229781. bool isClipEmpty() const
  229782. {
  229783. return getClipBounds().isEmpty();
  229784. }
  229785. void saveState()
  229786. {
  229787. CGContextSaveGState (context);
  229788. stateStack.add (new SavedState (*state));
  229789. }
  229790. void restoreState()
  229791. {
  229792. CGContextRestoreGState (context);
  229793. SavedState* const top = stateStack.getLast();
  229794. if (top != 0)
  229795. {
  229796. state = top;
  229797. stateStack.removeLast (1, false);
  229798. lastClipRectIsValid = false;
  229799. }
  229800. else
  229801. {
  229802. jassertfalse; // trying to pop with an empty stack!
  229803. }
  229804. }
  229805. void beginTransparencyLayer (float opacity)
  229806. {
  229807. saveState();
  229808. CGContextSetAlpha (context, opacity);
  229809. CGContextBeginTransparencyLayer (context, 0);
  229810. }
  229811. void endTransparencyLayer()
  229812. {
  229813. CGContextEndTransparencyLayer (context);
  229814. restoreState();
  229815. }
  229816. void setFill (const FillType& fillType)
  229817. {
  229818. state->fillType = fillType;
  229819. if (fillType.isColour())
  229820. {
  229821. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229822. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229823. CGContextSetAlpha (context, 1.0f);
  229824. }
  229825. }
  229826. void setOpacity (float newOpacity)
  229827. {
  229828. state->fillType.setOpacity (newOpacity);
  229829. setFill (state->fillType);
  229830. }
  229831. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229832. {
  229833. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229834. ? kCGInterpolationLow
  229835. : kCGInterpolationHigh);
  229836. }
  229837. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229838. {
  229839. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  229840. }
  229841. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  229842. {
  229843. if (replaceExistingContents)
  229844. {
  229845. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229846. CGContextClearRect (context, cgRect);
  229847. #else
  229848. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229849. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229850. CGContextClearRect (context, cgRect);
  229851. else
  229852. #endif
  229853. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229854. #endif
  229855. fillCGRect (cgRect, false);
  229856. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229857. }
  229858. else
  229859. {
  229860. if (state->fillType.isColour())
  229861. {
  229862. CGContextFillRect (context, cgRect);
  229863. }
  229864. else if (state->fillType.isGradient())
  229865. {
  229866. CGContextSaveGState (context);
  229867. CGContextClipToRect (context, cgRect);
  229868. drawGradient();
  229869. CGContextRestoreGState (context);
  229870. }
  229871. else
  229872. {
  229873. CGContextSaveGState (context);
  229874. CGContextClipToRect (context, cgRect);
  229875. drawImage (state->fillType.image, state->fillType.transform, true);
  229876. CGContextRestoreGState (context);
  229877. }
  229878. }
  229879. }
  229880. void fillPath (const Path& path, const AffineTransform& transform)
  229881. {
  229882. CGContextSaveGState (context);
  229883. if (state->fillType.isColour())
  229884. {
  229885. flip();
  229886. applyTransform (transform);
  229887. createPath (path);
  229888. if (path.isUsingNonZeroWinding())
  229889. CGContextFillPath (context);
  229890. else
  229891. CGContextEOFillPath (context);
  229892. }
  229893. else
  229894. {
  229895. createPath (path, transform);
  229896. if (path.isUsingNonZeroWinding())
  229897. CGContextClip (context);
  229898. else
  229899. CGContextEOClip (context);
  229900. if (state->fillType.isGradient())
  229901. drawGradient();
  229902. else
  229903. drawImage (state->fillType.image, state->fillType.transform, true);
  229904. }
  229905. CGContextRestoreGState (context);
  229906. }
  229907. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229908. {
  229909. const int iw = sourceImage.getWidth();
  229910. const int ih = sourceImage.getHeight();
  229911. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  229912. CGContextSaveGState (context);
  229913. CGContextSetAlpha (context, state->fillType.getOpacity());
  229914. flip();
  229915. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229916. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229917. if (fillEntireClipAsTiles)
  229918. {
  229919. #if JUCE_IOS
  229920. CGContextDrawTiledImage (context, imageRect, image);
  229921. #else
  229922. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229923. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229924. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229925. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229926. CGContextDrawTiledImage (context, imageRect, image);
  229927. else
  229928. #endif
  229929. {
  229930. // Fallback to manually doing a tiled fill on 10.4
  229931. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229932. int x = 0, y = 0;
  229933. while (x > clip.origin.x) x -= iw;
  229934. while (y > clip.origin.y) y -= ih;
  229935. const int right = (int) (clip.origin.x + clip.size.width);
  229936. const int bottom = (int) (clip.origin.y + clip.size.height);
  229937. while (y < bottom)
  229938. {
  229939. for (int x2 = x; x2 < right; x2 += iw)
  229940. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229941. y += ih;
  229942. }
  229943. }
  229944. #endif
  229945. }
  229946. else
  229947. {
  229948. CGContextDrawImage (context, imageRect, image);
  229949. }
  229950. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229951. CGContextRestoreGState (context);
  229952. }
  229953. void drawLine (const Line<float>& line)
  229954. {
  229955. if (state->fillType.isColour())
  229956. {
  229957. CGContextSetLineCap (context, kCGLineCapSquare);
  229958. CGContextSetLineWidth (context, 1.0f);
  229959. CGContextSetRGBStrokeColor (context,
  229960. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229961. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229962. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229963. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229964. CGContextStrokeLineSegments (context, cgLine, 1);
  229965. }
  229966. else
  229967. {
  229968. Path p;
  229969. p.addLineSegment (line, 1.0f);
  229970. fillPath (p, AffineTransform::identity);
  229971. }
  229972. }
  229973. void drawVerticalLine (const int x, float top, float bottom)
  229974. {
  229975. if (state->fillType.isColour())
  229976. {
  229977. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229978. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229979. #else
  229980. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229981. // the x co-ord slightly to trick it..
  229982. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229983. #endif
  229984. }
  229985. else
  229986. {
  229987. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  229988. }
  229989. }
  229990. void drawHorizontalLine (const int y, float left, float right)
  229991. {
  229992. if (state->fillType.isColour())
  229993. {
  229994. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229995. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229996. #else
  229997. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229998. // the x co-ord slightly to trick it..
  229999. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230000. #endif
  230001. }
  230002. else
  230003. {
  230004. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230005. }
  230006. }
  230007. void setFont (const Font& newFont)
  230008. {
  230009. if (state->font != newFont)
  230010. {
  230011. state->fontRef = 0;
  230012. state->font = newFont;
  230013. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230014. if (mf != 0)
  230015. {
  230016. state->fontRef = mf->fontRef;
  230017. CGContextSetFont (context, state->fontRef);
  230018. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230019. state->fontTransform = mf->renderingTransform;
  230020. state->fontTransform.a *= state->font.getHorizontalScale();
  230021. CGContextSetTextMatrix (context, state->fontTransform);
  230022. }
  230023. }
  230024. }
  230025. const Font getFont()
  230026. {
  230027. return state->font;
  230028. }
  230029. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230030. {
  230031. if (state->fontRef != 0 && state->fillType.isColour())
  230032. {
  230033. if (transform.isOnlyTranslation())
  230034. {
  230035. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230036. CGGlyph g = glyphNumber;
  230037. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230038. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230039. }
  230040. else
  230041. {
  230042. CGContextSaveGState (context);
  230043. flip();
  230044. applyTransform (transform);
  230045. CGAffineTransform t = state->fontTransform;
  230046. t.d = -t.d;
  230047. CGContextSetTextMatrix (context, t);
  230048. CGGlyph g = glyphNumber;
  230049. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230050. CGContextRestoreGState (context);
  230051. }
  230052. }
  230053. else
  230054. {
  230055. Path p;
  230056. Font& f = state->font;
  230057. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230058. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230059. .followedBy (transform));
  230060. }
  230061. }
  230062. private:
  230063. CGContextRef context;
  230064. const CGFloat flipHeight;
  230065. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230066. CGFunctionCallbacks gradientCallbacks;
  230067. mutable Rectangle<int> lastClipRect;
  230068. mutable bool lastClipRectIsValid;
  230069. struct SavedState
  230070. {
  230071. SavedState()
  230072. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230073. {
  230074. }
  230075. SavedState (const SavedState& other)
  230076. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230077. fontTransform (other.fontTransform)
  230078. {
  230079. }
  230080. FillType fillType;
  230081. Font font;
  230082. CGFontRef fontRef;
  230083. CGAffineTransform fontTransform;
  230084. };
  230085. ScopedPointer <SavedState> state;
  230086. OwnedArray <SavedState> stateStack;
  230087. HeapBlock <PixelARGB> gradientLookupTable;
  230088. int numGradientLookupEntries;
  230089. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230090. {
  230091. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230092. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230093. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230094. colour.unpremultiply();
  230095. outData[0] = colour.getRed() / 255.0f;
  230096. outData[1] = colour.getGreen() / 255.0f;
  230097. outData[2] = colour.getBlue() / 255.0f;
  230098. outData[3] = colour.getAlpha() / 255.0f;
  230099. }
  230100. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230101. {
  230102. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230103. CGShadingRef result = 0;
  230104. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230105. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230106. if (gradient.isRadial)
  230107. {
  230108. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230109. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230110. function, true, true);
  230111. }
  230112. else
  230113. {
  230114. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230115. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230116. function, true, true);
  230117. }
  230118. CGFunctionRelease (function);
  230119. return result;
  230120. }
  230121. void drawGradient()
  230122. {
  230123. flip();
  230124. applyTransform (state->fillType.transform);
  230125. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230126. // you draw a gradient with high quality interp enabled).
  230127. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230128. CGContextSetAlpha (context, state->fillType.getOpacity());
  230129. CGContextDrawShading (context, shading);
  230130. CGShadingRelease (shading);
  230131. }
  230132. void createPath (const Path& path) const
  230133. {
  230134. CGContextBeginPath (context);
  230135. Path::Iterator i (path);
  230136. while (i.next())
  230137. {
  230138. switch (i.elementType)
  230139. {
  230140. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230141. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230142. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230143. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230144. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230145. default: jassertfalse; break;
  230146. }
  230147. }
  230148. }
  230149. void createPath (const Path& path, const AffineTransform& transform) const
  230150. {
  230151. CGContextBeginPath (context);
  230152. Path::Iterator i (path);
  230153. while (i.next())
  230154. {
  230155. switch (i.elementType)
  230156. {
  230157. case Path::Iterator::startNewSubPath:
  230158. transform.transformPoint (i.x1, i.y1);
  230159. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230160. break;
  230161. case Path::Iterator::lineTo:
  230162. transform.transformPoint (i.x1, i.y1);
  230163. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230164. break;
  230165. case Path::Iterator::quadraticTo:
  230166. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230167. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230168. break;
  230169. case Path::Iterator::cubicTo:
  230170. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230171. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230172. break;
  230173. case Path::Iterator::closePath:
  230174. CGContextClosePath (context); break;
  230175. default:
  230176. jassertfalse;
  230177. break;
  230178. }
  230179. }
  230180. }
  230181. void flip() const
  230182. {
  230183. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230184. }
  230185. void applyTransform (const AffineTransform& transform) const
  230186. {
  230187. CGAffineTransform t;
  230188. t.a = transform.mat00;
  230189. t.b = transform.mat10;
  230190. t.c = transform.mat01;
  230191. t.d = transform.mat11;
  230192. t.tx = transform.mat02;
  230193. t.ty = transform.mat12;
  230194. CGContextConcatCTM (context, t);
  230195. }
  230196. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230197. };
  230198. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230199. {
  230200. return new CoreGraphicsContext (context, height);
  230201. }
  230202. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230203. const Image juce_loadWithCoreImage (InputStream& input)
  230204. {
  230205. MemoryBlock data;
  230206. input.readIntoMemoryBlock (data, -1);
  230207. #if JUCE_IOS
  230208. JUCE_AUTORELEASEPOOL
  230209. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230210. length: data.getSize()
  230211. freeWhenDone: NO]];
  230212. if (image != nil)
  230213. {
  230214. CGImageRef loadedImage = image.CGImage;
  230215. #else
  230216. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230217. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230218. CGDataProviderRelease (provider);
  230219. if (imageSource != 0)
  230220. {
  230221. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230222. CFRelease (imageSource);
  230223. #endif
  230224. if (loadedImage != 0)
  230225. {
  230226. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230227. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230228. && alphaInfo != kCGImageAlphaNoneSkipLast
  230229. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230230. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230231. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230232. hasAlphaChan, Image::NativeImage);
  230233. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230234. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230235. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230236. CGContextFlush (cgImage->context);
  230237. #if ! JUCE_IOS
  230238. CFRelease (loadedImage);
  230239. #endif
  230240. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230241. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230242. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230243. return image;
  230244. }
  230245. }
  230246. return Image::null;
  230247. }
  230248. #endif
  230249. #endif
  230250. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230251. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230252. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230253. // compiled on its own).
  230254. #if JUCE_INCLUDED_FILE
  230255. class NSViewComponentPeer;
  230256. END_JUCE_NAMESPACE
  230257. @interface NSEvent (JuceDeviceDelta)
  230258. - (float) deviceDeltaX;
  230259. - (float) deviceDeltaY;
  230260. @end
  230261. #define JuceNSView MakeObjCClassName(JuceNSView)
  230262. @interface JuceNSView : NSView<NSTextInput>
  230263. {
  230264. @public
  230265. NSViewComponentPeer* owner;
  230266. NSNotificationCenter* notificationCenter;
  230267. String* stringBeingComposed;
  230268. bool textWasInserted;
  230269. }
  230270. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230271. - (void) dealloc;
  230272. - (BOOL) isOpaque;
  230273. - (void) drawRect: (NSRect) r;
  230274. - (void) mouseDown: (NSEvent*) ev;
  230275. - (void) asyncMouseDown: (NSEvent*) ev;
  230276. - (void) mouseUp: (NSEvent*) ev;
  230277. - (void) asyncMouseUp: (NSEvent*) ev;
  230278. - (void) mouseDragged: (NSEvent*) ev;
  230279. - (void) mouseMoved: (NSEvent*) ev;
  230280. - (void) mouseEntered: (NSEvent*) ev;
  230281. - (void) mouseExited: (NSEvent*) ev;
  230282. - (void) rightMouseDown: (NSEvent*) ev;
  230283. - (void) rightMouseDragged: (NSEvent*) ev;
  230284. - (void) rightMouseUp: (NSEvent*) ev;
  230285. - (void) otherMouseDown: (NSEvent*) ev;
  230286. - (void) otherMouseDragged: (NSEvent*) ev;
  230287. - (void) otherMouseUp: (NSEvent*) ev;
  230288. - (void) scrollWheel: (NSEvent*) ev;
  230289. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230290. - (void) frameChanged: (NSNotification*) n;
  230291. - (void) viewDidMoveToWindow;
  230292. - (void) keyDown: (NSEvent*) ev;
  230293. - (void) keyUp: (NSEvent*) ev;
  230294. // NSTextInput Methods
  230295. - (void) insertText: (id) aString;
  230296. - (void) doCommandBySelector: (SEL) aSelector;
  230297. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230298. - (void) unmarkText;
  230299. - (BOOL) hasMarkedText;
  230300. - (long) conversationIdentifier;
  230301. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230302. - (NSRange) markedRange;
  230303. - (NSRange) selectedRange;
  230304. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230305. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230306. - (NSArray*) validAttributesForMarkedText;
  230307. - (void) flagsChanged: (NSEvent*) ev;
  230308. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230309. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230310. #endif
  230311. - (BOOL) becomeFirstResponder;
  230312. - (BOOL) resignFirstResponder;
  230313. - (BOOL) acceptsFirstResponder;
  230314. - (void) asyncRepaint: (id) rect;
  230315. - (NSArray*) getSupportedDragTypes;
  230316. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230317. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230318. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230319. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230320. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230321. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230322. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230323. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230324. @end
  230325. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230326. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230327. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230328. #else
  230329. @interface JuceNSWindow : NSWindow
  230330. #endif
  230331. {
  230332. @private
  230333. NSViewComponentPeer* owner;
  230334. bool isZooming;
  230335. }
  230336. - (void) setOwner: (NSViewComponentPeer*) owner;
  230337. - (BOOL) canBecomeKeyWindow;
  230338. - (void) becomeKeyWindow;
  230339. - (BOOL) windowShouldClose: (id) window;
  230340. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230341. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230342. - (void) zoom: (id) sender;
  230343. @end
  230344. BEGIN_JUCE_NAMESPACE
  230345. class NSViewComponentPeer : public ComponentPeer
  230346. {
  230347. public:
  230348. NSViewComponentPeer (Component* const component,
  230349. const int windowStyleFlags,
  230350. NSView* viewToAttachTo);
  230351. ~NSViewComponentPeer();
  230352. void* getNativeHandle() const;
  230353. void setVisible (bool shouldBeVisible);
  230354. void setTitle (const String& title);
  230355. void setPosition (int x, int y);
  230356. void setSize (int w, int h);
  230357. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230358. const Rectangle<int> getBounds (const bool global) const;
  230359. const Rectangle<int> getBounds() const;
  230360. const Point<int> getScreenPosition() const;
  230361. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230362. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230363. void setAlpha (float newAlpha);
  230364. void setMinimised (bool shouldBeMinimised);
  230365. bool isMinimised() const;
  230366. void setFullScreen (bool shouldBeFullScreen);
  230367. bool isFullScreen() const;
  230368. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230369. const BorderSize<int> getFrameSize() const;
  230370. bool setAlwaysOnTop (bool alwaysOnTop);
  230371. void toFront (bool makeActiveWindow);
  230372. void toBehind (ComponentPeer* other);
  230373. void setIcon (const Image& newIcon);
  230374. const StringArray getAvailableRenderingEngines();
  230375. int getCurrentRenderingEngine() throw();
  230376. void setCurrentRenderingEngine (int index);
  230377. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230378. for example having more than one juce plugin loaded into a host, then when a
  230379. method is called, the actual code that runs might actually be in a different module
  230380. than the one you expect... So any calls to library functions or statics that are
  230381. made inside obj-c methods will probably end up getting executed in a different DLL's
  230382. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230383. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230384. virtual methods of an object that's known to live inside the right module's space.
  230385. */
  230386. virtual void redirectMouseDown (NSEvent* ev);
  230387. virtual void redirectMouseUp (NSEvent* ev);
  230388. virtual void redirectMouseDrag (NSEvent* ev);
  230389. virtual void redirectMouseMove (NSEvent* ev);
  230390. virtual void redirectMouseEnter (NSEvent* ev);
  230391. virtual void redirectMouseExit (NSEvent* ev);
  230392. virtual void redirectMouseWheel (NSEvent* ev);
  230393. void sendMouseEvent (NSEvent* ev);
  230394. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230395. virtual bool redirectKeyDown (NSEvent* ev);
  230396. virtual bool redirectKeyUp (NSEvent* ev);
  230397. virtual void redirectModKeyChange (NSEvent* ev);
  230398. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230399. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230400. #endif
  230401. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230402. virtual bool isOpaque();
  230403. virtual void drawRect (NSRect r);
  230404. virtual bool canBecomeKeyWindow();
  230405. virtual bool windowShouldClose();
  230406. virtual void redirectMovedOrResized();
  230407. virtual void viewMovedToWindow();
  230408. virtual NSRect constrainRect (NSRect r);
  230409. static void showArrowCursorIfNeeded();
  230410. static void updateModifiers (NSEvent* e);
  230411. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230412. static int getKeyCodeFromEvent (NSEvent* ev)
  230413. {
  230414. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230415. int keyCode = unmodified[0];
  230416. if (keyCode == 0x19) // (backwards-tab)
  230417. keyCode = '\t';
  230418. else if (keyCode == 0x03) // (enter)
  230419. keyCode = '\r';
  230420. else
  230421. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230422. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230423. {
  230424. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230425. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230426. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230427. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230428. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230429. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230430. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230431. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230432. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230433. if (keyCode == numPadConversions [i])
  230434. keyCode = numPadConversions [i + 1];
  230435. }
  230436. return keyCode;
  230437. }
  230438. static int64 getMouseTime (NSEvent* e)
  230439. {
  230440. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230441. + (int64) ([e timestamp] * 1000.0);
  230442. }
  230443. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230444. {
  230445. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230446. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230447. }
  230448. static int getModifierForButtonNumber (const NSInteger num)
  230449. {
  230450. return num == 0 ? ModifierKeys::leftButtonModifier
  230451. : (num == 1 ? ModifierKeys::rightButtonModifier
  230452. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230453. }
  230454. virtual void viewFocusGain();
  230455. virtual void viewFocusLoss();
  230456. bool isFocused() const;
  230457. void grabFocus();
  230458. void textInputRequired (const Point<int>& position);
  230459. void repaint (const Rectangle<int>& area);
  230460. void performAnyPendingRepaintsNow();
  230461. NSWindow* window;
  230462. JuceNSView* view;
  230463. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230464. static ModifierKeys currentModifiers;
  230465. static ComponentPeer* currentlyFocusedPeer;
  230466. static Array<int> keysCurrentlyDown;
  230467. private:
  230468. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230469. };
  230470. END_JUCE_NAMESPACE
  230471. @implementation JuceNSView
  230472. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230473. withFrame: (NSRect) frame
  230474. {
  230475. [super initWithFrame: frame];
  230476. owner = owner_;
  230477. stringBeingComposed = 0;
  230478. textWasInserted = false;
  230479. notificationCenter = [NSNotificationCenter defaultCenter];
  230480. [notificationCenter addObserver: self
  230481. selector: @selector (frameChanged:)
  230482. name: NSViewFrameDidChangeNotification
  230483. object: self];
  230484. if (! owner_->isSharedWindow)
  230485. {
  230486. [notificationCenter addObserver: self
  230487. selector: @selector (frameChanged:)
  230488. name: NSWindowDidMoveNotification
  230489. object: owner_->window];
  230490. }
  230491. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230492. return self;
  230493. }
  230494. - (void) dealloc
  230495. {
  230496. [notificationCenter removeObserver: self];
  230497. delete stringBeingComposed;
  230498. [super dealloc];
  230499. }
  230500. - (void) drawRect: (NSRect) r
  230501. {
  230502. if (owner != 0)
  230503. owner->drawRect (r);
  230504. }
  230505. - (BOOL) isOpaque
  230506. {
  230507. return owner == 0 || owner->isOpaque();
  230508. }
  230509. - (void) mouseDown: (NSEvent*) ev
  230510. {
  230511. if (JUCEApplication::isStandaloneApp())
  230512. [self asyncMouseDown: ev];
  230513. else
  230514. // In some host situations, the host will stop modal loops from working
  230515. // correctly if they're called from a mouse event, so we'll trigger
  230516. // the event asynchronously..
  230517. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230518. withObject: ev
  230519. waitUntilDone: NO];
  230520. }
  230521. - (void) asyncMouseDown: (NSEvent*) ev
  230522. {
  230523. if (owner != 0)
  230524. owner->redirectMouseDown (ev);
  230525. }
  230526. - (void) mouseUp: (NSEvent*) ev
  230527. {
  230528. if (! JUCEApplication::isStandaloneApp())
  230529. [self asyncMouseUp: ev];
  230530. else
  230531. // In some host situations, the host will stop modal loops from working
  230532. // correctly if they're called from a mouse event, so we'll trigger
  230533. // the event asynchronously..
  230534. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230535. withObject: ev
  230536. waitUntilDone: NO];
  230537. }
  230538. - (void) asyncMouseUp: (NSEvent*) ev
  230539. {
  230540. if (owner != 0)
  230541. owner->redirectMouseUp (ev);
  230542. }
  230543. - (void) mouseDragged: (NSEvent*) ev
  230544. {
  230545. if (owner != 0)
  230546. owner->redirectMouseDrag (ev);
  230547. }
  230548. - (void) mouseMoved: (NSEvent*) ev
  230549. {
  230550. if (owner != 0)
  230551. owner->redirectMouseMove (ev);
  230552. }
  230553. - (void) mouseEntered: (NSEvent*) ev
  230554. {
  230555. if (owner != 0)
  230556. owner->redirectMouseEnter (ev);
  230557. }
  230558. - (void) mouseExited: (NSEvent*) ev
  230559. {
  230560. if (owner != 0)
  230561. owner->redirectMouseExit (ev);
  230562. }
  230563. - (void) rightMouseDown: (NSEvent*) ev
  230564. {
  230565. [self mouseDown: ev];
  230566. }
  230567. - (void) rightMouseDragged: (NSEvent*) ev
  230568. {
  230569. [self mouseDragged: ev];
  230570. }
  230571. - (void) rightMouseUp: (NSEvent*) ev
  230572. {
  230573. [self mouseUp: ev];
  230574. }
  230575. - (void) otherMouseDown: (NSEvent*) ev
  230576. {
  230577. [self mouseDown: ev];
  230578. }
  230579. - (void) otherMouseDragged: (NSEvent*) ev
  230580. {
  230581. [self mouseDragged: ev];
  230582. }
  230583. - (void) otherMouseUp: (NSEvent*) ev
  230584. {
  230585. [self mouseUp: ev];
  230586. }
  230587. - (void) scrollWheel: (NSEvent*) ev
  230588. {
  230589. if (owner != 0)
  230590. owner->redirectMouseWheel (ev);
  230591. }
  230592. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  230593. {
  230594. (void) ev;
  230595. return YES;
  230596. }
  230597. - (void) frameChanged: (NSNotification*) n
  230598. {
  230599. (void) n;
  230600. if (owner != 0)
  230601. owner->redirectMovedOrResized();
  230602. }
  230603. - (void) viewDidMoveToWindow
  230604. {
  230605. if (owner != 0)
  230606. owner->viewMovedToWindow();
  230607. }
  230608. - (void) asyncRepaint: (id) rect
  230609. {
  230610. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  230611. [self setNeedsDisplayInRect: *r];
  230612. }
  230613. - (void) keyDown: (NSEvent*) ev
  230614. {
  230615. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230616. textWasInserted = false;
  230617. if (target != 0)
  230618. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  230619. else
  230620. deleteAndZero (stringBeingComposed);
  230621. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  230622. [super keyDown: ev];
  230623. }
  230624. - (void) keyUp: (NSEvent*) ev
  230625. {
  230626. if (owner == 0 || ! owner->redirectKeyUp (ev))
  230627. [super keyUp: ev];
  230628. }
  230629. - (void) insertText: (id) aString
  230630. {
  230631. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  230632. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  230633. if ([newText length] > 0)
  230634. {
  230635. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230636. if (target != 0)
  230637. {
  230638. target->insertTextAtCaret (nsStringToJuce (newText));
  230639. textWasInserted = true;
  230640. }
  230641. }
  230642. deleteAndZero (stringBeingComposed);
  230643. }
  230644. - (void) doCommandBySelector: (SEL) aSelector
  230645. {
  230646. (void) aSelector;
  230647. }
  230648. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  230649. {
  230650. (void) selectionRange;
  230651. if (stringBeingComposed == 0)
  230652. stringBeingComposed = new String();
  230653. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  230654. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230655. if (target != 0)
  230656. {
  230657. const Range<int> currentHighlight (target->getHighlightedRegion());
  230658. target->insertTextAtCaret (*stringBeingComposed);
  230659. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  230660. textWasInserted = true;
  230661. }
  230662. }
  230663. - (void) unmarkText
  230664. {
  230665. if (stringBeingComposed != 0)
  230666. {
  230667. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230668. if (target != 0)
  230669. {
  230670. target->insertTextAtCaret (*stringBeingComposed);
  230671. textWasInserted = true;
  230672. }
  230673. }
  230674. deleteAndZero (stringBeingComposed);
  230675. }
  230676. - (BOOL) hasMarkedText
  230677. {
  230678. return stringBeingComposed != 0;
  230679. }
  230680. - (long) conversationIdentifier
  230681. {
  230682. return (long) (pointer_sized_int) self;
  230683. }
  230684. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230685. {
  230686. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230687. if (target != 0)
  230688. {
  230689. const Range<int> r ((int) theRange.location,
  230690. (int) (theRange.location + theRange.length));
  230691. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230692. }
  230693. return nil;
  230694. }
  230695. - (NSRange) markedRange
  230696. {
  230697. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230698. : NSMakeRange (NSNotFound, 0);
  230699. }
  230700. - (NSRange) selectedRange
  230701. {
  230702. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230703. if (target != 0)
  230704. {
  230705. const Range<int> highlight (target->getHighlightedRegion());
  230706. if (! highlight.isEmpty())
  230707. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230708. }
  230709. return NSMakeRange (NSNotFound, 0);
  230710. }
  230711. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230712. {
  230713. (void) theRange;
  230714. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230715. if (comp == 0)
  230716. return NSMakeRect (0, 0, 0, 0);
  230717. const Rectangle<int> bounds (comp->getScreenBounds());
  230718. return NSMakeRect (bounds.getX(),
  230719. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230720. bounds.getWidth(),
  230721. bounds.getHeight());
  230722. }
  230723. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230724. {
  230725. (void) thePoint;
  230726. return NSNotFound;
  230727. }
  230728. - (NSArray*) validAttributesForMarkedText
  230729. {
  230730. return [NSArray array];
  230731. }
  230732. - (void) flagsChanged: (NSEvent*) ev
  230733. {
  230734. if (owner != 0)
  230735. owner->redirectModKeyChange (ev);
  230736. }
  230737. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230738. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230739. {
  230740. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230741. return true;
  230742. return [super performKeyEquivalent: ev];
  230743. }
  230744. #endif
  230745. - (BOOL) becomeFirstResponder
  230746. {
  230747. if (owner != 0)
  230748. owner->viewFocusGain();
  230749. return true;
  230750. }
  230751. - (BOOL) resignFirstResponder
  230752. {
  230753. if (owner != 0)
  230754. owner->viewFocusLoss();
  230755. return true;
  230756. }
  230757. - (BOOL) acceptsFirstResponder
  230758. {
  230759. return owner != 0 && owner->canBecomeKeyWindow();
  230760. }
  230761. - (NSArray*) getSupportedDragTypes
  230762. {
  230763. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230764. }
  230765. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230766. {
  230767. return owner != 0 && owner->sendDragCallback (type, sender);
  230768. }
  230769. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230770. {
  230771. if ([self sendDragCallback: 0 sender: sender])
  230772. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230773. else
  230774. return NSDragOperationNone;
  230775. }
  230776. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230777. {
  230778. if ([self sendDragCallback: 0 sender: sender])
  230779. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230780. else
  230781. return NSDragOperationNone;
  230782. }
  230783. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230784. {
  230785. [self sendDragCallback: 1 sender: sender];
  230786. }
  230787. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230788. {
  230789. [self sendDragCallback: 1 sender: sender];
  230790. }
  230791. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230792. {
  230793. (void) sender;
  230794. return YES;
  230795. }
  230796. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230797. {
  230798. return [self sendDragCallback: 2 sender: sender];
  230799. }
  230800. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230801. {
  230802. (void) sender;
  230803. }
  230804. @end
  230805. @implementation JuceNSWindow
  230806. - (void) setOwner: (NSViewComponentPeer*) owner_
  230807. {
  230808. owner = owner_;
  230809. isZooming = false;
  230810. }
  230811. - (BOOL) canBecomeKeyWindow
  230812. {
  230813. return owner != 0 && owner->canBecomeKeyWindow();
  230814. }
  230815. - (void) becomeKeyWindow
  230816. {
  230817. [super becomeKeyWindow];
  230818. if (owner != 0)
  230819. owner->grabFocus();
  230820. }
  230821. - (BOOL) windowShouldClose: (id) window
  230822. {
  230823. (void) window;
  230824. return owner == 0 || owner->windowShouldClose();
  230825. }
  230826. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230827. {
  230828. (void) screen;
  230829. if (owner != 0)
  230830. frameRect = owner->constrainRect (frameRect);
  230831. return frameRect;
  230832. }
  230833. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230834. {
  230835. (void) window;
  230836. if (isZooming)
  230837. return proposedFrameSize;
  230838. NSRect frameRect = [self frame];
  230839. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230840. frameRect.size = proposedFrameSize;
  230841. if (owner != 0)
  230842. frameRect = owner->constrainRect (frameRect);
  230843. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230844. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230845. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230846. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230847. return frameRect.size;
  230848. }
  230849. - (void) zoom: (id) sender
  230850. {
  230851. isZooming = true;
  230852. [super zoom: sender];
  230853. isZooming = false;
  230854. }
  230855. - (void) windowWillMove: (NSNotification*) notification
  230856. {
  230857. (void) notification;
  230858. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230859. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230860. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230861. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230862. }
  230863. @end
  230864. BEGIN_JUCE_NAMESPACE
  230865. ModifierKeys NSViewComponentPeer::currentModifiers;
  230866. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230867. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230868. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230869. {
  230870. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230871. return true;
  230872. if (keyCode >= 'A' && keyCode <= 'Z'
  230873. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230874. return true;
  230875. if (keyCode >= 'a' && keyCode <= 'z'
  230876. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230877. return true;
  230878. return false;
  230879. }
  230880. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230881. {
  230882. int m = 0;
  230883. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230884. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230885. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230886. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230887. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230888. }
  230889. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230890. {
  230891. updateModifiers (ev);
  230892. int keyCode = getKeyCodeFromEvent (ev);
  230893. if (keyCode != 0)
  230894. {
  230895. if (isKeyDown)
  230896. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230897. else
  230898. keysCurrentlyDown.removeValue (keyCode);
  230899. }
  230900. }
  230901. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230902. {
  230903. return NSViewComponentPeer::currentModifiers;
  230904. }
  230905. void ModifierKeys::updateCurrentModifiers() throw()
  230906. {
  230907. currentModifiers = NSViewComponentPeer::currentModifiers;
  230908. }
  230909. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230910. const int windowStyleFlags,
  230911. NSView* viewToAttachTo)
  230912. : ComponentPeer (component_, windowStyleFlags),
  230913. window (0),
  230914. view (0),
  230915. isSharedWindow (viewToAttachTo != 0),
  230916. fullScreen (false),
  230917. insideDrawRect (false),
  230918. #if USE_COREGRAPHICS_RENDERING
  230919. usingCoreGraphics (true),
  230920. #else
  230921. usingCoreGraphics (false),
  230922. #endif
  230923. recursiveToFrontCall (false)
  230924. {
  230925. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  230926. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230927. [view setPostsFrameChangedNotifications: YES];
  230928. if (isSharedWindow)
  230929. {
  230930. window = [viewToAttachTo window];
  230931. [viewToAttachTo addSubview: view];
  230932. }
  230933. else
  230934. {
  230935. r.origin.x = (float) component->getX();
  230936. r.origin.y = (float) component->getY();
  230937. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230938. unsigned int style = 0;
  230939. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230940. style = NSBorderlessWindowMask;
  230941. else
  230942. style = NSTitledWindowMask;
  230943. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230944. style |= NSMiniaturizableWindowMask;
  230945. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230946. style |= NSClosableWindowMask;
  230947. if ((windowStyleFlags & windowIsResizable) != 0)
  230948. style |= NSResizableWindowMask;
  230949. window = [[JuceNSWindow alloc] initWithContentRect: r
  230950. styleMask: style
  230951. backing: NSBackingStoreBuffered
  230952. defer: YES];
  230953. [((JuceNSWindow*) window) setOwner: this];
  230954. [window orderOut: nil];
  230955. [window setDelegate: (JuceNSWindow*) window];
  230956. [window setOpaque: component->isOpaque()];
  230957. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230958. if (component->isAlwaysOnTop())
  230959. [window setLevel: NSFloatingWindowLevel];
  230960. [window setContentView: view];
  230961. [window setAutodisplay: YES];
  230962. [window setAcceptsMouseMovedEvents: YES];
  230963. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230964. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230965. [window setReleasedWhenClosed: YES];
  230966. [window retain];
  230967. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230968. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230969. }
  230970. const float alpha = component->getAlpha();
  230971. if (alpha < 1.0f)
  230972. setAlpha (alpha);
  230973. setTitle (component->getName());
  230974. }
  230975. NSViewComponentPeer::~NSViewComponentPeer()
  230976. {
  230977. view->owner = 0;
  230978. [view removeFromSuperview];
  230979. [view release];
  230980. if (! isSharedWindow)
  230981. {
  230982. [((JuceNSWindow*) window) setOwner: 0];
  230983. [window close];
  230984. [window release];
  230985. }
  230986. }
  230987. void* NSViewComponentPeer::getNativeHandle() const
  230988. {
  230989. return view;
  230990. }
  230991. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230992. {
  230993. if (isSharedWindow)
  230994. {
  230995. [view setHidden: ! shouldBeVisible];
  230996. }
  230997. else
  230998. {
  230999. if (shouldBeVisible)
  231000. {
  231001. [window orderFront: nil];
  231002. handleBroughtToFront();
  231003. }
  231004. else
  231005. {
  231006. [window orderOut: nil];
  231007. }
  231008. }
  231009. }
  231010. void NSViewComponentPeer::setTitle (const String& title)
  231011. {
  231012. const ScopedAutoReleasePool pool;
  231013. if (! isSharedWindow)
  231014. [window setTitle: juceStringToNS (title)];
  231015. }
  231016. void NSViewComponentPeer::setPosition (int x, int y)
  231017. {
  231018. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231019. }
  231020. void NSViewComponentPeer::setSize (int w, int h)
  231021. {
  231022. setBounds (component->getX(), component->getY(), w, h, false);
  231023. }
  231024. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231025. {
  231026. fullScreen = isNowFullScreen;
  231027. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231028. if (isSharedWindow)
  231029. {
  231030. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231031. if ([view frame].size.width != r.size.width
  231032. || [view frame].size.height != r.size.height)
  231033. [view setNeedsDisplay: true];
  231034. [view setFrame: r];
  231035. }
  231036. else
  231037. {
  231038. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231039. [window setFrame: [window frameRectForContentRect: r]
  231040. display: true];
  231041. }
  231042. }
  231043. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231044. {
  231045. NSRect r = [view frame];
  231046. if (global && [view window] != 0)
  231047. {
  231048. r = [view convertRect: r toView: nil];
  231049. NSRect wr = [[view window] frame];
  231050. r.origin.x += wr.origin.x;
  231051. r.origin.y += wr.origin.y;
  231052. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231053. }
  231054. else
  231055. {
  231056. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231057. }
  231058. return Rectangle<int> (convertToRectInt (r));
  231059. }
  231060. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231061. {
  231062. return getBounds (! isSharedWindow);
  231063. }
  231064. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231065. {
  231066. return getBounds (true).getPosition();
  231067. }
  231068. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231069. {
  231070. return relativePosition + getScreenPosition();
  231071. }
  231072. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231073. {
  231074. return screenPosition - getScreenPosition();
  231075. }
  231076. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231077. {
  231078. if (constrainer != 0)
  231079. {
  231080. NSRect current = [window frame];
  231081. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231082. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231083. Rectangle<int> pos (convertToRectInt (r));
  231084. Rectangle<int> original (convertToRectInt (current));
  231085. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231086. if ([window inLiveResize])
  231087. #else
  231088. if ([window respondsToSelector: @selector (inLiveResize)]
  231089. && [window performSelector: @selector (inLiveResize)])
  231090. #endif
  231091. {
  231092. constrainer->checkBounds (pos, original,
  231093. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231094. false, false, true, true);
  231095. }
  231096. else
  231097. {
  231098. constrainer->checkBounds (pos, original,
  231099. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231100. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231101. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231102. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231103. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231104. }
  231105. r.origin.x = pos.getX();
  231106. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231107. r.size.width = pos.getWidth();
  231108. r.size.height = pos.getHeight();
  231109. }
  231110. return r;
  231111. }
  231112. void NSViewComponentPeer::setAlpha (float newAlpha)
  231113. {
  231114. if (! isSharedWindow)
  231115. [window setAlphaValue: (CGFloat) newAlpha];
  231116. else
  231117. [view setAlphaValue: (CGFloat) newAlpha];
  231118. }
  231119. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231120. {
  231121. if (! isSharedWindow)
  231122. {
  231123. if (shouldBeMinimised)
  231124. [window miniaturize: nil];
  231125. else
  231126. [window deminiaturize: nil];
  231127. }
  231128. }
  231129. bool NSViewComponentPeer::isMinimised() const
  231130. {
  231131. return window != 0 && [window isMiniaturized];
  231132. }
  231133. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231134. {
  231135. if (! isSharedWindow)
  231136. {
  231137. Rectangle<int> r (lastNonFullscreenBounds);
  231138. setMinimised (false);
  231139. if (fullScreen != shouldBeFullScreen)
  231140. {
  231141. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231142. {
  231143. fullScreen = true;
  231144. [window performZoom: nil];
  231145. }
  231146. else
  231147. {
  231148. if (shouldBeFullScreen)
  231149. r = Desktop::getInstance().getMainMonitorArea();
  231150. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231151. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231152. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231153. }
  231154. }
  231155. }
  231156. }
  231157. bool NSViewComponentPeer::isFullScreen() const
  231158. {
  231159. return fullScreen;
  231160. }
  231161. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231162. {
  231163. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231164. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231165. return false;
  231166. NSPoint p;
  231167. p.x = (float) position.getX();
  231168. p.y = (float) position.getY();
  231169. NSView* v = [view hitTest: p];
  231170. if (trueIfInAChildWindow)
  231171. return v != nil;
  231172. return v == view;
  231173. }
  231174. const BorderSize<int> NSViewComponentPeer::getFrameSize() const
  231175. {
  231176. BorderSize<int> b;
  231177. if (! isSharedWindow)
  231178. {
  231179. NSRect v = [view convertRect: [view frame] toView: nil];
  231180. NSRect w = [window frame];
  231181. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231182. b.setBottom ((int) v.origin.y);
  231183. b.setLeft ((int) v.origin.x);
  231184. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231185. }
  231186. return b;
  231187. }
  231188. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231189. {
  231190. if (! isSharedWindow)
  231191. {
  231192. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231193. : NSNormalWindowLevel];
  231194. }
  231195. return true;
  231196. }
  231197. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231198. {
  231199. if (isSharedWindow)
  231200. {
  231201. [[view superview] addSubview: view
  231202. positioned: NSWindowAbove
  231203. relativeTo: nil];
  231204. }
  231205. if (window != 0 && component->isVisible())
  231206. {
  231207. if (makeActiveWindow)
  231208. [window makeKeyAndOrderFront: nil];
  231209. else
  231210. [window orderFront: nil];
  231211. if (! recursiveToFrontCall)
  231212. {
  231213. recursiveToFrontCall = true;
  231214. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231215. handleBroughtToFront();
  231216. recursiveToFrontCall = false;
  231217. }
  231218. }
  231219. }
  231220. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231221. {
  231222. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231223. jassert (otherPeer != 0); // wrong type of window?
  231224. if (otherPeer != 0)
  231225. {
  231226. if (isSharedWindow)
  231227. {
  231228. [[view superview] addSubview: view
  231229. positioned: NSWindowBelow
  231230. relativeTo: otherPeer->view];
  231231. }
  231232. else
  231233. {
  231234. [window orderWindow: NSWindowBelow
  231235. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231236. : nil ];
  231237. }
  231238. }
  231239. }
  231240. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231241. {
  231242. // to do..
  231243. }
  231244. void NSViewComponentPeer::viewFocusGain()
  231245. {
  231246. if (currentlyFocusedPeer != this)
  231247. {
  231248. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231249. currentlyFocusedPeer->handleFocusLoss();
  231250. currentlyFocusedPeer = this;
  231251. handleFocusGain();
  231252. }
  231253. }
  231254. void NSViewComponentPeer::viewFocusLoss()
  231255. {
  231256. if (currentlyFocusedPeer == this)
  231257. {
  231258. currentlyFocusedPeer = 0;
  231259. handleFocusLoss();
  231260. }
  231261. }
  231262. void juce_HandleProcessFocusChange()
  231263. {
  231264. NSViewComponentPeer::keysCurrentlyDown.clear();
  231265. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231266. {
  231267. if (Process::isForegroundProcess())
  231268. {
  231269. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231270. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231271. }
  231272. else
  231273. {
  231274. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231275. // turn kiosk mode off if we lose focus..
  231276. Desktop::getInstance().setKioskModeComponent (0);
  231277. }
  231278. }
  231279. }
  231280. bool NSViewComponentPeer::isFocused() const
  231281. {
  231282. return isSharedWindow ? this == currentlyFocusedPeer
  231283. : (window != 0 && [window isKeyWindow]);
  231284. }
  231285. void NSViewComponentPeer::grabFocus()
  231286. {
  231287. if (window != 0)
  231288. {
  231289. [window makeKeyWindow];
  231290. [window makeFirstResponder: view];
  231291. viewFocusGain();
  231292. }
  231293. }
  231294. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231295. {
  231296. }
  231297. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231298. {
  231299. String unicode (nsStringToJuce ([ev characters]));
  231300. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231301. int keyCode = getKeyCodeFromEvent (ev);
  231302. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231303. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231304. if (unicode.isNotEmpty() || keyCode != 0)
  231305. {
  231306. if (isKeyDown)
  231307. {
  231308. bool used = false;
  231309. while (unicode.length() > 0)
  231310. {
  231311. juce_wchar textCharacter = unicode[0];
  231312. unicode = unicode.substring (1);
  231313. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231314. textCharacter = 0;
  231315. used = handleKeyUpOrDown (true) || used;
  231316. used = handleKeyPress (keyCode, textCharacter) || used;
  231317. }
  231318. return used;
  231319. }
  231320. else
  231321. {
  231322. if (handleKeyUpOrDown (false))
  231323. return true;
  231324. }
  231325. }
  231326. return false;
  231327. }
  231328. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231329. {
  231330. updateKeysDown (ev, true);
  231331. bool used = handleKeyEvent (ev, true);
  231332. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231333. {
  231334. // for command keys, the key-up event is thrown away, so simulate one..
  231335. updateKeysDown (ev, false);
  231336. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231337. }
  231338. // (If we're running modally, don't allow unused keystrokes to be passed
  231339. // along to other blocked views..)
  231340. if (Component::getCurrentlyModalComponent() != 0)
  231341. used = true;
  231342. return used;
  231343. }
  231344. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231345. {
  231346. updateKeysDown (ev, false);
  231347. return handleKeyEvent (ev, false)
  231348. || Component::getCurrentlyModalComponent() != 0;
  231349. }
  231350. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231351. {
  231352. keysCurrentlyDown.clear();
  231353. handleKeyUpOrDown (true);
  231354. updateModifiers (ev);
  231355. handleModifierKeysChange();
  231356. }
  231357. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231358. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231359. {
  231360. if ([ev type] == NSKeyDown)
  231361. return redirectKeyDown (ev);
  231362. else if ([ev type] == NSKeyUp)
  231363. return redirectKeyUp (ev);
  231364. return false;
  231365. }
  231366. #endif
  231367. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231368. {
  231369. updateModifiers (ev);
  231370. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231371. }
  231372. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231373. {
  231374. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231375. sendMouseEvent (ev);
  231376. }
  231377. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231378. {
  231379. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231380. sendMouseEvent (ev);
  231381. showArrowCursorIfNeeded();
  231382. }
  231383. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231384. {
  231385. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231386. sendMouseEvent (ev);
  231387. }
  231388. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231389. {
  231390. currentModifiers = currentModifiers.withoutMouseButtons();
  231391. sendMouseEvent (ev);
  231392. showArrowCursorIfNeeded();
  231393. }
  231394. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231395. {
  231396. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231397. currentModifiers = currentModifiers.withoutMouseButtons();
  231398. sendMouseEvent (ev);
  231399. }
  231400. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231401. {
  231402. currentModifiers = currentModifiers.withoutMouseButtons();
  231403. sendMouseEvent (ev);
  231404. }
  231405. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231406. {
  231407. updateModifiers (ev);
  231408. float x = 0, y = 0;
  231409. @try
  231410. {
  231411. x = [ev deviceDeltaX] * 0.5f;
  231412. y = [ev deviceDeltaY] * 0.5f;
  231413. }
  231414. @catch (...)
  231415. {}
  231416. if (x == 0 && y == 0)
  231417. {
  231418. x = [ev deltaX] * 10.0f;
  231419. y = [ev deltaY] * 10.0f;
  231420. }
  231421. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231422. }
  231423. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231424. {
  231425. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231426. if (mouse.getComponentUnderMouse() == 0
  231427. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231428. {
  231429. [[NSCursor arrowCursor] set];
  231430. }
  231431. }
  231432. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231433. {
  231434. NSString* bestType
  231435. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231436. if (bestType == nil)
  231437. return false;
  231438. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231439. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231440. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231441. if (list == nil)
  231442. return false;
  231443. StringArray files;
  231444. if ([list isKindOfClass: [NSArray class]])
  231445. {
  231446. NSArray* items = (NSArray*) list;
  231447. for (unsigned int i = 0; i < [items count]; ++i)
  231448. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231449. }
  231450. if (files.size() == 0)
  231451. return false;
  231452. if (type == 0)
  231453. handleFileDragMove (files, pos);
  231454. else if (type == 1)
  231455. handleFileDragExit (files);
  231456. else if (type == 2)
  231457. handleFileDragDrop (files, pos);
  231458. return true;
  231459. }
  231460. bool NSViewComponentPeer::isOpaque()
  231461. {
  231462. return component == 0 || component->isOpaque();
  231463. }
  231464. void NSViewComponentPeer::drawRect (NSRect r)
  231465. {
  231466. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231467. return;
  231468. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231469. if (! component->isOpaque())
  231470. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231471. #if USE_COREGRAPHICS_RENDERING
  231472. if (usingCoreGraphics)
  231473. {
  231474. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231475. insideDrawRect = true;
  231476. handlePaint (context);
  231477. insideDrawRect = false;
  231478. }
  231479. else
  231480. #endif
  231481. {
  231482. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231483. (int) (r.size.width + 0.5f),
  231484. (int) (r.size.height + 0.5f),
  231485. ! getComponent()->isOpaque());
  231486. const int xOffset = -roundToInt (r.origin.x);
  231487. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231488. const NSRect* rects = 0;
  231489. NSInteger numRects = 0;
  231490. [view getRectsBeingDrawn: &rects count: &numRects];
  231491. const Rectangle<int> clipBounds (temp.getBounds());
  231492. RectangleList clip;
  231493. for (int i = 0; i < numRects; ++i)
  231494. {
  231495. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231496. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231497. roundToInt (rects[i].size.width),
  231498. roundToInt (rects[i].size.height))));
  231499. }
  231500. if (! clip.isEmpty())
  231501. {
  231502. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231503. insideDrawRect = true;
  231504. handlePaint (context);
  231505. insideDrawRect = false;
  231506. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231507. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace, false);
  231508. CGColorSpaceRelease (colourSpace);
  231509. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231510. CGImageRelease (image);
  231511. }
  231512. }
  231513. }
  231514. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231515. {
  231516. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231517. #if USE_COREGRAPHICS_RENDERING
  231518. s.add ("CoreGraphics Renderer");
  231519. #endif
  231520. return s;
  231521. }
  231522. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231523. {
  231524. return usingCoreGraphics ? 1 : 0;
  231525. }
  231526. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231527. {
  231528. #if USE_COREGRAPHICS_RENDERING
  231529. if (usingCoreGraphics != (index > 0))
  231530. {
  231531. usingCoreGraphics = index > 0;
  231532. [view setNeedsDisplay: true];
  231533. }
  231534. #endif
  231535. }
  231536. bool NSViewComponentPeer::canBecomeKeyWindow()
  231537. {
  231538. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231539. }
  231540. bool NSViewComponentPeer::windowShouldClose()
  231541. {
  231542. if (! isValidPeer (this))
  231543. return YES;
  231544. handleUserClosingWindow();
  231545. return NO;
  231546. }
  231547. void NSViewComponentPeer::redirectMovedOrResized()
  231548. {
  231549. handleMovedOrResized();
  231550. }
  231551. void NSViewComponentPeer::viewMovedToWindow()
  231552. {
  231553. if (isSharedWindow)
  231554. window = [view window];
  231555. }
  231556. void Desktop::createMouseInputSources()
  231557. {
  231558. mouseSources.add (new MouseInputSource (0, true));
  231559. }
  231560. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231561. {
  231562. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  231563. if (enableOrDisable)
  231564. {
  231565. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  231566. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  231567. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231568. }
  231569. else
  231570. {
  231571. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  231572. }
  231573. #else
  231574. if (enableOrDisable)
  231575. {
  231576. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  231577. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231578. }
  231579. else
  231580. {
  231581. SetSystemUIMode (kUIModeNormal, 0);
  231582. }
  231583. #endif
  231584. }
  231585. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  231586. {
  231587. if (insideDrawRect)
  231588. {
  231589. class AsyncRepaintMessage : public CallbackMessage
  231590. {
  231591. public:
  231592. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  231593. : peer (peer_), rect (rect_)
  231594. {
  231595. }
  231596. void messageCallback()
  231597. {
  231598. if (ComponentPeer::isValidPeer (peer))
  231599. peer->repaint (rect);
  231600. }
  231601. private:
  231602. NSViewComponentPeer* const peer;
  231603. const Rectangle<int> rect;
  231604. };
  231605. (new AsyncRepaintMessage (this, area))->post();
  231606. }
  231607. else
  231608. {
  231609. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  231610. (float) area.getWidth(), (float) area.getHeight())];
  231611. }
  231612. }
  231613. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  231614. {
  231615. [view displayIfNeeded];
  231616. }
  231617. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  231618. {
  231619. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  231620. }
  231621. const Image juce_createIconForFile (const File& file)
  231622. {
  231623. const ScopedAutoReleasePool pool;
  231624. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  231625. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  231626. [NSGraphicsContext saveGraphicsState];
  231627. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  231628. [image drawAtPoint: NSMakePoint (0, 0)
  231629. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  231630. operation: NSCompositeSourceOver fraction: 1.0f];
  231631. [[NSGraphicsContext currentContext] flushGraphics];
  231632. [NSGraphicsContext restoreGraphicsState];
  231633. return Image (result);
  231634. }
  231635. const int KeyPress::spaceKey = ' ';
  231636. const int KeyPress::returnKey = 0x0d;
  231637. const int KeyPress::escapeKey = 0x1b;
  231638. const int KeyPress::backspaceKey = 0x7f;
  231639. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  231640. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  231641. const int KeyPress::upKey = NSUpArrowFunctionKey;
  231642. const int KeyPress::downKey = NSDownArrowFunctionKey;
  231643. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  231644. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  231645. const int KeyPress::endKey = NSEndFunctionKey;
  231646. const int KeyPress::homeKey = NSHomeFunctionKey;
  231647. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  231648. const int KeyPress::insertKey = -1;
  231649. const int KeyPress::tabKey = 9;
  231650. const int KeyPress::F1Key = NSF1FunctionKey;
  231651. const int KeyPress::F2Key = NSF2FunctionKey;
  231652. const int KeyPress::F3Key = NSF3FunctionKey;
  231653. const int KeyPress::F4Key = NSF4FunctionKey;
  231654. const int KeyPress::F5Key = NSF5FunctionKey;
  231655. const int KeyPress::F6Key = NSF6FunctionKey;
  231656. const int KeyPress::F7Key = NSF7FunctionKey;
  231657. const int KeyPress::F8Key = NSF8FunctionKey;
  231658. const int KeyPress::F9Key = NSF9FunctionKey;
  231659. const int KeyPress::F10Key = NSF10FunctionKey;
  231660. const int KeyPress::F11Key = NSF1FunctionKey;
  231661. const int KeyPress::F12Key = NSF12FunctionKey;
  231662. const int KeyPress::F13Key = NSF13FunctionKey;
  231663. const int KeyPress::F14Key = NSF14FunctionKey;
  231664. const int KeyPress::F15Key = NSF15FunctionKey;
  231665. const int KeyPress::F16Key = NSF16FunctionKey;
  231666. const int KeyPress::numberPad0 = 0x30020;
  231667. const int KeyPress::numberPad1 = 0x30021;
  231668. const int KeyPress::numberPad2 = 0x30022;
  231669. const int KeyPress::numberPad3 = 0x30023;
  231670. const int KeyPress::numberPad4 = 0x30024;
  231671. const int KeyPress::numberPad5 = 0x30025;
  231672. const int KeyPress::numberPad6 = 0x30026;
  231673. const int KeyPress::numberPad7 = 0x30027;
  231674. const int KeyPress::numberPad8 = 0x30028;
  231675. const int KeyPress::numberPad9 = 0x30029;
  231676. const int KeyPress::numberPadAdd = 0x3002a;
  231677. const int KeyPress::numberPadSubtract = 0x3002b;
  231678. const int KeyPress::numberPadMultiply = 0x3002c;
  231679. const int KeyPress::numberPadDivide = 0x3002d;
  231680. const int KeyPress::numberPadSeparator = 0x3002e;
  231681. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  231682. const int KeyPress::numberPadEquals = 0x30030;
  231683. const int KeyPress::numberPadDelete = 0x30031;
  231684. const int KeyPress::playKey = 0x30000;
  231685. const int KeyPress::stopKey = 0x30001;
  231686. const int KeyPress::fastForwardKey = 0x30002;
  231687. const int KeyPress::rewindKey = 0x30003;
  231688. #endif
  231689. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231690. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  231691. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231692. // compiled on its own).
  231693. #if JUCE_INCLUDED_FILE
  231694. #if JUCE_MAC
  231695. namespace MouseCursorHelpers
  231696. {
  231697. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231698. {
  231699. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231700. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231701. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231702. [im release];
  231703. return c;
  231704. }
  231705. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231706. {
  231707. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231708. BufferedInputStream buf (fileStream, 4096);
  231709. PNGImageFormat pngFormat;
  231710. Image im (pngFormat.decodeImage (buf));
  231711. if (im.isValid())
  231712. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231713. jassertfalse;
  231714. return 0;
  231715. }
  231716. }
  231717. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231718. {
  231719. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231720. }
  231721. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231722. {
  231723. const ScopedAutoReleasePool pool;
  231724. NSCursor* c = 0;
  231725. switch (type)
  231726. {
  231727. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231728. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231729. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231730. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231731. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231732. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231733. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231734. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231735. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231736. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231737. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231738. case UpDownResizeCursor:
  231739. case TopEdgeResizeCursor:
  231740. case BottomEdgeResizeCursor:
  231741. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231742. case TopLeftCornerResizeCursor:
  231743. case BottomRightCornerResizeCursor:
  231744. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231745. case TopRightCornerResizeCursor:
  231746. case BottomLeftCornerResizeCursor:
  231747. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231748. case UpDownLeftRightResizeCursor:
  231749. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231750. default:
  231751. jassertfalse;
  231752. break;
  231753. }
  231754. [c retain];
  231755. return c;
  231756. }
  231757. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231758. {
  231759. [((NSCursor*) cursorHandle) release];
  231760. }
  231761. void MouseCursor::showInAllWindows() const
  231762. {
  231763. showInWindow (0);
  231764. }
  231765. void MouseCursor::showInWindow (ComponentPeer*) const
  231766. {
  231767. NSCursor* c = (NSCursor*) getHandle();
  231768. if (c == 0)
  231769. c = [NSCursor arrowCursor];
  231770. [c set];
  231771. }
  231772. #else
  231773. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231774. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231775. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231776. void MouseCursor::showInAllWindows() const {}
  231777. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231778. #endif
  231779. #endif
  231780. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231781. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231782. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231783. // compiled on its own).
  231784. #if JUCE_INCLUDED_FILE
  231785. class NSViewComponentInternal : public ComponentMovementWatcher
  231786. {
  231787. public:
  231788. NSViewComponentInternal (NSView* const view_, Component& owner_)
  231789. : ComponentMovementWatcher (&owner_),
  231790. owner (owner_),
  231791. currentPeer (0),
  231792. view (view_)
  231793. {
  231794. [view_ retain];
  231795. if (owner.isShowing())
  231796. componentPeerChanged();
  231797. }
  231798. ~NSViewComponentInternal()
  231799. {
  231800. [view removeFromSuperview];
  231801. [view release];
  231802. }
  231803. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231804. {
  231805. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231806. // The ComponentMovementWatcher version of this method avoids calling
  231807. // us when the top-level comp is resized, but for an NSView we need to know this
  231808. // because with inverted co-ords, we need to update the position even if the
  231809. // top-left pos hasn't changed
  231810. if (comp.isOnDesktop() && wasResized)
  231811. componentMovedOrResized (wasMoved, wasResized);
  231812. }
  231813. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231814. {
  231815. Component* const topComp = owner.getTopLevelComponent();
  231816. if (topComp->getPeer() != 0)
  231817. {
  231818. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  231819. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  231820. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231821. [view setFrame: r];
  231822. }
  231823. }
  231824. void componentPeerChanged()
  231825. {
  231826. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  231827. if (currentPeer != peer)
  231828. {
  231829. if ([view superview] != nil)
  231830. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  231831. // override the call and use it as a sign that they're being deleted, which breaks everything..
  231832. currentPeer = peer;
  231833. if (peer != 0)
  231834. {
  231835. [peer->view addSubview: view];
  231836. componentMovedOrResized (false, false);
  231837. }
  231838. }
  231839. [view setHidden: ! owner.isShowing()];
  231840. }
  231841. void componentVisibilityChanged()
  231842. {
  231843. componentPeerChanged();
  231844. }
  231845. const Rectangle<int> getViewBounds() const
  231846. {
  231847. NSRect r = [view frame];
  231848. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  231849. }
  231850. private:
  231851. Component& owner;
  231852. NSViewComponentPeer* currentPeer;
  231853. public:
  231854. NSView* const view;
  231855. private:
  231856. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  231857. };
  231858. NSViewComponent::NSViewComponent()
  231859. {
  231860. }
  231861. NSViewComponent::~NSViewComponent()
  231862. {
  231863. }
  231864. void NSViewComponent::setView (void* view)
  231865. {
  231866. if (view != getView())
  231867. {
  231868. if (view != 0)
  231869. info = new NSViewComponentInternal ((NSView*) view, *this);
  231870. else
  231871. info = 0;
  231872. }
  231873. }
  231874. void* NSViewComponent::getView() const
  231875. {
  231876. return info == 0 ? 0 : info->view;
  231877. }
  231878. void NSViewComponent::resizeToFitView()
  231879. {
  231880. if (info != 0)
  231881. setBounds (info->getViewBounds());
  231882. }
  231883. void NSViewComponent::paint (Graphics&)
  231884. {
  231885. }
  231886. #endif
  231887. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231888. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231889. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231890. // compiled on its own).
  231891. #if JUCE_INCLUDED_FILE
  231892. AppleRemoteDevice::AppleRemoteDevice()
  231893. : device (0),
  231894. queue (0),
  231895. remoteId (0)
  231896. {
  231897. }
  231898. AppleRemoteDevice::~AppleRemoteDevice()
  231899. {
  231900. stop();
  231901. }
  231902. namespace
  231903. {
  231904. io_object_t getAppleRemoteDevice()
  231905. {
  231906. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231907. io_iterator_t iter = 0;
  231908. io_object_t iod = 0;
  231909. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231910. && iter != 0)
  231911. {
  231912. iod = IOIteratorNext (iter);
  231913. }
  231914. IOObjectRelease (iter);
  231915. return iod;
  231916. }
  231917. bool createAppleRemoteInterface (io_object_t iod, void** device)
  231918. {
  231919. jassert (*device == 0);
  231920. io_name_t classname;
  231921. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231922. {
  231923. IOCFPlugInInterface** cfPlugInInterface = 0;
  231924. SInt32 score = 0;
  231925. if (IOCreatePlugInInterfaceForService (iod,
  231926. kIOHIDDeviceUserClientTypeID,
  231927. kIOCFPlugInInterfaceID,
  231928. &cfPlugInInterface,
  231929. &score) == kIOReturnSuccess)
  231930. {
  231931. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231932. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231933. device);
  231934. (void) hr;
  231935. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231936. }
  231937. }
  231938. return *device != 0;
  231939. }
  231940. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231941. {
  231942. if (result == kIOReturnSuccess)
  231943. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231944. }
  231945. }
  231946. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231947. {
  231948. if (queue != 0)
  231949. return true;
  231950. stop();
  231951. bool result = false;
  231952. io_object_t iod = getAppleRemoteDevice();
  231953. if (iod != 0)
  231954. {
  231955. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231956. result = true;
  231957. else
  231958. stop();
  231959. IOObjectRelease (iod);
  231960. }
  231961. return result;
  231962. }
  231963. void AppleRemoteDevice::stop()
  231964. {
  231965. if (queue != 0)
  231966. {
  231967. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231968. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231969. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231970. queue = 0;
  231971. }
  231972. if (device != 0)
  231973. {
  231974. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  231975. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  231976. device = 0;
  231977. }
  231978. }
  231979. bool AppleRemoteDevice::isActive() const
  231980. {
  231981. return queue != 0;
  231982. }
  231983. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  231984. {
  231985. Array <int> cookies;
  231986. CFArrayRef elements;
  231987. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  231988. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  231989. return false;
  231990. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  231991. {
  231992. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  231993. // get the cookie
  231994. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  231995. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  231996. continue;
  231997. long number;
  231998. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  231999. continue;
  232000. cookies.add ((int) number);
  232001. }
  232002. CFRelease (elements);
  232003. if ((*(IOHIDDeviceInterface**) device)
  232004. ->open ((IOHIDDeviceInterface**) device,
  232005. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232006. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232007. {
  232008. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232009. if (queue != 0)
  232010. {
  232011. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232012. for (int i = 0; i < cookies.size(); ++i)
  232013. {
  232014. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232015. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232016. }
  232017. CFRunLoopSourceRef eventSource;
  232018. if ((*(IOHIDQueueInterface**) queue)
  232019. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232020. {
  232021. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232022. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232023. {
  232024. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232025. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232026. return true;
  232027. }
  232028. }
  232029. }
  232030. }
  232031. return false;
  232032. }
  232033. void AppleRemoteDevice::handleCallbackInternal()
  232034. {
  232035. int totalValues = 0;
  232036. AbsoluteTime nullTime = { 0, 0 };
  232037. char cookies [12];
  232038. int numCookies = 0;
  232039. while (numCookies < numElementsInArray (cookies))
  232040. {
  232041. IOHIDEventStruct e;
  232042. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232043. break;
  232044. if ((int) e.elementCookie == 19)
  232045. {
  232046. remoteId = e.value;
  232047. buttonPressed (switched, false);
  232048. }
  232049. else
  232050. {
  232051. totalValues += e.value;
  232052. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232053. }
  232054. }
  232055. cookies [numCookies++] = 0;
  232056. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232057. static const char buttonPatterns[] =
  232058. {
  232059. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232060. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232061. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232062. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232063. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232064. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232065. 0x1f, 0x12, 0x04, 0x02, 0,
  232066. 0x1f, 0x12, 0x03, 0x02, 0,
  232067. 0x1f, 0x12, 0x1f, 0x12, 0,
  232068. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232069. 19, 0
  232070. };
  232071. int buttonNum = (int) menuButton;
  232072. int i = 0;
  232073. while (i < numElementsInArray (buttonPatterns))
  232074. {
  232075. if (strcmp (cookies, buttonPatterns + i) == 0)
  232076. {
  232077. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232078. break;
  232079. }
  232080. i += (int) strlen (buttonPatterns + i) + 1;
  232081. ++buttonNum;
  232082. }
  232083. }
  232084. #endif
  232085. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232086. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232087. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232088. // compiled on its own).
  232089. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232090. #if JUCE_MAC
  232091. END_JUCE_NAMESPACE
  232092. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232093. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232094. {
  232095. CriticalSection* contextLock;
  232096. bool needsUpdate;
  232097. }
  232098. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232099. - (bool) makeActive;
  232100. - (void) makeInactive;
  232101. - (void) reshape;
  232102. @end
  232103. @implementation ThreadSafeNSOpenGLView
  232104. - (id) initWithFrame: (NSRect) frameRect
  232105. pixelFormat: (NSOpenGLPixelFormat*) format
  232106. {
  232107. contextLock = new CriticalSection();
  232108. self = [super initWithFrame: frameRect pixelFormat: format];
  232109. if (self != nil)
  232110. [[NSNotificationCenter defaultCenter] addObserver: self
  232111. selector: @selector (_surfaceNeedsUpdate:)
  232112. name: NSViewGlobalFrameDidChangeNotification
  232113. object: self];
  232114. return self;
  232115. }
  232116. - (void) dealloc
  232117. {
  232118. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232119. delete contextLock;
  232120. [super dealloc];
  232121. }
  232122. - (bool) makeActive
  232123. {
  232124. const ScopedLock sl (*contextLock);
  232125. if ([self openGLContext] == 0)
  232126. return false;
  232127. [[self openGLContext] makeCurrentContext];
  232128. if (needsUpdate)
  232129. {
  232130. [super update];
  232131. needsUpdate = false;
  232132. }
  232133. return true;
  232134. }
  232135. - (void) makeInactive
  232136. {
  232137. const ScopedLock sl (*contextLock);
  232138. [NSOpenGLContext clearCurrentContext];
  232139. }
  232140. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232141. {
  232142. (void) notification;
  232143. const ScopedLock sl (*contextLock);
  232144. needsUpdate = true;
  232145. }
  232146. - (void) update
  232147. {
  232148. const ScopedLock sl (*contextLock);
  232149. needsUpdate = true;
  232150. }
  232151. - (void) reshape
  232152. {
  232153. const ScopedLock sl (*contextLock);
  232154. needsUpdate = true;
  232155. }
  232156. @end
  232157. BEGIN_JUCE_NAMESPACE
  232158. class WindowedGLContext : public OpenGLContext
  232159. {
  232160. public:
  232161. WindowedGLContext (Component& component,
  232162. const OpenGLPixelFormat& pixelFormat_,
  232163. NSOpenGLContext* sharedContext)
  232164. : renderContext (0),
  232165. pixelFormat (pixelFormat_)
  232166. {
  232167. NSOpenGLPixelFormatAttribute attribs [64];
  232168. int n = 0;
  232169. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232170. attribs[n++] = NSOpenGLPFAAccelerated;
  232171. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232172. attribs[n++] = NSOpenGLPFAColorSize;
  232173. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232174. pixelFormat.greenBits,
  232175. pixelFormat.blueBits);
  232176. attribs[n++] = NSOpenGLPFAAlphaSize;
  232177. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232178. attribs[n++] = NSOpenGLPFADepthSize;
  232179. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232180. attribs[n++] = NSOpenGLPFAStencilSize;
  232181. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232182. attribs[n++] = NSOpenGLPFAAccumSize;
  232183. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232184. pixelFormat.accumulationBufferGreenBits,
  232185. pixelFormat.accumulationBufferBlueBits,
  232186. pixelFormat.accumulationBufferAlphaBits);
  232187. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232188. attribs[n++] = NSOpenGLPFASampleBuffers;
  232189. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232190. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232191. attribs[n++] = NSOpenGLPFANoRecovery;
  232192. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232193. NSOpenGLPixelFormat* format
  232194. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232195. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232196. pixelFormat: format];
  232197. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232198. shareContext: sharedContext] autorelease];
  232199. const GLint swapInterval = 1;
  232200. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232201. [view setOpenGLContext: renderContext];
  232202. [format release];
  232203. viewHolder = new NSViewComponentInternal (view, component);
  232204. }
  232205. ~WindowedGLContext()
  232206. {
  232207. deleteContext();
  232208. viewHolder = 0;
  232209. }
  232210. void deleteContext()
  232211. {
  232212. makeInactive();
  232213. [renderContext clearDrawable];
  232214. [renderContext setView: nil];
  232215. [view setOpenGLContext: nil];
  232216. renderContext = nil;
  232217. }
  232218. bool makeActive() const throw()
  232219. {
  232220. jassert (renderContext != 0);
  232221. if ([renderContext view] != view)
  232222. [renderContext setView: view];
  232223. [view makeActive];
  232224. return isActive();
  232225. }
  232226. bool makeInactive() const throw()
  232227. {
  232228. [view makeInactive];
  232229. return true;
  232230. }
  232231. bool isActive() const throw()
  232232. {
  232233. return [NSOpenGLContext currentContext] == renderContext;
  232234. }
  232235. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232236. void* getRawContext() const throw() { return renderContext; }
  232237. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232238. {
  232239. }
  232240. void swapBuffers()
  232241. {
  232242. [renderContext flushBuffer];
  232243. }
  232244. bool setSwapInterval (const int numFramesPerSwap)
  232245. {
  232246. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232247. forParameter: NSOpenGLCPSwapInterval];
  232248. return true;
  232249. }
  232250. int getSwapInterval() const
  232251. {
  232252. GLint numFrames = 0;
  232253. [renderContext getValues: &numFrames
  232254. forParameter: NSOpenGLCPSwapInterval];
  232255. return numFrames;
  232256. }
  232257. void repaint()
  232258. {
  232259. // we need to invalidate the juce view that holds this gl view, to make it
  232260. // cause a repaint callback
  232261. NSView* v = (NSView*) viewHolder->view;
  232262. NSRect r = [v frame];
  232263. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232264. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232265. // repaint message, thus never causing our paint() callback, and never repainting
  232266. // the comp. So invalidating just a little bit around the edge helps..
  232267. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232268. }
  232269. void* getNativeWindowHandle() const { return viewHolder->view; }
  232270. NSOpenGLContext* renderContext;
  232271. ThreadSafeNSOpenGLView* view;
  232272. private:
  232273. OpenGLPixelFormat pixelFormat;
  232274. ScopedPointer <NSViewComponentInternal> viewHolder;
  232275. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232276. };
  232277. OpenGLContext* OpenGLComponent::createContext()
  232278. {
  232279. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232280. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232281. return (c->renderContext != 0) ? c.release() : 0;
  232282. }
  232283. void* OpenGLComponent::getNativeWindowHandle() const
  232284. {
  232285. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232286. : 0;
  232287. }
  232288. void juce_glViewport (const int w, const int h)
  232289. {
  232290. glViewport (0, 0, w, h);
  232291. }
  232292. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232293. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232294. {
  232295. /* GLint attribs [64];
  232296. int n = 0;
  232297. attribs[n++] = AGL_RGBA;
  232298. attribs[n++] = AGL_DOUBLEBUFFER;
  232299. attribs[n++] = AGL_ACCELERATED;
  232300. attribs[n++] = AGL_NO_RECOVERY;
  232301. attribs[n++] = AGL_NONE;
  232302. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232303. while (p != 0)
  232304. {
  232305. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232306. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232307. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232308. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232309. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232310. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232311. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232312. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232313. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232314. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232315. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232316. results.add (pf);
  232317. p = aglNextPixelFormat (p);
  232318. }*/
  232319. //jassertfalse // can't see how you do this in cocoa!
  232320. }
  232321. #else
  232322. END_JUCE_NAMESPACE
  232323. @interface JuceGLView : UIView
  232324. {
  232325. }
  232326. + (Class) layerClass;
  232327. @end
  232328. @implementation JuceGLView
  232329. + (Class) layerClass
  232330. {
  232331. return [CAEAGLLayer class];
  232332. }
  232333. @end
  232334. BEGIN_JUCE_NAMESPACE
  232335. class GLESContext : public OpenGLContext
  232336. {
  232337. public:
  232338. GLESContext (UIViewComponentPeer* peer,
  232339. Component* const component_,
  232340. const OpenGLPixelFormat& pixelFormat_,
  232341. const GLESContext* const sharedContext,
  232342. NSUInteger apiType)
  232343. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232344. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232345. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232346. {
  232347. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232348. view.opaque = YES;
  232349. view.hidden = NO;
  232350. view.backgroundColor = [UIColor blackColor];
  232351. view.userInteractionEnabled = NO;
  232352. glLayer = (CAEAGLLayer*) [view layer];
  232353. [peer->view addSubview: view];
  232354. if (sharedContext != 0)
  232355. context = [[EAGLContext alloc] initWithAPI: apiType
  232356. sharegroup: [sharedContext->context sharegroup]];
  232357. else
  232358. context = [[EAGLContext alloc] initWithAPI: apiType];
  232359. createGLBuffers();
  232360. }
  232361. ~GLESContext()
  232362. {
  232363. deleteContext();
  232364. [view removeFromSuperview];
  232365. [view release];
  232366. freeGLBuffers();
  232367. }
  232368. void deleteContext()
  232369. {
  232370. makeInactive();
  232371. [context release];
  232372. context = nil;
  232373. }
  232374. bool makeActive() const throw()
  232375. {
  232376. jassert (context != 0);
  232377. [EAGLContext setCurrentContext: context];
  232378. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232379. return true;
  232380. }
  232381. void swapBuffers()
  232382. {
  232383. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232384. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232385. }
  232386. bool makeInactive() const throw()
  232387. {
  232388. return [EAGLContext setCurrentContext: nil];
  232389. }
  232390. bool isActive() const throw()
  232391. {
  232392. return [EAGLContext currentContext] == context;
  232393. }
  232394. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232395. void* getRawContext() const throw() { return glLayer; }
  232396. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232397. {
  232398. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232399. if (lastWidth != w || lastHeight != h)
  232400. {
  232401. lastWidth = w;
  232402. lastHeight = h;
  232403. freeGLBuffers();
  232404. createGLBuffers();
  232405. }
  232406. }
  232407. bool setSwapInterval (const int numFramesPerSwap)
  232408. {
  232409. numFrames = numFramesPerSwap;
  232410. return true;
  232411. }
  232412. int getSwapInterval() const
  232413. {
  232414. return numFrames;
  232415. }
  232416. void repaint()
  232417. {
  232418. }
  232419. void createGLBuffers()
  232420. {
  232421. makeActive();
  232422. glGenFramebuffersOES (1, &frameBufferHandle);
  232423. glGenRenderbuffersOES (1, &colorBufferHandle);
  232424. glGenRenderbuffersOES (1, &depthBufferHandle);
  232425. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232426. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232427. GLint width, height;
  232428. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232429. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232430. if (useDepthBuffer)
  232431. {
  232432. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232433. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232434. }
  232435. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232436. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232437. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232438. if (useDepthBuffer)
  232439. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232440. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232441. }
  232442. void freeGLBuffers()
  232443. {
  232444. if (frameBufferHandle != 0)
  232445. {
  232446. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232447. frameBufferHandle = 0;
  232448. }
  232449. if (colorBufferHandle != 0)
  232450. {
  232451. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232452. colorBufferHandle = 0;
  232453. }
  232454. if (depthBufferHandle != 0)
  232455. {
  232456. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232457. depthBufferHandle = 0;
  232458. }
  232459. }
  232460. private:
  232461. WeakReference<Component> component;
  232462. OpenGLPixelFormat pixelFormat;
  232463. JuceGLView* view;
  232464. CAEAGLLayer* glLayer;
  232465. EAGLContext* context;
  232466. bool useDepthBuffer;
  232467. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232468. int numFrames;
  232469. int lastWidth, lastHeight;
  232470. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232471. };
  232472. OpenGLContext* OpenGLComponent::createContext()
  232473. {
  232474. ScopedAutoReleasePool pool;
  232475. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232476. if (peer != 0)
  232477. return new GLESContext (peer, this, preferredPixelFormat,
  232478. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232479. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232480. return 0;
  232481. }
  232482. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232483. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232484. {
  232485. }
  232486. void juce_glViewport (const int w, const int h)
  232487. {
  232488. glViewport (0, 0, w, h);
  232489. }
  232490. #endif
  232491. #endif
  232492. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232493. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232494. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232495. // compiled on its own).
  232496. #if JUCE_INCLUDED_FILE
  232497. class JuceMainMenuHandler;
  232498. END_JUCE_NAMESPACE
  232499. using namespace JUCE_NAMESPACE;
  232500. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232501. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232502. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232503. #else
  232504. @interface JuceMenuCallback : NSObject
  232505. #endif
  232506. {
  232507. JuceMainMenuHandler* owner;
  232508. }
  232509. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232510. - (void) dealloc;
  232511. - (void) menuItemInvoked: (id) menu;
  232512. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232513. @end
  232514. BEGIN_JUCE_NAMESPACE
  232515. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232516. private DeletedAtShutdown
  232517. {
  232518. public:
  232519. JuceMainMenuHandler()
  232520. : currentModel (0),
  232521. lastUpdateTime (0)
  232522. {
  232523. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232524. }
  232525. ~JuceMainMenuHandler()
  232526. {
  232527. setMenu (0);
  232528. jassert (instance == this);
  232529. instance = 0;
  232530. [callback release];
  232531. }
  232532. void setMenu (MenuBarModel* const newMenuBarModel)
  232533. {
  232534. if (currentModel != newMenuBarModel)
  232535. {
  232536. if (currentModel != 0)
  232537. currentModel->removeListener (this);
  232538. currentModel = newMenuBarModel;
  232539. if (currentModel != 0)
  232540. currentModel->addListener (this);
  232541. menuBarItemsChanged (0);
  232542. }
  232543. }
  232544. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232545. const String& name, const int menuId, const int tag)
  232546. {
  232547. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232548. action: nil
  232549. keyEquivalent: @""];
  232550. [item setTag: tag];
  232551. NSMenu* sub = createMenu (child, name, menuId, tag);
  232552. [parent setSubmenu: sub forItem: item];
  232553. [sub setAutoenablesItems: false];
  232554. [sub release];
  232555. }
  232556. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232557. const String& name, const int menuId, const int tag)
  232558. {
  232559. [parentItem setTag: tag];
  232560. NSMenu* menu = [parentItem submenu];
  232561. [menu setTitle: juceStringToNS (name)];
  232562. while ([menu numberOfItems] > 0)
  232563. [menu removeItemAtIndex: 0];
  232564. PopupMenu::MenuItemIterator iter (menuToCopy);
  232565. while (iter.next())
  232566. addMenuItem (iter, menu, menuId, tag);
  232567. [menu setAutoenablesItems: false];
  232568. [menu update];
  232569. }
  232570. void menuBarItemsChanged (MenuBarModel*)
  232571. {
  232572. lastUpdateTime = Time::getMillisecondCounter();
  232573. StringArray menuNames;
  232574. if (currentModel != 0)
  232575. menuNames = currentModel->getMenuBarNames();
  232576. NSMenu* menuBar = [NSApp mainMenu];
  232577. while ([menuBar numberOfItems] > 1 + menuNames.size())
  232578. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  232579. int menuId = 1;
  232580. for (int i = 0; i < menuNames.size(); ++i)
  232581. {
  232582. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  232583. if (i >= [menuBar numberOfItems] - 1)
  232584. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  232585. else
  232586. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  232587. }
  232588. }
  232589. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  232590. {
  232591. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  232592. if (item != 0)
  232593. flashMenuBar ([item menu]);
  232594. }
  232595. void updateMenus (NSMenu* menu)
  232596. {
  232597. if (PopupMenu::dismissAllActiveMenus())
  232598. {
  232599. // If we were running a juce menu, then we should let that modal loop finish before allowing
  232600. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  232601. if ([menu respondsToSelector: @selector (cancelTracking)])
  232602. [menu performSelector: @selector (cancelTracking)];
  232603. }
  232604. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  232605. menuBarItemsChanged (0);
  232606. }
  232607. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  232608. {
  232609. if (currentModel != 0)
  232610. {
  232611. if (commandManager != 0)
  232612. {
  232613. ApplicationCommandTarget::InvocationInfo info (commandId);
  232614. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  232615. commandManager->invoke (info, true);
  232616. }
  232617. currentModel->menuItemSelected (commandId, topLevelIndex);
  232618. }
  232619. }
  232620. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  232621. const int topLevelMenuId, const int topLevelIndex)
  232622. {
  232623. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  232624. if (text == 0)
  232625. text = @"";
  232626. if (iter.isSeparator)
  232627. {
  232628. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  232629. }
  232630. else if (iter.isSectionHeader)
  232631. {
  232632. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232633. action: nil
  232634. keyEquivalent: @""];
  232635. [item setEnabled: false];
  232636. }
  232637. else if (iter.subMenu != 0)
  232638. {
  232639. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232640. action: nil
  232641. keyEquivalent: @""];
  232642. [item setTag: iter.itemId];
  232643. [item setEnabled: iter.isEnabled];
  232644. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  232645. [sub setDelegate: nil];
  232646. [menuToAddTo setSubmenu: sub forItem: item];
  232647. [sub release];
  232648. }
  232649. else
  232650. {
  232651. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232652. action: @selector (menuItemInvoked:)
  232653. keyEquivalent: @""];
  232654. [item setTag: iter.itemId];
  232655. [item setEnabled: iter.isEnabled];
  232656. [item setState: iter.isTicked ? NSOnState : NSOffState];
  232657. [item setTarget: (id) callback];
  232658. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  232659. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232660. [item setRepresentedObject: info];
  232661. if (iter.commandManager != 0)
  232662. {
  232663. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232664. ->getKeyPressesAssignedToCommand (iter.itemId));
  232665. if (keyPresses.size() > 0)
  232666. {
  232667. const KeyPress& kp = keyPresses.getReference(0);
  232668. if (kp.getKeyCode() != KeyPress::backspaceKey
  232669. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232670. // every time you press the key while editing text)
  232671. {
  232672. juce_wchar key = kp.getTextCharacter();
  232673. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232674. key = NSBackspaceCharacter;
  232675. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232676. key = NSDeleteCharacter;
  232677. else if (key == 0)
  232678. key = (juce_wchar) kp.getKeyCode();
  232679. unsigned int mods = 0;
  232680. if (kp.getModifiers().isShiftDown())
  232681. mods |= NSShiftKeyMask;
  232682. if (kp.getModifiers().isCtrlDown())
  232683. mods |= NSControlKeyMask;
  232684. if (kp.getModifiers().isAltDown())
  232685. mods |= NSAlternateKeyMask;
  232686. if (kp.getModifiers().isCommandDown())
  232687. mods |= NSCommandKeyMask;
  232688. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232689. [item setKeyEquivalentModifierMask: mods];
  232690. }
  232691. }
  232692. }
  232693. }
  232694. }
  232695. static JuceMainMenuHandler* instance;
  232696. MenuBarModel* currentModel;
  232697. uint32 lastUpdateTime;
  232698. JuceMenuCallback* callback;
  232699. private:
  232700. NSMenu* createMenu (const PopupMenu menu,
  232701. const String& menuName,
  232702. const int topLevelMenuId,
  232703. const int topLevelIndex)
  232704. {
  232705. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232706. [m setAutoenablesItems: false];
  232707. [m setDelegate: callback];
  232708. PopupMenu::MenuItemIterator iter (menu);
  232709. while (iter.next())
  232710. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232711. [m update];
  232712. return m;
  232713. }
  232714. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232715. {
  232716. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  232717. {
  232718. NSMenuItem* m = [menu itemAtIndex: i];
  232719. if ([m tag] == info.commandID)
  232720. return m;
  232721. if ([m submenu] != 0)
  232722. {
  232723. NSMenuItem* found = findMenuItem ([m submenu], info);
  232724. if (found != 0)
  232725. return found;
  232726. }
  232727. }
  232728. return 0;
  232729. }
  232730. static void flashMenuBar (NSMenu* menu)
  232731. {
  232732. if ([[menu title] isEqualToString: @"Apple"])
  232733. return;
  232734. [menu retain];
  232735. const unichar f35Key = NSF35FunctionKey;
  232736. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  232737. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  232738. action: nil
  232739. keyEquivalent: f35String];
  232740. [item setTarget: nil];
  232741. [menu insertItem: item atIndex: [menu numberOfItems]];
  232742. [item release];
  232743. if ([menu indexOfItem: item] >= 0)
  232744. {
  232745. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  232746. location: NSZeroPoint
  232747. modifierFlags: NSCommandKeyMask
  232748. timestamp: 0
  232749. windowNumber: 0
  232750. context: [NSGraphicsContext currentContext]
  232751. characters: f35String
  232752. charactersIgnoringModifiers: f35String
  232753. isARepeat: NO
  232754. keyCode: 0];
  232755. [menu performKeyEquivalent: f35Event];
  232756. if ([menu indexOfItem: item] >= 0)
  232757. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  232758. }
  232759. [menu release];
  232760. }
  232761. };
  232762. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232763. END_JUCE_NAMESPACE
  232764. @implementation JuceMenuCallback
  232765. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232766. {
  232767. [super init];
  232768. owner = owner_;
  232769. return self;
  232770. }
  232771. - (void) dealloc
  232772. {
  232773. [super dealloc];
  232774. }
  232775. - (void) menuItemInvoked: (id) menu
  232776. {
  232777. NSMenuItem* item = (NSMenuItem*) menu;
  232778. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232779. {
  232780. // 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
  232781. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232782. // into the focused component and let it trigger the menu item indirectly.
  232783. NSEvent* e = [NSApp currentEvent];
  232784. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232785. {
  232786. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232787. {
  232788. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232789. if (peer != 0)
  232790. {
  232791. if ([e type] == NSKeyDown)
  232792. peer->redirectKeyDown (e);
  232793. else
  232794. peer->redirectKeyUp (e);
  232795. return;
  232796. }
  232797. }
  232798. }
  232799. NSArray* info = (NSArray*) [item representedObject];
  232800. owner->invoke ((int) [item tag],
  232801. (ApplicationCommandManager*) (pointer_sized_int)
  232802. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232803. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232804. }
  232805. }
  232806. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232807. {
  232808. if (JuceMainMenuHandler::instance != 0)
  232809. JuceMainMenuHandler::instance->updateMenus (menu);
  232810. }
  232811. @end
  232812. BEGIN_JUCE_NAMESPACE
  232813. namespace MainMenuHelpers
  232814. {
  232815. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  232816. {
  232817. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232818. {
  232819. PopupMenu::MenuItemIterator iter (*extraItems);
  232820. while (iter.next())
  232821. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232822. [menu addItem: [NSMenuItem separatorItem]];
  232823. }
  232824. NSMenuItem* item;
  232825. // Services...
  232826. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232827. action: nil keyEquivalent: @""];
  232828. [menu addItem: item];
  232829. [item release];
  232830. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232831. [menu setSubmenu: servicesMenu forItem: item];
  232832. [NSApp setServicesMenu: servicesMenu];
  232833. [servicesMenu release];
  232834. [menu addItem: [NSMenuItem separatorItem]];
  232835. // Hide + Show stuff...
  232836. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232837. action: @selector (hide:) keyEquivalent: @"h"];
  232838. [item setTarget: NSApp];
  232839. [menu addItem: item];
  232840. [item release];
  232841. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232842. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232843. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232844. [item setTarget: NSApp];
  232845. [menu addItem: item];
  232846. [item release];
  232847. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232848. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232849. [item setTarget: NSApp];
  232850. [menu addItem: item];
  232851. [item release];
  232852. [menu addItem: [NSMenuItem separatorItem]];
  232853. // Quit item....
  232854. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232855. action: @selector (terminate:) keyEquivalent: @"q"];
  232856. [item setTarget: NSApp];
  232857. [menu addItem: item];
  232858. [item release];
  232859. return menu;
  232860. }
  232861. // Since our app has no NIB, this initialises a standard app menu...
  232862. void rebuildMainMenu (const PopupMenu* extraItems)
  232863. {
  232864. // this can't be used in a plugin!
  232865. jassert (JUCEApplication::isStandaloneApp());
  232866. if (JUCEApplication::getInstance() != 0)
  232867. {
  232868. const ScopedAutoReleasePool pool;
  232869. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232870. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232871. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232872. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232873. [mainMenu setSubmenu: appMenu forItem: item];
  232874. [NSApp setMainMenu: mainMenu];
  232875. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232876. [appMenu release];
  232877. [mainMenu release];
  232878. }
  232879. }
  232880. }
  232881. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232882. const PopupMenu* extraAppleMenuItems)
  232883. {
  232884. if (getMacMainMenu() != newMenuBarModel)
  232885. {
  232886. const ScopedAutoReleasePool pool;
  232887. if (newMenuBarModel == 0)
  232888. {
  232889. delete JuceMainMenuHandler::instance;
  232890. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232891. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232892. extraAppleMenuItems = 0;
  232893. }
  232894. else
  232895. {
  232896. if (JuceMainMenuHandler::instance == 0)
  232897. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232898. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232899. }
  232900. }
  232901. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  232902. if (newMenuBarModel != 0)
  232903. newMenuBarModel->menuItemsChanged();
  232904. }
  232905. MenuBarModel* MenuBarModel::getMacMainMenu()
  232906. {
  232907. return JuceMainMenuHandler::instance != 0
  232908. ? JuceMainMenuHandler::instance->currentModel : 0;
  232909. }
  232910. void juce_initialiseMacMainMenu()
  232911. {
  232912. if (JuceMainMenuHandler::instance == 0)
  232913. MainMenuHelpers::rebuildMainMenu (0);
  232914. }
  232915. #endif
  232916. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232917. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232918. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232919. // compiled on its own).
  232920. #if JUCE_INCLUDED_FILE
  232921. #if JUCE_MAC
  232922. END_JUCE_NAMESPACE
  232923. using namespace JUCE_NAMESPACE;
  232924. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232925. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232926. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232927. #else
  232928. @interface JuceFileChooserDelegate : NSObject
  232929. #endif
  232930. {
  232931. StringArray* filters;
  232932. }
  232933. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232934. - (void) dealloc;
  232935. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232936. @end
  232937. @implementation JuceFileChooserDelegate
  232938. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232939. {
  232940. [super init];
  232941. filters = filters_;
  232942. return self;
  232943. }
  232944. - (void) dealloc
  232945. {
  232946. delete filters;
  232947. [super dealloc];
  232948. }
  232949. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232950. {
  232951. (void) sender;
  232952. const File f (nsStringToJuce (filename));
  232953. for (int i = filters->size(); --i >= 0;)
  232954. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232955. return true;
  232956. return f.isDirectory();
  232957. }
  232958. @end
  232959. BEGIN_JUCE_NAMESPACE
  232960. void FileChooser::showPlatformDialog (Array<File>& results,
  232961. const String& title,
  232962. const File& currentFileOrDirectory,
  232963. const String& filter,
  232964. bool selectsDirectory,
  232965. bool selectsFiles,
  232966. bool isSaveDialogue,
  232967. bool /*warnAboutOverwritingExistingFiles*/,
  232968. bool selectMultipleFiles,
  232969. FilePreviewComponent* /*extraInfoComponent*/)
  232970. {
  232971. const ScopedAutoReleasePool pool;
  232972. StringArray* filters = new StringArray();
  232973. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  232974. filters->trim();
  232975. filters->removeEmptyStrings();
  232976. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  232977. [delegate autorelease];
  232978. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  232979. : [NSOpenPanel openPanel];
  232980. [panel setTitle: juceStringToNS (title)];
  232981. if (! isSaveDialogue)
  232982. {
  232983. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232984. [openPanel setCanChooseDirectories: selectsDirectory];
  232985. [openPanel setCanChooseFiles: selectsFiles];
  232986. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  232987. }
  232988. [panel setDelegate: delegate];
  232989. if (isSaveDialogue || selectsDirectory)
  232990. [panel setCanCreateDirectories: YES];
  232991. String directory, filename;
  232992. if (currentFileOrDirectory.isDirectory())
  232993. {
  232994. directory = currentFileOrDirectory.getFullPathName();
  232995. }
  232996. else
  232997. {
  232998. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  232999. filename = currentFileOrDirectory.getFileName();
  233000. }
  233001. if ([panel runModalForDirectory: juceStringToNS (directory)
  233002. file: juceStringToNS (filename)]
  233003. == NSOKButton)
  233004. {
  233005. if (isSaveDialogue)
  233006. {
  233007. results.add (File (nsStringToJuce ([panel filename])));
  233008. }
  233009. else
  233010. {
  233011. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233012. NSArray* urls = [openPanel filenames];
  233013. for (unsigned int i = 0; i < [urls count]; ++i)
  233014. {
  233015. NSString* f = [urls objectAtIndex: i];
  233016. results.add (File (nsStringToJuce (f)));
  233017. }
  233018. }
  233019. }
  233020. [panel setDelegate: nil];
  233021. }
  233022. #else
  233023. void FileChooser::showPlatformDialog (Array<File>& results,
  233024. const String& title,
  233025. const File& currentFileOrDirectory,
  233026. const String& filter,
  233027. bool selectsDirectory,
  233028. bool selectsFiles,
  233029. bool isSaveDialogue,
  233030. bool warnAboutOverwritingExistingFiles,
  233031. bool selectMultipleFiles,
  233032. FilePreviewComponent* extraInfoComponent)
  233033. {
  233034. const ScopedAutoReleasePool pool;
  233035. jassertfalse; //xxx to do
  233036. }
  233037. #endif
  233038. #endif
  233039. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233040. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233041. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233042. // compiled on its own).
  233043. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233044. END_JUCE_NAMESPACE
  233045. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233046. @interface NonInterceptingQTMovieView : QTMovieView
  233047. {
  233048. }
  233049. - (id) initWithFrame: (NSRect) frame;
  233050. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233051. - (NSView*) hitTest: (NSPoint) p;
  233052. @end
  233053. @implementation NonInterceptingQTMovieView
  233054. - (id) initWithFrame: (NSRect) frame
  233055. {
  233056. self = [super initWithFrame: frame];
  233057. [self setNextResponder: [self superview]];
  233058. return self;
  233059. }
  233060. - (void) dealloc
  233061. {
  233062. [super dealloc];
  233063. }
  233064. - (NSView*) hitTest: (NSPoint) point
  233065. {
  233066. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233067. }
  233068. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233069. {
  233070. return YES;
  233071. }
  233072. @end
  233073. BEGIN_JUCE_NAMESPACE
  233074. #define theMovie (static_cast <QTMovie*> (movie))
  233075. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233076. : movie (0)
  233077. {
  233078. setOpaque (true);
  233079. setVisible (true);
  233080. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233081. setView (view);
  233082. [view release];
  233083. }
  233084. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233085. {
  233086. closeMovie();
  233087. setView (0);
  233088. }
  233089. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233090. {
  233091. return true;
  233092. }
  233093. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233094. {
  233095. // unfortunately, QTMovie objects can only be created on the main thread..
  233096. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233097. QTMovie* movie = 0;
  233098. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233099. if (fin != 0)
  233100. {
  233101. movieFile = fin->getFile();
  233102. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233103. error: nil];
  233104. }
  233105. else
  233106. {
  233107. MemoryBlock temp;
  233108. movieStream->readIntoMemoryBlock (temp);
  233109. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233110. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233111. {
  233112. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233113. length: temp.getSize()]
  233114. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233115. MIMEType: @""]
  233116. error: nil];
  233117. if (movie != 0)
  233118. break;
  233119. }
  233120. }
  233121. return movie;
  233122. }
  233123. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233124. const bool isControllerVisible_)
  233125. {
  233126. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233127. }
  233128. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233129. const bool controllerVisible_)
  233130. {
  233131. closeMovie();
  233132. if (getPeer() == 0)
  233133. {
  233134. // To open a movie, this component must be visible inside a functioning window, so that
  233135. // the QT control can be assigned to the window.
  233136. jassertfalse;
  233137. return false;
  233138. }
  233139. movie = openMovieFromStream (movieStream, movieFile);
  233140. [theMovie retain];
  233141. QTMovieView* view = (QTMovieView*) getView();
  233142. [view setMovie: theMovie];
  233143. [view setControllerVisible: controllerVisible_];
  233144. setLooping (looping);
  233145. return movie != nil;
  233146. }
  233147. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233148. const bool isControllerVisible_)
  233149. {
  233150. // unfortunately, QTMovie objects can only be created on the main thread..
  233151. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233152. closeMovie();
  233153. if (getPeer() == 0)
  233154. {
  233155. // To open a movie, this component must be visible inside a functioning window, so that
  233156. // the QT control can be assigned to the window.
  233157. jassertfalse;
  233158. return false;
  233159. }
  233160. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233161. NSError* err;
  233162. if ([QTMovie canInitWithURL: url])
  233163. movie = [QTMovie movieWithURL: url error: &err];
  233164. [theMovie retain];
  233165. QTMovieView* view = (QTMovieView*) getView();
  233166. [view setMovie: theMovie];
  233167. [view setControllerVisible: controllerVisible];
  233168. setLooping (looping);
  233169. return movie != nil;
  233170. }
  233171. void QuickTimeMovieComponent::closeMovie()
  233172. {
  233173. stop();
  233174. QTMovieView* view = (QTMovieView*) getView();
  233175. [view setMovie: nil];
  233176. [theMovie release];
  233177. movie = 0;
  233178. movieFile = File::nonexistent;
  233179. }
  233180. bool QuickTimeMovieComponent::isMovieOpen() const
  233181. {
  233182. return movie != nil;
  233183. }
  233184. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233185. {
  233186. return movieFile;
  233187. }
  233188. void QuickTimeMovieComponent::play()
  233189. {
  233190. [theMovie play];
  233191. }
  233192. void QuickTimeMovieComponent::stop()
  233193. {
  233194. [theMovie stop];
  233195. }
  233196. bool QuickTimeMovieComponent::isPlaying() const
  233197. {
  233198. return movie != 0 && [theMovie rate] != 0;
  233199. }
  233200. void QuickTimeMovieComponent::setPosition (const double seconds)
  233201. {
  233202. if (movie != 0)
  233203. {
  233204. QTTime t;
  233205. t.timeValue = (uint64) (100000.0 * seconds);
  233206. t.timeScale = 100000;
  233207. t.flags = 0;
  233208. [theMovie setCurrentTime: t];
  233209. }
  233210. }
  233211. double QuickTimeMovieComponent::getPosition() const
  233212. {
  233213. if (movie == 0)
  233214. return 0.0;
  233215. QTTime t = [theMovie currentTime];
  233216. return t.timeValue / (double) t.timeScale;
  233217. }
  233218. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233219. {
  233220. [theMovie setRate: newSpeed];
  233221. }
  233222. double QuickTimeMovieComponent::getMovieDuration() const
  233223. {
  233224. if (movie == 0)
  233225. return 0.0;
  233226. QTTime t = [theMovie duration];
  233227. return t.timeValue / (double) t.timeScale;
  233228. }
  233229. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233230. {
  233231. looping = shouldLoop;
  233232. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233233. forKey: QTMovieLoopsAttribute];
  233234. }
  233235. bool QuickTimeMovieComponent::isLooping() const
  233236. {
  233237. return looping;
  233238. }
  233239. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233240. {
  233241. [theMovie setVolume: newVolume];
  233242. }
  233243. float QuickTimeMovieComponent::getMovieVolume() const
  233244. {
  233245. return movie != 0 ? [theMovie volume] : 0.0f;
  233246. }
  233247. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233248. {
  233249. width = 0;
  233250. height = 0;
  233251. if (movie != 0)
  233252. {
  233253. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233254. width = (int) s.width;
  233255. height = (int) s.height;
  233256. }
  233257. }
  233258. void QuickTimeMovieComponent::paint (Graphics& g)
  233259. {
  233260. if (movie == 0)
  233261. g.fillAll (Colours::black);
  233262. }
  233263. bool QuickTimeMovieComponent::isControllerVisible() const
  233264. {
  233265. return controllerVisible;
  233266. }
  233267. void QuickTimeMovieComponent::goToStart()
  233268. {
  233269. setPosition (0.0);
  233270. }
  233271. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233272. const RectanglePlacement& placement)
  233273. {
  233274. int normalWidth, normalHeight;
  233275. getMovieNormalSize (normalWidth, normalHeight);
  233276. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233277. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233278. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233279. else
  233280. setBounds (spaceToFitWithin);
  233281. }
  233282. #if ! (JUCE_MAC && JUCE_64BIT)
  233283. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233284. {
  233285. if (movieStream == 0)
  233286. return false;
  233287. File file;
  233288. QTMovie* movie = openMovieFromStream (movieStream, file);
  233289. if (movie != nil)
  233290. result = [movie quickTimeMovie];
  233291. return movie != nil;
  233292. }
  233293. #endif
  233294. #endif
  233295. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233296. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233297. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233298. // compiled on its own).
  233299. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233300. const int kilobytesPerSecond1x = 176;
  233301. END_JUCE_NAMESPACE
  233302. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233303. @interface OpenDiskDevice : NSObject
  233304. {
  233305. @public
  233306. DRDevice* device;
  233307. NSMutableArray* tracks;
  233308. bool underrunProtection;
  233309. }
  233310. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233311. - (void) dealloc;
  233312. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233313. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233314. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233315. @end
  233316. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233317. @interface AudioTrackProducer : NSObject
  233318. {
  233319. JUCE_NAMESPACE::AudioSource* source;
  233320. int readPosition, lengthInFrames;
  233321. }
  233322. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233323. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233324. - (void) dealloc;
  233325. - (void) setupTrackProperties: (DRTrack*) track;
  233326. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233327. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233328. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233329. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233330. toMedia:(NSDictionary*)mediaInfo;
  233331. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233332. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233333. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233334. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233335. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233336. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233337. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233338. ioFlags:(uint32_t*)flags;
  233339. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233340. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233341. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233342. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233343. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233344. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233345. ioFlags:(uint32_t*)flags;
  233346. @end
  233347. @implementation OpenDiskDevice
  233348. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233349. {
  233350. [super init];
  233351. device = device_;
  233352. tracks = [[NSMutableArray alloc] init];
  233353. underrunProtection = true;
  233354. return self;
  233355. }
  233356. - (void) dealloc
  233357. {
  233358. [tracks release];
  233359. [super dealloc];
  233360. }
  233361. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233362. {
  233363. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233364. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233365. [p setupTrackProperties: t];
  233366. [tracks addObject: t];
  233367. [t release];
  233368. [p release];
  233369. }
  233370. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233371. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233372. {
  233373. DRBurn* burn = [DRBurn burnForDevice: device];
  233374. if (! [device acquireExclusiveAccess])
  233375. {
  233376. *error = "Couldn't open or write to the CD device";
  233377. return;
  233378. }
  233379. [device acquireMediaReservation];
  233380. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233381. [d autorelease];
  233382. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233383. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233384. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233385. if (burnSpeed > 0)
  233386. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233387. if (! underrunProtection)
  233388. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233389. [burn setProperties: d];
  233390. [burn writeLayout: tracks];
  233391. for (;;)
  233392. {
  233393. JUCE_NAMESPACE::Thread::sleep (300);
  233394. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233395. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233396. {
  233397. [burn abort];
  233398. *error = "User cancelled the write operation";
  233399. break;
  233400. }
  233401. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233402. {
  233403. *error = "Write operation failed";
  233404. break;
  233405. }
  233406. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233407. {
  233408. break;
  233409. }
  233410. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233411. objectForKey: DRErrorStatusErrorStringKey];
  233412. if ([err length] > 0)
  233413. {
  233414. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233415. break;
  233416. }
  233417. }
  233418. [device releaseMediaReservation];
  233419. [device releaseExclusiveAccess];
  233420. }
  233421. @end
  233422. @implementation AudioTrackProducer
  233423. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233424. {
  233425. lengthInFrames = lengthInFrames_;
  233426. readPosition = 0;
  233427. return self;
  233428. }
  233429. - (void) setupTrackProperties: (DRTrack*) track
  233430. {
  233431. NSMutableDictionary* p = [[track properties] mutableCopy];
  233432. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233433. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233434. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233435. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233436. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233437. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233438. [track setProperties: p];
  233439. [p release];
  233440. }
  233441. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233442. {
  233443. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233444. if (s != nil)
  233445. s->source = source_;
  233446. return s;
  233447. }
  233448. - (void) dealloc
  233449. {
  233450. if (source != 0)
  233451. {
  233452. source->releaseResources();
  233453. delete source;
  233454. }
  233455. [super dealloc];
  233456. }
  233457. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233458. {
  233459. (void) track;
  233460. }
  233461. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233462. {
  233463. (void) track;
  233464. return true;
  233465. }
  233466. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233467. {
  233468. (void) track;
  233469. return lengthInFrames;
  233470. }
  233471. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233472. toMedia: (NSDictionary*) mediaInfo
  233473. {
  233474. (void) track; (void) burn; (void) mediaInfo;
  233475. if (source != 0)
  233476. source->prepareToPlay (44100 / 75, 44100);
  233477. readPosition = 0;
  233478. return true;
  233479. }
  233480. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233481. {
  233482. (void) track;
  233483. if (source != 0)
  233484. source->prepareToPlay (44100 / 75, 44100);
  233485. return true;
  233486. }
  233487. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233488. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233489. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233490. {
  233491. (void) track; (void) address; (void) blockSize; (void) flags;
  233492. if (source != 0)
  233493. {
  233494. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233495. if (numSamples > 0)
  233496. {
  233497. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233498. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233499. info.buffer = &tempBuffer;
  233500. info.startSample = 0;
  233501. info.numSamples = numSamples;
  233502. source->getNextAudioBlock (info);
  233503. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233504. JUCE_NAMESPACE::AudioData::LittleEndian,
  233505. JUCE_NAMESPACE::AudioData::Interleaved,
  233506. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233507. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233508. JUCE_NAMESPACE::AudioData::NativeEndian,
  233509. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233510. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233511. CDSampleFormat left (buffer, 2);
  233512. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233513. CDSampleFormat right (buffer + 2, 2);
  233514. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233515. readPosition += numSamples;
  233516. }
  233517. return numSamples * 4;
  233518. }
  233519. return 0;
  233520. }
  233521. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233522. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233523. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233524. ioFlags: (uint32_t*) flags
  233525. {
  233526. (void) track; (void) address; (void) blockSize; (void) flags;
  233527. zeromem (buffer, bufferLength);
  233528. return bufferLength;
  233529. }
  233530. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233531. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233532. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233533. {
  233534. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  233535. return true;
  233536. }
  233537. @end
  233538. BEGIN_JUCE_NAMESPACE
  233539. class AudioCDBurner::Pimpl : public Timer
  233540. {
  233541. public:
  233542. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233543. : device (0), owner (owner_)
  233544. {
  233545. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233546. if (dev != 0)
  233547. {
  233548. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233549. lastState = getDiskState();
  233550. startTimer (1000);
  233551. }
  233552. }
  233553. ~Pimpl()
  233554. {
  233555. stopTimer();
  233556. [device release];
  233557. }
  233558. void timerCallback()
  233559. {
  233560. const DiskState state = getDiskState();
  233561. if (state != lastState)
  233562. {
  233563. lastState = state;
  233564. owner.sendChangeMessage();
  233565. }
  233566. }
  233567. DiskState getDiskState() const
  233568. {
  233569. if ([device->device isValid])
  233570. {
  233571. NSDictionary* status = [device->device status];
  233572. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  233573. if ([state isEqualTo: DRDeviceMediaStateNone])
  233574. {
  233575. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  233576. return trayOpen;
  233577. return noDisc;
  233578. }
  233579. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  233580. {
  233581. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  233582. return writableDiskPresent;
  233583. else
  233584. return readOnlyDiskPresent;
  233585. }
  233586. }
  233587. return unknown;
  233588. }
  233589. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  233590. const Array<int> getAvailableWriteSpeeds() const
  233591. {
  233592. Array<int> results;
  233593. if ([device->device isValid])
  233594. {
  233595. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  233596. for (unsigned int i = 0; i < [speeds count]; ++i)
  233597. {
  233598. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  233599. results.add (kbPerSec / kilobytesPerSecond1x);
  233600. }
  233601. }
  233602. return results;
  233603. }
  233604. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  233605. {
  233606. if ([device->device isValid])
  233607. {
  233608. device->underrunProtection = shouldBeEnabled;
  233609. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  233610. }
  233611. return false;
  233612. }
  233613. int getNumAvailableAudioBlocks() const
  233614. {
  233615. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  233616. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  233617. }
  233618. OpenDiskDevice* device;
  233619. private:
  233620. DiskState lastState;
  233621. AudioCDBurner& owner;
  233622. };
  233623. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  233624. {
  233625. pimpl = new Pimpl (*this, deviceIndex);
  233626. }
  233627. AudioCDBurner::~AudioCDBurner()
  233628. {
  233629. }
  233630. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  233631. {
  233632. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  233633. if (b->pimpl->device == 0)
  233634. b = 0;
  233635. return b.release();
  233636. }
  233637. namespace
  233638. {
  233639. NSArray* findDiskBurnerDevices()
  233640. {
  233641. NSMutableArray* results = [NSMutableArray array];
  233642. NSArray* devs = [DRDevice devices];
  233643. for (int i = 0; i < [devs count]; ++i)
  233644. {
  233645. NSDictionary* dic = [[devs objectAtIndex: i] info];
  233646. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  233647. if (name != nil)
  233648. [results addObject: name];
  233649. }
  233650. return results;
  233651. }
  233652. }
  233653. const StringArray AudioCDBurner::findAvailableDevices()
  233654. {
  233655. NSArray* names = findDiskBurnerDevices();
  233656. StringArray s;
  233657. for (unsigned int i = 0; i < [names count]; ++i)
  233658. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  233659. return s;
  233660. }
  233661. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  233662. {
  233663. return pimpl->getDiskState();
  233664. }
  233665. bool AudioCDBurner::isDiskPresent() const
  233666. {
  233667. return getDiskState() == writableDiskPresent;
  233668. }
  233669. bool AudioCDBurner::openTray()
  233670. {
  233671. return pimpl->openTray();
  233672. }
  233673. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  233674. {
  233675. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  233676. DiskState oldState = getDiskState();
  233677. DiskState newState = oldState;
  233678. while (newState == oldState && Time::currentTimeMillis() < timeout)
  233679. {
  233680. newState = getDiskState();
  233681. Thread::sleep (100);
  233682. }
  233683. return newState;
  233684. }
  233685. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  233686. {
  233687. return pimpl->getAvailableWriteSpeeds();
  233688. }
  233689. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  233690. {
  233691. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  233692. }
  233693. int AudioCDBurner::getNumAvailableAudioBlocks() const
  233694. {
  233695. return pimpl->getNumAvailableAudioBlocks();
  233696. }
  233697. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  233698. {
  233699. if ([pimpl->device->device isValid])
  233700. {
  233701. [pimpl->device addSourceTrack: source numSamples: numSamps];
  233702. return true;
  233703. }
  233704. return false;
  233705. }
  233706. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  233707. bool ejectDiscAfterwards,
  233708. bool performFakeBurnForTesting,
  233709. int writeSpeed)
  233710. {
  233711. String error ("Couldn't open or write to the CD device");
  233712. if ([pimpl->device->device isValid])
  233713. {
  233714. error = String::empty;
  233715. [pimpl->device burn: listener
  233716. errorString: &error
  233717. ejectAfterwards: ejectDiscAfterwards
  233718. isFake: performFakeBurnForTesting
  233719. speed: writeSpeed];
  233720. }
  233721. return error;
  233722. }
  233723. #endif
  233724. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233725. void AudioCDReader::ejectDisk()
  233726. {
  233727. const ScopedAutoReleasePool p;
  233728. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233729. }
  233730. #endif
  233731. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233732. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233733. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233734. // compiled on its own).
  233735. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233736. namespace CDReaderHelpers
  233737. {
  233738. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  233739. {
  233740. forEachXmlChildElementWithTagName (xml, child, "key")
  233741. if (child->getAllSubText().trim() == key)
  233742. return child->getNextElement();
  233743. return 0;
  233744. }
  233745. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  233746. {
  233747. const XmlElement* const block = getElementForKey (xml, key);
  233748. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  233749. }
  233750. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  233751. // Returns NULL on success, otherwise a const char* representing an error.
  233752. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  233753. {
  233754. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  233755. if (xml == 0)
  233756. return "Couldn't parse XML in file";
  233757. const XmlElement* const dict = xml->getChildByName ("dict");
  233758. if (dict == 0)
  233759. return "Couldn't get top level dictionary";
  233760. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  233761. if (sessions == 0)
  233762. return "Couldn't find sessions key";
  233763. const XmlElement* const session = sessions->getFirstChildElement();
  233764. if (session == 0)
  233765. return "Couldn't find first session";
  233766. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233767. if (leadOut < 0)
  233768. return "Couldn't find Leadout Block";
  233769. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233770. if (trackArray == 0)
  233771. return "Couldn't find Track Array";
  233772. forEachXmlChildElement (*trackArray, track)
  233773. {
  233774. const int trackValue = getIntValueForKey (*track, "Start Block");
  233775. if (trackValue < 0)
  233776. return "Couldn't find Start Block in the track";
  233777. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233778. }
  233779. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233780. return 0;
  233781. }
  233782. static void findDevices (Array<File>& cds)
  233783. {
  233784. File volumes ("/Volumes");
  233785. volumes.findChildFiles (cds, File::findDirectories, false);
  233786. for (int i = cds.size(); --i >= 0;)
  233787. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233788. cds.remove (i);
  233789. }
  233790. struct TrackSorter
  233791. {
  233792. static int getCDTrackNumber (const File& file)
  233793. {
  233794. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233795. }
  233796. static int compareElements (const File& first, const File& second)
  233797. {
  233798. const int firstTrack = getCDTrackNumber (first);
  233799. const int secondTrack = getCDTrackNumber (second);
  233800. jassert (firstTrack > 0 && secondTrack > 0);
  233801. return firstTrack - secondTrack;
  233802. }
  233803. };
  233804. }
  233805. const StringArray AudioCDReader::getAvailableCDNames()
  233806. {
  233807. Array<File> cds;
  233808. CDReaderHelpers::findDevices (cds);
  233809. StringArray names;
  233810. for (int i = 0; i < cds.size(); ++i)
  233811. names.add (cds.getReference(i).getFileName());
  233812. return names;
  233813. }
  233814. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233815. {
  233816. Array<File> cds;
  233817. CDReaderHelpers::findDevices (cds);
  233818. if (cds[index].exists())
  233819. return new AudioCDReader (cds[index]);
  233820. return 0;
  233821. }
  233822. AudioCDReader::AudioCDReader (const File& volume)
  233823. : AudioFormatReader (0, "CD Audio"),
  233824. volumeDir (volume),
  233825. currentReaderTrack (-1),
  233826. reader (0)
  233827. {
  233828. sampleRate = 44100.0;
  233829. bitsPerSample = 16;
  233830. numChannels = 2;
  233831. usesFloatingPointData = false;
  233832. refreshTrackLengths();
  233833. }
  233834. AudioCDReader::~AudioCDReader()
  233835. {
  233836. }
  233837. void AudioCDReader::refreshTrackLengths()
  233838. {
  233839. tracks.clear();
  233840. trackStartSamples.clear();
  233841. lengthInSamples = 0;
  233842. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233843. CDReaderHelpers::TrackSorter sorter;
  233844. tracks.sort (sorter);
  233845. const File toc (volumeDir.getChildFile (".TOC.plist"));
  233846. if (toc.exists())
  233847. {
  233848. XmlDocument doc (toc);
  233849. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  233850. (void) error; // could be logged..
  233851. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  233852. }
  233853. }
  233854. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233855. int64 startSampleInFile, int numSamples)
  233856. {
  233857. while (numSamples > 0)
  233858. {
  233859. int track = -1;
  233860. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233861. {
  233862. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233863. {
  233864. track = i;
  233865. break;
  233866. }
  233867. }
  233868. if (track < 0)
  233869. return false;
  233870. if (track != currentReaderTrack)
  233871. {
  233872. reader = 0;
  233873. FileInputStream* const in = tracks [track].createInputStream();
  233874. if (in != 0)
  233875. {
  233876. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233877. AiffAudioFormat format;
  233878. reader = format.createReaderFor (bin, true);
  233879. if (reader == 0)
  233880. currentReaderTrack = -1;
  233881. else
  233882. currentReaderTrack = track;
  233883. }
  233884. }
  233885. if (reader == 0)
  233886. return false;
  233887. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233888. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233889. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233890. numSamples -= numAvailable;
  233891. startSampleInFile += numAvailable;
  233892. }
  233893. return true;
  233894. }
  233895. bool AudioCDReader::isCDStillPresent() const
  233896. {
  233897. return volumeDir.exists();
  233898. }
  233899. bool AudioCDReader::isTrackAudio (int trackNum) const
  233900. {
  233901. return tracks [trackNum].hasFileExtension (".aiff");
  233902. }
  233903. void AudioCDReader::enableIndexScanning (bool)
  233904. {
  233905. // any way to do this on a Mac??
  233906. }
  233907. int AudioCDReader::getLastIndex() const
  233908. {
  233909. return 0;
  233910. }
  233911. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  233912. {
  233913. return Array <int>();
  233914. }
  233915. #endif
  233916. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233917. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233918. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233919. // compiled on its own).
  233920. #if JUCE_INCLUDED_FILE
  233921. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233922. for example having more than one juce plugin loaded into a host, then when a
  233923. method is called, the actual code that runs might actually be in a different module
  233924. than the one you expect... So any calls to library functions or statics that are
  233925. made inside obj-c methods will probably end up getting executed in a different DLL's
  233926. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233927. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233928. virtual methods of an object that's known to live inside the right module's space.
  233929. */
  233930. class AppDelegateRedirector
  233931. {
  233932. public:
  233933. AppDelegateRedirector()
  233934. {
  233935. }
  233936. virtual ~AppDelegateRedirector()
  233937. {
  233938. }
  233939. virtual NSApplicationTerminateReply shouldTerminate()
  233940. {
  233941. if (JUCEApplication::getInstance() != 0)
  233942. {
  233943. JUCEApplication::getInstance()->systemRequestedQuit();
  233944. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  233945. return NSTerminateCancel;
  233946. }
  233947. return NSTerminateNow;
  233948. }
  233949. virtual void willTerminate()
  233950. {
  233951. JUCEApplication::appWillTerminateByForce();
  233952. }
  233953. virtual BOOL openFile (NSString* filename)
  233954. {
  233955. if (JUCEApplication::getInstance() != 0)
  233956. {
  233957. JUCEApplication::getInstance()->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  233958. return YES;
  233959. }
  233960. return NO;
  233961. }
  233962. virtual void openFiles (NSArray* filenames)
  233963. {
  233964. StringArray files;
  233965. for (unsigned int i = 0; i < [filenames count]; ++i)
  233966. files.add (quotedIfContainsSpaces ((NSString*) [filenames objectAtIndex: i]));
  233967. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  233968. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  233969. }
  233970. virtual void focusChanged()
  233971. {
  233972. juce_HandleProcessFocusChange();
  233973. }
  233974. struct CallbackMessagePayload
  233975. {
  233976. MessageCallbackFunction* function;
  233977. void* parameter;
  233978. void* volatile result;
  233979. bool volatile hasBeenExecuted;
  233980. };
  233981. virtual void performCallback (CallbackMessagePayload* pl)
  233982. {
  233983. pl->result = (*pl->function) (pl->parameter);
  233984. pl->hasBeenExecuted = true;
  233985. }
  233986. virtual void deleteSelf()
  233987. {
  233988. delete this;
  233989. }
  233990. void postMessage (Message* const m)
  233991. {
  233992. messageQueue.post (m);
  233993. }
  233994. private:
  233995. CFRunLoopRef runLoop;
  233996. CFRunLoopSourceRef runLoopSource;
  233997. MessageQueue messageQueue;
  233998. static const String quotedIfContainsSpaces (NSString* file)
  233999. {
  234000. String s (nsStringToJuce (file));
  234001. if (s.containsChar (' '))
  234002. s = s.quoted ('"');
  234003. return s;
  234004. }
  234005. };
  234006. END_JUCE_NAMESPACE
  234007. using namespace JUCE_NAMESPACE;
  234008. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234009. @interface JuceAppDelegate : NSObject
  234010. {
  234011. @private
  234012. id oldDelegate;
  234013. @public
  234014. AppDelegateRedirector* redirector;
  234015. }
  234016. - (JuceAppDelegate*) init;
  234017. - (void) dealloc;
  234018. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234019. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234020. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234021. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234022. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234023. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234024. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234025. - (void) performCallback: (id) info;
  234026. - (void) dummyMethod;
  234027. @end
  234028. @implementation JuceAppDelegate
  234029. - (JuceAppDelegate*) init
  234030. {
  234031. [super init];
  234032. redirector = new AppDelegateRedirector();
  234033. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234034. if (JUCEApplication::isStandaloneApp())
  234035. {
  234036. oldDelegate = [NSApp delegate];
  234037. [NSApp setDelegate: self];
  234038. }
  234039. else
  234040. {
  234041. oldDelegate = 0;
  234042. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234043. name: NSApplicationDidResignActiveNotification object: NSApp];
  234044. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234045. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234046. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234047. name: NSApplicationWillUnhideNotification object: NSApp];
  234048. }
  234049. return self;
  234050. }
  234051. - (void) dealloc
  234052. {
  234053. if (oldDelegate != 0)
  234054. [NSApp setDelegate: oldDelegate];
  234055. redirector->deleteSelf();
  234056. [super dealloc];
  234057. }
  234058. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234059. {
  234060. (void) app;
  234061. return redirector->shouldTerminate();
  234062. }
  234063. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234064. {
  234065. (void) aNotification;
  234066. redirector->willTerminate();
  234067. }
  234068. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234069. {
  234070. (void) app;
  234071. return redirector->openFile (filename);
  234072. }
  234073. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234074. {
  234075. (void) sender;
  234076. return redirector->openFiles (filenames);
  234077. }
  234078. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234079. {
  234080. (void) notification;
  234081. redirector->focusChanged();
  234082. }
  234083. - (void) applicationDidResignActive: (NSNotification*) notification
  234084. {
  234085. (void) notification;
  234086. redirector->focusChanged();
  234087. }
  234088. - (void) applicationWillUnhide: (NSNotification*) notification
  234089. {
  234090. (void) notification;
  234091. redirector->focusChanged();
  234092. }
  234093. - (void) performCallback: (id) info
  234094. {
  234095. if ([info isKindOfClass: [NSData class]])
  234096. {
  234097. AppDelegateRedirector::CallbackMessagePayload* pl
  234098. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234099. if (pl != 0)
  234100. redirector->performCallback (pl);
  234101. }
  234102. else
  234103. {
  234104. jassertfalse; // should never get here!
  234105. }
  234106. }
  234107. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234108. @end
  234109. BEGIN_JUCE_NAMESPACE
  234110. static JuceAppDelegate* juceAppDelegate = 0;
  234111. void MessageManager::runDispatchLoop()
  234112. {
  234113. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234114. {
  234115. const ScopedAutoReleasePool pool;
  234116. // must only be called by the message thread!
  234117. jassert (isThisTheMessageThread());
  234118. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234119. @try
  234120. {
  234121. [NSApp run];
  234122. }
  234123. @catch (NSException* e)
  234124. {
  234125. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234126. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234127. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234128. }
  234129. @finally
  234130. {
  234131. }
  234132. #else
  234133. [NSApp run];
  234134. #endif
  234135. }
  234136. }
  234137. void MessageManager::stopDispatchLoop()
  234138. {
  234139. quitMessagePosted = true;
  234140. [NSApp stop: nil];
  234141. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234142. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234143. }
  234144. namespace
  234145. {
  234146. bool isEventBlockedByModalComps (NSEvent* e)
  234147. {
  234148. if (Component::getNumCurrentlyModalComponents() == 0)
  234149. return false;
  234150. NSWindow* const w = [e window];
  234151. if (w == 0 || [w worksWhenModal])
  234152. return false;
  234153. bool isKey = false, isInputAttempt = false;
  234154. switch ([e type])
  234155. {
  234156. case NSKeyDown:
  234157. case NSKeyUp:
  234158. isKey = isInputAttempt = true;
  234159. break;
  234160. case NSLeftMouseDown:
  234161. case NSRightMouseDown:
  234162. case NSOtherMouseDown:
  234163. isInputAttempt = true;
  234164. break;
  234165. case NSLeftMouseDragged:
  234166. case NSRightMouseDragged:
  234167. case NSLeftMouseUp:
  234168. case NSRightMouseUp:
  234169. case NSOtherMouseUp:
  234170. case NSOtherMouseDragged:
  234171. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234172. return false;
  234173. break;
  234174. case NSMouseMoved:
  234175. case NSMouseEntered:
  234176. case NSMouseExited:
  234177. case NSCursorUpdate:
  234178. case NSScrollWheel:
  234179. case NSTabletPoint:
  234180. case NSTabletProximity:
  234181. break;
  234182. default:
  234183. return false;
  234184. }
  234185. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234186. {
  234187. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234188. NSView* const compView = (NSView*) peer->getNativeHandle();
  234189. if ([compView window] == w)
  234190. {
  234191. if (isKey)
  234192. {
  234193. if (compView == [w firstResponder])
  234194. return false;
  234195. }
  234196. else
  234197. {
  234198. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234199. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234200. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234201. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234202. return false;
  234203. }
  234204. }
  234205. }
  234206. if (isInputAttempt)
  234207. {
  234208. if (! [NSApp isActive])
  234209. [NSApp activateIgnoringOtherApps: YES];
  234210. Component* const modal = Component::getCurrentlyModalComponent (0);
  234211. if (modal != 0)
  234212. modal->inputAttemptWhenModal();
  234213. }
  234214. return true;
  234215. }
  234216. }
  234217. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234218. {
  234219. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234220. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234221. while (! quitMessagePosted)
  234222. {
  234223. const ScopedAutoReleasePool pool;
  234224. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234225. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234226. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234227. inMode: NSDefaultRunLoopMode
  234228. dequeue: YES];
  234229. if (e != 0 && ! isEventBlockedByModalComps (e))
  234230. [NSApp sendEvent: e];
  234231. if (Time::getMillisecondCounter() >= endTime)
  234232. break;
  234233. }
  234234. return ! quitMessagePosted;
  234235. }
  234236. void MessageManager::doPlatformSpecificInitialisation()
  234237. {
  234238. if (juceAppDelegate == 0)
  234239. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234240. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234241. // correctly (needed prior to 10.5)
  234242. if (! [NSThread isMultiThreaded])
  234243. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234244. toTarget: juceAppDelegate
  234245. withObject: nil];
  234246. }
  234247. void MessageManager::doPlatformSpecificShutdown()
  234248. {
  234249. if (juceAppDelegate != 0)
  234250. {
  234251. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234252. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234253. [juceAppDelegate release];
  234254. juceAppDelegate = 0;
  234255. }
  234256. }
  234257. bool juce_postMessageToSystemQueue (Message* message)
  234258. {
  234259. juceAppDelegate->redirector->postMessage (message);
  234260. return true;
  234261. }
  234262. void MessageManager::broadcastMessage (const String&)
  234263. {
  234264. }
  234265. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234266. {
  234267. if (isThisTheMessageThread())
  234268. {
  234269. return (*callback) (data);
  234270. }
  234271. else
  234272. {
  234273. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234274. // deadlock because the message manager is blocked from running, so can never
  234275. // call your function..
  234276. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234277. const ScopedAutoReleasePool pool;
  234278. AppDelegateRedirector::CallbackMessagePayload cmp;
  234279. cmp.function = callback;
  234280. cmp.parameter = data;
  234281. cmp.result = 0;
  234282. cmp.hasBeenExecuted = false;
  234283. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234284. withObject: [NSData dataWithBytesNoCopy: &cmp
  234285. length: sizeof (cmp)
  234286. freeWhenDone: NO]
  234287. waitUntilDone: YES];
  234288. return cmp.result;
  234289. }
  234290. }
  234291. #endif
  234292. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234293. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234294. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234295. // compiled on its own).
  234296. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234297. #if JUCE_MAC
  234298. END_JUCE_NAMESPACE
  234299. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234300. @interface DownloadClickDetector : NSObject
  234301. {
  234302. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234303. }
  234304. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234305. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234306. request: (NSURLRequest*) request
  234307. frame: (WebFrame*) frame
  234308. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234309. @end
  234310. @implementation DownloadClickDetector
  234311. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234312. {
  234313. [super init];
  234314. ownerComponent = ownerComponent_;
  234315. return self;
  234316. }
  234317. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234318. request: (NSURLRequest*) request
  234319. frame: (WebFrame*) frame
  234320. decisionListener: (id <WebPolicyDecisionListener>) listener
  234321. {
  234322. (void) sender;
  234323. (void) request;
  234324. (void) frame;
  234325. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234326. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234327. [listener use];
  234328. else
  234329. [listener ignore];
  234330. }
  234331. @end
  234332. BEGIN_JUCE_NAMESPACE
  234333. class WebBrowserComponentInternal : public NSViewComponent
  234334. {
  234335. public:
  234336. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234337. {
  234338. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234339. frameName: @""
  234340. groupName: @""];
  234341. setView (webView);
  234342. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234343. [webView setPolicyDelegate: clickListener];
  234344. }
  234345. ~WebBrowserComponentInternal()
  234346. {
  234347. [webView setPolicyDelegate: nil];
  234348. [clickListener release];
  234349. setView (0);
  234350. }
  234351. void goToURL (const String& url,
  234352. const StringArray* headers,
  234353. const MemoryBlock* postData)
  234354. {
  234355. NSMutableURLRequest* r
  234356. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234357. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234358. timeoutInterval: 30.0];
  234359. if (postData != 0 && postData->getSize() > 0)
  234360. {
  234361. [r setHTTPMethod: @"POST"];
  234362. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234363. length: postData->getSize()]];
  234364. }
  234365. if (headers != 0)
  234366. {
  234367. for (int i = 0; i < headers->size(); ++i)
  234368. {
  234369. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234370. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234371. [r setValue: juceStringToNS (headerValue)
  234372. forHTTPHeaderField: juceStringToNS (headerName)];
  234373. }
  234374. }
  234375. stop();
  234376. [[webView mainFrame] loadRequest: r];
  234377. }
  234378. void goBack()
  234379. {
  234380. [webView goBack];
  234381. }
  234382. void goForward()
  234383. {
  234384. [webView goForward];
  234385. }
  234386. void stop()
  234387. {
  234388. [webView stopLoading: nil];
  234389. }
  234390. void refresh()
  234391. {
  234392. [webView reload: nil];
  234393. }
  234394. void mouseMove (const MouseEvent&)
  234395. {
  234396. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234397. // them work is to push them via this non-public method..
  234398. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234399. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234400. }
  234401. private:
  234402. WebView* webView;
  234403. DownloadClickDetector* clickListener;
  234404. };
  234405. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234406. : browser (0),
  234407. blankPageShown (false),
  234408. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234409. {
  234410. setOpaque (true);
  234411. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234412. }
  234413. WebBrowserComponent::~WebBrowserComponent()
  234414. {
  234415. deleteAndZero (browser);
  234416. }
  234417. void WebBrowserComponent::goToURL (const String& url,
  234418. const StringArray* headers,
  234419. const MemoryBlock* postData)
  234420. {
  234421. lastURL = url;
  234422. lastHeaders.clear();
  234423. if (headers != 0)
  234424. lastHeaders = *headers;
  234425. lastPostData.setSize (0);
  234426. if (postData != 0)
  234427. lastPostData = *postData;
  234428. blankPageShown = false;
  234429. browser->goToURL (url, headers, postData);
  234430. }
  234431. void WebBrowserComponent::stop()
  234432. {
  234433. browser->stop();
  234434. }
  234435. void WebBrowserComponent::goBack()
  234436. {
  234437. lastURL = String::empty;
  234438. blankPageShown = false;
  234439. browser->goBack();
  234440. }
  234441. void WebBrowserComponent::goForward()
  234442. {
  234443. lastURL = String::empty;
  234444. browser->goForward();
  234445. }
  234446. void WebBrowserComponent::refresh()
  234447. {
  234448. browser->refresh();
  234449. }
  234450. void WebBrowserComponent::paint (Graphics&)
  234451. {
  234452. }
  234453. void WebBrowserComponent::checkWindowAssociation()
  234454. {
  234455. if (isShowing())
  234456. {
  234457. if (blankPageShown)
  234458. goBack();
  234459. }
  234460. else
  234461. {
  234462. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234463. {
  234464. // when the component becomes invisible, some stuff like flash
  234465. // carries on playing audio, so we need to force it onto a blank
  234466. // page to avoid this, (and send it back when it's made visible again).
  234467. blankPageShown = true;
  234468. browser->goToURL ("about:blank", 0, 0);
  234469. }
  234470. }
  234471. }
  234472. void WebBrowserComponent::reloadLastURL()
  234473. {
  234474. if (lastURL.isNotEmpty())
  234475. {
  234476. goToURL (lastURL, &lastHeaders, &lastPostData);
  234477. lastURL = String::empty;
  234478. }
  234479. }
  234480. void WebBrowserComponent::parentHierarchyChanged()
  234481. {
  234482. checkWindowAssociation();
  234483. }
  234484. void WebBrowserComponent::resized()
  234485. {
  234486. browser->setSize (getWidth(), getHeight());
  234487. }
  234488. void WebBrowserComponent::visibilityChanged()
  234489. {
  234490. checkWindowAssociation();
  234491. }
  234492. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234493. {
  234494. return true;
  234495. }
  234496. #else
  234497. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234498. {
  234499. }
  234500. WebBrowserComponent::~WebBrowserComponent()
  234501. {
  234502. }
  234503. void WebBrowserComponent::goToURL (const String& url,
  234504. const StringArray* headers,
  234505. const MemoryBlock* postData)
  234506. {
  234507. }
  234508. void WebBrowserComponent::stop()
  234509. {
  234510. }
  234511. void WebBrowserComponent::goBack()
  234512. {
  234513. }
  234514. void WebBrowserComponent::goForward()
  234515. {
  234516. }
  234517. void WebBrowserComponent::refresh()
  234518. {
  234519. }
  234520. void WebBrowserComponent::paint (Graphics& g)
  234521. {
  234522. }
  234523. void WebBrowserComponent::checkWindowAssociation()
  234524. {
  234525. }
  234526. void WebBrowserComponent::reloadLastURL()
  234527. {
  234528. }
  234529. void WebBrowserComponent::parentHierarchyChanged()
  234530. {
  234531. }
  234532. void WebBrowserComponent::resized()
  234533. {
  234534. }
  234535. void WebBrowserComponent::visibilityChanged()
  234536. {
  234537. }
  234538. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234539. {
  234540. return true;
  234541. }
  234542. #endif
  234543. #endif
  234544. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234545. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234546. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234547. // compiled on its own).
  234548. #if JUCE_INCLUDED_FILE
  234549. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234550. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234551. #endif
  234552. #undef log
  234553. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234554. #define log(a) Logger::writeToLog (a)
  234555. #else
  234556. #define log(a)
  234557. #endif
  234558. #undef OK
  234559. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234560. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234561. {
  234562. if (err == noErr)
  234563. return true;
  234564. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234565. jassertfalse;
  234566. return false;
  234567. }
  234568. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  234569. #else
  234570. #define OK(a) (a == noErr)
  234571. #endif
  234572. class CoreAudioInternal : public Timer
  234573. {
  234574. public:
  234575. CoreAudioInternal (AudioDeviceID id)
  234576. : inputLatency (0),
  234577. outputLatency (0),
  234578. callback (0),
  234579. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234580. audioProcID (0),
  234581. #endif
  234582. isSlaveDevice (false),
  234583. deviceID (id),
  234584. started (false),
  234585. sampleRate (0),
  234586. bufferSize (512),
  234587. numInputChans (0),
  234588. numOutputChans (0),
  234589. callbacksAllowed (true),
  234590. numInputChannelInfos (0),
  234591. numOutputChannelInfos (0)
  234592. {
  234593. jassert (deviceID != 0);
  234594. updateDetailsFromDevice();
  234595. AudioObjectPropertyAddress pa;
  234596. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234597. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234598. pa.mElement = kAudioObjectPropertyElementWildcard;
  234599. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  234600. }
  234601. ~CoreAudioInternal()
  234602. {
  234603. AudioObjectPropertyAddress pa;
  234604. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234605. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234606. pa.mElement = kAudioObjectPropertyElementWildcard;
  234607. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  234608. stop (false);
  234609. }
  234610. void allocateTempBuffers()
  234611. {
  234612. const int tempBufSize = bufferSize + 4;
  234613. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  234614. tempInputBuffers.calloc (numInputChans + 2);
  234615. tempOutputBuffers.calloc (numOutputChans + 2);
  234616. int i, count = 0;
  234617. for (i = 0; i < numInputChans; ++i)
  234618. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234619. for (i = 0; i < numOutputChans; ++i)
  234620. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234621. }
  234622. // returns the number of actual available channels
  234623. void fillInChannelInfo (const bool input)
  234624. {
  234625. int chanNum = 0;
  234626. UInt32 size;
  234627. AudioObjectPropertyAddress pa;
  234628. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234629. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234630. pa.mElement = kAudioObjectPropertyElementMaster;
  234631. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234632. {
  234633. HeapBlock <AudioBufferList> bufList;
  234634. bufList.calloc (size, 1);
  234635. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234636. {
  234637. const int numStreams = bufList->mNumberBuffers;
  234638. for (int i = 0; i < numStreams; ++i)
  234639. {
  234640. const AudioBuffer& b = bufList->mBuffers[i];
  234641. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  234642. {
  234643. String name;
  234644. {
  234645. char channelName [256];
  234646. zerostruct (channelName);
  234647. UInt32 nameSize = sizeof (channelName);
  234648. UInt32 channelNum = chanNum + 1;
  234649. pa.mSelector = kAudioDevicePropertyChannelName;
  234650. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  234651. name = String::fromUTF8 (channelName, nameSize);
  234652. }
  234653. if (input)
  234654. {
  234655. if (activeInputChans[chanNum])
  234656. {
  234657. inputChannelInfo [numInputChannelInfos].streamNum = i;
  234658. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  234659. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234660. ++numInputChannelInfos;
  234661. }
  234662. if (name.isEmpty())
  234663. name << "Input " << (chanNum + 1);
  234664. inChanNames.add (name);
  234665. }
  234666. else
  234667. {
  234668. if (activeOutputChans[chanNum])
  234669. {
  234670. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  234671. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  234672. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234673. ++numOutputChannelInfos;
  234674. }
  234675. if (name.isEmpty())
  234676. name << "Output " << (chanNum + 1);
  234677. outChanNames.add (name);
  234678. }
  234679. ++chanNum;
  234680. }
  234681. }
  234682. }
  234683. }
  234684. }
  234685. void updateDetailsFromDevice()
  234686. {
  234687. stopTimer();
  234688. if (deviceID == 0)
  234689. return;
  234690. const ScopedLock sl (callbackLock);
  234691. Float64 sr;
  234692. UInt32 size = sizeof (Float64);
  234693. AudioObjectPropertyAddress pa;
  234694. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234695. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234696. pa.mElement = kAudioObjectPropertyElementMaster;
  234697. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  234698. sampleRate = sr;
  234699. UInt32 framesPerBuf;
  234700. size = sizeof (framesPerBuf);
  234701. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234702. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  234703. {
  234704. bufferSize = framesPerBuf;
  234705. allocateTempBuffers();
  234706. }
  234707. bufferSizes.clear();
  234708. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  234709. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234710. {
  234711. HeapBlock <AudioValueRange> ranges;
  234712. ranges.calloc (size, 1);
  234713. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234714. {
  234715. bufferSizes.add ((int) ranges[0].mMinimum);
  234716. for (int i = 32; i < 2048; i += 32)
  234717. {
  234718. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234719. {
  234720. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  234721. {
  234722. bufferSizes.addIfNotAlreadyThere (i);
  234723. break;
  234724. }
  234725. }
  234726. }
  234727. if (bufferSize > 0)
  234728. bufferSizes.addIfNotAlreadyThere (bufferSize);
  234729. }
  234730. }
  234731. if (bufferSizes.size() == 0 && bufferSize > 0)
  234732. bufferSizes.add (bufferSize);
  234733. sampleRates.clear();
  234734. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234735. String rates;
  234736. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234737. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234738. {
  234739. HeapBlock <AudioValueRange> ranges;
  234740. ranges.calloc (size, 1);
  234741. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234742. {
  234743. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234744. {
  234745. bool ok = false;
  234746. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234747. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234748. ok = true;
  234749. if (ok)
  234750. {
  234751. sampleRates.add (possibleRates[i]);
  234752. rates << possibleRates[i] << ' ';
  234753. }
  234754. }
  234755. }
  234756. }
  234757. if (sampleRates.size() == 0 && sampleRate > 0)
  234758. {
  234759. sampleRates.add (sampleRate);
  234760. rates << sampleRate;
  234761. }
  234762. log ("sr: " + rates);
  234763. inputLatency = 0;
  234764. outputLatency = 0;
  234765. UInt32 lat;
  234766. size = sizeof (lat);
  234767. pa.mSelector = kAudioDevicePropertyLatency;
  234768. pa.mScope = kAudioDevicePropertyScopeInput;
  234769. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234770. inputLatency = (int) lat;
  234771. pa.mScope = kAudioDevicePropertyScopeOutput;
  234772. size = sizeof (lat);
  234773. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234774. outputLatency = (int) lat;
  234775. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234776. inChanNames.clear();
  234777. outChanNames.clear();
  234778. inputChannelInfo.calloc (numInputChans + 2);
  234779. numInputChannelInfos = 0;
  234780. outputChannelInfo.calloc (numOutputChans + 2);
  234781. numOutputChannelInfos = 0;
  234782. fillInChannelInfo (true);
  234783. fillInChannelInfo (false);
  234784. }
  234785. const StringArray getSources (bool input)
  234786. {
  234787. StringArray s;
  234788. HeapBlock <OSType> types;
  234789. const int num = getAllDataSourcesForDevice (deviceID, types);
  234790. for (int i = 0; i < num; ++i)
  234791. {
  234792. AudioValueTranslation avt;
  234793. char buffer[256];
  234794. avt.mInputData = &(types[i]);
  234795. avt.mInputDataSize = sizeof (UInt32);
  234796. avt.mOutputData = buffer;
  234797. avt.mOutputDataSize = 256;
  234798. UInt32 transSize = sizeof (avt);
  234799. AudioObjectPropertyAddress pa;
  234800. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234801. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234802. pa.mElement = kAudioObjectPropertyElementMaster;
  234803. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234804. {
  234805. DBG (buffer);
  234806. s.add (buffer);
  234807. }
  234808. }
  234809. return s;
  234810. }
  234811. int getCurrentSourceIndex (bool input) const
  234812. {
  234813. OSType currentSourceID = 0;
  234814. UInt32 size = sizeof (currentSourceID);
  234815. int result = -1;
  234816. AudioObjectPropertyAddress pa;
  234817. pa.mSelector = kAudioDevicePropertyDataSource;
  234818. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234819. pa.mElement = kAudioObjectPropertyElementMaster;
  234820. if (deviceID != 0)
  234821. {
  234822. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234823. {
  234824. HeapBlock <OSType> types;
  234825. const int num = getAllDataSourcesForDevice (deviceID, types);
  234826. for (int i = 0; i < num; ++i)
  234827. {
  234828. if (types[num] == currentSourceID)
  234829. {
  234830. result = i;
  234831. break;
  234832. }
  234833. }
  234834. }
  234835. }
  234836. return result;
  234837. }
  234838. void setCurrentSourceIndex (int index, bool input)
  234839. {
  234840. if (deviceID != 0)
  234841. {
  234842. HeapBlock <OSType> types;
  234843. const int num = getAllDataSourcesForDevice (deviceID, types);
  234844. if (isPositiveAndBelow (index, num))
  234845. {
  234846. AudioObjectPropertyAddress pa;
  234847. pa.mSelector = kAudioDevicePropertyDataSource;
  234848. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234849. pa.mElement = kAudioObjectPropertyElementMaster;
  234850. OSType typeId = types[index];
  234851. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234852. }
  234853. }
  234854. }
  234855. const String reopen (const BigInteger& inputChannels,
  234856. const BigInteger& outputChannels,
  234857. double newSampleRate,
  234858. int bufferSizeSamples)
  234859. {
  234860. String error;
  234861. log ("CoreAudio reopen");
  234862. callbacksAllowed = false;
  234863. stopTimer();
  234864. stop (false);
  234865. activeInputChans = inputChannels;
  234866. activeInputChans.setRange (inChanNames.size(),
  234867. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234868. false);
  234869. activeOutputChans = outputChannels;
  234870. activeOutputChans.setRange (outChanNames.size(),
  234871. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234872. false);
  234873. numInputChans = activeInputChans.countNumberOfSetBits();
  234874. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234875. // set sample rate
  234876. AudioObjectPropertyAddress pa;
  234877. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234878. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234879. pa.mElement = kAudioObjectPropertyElementMaster;
  234880. Float64 sr = newSampleRate;
  234881. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234882. {
  234883. error = "Couldn't change sample rate";
  234884. }
  234885. else
  234886. {
  234887. // change buffer size
  234888. UInt32 framesPerBuf = bufferSizeSamples;
  234889. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234890. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234891. {
  234892. error = "Couldn't change buffer size";
  234893. }
  234894. else
  234895. {
  234896. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234897. // correctly report their new settings until some random time in the future, so
  234898. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234899. // to make sure we're using the correct numbers..
  234900. updateDetailsFromDevice();
  234901. sampleRate = newSampleRate;
  234902. bufferSize = bufferSizeSamples;
  234903. if (sampleRates.size() == 0)
  234904. error = "Device has no available sample-rates";
  234905. else if (bufferSizes.size() == 0)
  234906. error = "Device has no available buffer-sizes";
  234907. else if (inputDevice != 0)
  234908. error = inputDevice->reopen (inputChannels,
  234909. outputChannels,
  234910. newSampleRate,
  234911. bufferSizeSamples);
  234912. }
  234913. }
  234914. callbacksAllowed = true;
  234915. return error;
  234916. }
  234917. bool start (AudioIODeviceCallback* cb)
  234918. {
  234919. if (! started)
  234920. {
  234921. callback = 0;
  234922. if (deviceID != 0)
  234923. {
  234924. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234925. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234926. #else
  234927. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234928. #endif
  234929. {
  234930. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234931. {
  234932. started = true;
  234933. }
  234934. else
  234935. {
  234936. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234937. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234938. #else
  234939. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234940. audioProcID = 0;
  234941. #endif
  234942. }
  234943. }
  234944. }
  234945. }
  234946. if (started)
  234947. {
  234948. const ScopedLock sl (callbackLock);
  234949. callback = cb;
  234950. }
  234951. if (inputDevice != 0)
  234952. return started && inputDevice->start (cb);
  234953. else
  234954. return started;
  234955. }
  234956. void stop (bool leaveInterruptRunning)
  234957. {
  234958. {
  234959. const ScopedLock sl (callbackLock);
  234960. callback = 0;
  234961. }
  234962. if (started
  234963. && (deviceID != 0)
  234964. && ! leaveInterruptRunning)
  234965. {
  234966. OK (AudioDeviceStop (deviceID, audioIOProc));
  234967. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234968. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234969. #else
  234970. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234971. audioProcID = 0;
  234972. #endif
  234973. started = false;
  234974. { const ScopedLock sl (callbackLock); }
  234975. // wait until it's definately stopped calling back..
  234976. for (int i = 40; --i >= 0;)
  234977. {
  234978. Thread::sleep (50);
  234979. UInt32 running = 0;
  234980. UInt32 size = sizeof (running);
  234981. AudioObjectPropertyAddress pa;
  234982. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  234983. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234984. pa.mElement = kAudioObjectPropertyElementMaster;
  234985. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  234986. if (running == 0)
  234987. break;
  234988. }
  234989. const ScopedLock sl (callbackLock);
  234990. }
  234991. if (inputDevice != 0)
  234992. inputDevice->stop (leaveInterruptRunning);
  234993. }
  234994. double getSampleRate() const
  234995. {
  234996. return sampleRate;
  234997. }
  234998. int getBufferSize() const
  234999. {
  235000. return bufferSize;
  235001. }
  235002. void audioCallback (const AudioBufferList* inInputData,
  235003. AudioBufferList* outOutputData)
  235004. {
  235005. int i;
  235006. const ScopedLock sl (callbackLock);
  235007. if (callback != 0)
  235008. {
  235009. if (inputDevice == 0)
  235010. {
  235011. for (i = numInputChans; --i >= 0;)
  235012. {
  235013. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235014. float* dest = tempInputBuffers [i];
  235015. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235016. + info.dataOffsetSamples;
  235017. const int stride = info.dataStrideSamples;
  235018. if (stride != 0) // if this is zero, info is invalid
  235019. {
  235020. for (int j = bufferSize; --j >= 0;)
  235021. {
  235022. *dest++ = *src;
  235023. src += stride;
  235024. }
  235025. }
  235026. }
  235027. }
  235028. if (! isSlaveDevice)
  235029. {
  235030. if (inputDevice == 0)
  235031. {
  235032. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235033. numInputChans,
  235034. tempOutputBuffers,
  235035. numOutputChans,
  235036. bufferSize);
  235037. }
  235038. else
  235039. {
  235040. jassert (inputDevice->bufferSize == bufferSize);
  235041. // Sometimes the two linked devices seem to get their callbacks in
  235042. // parallel, so we need to lock both devices to stop the input data being
  235043. // changed while inside our callback..
  235044. const ScopedLock sl2 (inputDevice->callbackLock);
  235045. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235046. inputDevice->numInputChans,
  235047. tempOutputBuffers,
  235048. numOutputChans,
  235049. bufferSize);
  235050. }
  235051. for (i = numOutputChans; --i >= 0;)
  235052. {
  235053. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235054. const float* src = tempOutputBuffers [i];
  235055. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235056. + info.dataOffsetSamples;
  235057. const int stride = info.dataStrideSamples;
  235058. if (stride != 0) // if this is zero, info is invalid
  235059. {
  235060. for (int j = bufferSize; --j >= 0;)
  235061. {
  235062. *dest = *src++;
  235063. dest += stride;
  235064. }
  235065. }
  235066. }
  235067. }
  235068. }
  235069. else
  235070. {
  235071. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235072. {
  235073. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235074. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235075. + info.dataOffsetSamples;
  235076. const int stride = info.dataStrideSamples;
  235077. if (stride != 0) // if this is zero, info is invalid
  235078. {
  235079. for (int j = bufferSize; --j >= 0;)
  235080. {
  235081. *dest = 0.0f;
  235082. dest += stride;
  235083. }
  235084. }
  235085. }
  235086. }
  235087. }
  235088. // called by callbacks
  235089. void deviceDetailsChanged()
  235090. {
  235091. if (callbacksAllowed)
  235092. startTimer (100);
  235093. }
  235094. void timerCallback()
  235095. {
  235096. stopTimer();
  235097. log ("CoreAudio device changed callback");
  235098. const double oldSampleRate = sampleRate;
  235099. const int oldBufferSize = bufferSize;
  235100. updateDetailsFromDevice();
  235101. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235102. {
  235103. callbacksAllowed = false;
  235104. stop (false);
  235105. updateDetailsFromDevice();
  235106. callbacksAllowed = true;
  235107. }
  235108. }
  235109. CoreAudioInternal* getRelatedDevice() const
  235110. {
  235111. UInt32 size = 0;
  235112. ScopedPointer <CoreAudioInternal> result;
  235113. AudioObjectPropertyAddress pa;
  235114. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235115. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235116. pa.mElement = kAudioObjectPropertyElementMaster;
  235117. if (deviceID != 0
  235118. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235119. && size > 0)
  235120. {
  235121. HeapBlock <AudioDeviceID> devs;
  235122. devs.calloc (size, 1);
  235123. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235124. {
  235125. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235126. {
  235127. if (devs[i] != deviceID && devs[i] != 0)
  235128. {
  235129. result = new CoreAudioInternal (devs[i]);
  235130. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235131. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235132. if (thisIsInput != otherIsInput
  235133. || (inChanNames.size() + outChanNames.size() == 0)
  235134. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235135. break;
  235136. result = 0;
  235137. }
  235138. }
  235139. }
  235140. }
  235141. return result.release();
  235142. }
  235143. int inputLatency, outputLatency;
  235144. BigInteger activeInputChans, activeOutputChans;
  235145. StringArray inChanNames, outChanNames;
  235146. Array <double> sampleRates;
  235147. Array <int> bufferSizes;
  235148. AudioIODeviceCallback* callback;
  235149. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235150. AudioDeviceIOProcID audioProcID;
  235151. #endif
  235152. ScopedPointer<CoreAudioInternal> inputDevice;
  235153. bool isSlaveDevice;
  235154. private:
  235155. CriticalSection callbackLock;
  235156. AudioDeviceID deviceID;
  235157. bool started;
  235158. double sampleRate;
  235159. int bufferSize;
  235160. HeapBlock <float> audioBuffer;
  235161. int numInputChans, numOutputChans;
  235162. bool callbacksAllowed;
  235163. struct CallbackDetailsForChannel
  235164. {
  235165. int streamNum;
  235166. int dataOffsetSamples;
  235167. int dataStrideSamples;
  235168. };
  235169. int numInputChannelInfos, numOutputChannelInfos;
  235170. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235171. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235172. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235173. const AudioTimeStamp* /*inNow*/,
  235174. const AudioBufferList* inInputData,
  235175. const AudioTimeStamp* /*inInputTime*/,
  235176. AudioBufferList* outOutputData,
  235177. const AudioTimeStamp* /*inOutputTime*/,
  235178. void* device)
  235179. {
  235180. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235181. return noErr;
  235182. }
  235183. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235184. {
  235185. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235186. switch (pa->mSelector)
  235187. {
  235188. case kAudioDevicePropertyBufferSize:
  235189. case kAudioDevicePropertyBufferFrameSize:
  235190. case kAudioDevicePropertyNominalSampleRate:
  235191. case kAudioDevicePropertyStreamFormat:
  235192. case kAudioDevicePropertyDeviceIsAlive:
  235193. intern->deviceDetailsChanged();
  235194. break;
  235195. case kAudioDevicePropertyBufferSizeRange:
  235196. case kAudioDevicePropertyVolumeScalar:
  235197. case kAudioDevicePropertyMute:
  235198. case kAudioDevicePropertyPlayThru:
  235199. case kAudioDevicePropertyDataSource:
  235200. case kAudioDevicePropertyDeviceIsRunning:
  235201. break;
  235202. }
  235203. return noErr;
  235204. }
  235205. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235206. {
  235207. AudioObjectPropertyAddress pa;
  235208. pa.mSelector = kAudioDevicePropertyDataSources;
  235209. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235210. pa.mElement = kAudioObjectPropertyElementMaster;
  235211. UInt32 size = 0;
  235212. if (deviceID != 0
  235213. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235214. {
  235215. types.calloc (size, 1);
  235216. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235217. return size / (int) sizeof (OSType);
  235218. }
  235219. return 0;
  235220. }
  235221. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235222. };
  235223. class CoreAudioIODevice : public AudioIODevice
  235224. {
  235225. public:
  235226. CoreAudioIODevice (const String& deviceName,
  235227. AudioDeviceID inputDeviceId,
  235228. const int inputIndex_,
  235229. AudioDeviceID outputDeviceId,
  235230. const int outputIndex_)
  235231. : AudioIODevice (deviceName, "CoreAudio"),
  235232. inputIndex (inputIndex_),
  235233. outputIndex (outputIndex_),
  235234. isOpen_ (false),
  235235. isStarted (false)
  235236. {
  235237. CoreAudioInternal* device = 0;
  235238. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235239. {
  235240. jassert (inputDeviceId != 0);
  235241. device = new CoreAudioInternal (inputDeviceId);
  235242. }
  235243. else
  235244. {
  235245. device = new CoreAudioInternal (outputDeviceId);
  235246. if (inputDeviceId != 0)
  235247. {
  235248. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235249. device->inputDevice = secondDevice;
  235250. secondDevice->isSlaveDevice = true;
  235251. }
  235252. }
  235253. internal = device;
  235254. AudioObjectPropertyAddress pa;
  235255. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235256. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235257. pa.mElement = kAudioObjectPropertyElementWildcard;
  235258. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235259. }
  235260. ~CoreAudioIODevice()
  235261. {
  235262. AudioObjectPropertyAddress pa;
  235263. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235264. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235265. pa.mElement = kAudioObjectPropertyElementWildcard;
  235266. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235267. }
  235268. const StringArray getOutputChannelNames()
  235269. {
  235270. return internal->outChanNames;
  235271. }
  235272. const StringArray getInputChannelNames()
  235273. {
  235274. if (internal->inputDevice != 0)
  235275. return internal->inputDevice->inChanNames;
  235276. else
  235277. return internal->inChanNames;
  235278. }
  235279. int getNumSampleRates()
  235280. {
  235281. return internal->sampleRates.size();
  235282. }
  235283. double getSampleRate (int index)
  235284. {
  235285. return internal->sampleRates [index];
  235286. }
  235287. int getNumBufferSizesAvailable()
  235288. {
  235289. return internal->bufferSizes.size();
  235290. }
  235291. int getBufferSizeSamples (int index)
  235292. {
  235293. return internal->bufferSizes [index];
  235294. }
  235295. int getDefaultBufferSize()
  235296. {
  235297. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235298. if (getBufferSizeSamples(i) >= 512)
  235299. return getBufferSizeSamples(i);
  235300. return 512;
  235301. }
  235302. const String open (const BigInteger& inputChannels,
  235303. const BigInteger& outputChannels,
  235304. double sampleRate,
  235305. int bufferSizeSamples)
  235306. {
  235307. isOpen_ = true;
  235308. if (bufferSizeSamples <= 0)
  235309. bufferSizeSamples = getDefaultBufferSize();
  235310. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235311. isOpen_ = lastError.isEmpty();
  235312. return lastError;
  235313. }
  235314. void close()
  235315. {
  235316. isOpen_ = false;
  235317. internal->stop (false);
  235318. }
  235319. bool isOpen()
  235320. {
  235321. return isOpen_;
  235322. }
  235323. int getCurrentBufferSizeSamples()
  235324. {
  235325. return internal != 0 ? internal->getBufferSize() : 512;
  235326. }
  235327. double getCurrentSampleRate()
  235328. {
  235329. return internal != 0 ? internal->getSampleRate() : 0;
  235330. }
  235331. int getCurrentBitDepth()
  235332. {
  235333. return 32; // no way to find out, so just assume it's high..
  235334. }
  235335. const BigInteger getActiveOutputChannels() const
  235336. {
  235337. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235338. }
  235339. const BigInteger getActiveInputChannels() const
  235340. {
  235341. BigInteger chans;
  235342. if (internal != 0)
  235343. {
  235344. chans = internal->activeInputChans;
  235345. if (internal->inputDevice != 0)
  235346. chans |= internal->inputDevice->activeInputChans;
  235347. }
  235348. return chans;
  235349. }
  235350. int getOutputLatencyInSamples()
  235351. {
  235352. if (internal == 0)
  235353. return 0;
  235354. // this seems like a good guess at getting the latency right - comparing
  235355. // this with a round-trip measurement, it gets it to within a few millisecs
  235356. // for the built-in mac soundcard
  235357. return internal->outputLatency + internal->getBufferSize() * 2;
  235358. }
  235359. int getInputLatencyInSamples()
  235360. {
  235361. if (internal == 0)
  235362. return 0;
  235363. return internal->inputLatency + internal->getBufferSize() * 2;
  235364. }
  235365. void start (AudioIODeviceCallback* callback)
  235366. {
  235367. if (internal != 0 && ! isStarted)
  235368. {
  235369. if (callback != 0)
  235370. callback->audioDeviceAboutToStart (this);
  235371. isStarted = true;
  235372. internal->start (callback);
  235373. }
  235374. }
  235375. void stop()
  235376. {
  235377. if (isStarted && internal != 0)
  235378. {
  235379. AudioIODeviceCallback* const lastCallback = internal->callback;
  235380. isStarted = false;
  235381. internal->stop (true);
  235382. if (lastCallback != 0)
  235383. lastCallback->audioDeviceStopped();
  235384. }
  235385. }
  235386. bool isPlaying()
  235387. {
  235388. if (internal->callback == 0)
  235389. isStarted = false;
  235390. return isStarted;
  235391. }
  235392. const String getLastError()
  235393. {
  235394. return lastError;
  235395. }
  235396. int inputIndex, outputIndex;
  235397. private:
  235398. ScopedPointer<CoreAudioInternal> internal;
  235399. bool isOpen_, isStarted;
  235400. String lastError;
  235401. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235402. {
  235403. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235404. switch (pa->mSelector)
  235405. {
  235406. case kAudioHardwarePropertyDevices:
  235407. intern->deviceDetailsChanged();
  235408. break;
  235409. case kAudioHardwarePropertyDefaultOutputDevice:
  235410. case kAudioHardwarePropertyDefaultInputDevice:
  235411. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235412. break;
  235413. }
  235414. return noErr;
  235415. }
  235416. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235417. };
  235418. class CoreAudioIODeviceType : public AudioIODeviceType
  235419. {
  235420. public:
  235421. CoreAudioIODeviceType()
  235422. : AudioIODeviceType ("CoreAudio"),
  235423. hasScanned (false)
  235424. {
  235425. }
  235426. ~CoreAudioIODeviceType()
  235427. {
  235428. }
  235429. void scanForDevices()
  235430. {
  235431. hasScanned = true;
  235432. inputDeviceNames.clear();
  235433. outputDeviceNames.clear();
  235434. inputIds.clear();
  235435. outputIds.clear();
  235436. UInt32 size;
  235437. AudioObjectPropertyAddress pa;
  235438. pa.mSelector = kAudioHardwarePropertyDevices;
  235439. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235440. pa.mElement = kAudioObjectPropertyElementMaster;
  235441. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235442. {
  235443. HeapBlock <AudioDeviceID> devs;
  235444. devs.calloc (size, 1);
  235445. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235446. {
  235447. const int num = size / (int) sizeof (AudioDeviceID);
  235448. for (int i = 0; i < num; ++i)
  235449. {
  235450. char name [1024];
  235451. size = sizeof (name);
  235452. pa.mSelector = kAudioDevicePropertyDeviceName;
  235453. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235454. {
  235455. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235456. const int numIns = getNumChannels (devs[i], true);
  235457. const int numOuts = getNumChannels (devs[i], false);
  235458. if (numIns > 0)
  235459. {
  235460. inputDeviceNames.add (nameString);
  235461. inputIds.add (devs[i]);
  235462. }
  235463. if (numOuts > 0)
  235464. {
  235465. outputDeviceNames.add (nameString);
  235466. outputIds.add (devs[i]);
  235467. }
  235468. }
  235469. }
  235470. }
  235471. }
  235472. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235473. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235474. }
  235475. const StringArray getDeviceNames (bool wantInputNames) const
  235476. {
  235477. jassert (hasScanned); // need to call scanForDevices() before doing this
  235478. if (wantInputNames)
  235479. return inputDeviceNames;
  235480. else
  235481. return outputDeviceNames;
  235482. }
  235483. int getDefaultDeviceIndex (bool forInput) const
  235484. {
  235485. jassert (hasScanned); // need to call scanForDevices() before doing this
  235486. AudioDeviceID deviceID;
  235487. UInt32 size = sizeof (deviceID);
  235488. // if they're asking for any input channels at all, use the default input, so we
  235489. // get the built-in mic rather than the built-in output with no inputs..
  235490. AudioObjectPropertyAddress pa;
  235491. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235492. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235493. pa.mElement = kAudioObjectPropertyElementMaster;
  235494. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235495. {
  235496. if (forInput)
  235497. {
  235498. for (int i = inputIds.size(); --i >= 0;)
  235499. if (inputIds[i] == deviceID)
  235500. return i;
  235501. }
  235502. else
  235503. {
  235504. for (int i = outputIds.size(); --i >= 0;)
  235505. if (outputIds[i] == deviceID)
  235506. return i;
  235507. }
  235508. }
  235509. return 0;
  235510. }
  235511. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235512. {
  235513. jassert (hasScanned); // need to call scanForDevices() before doing this
  235514. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235515. if (d == 0)
  235516. return -1;
  235517. return asInput ? d->inputIndex
  235518. : d->outputIndex;
  235519. }
  235520. bool hasSeparateInputsAndOutputs() const { return true; }
  235521. AudioIODevice* createDevice (const String& outputDeviceName,
  235522. const String& inputDeviceName)
  235523. {
  235524. jassert (hasScanned); // need to call scanForDevices() before doing this
  235525. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235526. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235527. String deviceName (outputDeviceName);
  235528. if (deviceName.isEmpty())
  235529. deviceName = inputDeviceName;
  235530. if (index >= 0)
  235531. return new CoreAudioIODevice (deviceName,
  235532. inputIds [inputIndex],
  235533. inputIndex,
  235534. outputIds [outputIndex],
  235535. outputIndex);
  235536. return 0;
  235537. }
  235538. private:
  235539. StringArray inputDeviceNames, outputDeviceNames;
  235540. Array <AudioDeviceID> inputIds, outputIds;
  235541. bool hasScanned;
  235542. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235543. {
  235544. int total = 0;
  235545. UInt32 size;
  235546. AudioObjectPropertyAddress pa;
  235547. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235548. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235549. pa.mElement = kAudioObjectPropertyElementMaster;
  235550. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235551. {
  235552. HeapBlock <AudioBufferList> bufList;
  235553. bufList.calloc (size, 1);
  235554. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235555. {
  235556. const int numStreams = bufList->mNumberBuffers;
  235557. for (int i = 0; i < numStreams; ++i)
  235558. {
  235559. const AudioBuffer& b = bufList->mBuffers[i];
  235560. total += b.mNumberChannels;
  235561. }
  235562. }
  235563. }
  235564. return total;
  235565. }
  235566. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235567. };
  235568. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  235569. {
  235570. return new CoreAudioIODeviceType();
  235571. }
  235572. #undef log
  235573. #endif
  235574. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  235575. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  235576. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235577. // compiled on its own).
  235578. #if JUCE_INCLUDED_FILE
  235579. #if JUCE_MAC
  235580. namespace CoreMidiHelpers
  235581. {
  235582. bool logError (const OSStatus err, const int lineNum)
  235583. {
  235584. if (err == noErr)
  235585. return true;
  235586. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235587. jassertfalse;
  235588. return false;
  235589. }
  235590. #undef CHECK_ERROR
  235591. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  235592. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  235593. {
  235594. String result;
  235595. CFStringRef str = 0;
  235596. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  235597. if (str != 0)
  235598. {
  235599. result = PlatformUtilities::cfStringToJuceString (str);
  235600. CFRelease (str);
  235601. str = 0;
  235602. }
  235603. MIDIEntityRef entity = 0;
  235604. MIDIEndpointGetEntity (endpoint, &entity);
  235605. if (entity == 0)
  235606. return result; // probably virtual
  235607. if (result.isEmpty())
  235608. {
  235609. // endpoint name has zero length - try the entity
  235610. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  235611. if (str != 0)
  235612. {
  235613. result += PlatformUtilities::cfStringToJuceString (str);
  235614. CFRelease (str);
  235615. str = 0;
  235616. }
  235617. }
  235618. // now consider the device's name
  235619. MIDIDeviceRef device = 0;
  235620. MIDIEntityGetDevice (entity, &device);
  235621. if (device == 0)
  235622. return result;
  235623. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  235624. if (str != 0)
  235625. {
  235626. const String s (PlatformUtilities::cfStringToJuceString (str));
  235627. CFRelease (str);
  235628. // if an external device has only one entity, throw away
  235629. // the endpoint name and just use the device name
  235630. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  235631. {
  235632. result = s;
  235633. }
  235634. else if (! result.startsWithIgnoreCase (s))
  235635. {
  235636. // prepend the device name to the entity name
  235637. result = (s + " " + result).trimEnd();
  235638. }
  235639. }
  235640. return result;
  235641. }
  235642. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  235643. {
  235644. String result;
  235645. // Does the endpoint have connections?
  235646. CFDataRef connections = 0;
  235647. int numConnections = 0;
  235648. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  235649. if (connections != 0)
  235650. {
  235651. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  235652. if (numConnections > 0)
  235653. {
  235654. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  235655. for (int i = 0; i < numConnections; ++i, ++pid)
  235656. {
  235657. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  235658. MIDIObjectRef connObject;
  235659. MIDIObjectType connObjectType;
  235660. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  235661. if (err == noErr)
  235662. {
  235663. String s;
  235664. if (connObjectType == kMIDIObjectType_ExternalSource
  235665. || connObjectType == kMIDIObjectType_ExternalDestination)
  235666. {
  235667. // Connected to an external device's endpoint (10.3 and later).
  235668. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  235669. }
  235670. else
  235671. {
  235672. // Connected to an external device (10.2) (or something else, catch-all)
  235673. CFStringRef str = 0;
  235674. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  235675. if (str != 0)
  235676. {
  235677. s = PlatformUtilities::cfStringToJuceString (str);
  235678. CFRelease (str);
  235679. }
  235680. }
  235681. if (s.isNotEmpty())
  235682. {
  235683. if (result.isNotEmpty())
  235684. result += ", ";
  235685. result += s;
  235686. }
  235687. }
  235688. }
  235689. }
  235690. CFRelease (connections);
  235691. }
  235692. if (result.isNotEmpty())
  235693. return result;
  235694. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  235695. return getEndpointName (endpoint, false);
  235696. }
  235697. MIDIClientRef getGlobalMidiClient()
  235698. {
  235699. static MIDIClientRef globalMidiClient = 0;
  235700. if (globalMidiClient == 0)
  235701. {
  235702. String name ("JUCE");
  235703. if (JUCEApplication::getInstance() != 0)
  235704. name = JUCEApplication::getInstance()->getApplicationName();
  235705. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235706. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235707. CFRelease (appName);
  235708. }
  235709. return globalMidiClient;
  235710. }
  235711. class MidiPortAndEndpoint
  235712. {
  235713. public:
  235714. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235715. : port (port_), endPoint (endPoint_)
  235716. {
  235717. }
  235718. ~MidiPortAndEndpoint()
  235719. {
  235720. if (port != 0)
  235721. MIDIPortDispose (port);
  235722. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235723. MIDIEndpointDispose (endPoint);
  235724. }
  235725. void send (const MIDIPacketList* const packets)
  235726. {
  235727. if (port != 0)
  235728. MIDISend (port, endPoint, packets);
  235729. else
  235730. MIDIReceived (endPoint, packets);
  235731. }
  235732. MIDIPortRef port;
  235733. MIDIEndpointRef endPoint;
  235734. };
  235735. class MidiPortAndCallback;
  235736. CriticalSection callbackLock;
  235737. Array<MidiPortAndCallback*> activeCallbacks;
  235738. class MidiPortAndCallback
  235739. {
  235740. public:
  235741. MidiPortAndCallback (MidiInputCallback& callback_)
  235742. : input (0), active (false), callback (callback_), concatenator (2048)
  235743. {
  235744. }
  235745. ~MidiPortAndCallback()
  235746. {
  235747. active = false;
  235748. {
  235749. const ScopedLock sl (callbackLock);
  235750. activeCallbacks.removeValue (this);
  235751. }
  235752. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  235753. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  235754. }
  235755. void handlePackets (const MIDIPacketList* const pktlist)
  235756. {
  235757. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  235758. const ScopedLock sl (callbackLock);
  235759. if (activeCallbacks.contains (this) && active)
  235760. {
  235761. const MIDIPacket* packet = &pktlist->packet[0];
  235762. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235763. {
  235764. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  235765. input, callback);
  235766. packet = MIDIPacketNext (packet);
  235767. }
  235768. }
  235769. }
  235770. MidiInput* input;
  235771. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  235772. volatile bool active;
  235773. private:
  235774. MidiInputCallback& callback;
  235775. MidiDataConcatenator concatenator;
  235776. };
  235777. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  235778. {
  235779. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  235780. }
  235781. }
  235782. const StringArray MidiOutput::getDevices()
  235783. {
  235784. StringArray s;
  235785. const ItemCount num = MIDIGetNumberOfDestinations();
  235786. for (ItemCount i = 0; i < num; ++i)
  235787. {
  235788. MIDIEndpointRef dest = MIDIGetDestination (i);
  235789. if (dest != 0)
  235790. {
  235791. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  235792. if (name.isEmpty())
  235793. name = "<error>";
  235794. s.add (name);
  235795. }
  235796. else
  235797. {
  235798. s.add ("<error>");
  235799. }
  235800. }
  235801. return s;
  235802. }
  235803. int MidiOutput::getDefaultDeviceIndex()
  235804. {
  235805. return 0;
  235806. }
  235807. MidiOutput* MidiOutput::openDevice (int index)
  235808. {
  235809. MidiOutput* mo = 0;
  235810. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  235811. {
  235812. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235813. CFStringRef pname;
  235814. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235815. {
  235816. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235817. MIDIPortRef port;
  235818. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  235819. {
  235820. mo = new MidiOutput();
  235821. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  235822. }
  235823. CFRelease (pname);
  235824. }
  235825. }
  235826. return mo;
  235827. }
  235828. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235829. {
  235830. MidiOutput* mo = 0;
  235831. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235832. MIDIEndpointRef endPoint;
  235833. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235834. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  235835. {
  235836. mo = new MidiOutput();
  235837. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  235838. }
  235839. CFRelease (name);
  235840. return mo;
  235841. }
  235842. MidiOutput::~MidiOutput()
  235843. {
  235844. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235845. }
  235846. void MidiOutput::reset()
  235847. {
  235848. }
  235849. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235850. {
  235851. return false;
  235852. }
  235853. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235854. {
  235855. }
  235856. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235857. {
  235858. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235859. if (message.isSysEx())
  235860. {
  235861. const int maxPacketSize = 256;
  235862. int pos = 0, bytesLeft = message.getRawDataSize();
  235863. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235864. HeapBlock <MIDIPacketList> packets;
  235865. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235866. packets->numPackets = numPackets;
  235867. MIDIPacket* p = packets->packet;
  235868. for (int i = 0; i < numPackets; ++i)
  235869. {
  235870. p->timeStamp = AudioGetCurrentHostTime();
  235871. p->length = jmin (maxPacketSize, bytesLeft);
  235872. memcpy (p->data, message.getRawData() + pos, p->length);
  235873. pos += p->length;
  235874. bytesLeft -= p->length;
  235875. p = MIDIPacketNext (p);
  235876. }
  235877. mpe->send (packets);
  235878. }
  235879. else
  235880. {
  235881. MIDIPacketList packets;
  235882. packets.numPackets = 1;
  235883. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  235884. packets.packet[0].length = message.getRawDataSize();
  235885. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235886. mpe->send (&packets);
  235887. }
  235888. }
  235889. const StringArray MidiInput::getDevices()
  235890. {
  235891. StringArray s;
  235892. const ItemCount num = MIDIGetNumberOfSources();
  235893. for (ItemCount i = 0; i < num; ++i)
  235894. {
  235895. MIDIEndpointRef source = MIDIGetSource (i);
  235896. if (source != 0)
  235897. {
  235898. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  235899. if (name.isEmpty())
  235900. name = "<error>";
  235901. s.add (name);
  235902. }
  235903. else
  235904. {
  235905. s.add ("<error>");
  235906. }
  235907. }
  235908. return s;
  235909. }
  235910. int MidiInput::getDefaultDeviceIndex()
  235911. {
  235912. return 0;
  235913. }
  235914. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235915. {
  235916. jassert (callback != 0);
  235917. using namespace CoreMidiHelpers;
  235918. MidiInput* newInput = 0;
  235919. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  235920. {
  235921. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235922. if (endPoint != 0)
  235923. {
  235924. CFStringRef name;
  235925. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  235926. {
  235927. MIDIClientRef client = getGlobalMidiClient();
  235928. if (client != 0)
  235929. {
  235930. MIDIPortRef port;
  235931. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235932. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  235933. {
  235934. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  235935. {
  235936. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235937. newInput = new MidiInput (getDevices() [index]);
  235938. mpc->input = newInput;
  235939. newInput->internal = mpc;
  235940. const ScopedLock sl (callbackLock);
  235941. activeCallbacks.add (mpc.release());
  235942. }
  235943. else
  235944. {
  235945. CHECK_ERROR (MIDIPortDispose (port));
  235946. }
  235947. }
  235948. }
  235949. }
  235950. CFRelease (name);
  235951. }
  235952. }
  235953. return newInput;
  235954. }
  235955. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235956. {
  235957. jassert (callback != 0);
  235958. using namespace CoreMidiHelpers;
  235959. MidiInput* mi = 0;
  235960. MIDIClientRef client = getGlobalMidiClient();
  235961. if (client != 0)
  235962. {
  235963. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235964. mpc->active = false;
  235965. MIDIEndpointRef endPoint;
  235966. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  235967. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  235968. {
  235969. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235970. mi = new MidiInput (deviceName);
  235971. mpc->input = mi;
  235972. mi->internal = mpc;
  235973. const ScopedLock sl (callbackLock);
  235974. activeCallbacks.add (mpc.release());
  235975. }
  235976. CFRelease (name);
  235977. }
  235978. return mi;
  235979. }
  235980. MidiInput::MidiInput (const String& name_)
  235981. : name (name_)
  235982. {
  235983. }
  235984. MidiInput::~MidiInput()
  235985. {
  235986. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  235987. }
  235988. void MidiInput::start()
  235989. {
  235990. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  235991. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  235992. }
  235993. void MidiInput::stop()
  235994. {
  235995. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  235996. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  235997. }
  235998. #undef CHECK_ERROR
  235999. #else // Stubs for iOS...
  236000. MidiOutput::~MidiOutput() {}
  236001. void MidiOutput::reset() {}
  236002. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236003. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236004. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236005. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236006. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236007. const StringArray MidiInput::getDevices() { return StringArray(); }
  236008. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236009. #endif
  236010. #endif
  236011. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236012. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236013. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236014. // compiled on its own).
  236015. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236016. #if ! JUCE_QUICKTIME
  236017. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236018. #endif
  236019. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236020. class QTCameraDeviceInteral;
  236021. END_JUCE_NAMESPACE
  236022. @interface QTCaptureCallbackDelegate : NSObject
  236023. {
  236024. @public
  236025. CameraDevice* owner;
  236026. QTCameraDeviceInteral* internal;
  236027. int64 firstPresentationTime;
  236028. int64 averageTimeOffset;
  236029. }
  236030. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236031. - (void) dealloc;
  236032. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236033. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236034. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236035. fromConnection: (QTCaptureConnection*) connection;
  236036. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236037. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236038. fromConnection: (QTCaptureConnection*) connection;
  236039. @end
  236040. BEGIN_JUCE_NAMESPACE
  236041. class QTCameraDeviceInteral
  236042. {
  236043. public:
  236044. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236045. {
  236046. const ScopedAutoReleasePool pool;
  236047. session = [[QTCaptureSession alloc] init];
  236048. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236049. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236050. input = 0;
  236051. audioInput = 0;
  236052. audioDevice = 0;
  236053. fileOutput = 0;
  236054. imageOutput = 0;
  236055. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236056. internalDev: this];
  236057. NSError* err = 0;
  236058. [device retain];
  236059. [device open: &err];
  236060. if (err == 0)
  236061. {
  236062. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236063. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236064. [session addInput: input error: &err];
  236065. if (err == 0)
  236066. {
  236067. resetFile();
  236068. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236069. [imageOutput setDelegate: callbackDelegate];
  236070. if (err == 0)
  236071. {
  236072. [session startRunning];
  236073. return;
  236074. }
  236075. }
  236076. }
  236077. openingError = nsStringToJuce ([err description]);
  236078. DBG (openingError);
  236079. }
  236080. ~QTCameraDeviceInteral()
  236081. {
  236082. [session stopRunning];
  236083. [session removeOutput: imageOutput];
  236084. [session release];
  236085. [input release];
  236086. [device release];
  236087. [audioDevice release];
  236088. [audioInput release];
  236089. [fileOutput release];
  236090. [imageOutput release];
  236091. [callbackDelegate release];
  236092. }
  236093. void resetFile()
  236094. {
  236095. [fileOutput recordToOutputFileURL: nil];
  236096. [session removeOutput: fileOutput];
  236097. [fileOutput release];
  236098. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236099. [session removeInput: audioInput];
  236100. [audioInput release];
  236101. audioInput = 0;
  236102. [audioDevice release];
  236103. audioDevice = 0;
  236104. [fileOutput setDelegate: callbackDelegate];
  236105. }
  236106. void addDefaultAudioInput()
  236107. {
  236108. NSError* err = nil;
  236109. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236110. if ([audioDevice open: &err])
  236111. [audioDevice retain];
  236112. else
  236113. audioDevice = nil;
  236114. if (audioDevice != 0)
  236115. {
  236116. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236117. [session addInput: audioInput error: &err];
  236118. }
  236119. }
  236120. void addListener (CameraDevice::Listener* listenerToAdd)
  236121. {
  236122. const ScopedLock sl (listenerLock);
  236123. if (listeners.size() == 0)
  236124. [session addOutput: imageOutput error: nil];
  236125. listeners.addIfNotAlreadyThere (listenerToAdd);
  236126. }
  236127. void removeListener (CameraDevice::Listener* listenerToRemove)
  236128. {
  236129. const ScopedLock sl (listenerLock);
  236130. listeners.removeValue (listenerToRemove);
  236131. if (listeners.size() == 0)
  236132. [session removeOutput: imageOutput];
  236133. }
  236134. void callListeners (CIImage* frame, int w, int h)
  236135. {
  236136. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236137. Image image (cgImage);
  236138. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236139. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236140. CGContextFlush (cgImage->context);
  236141. const ScopedLock sl (listenerLock);
  236142. for (int i = listeners.size(); --i >= 0;)
  236143. {
  236144. CameraDevice::Listener* const l = listeners[i];
  236145. if (l != 0)
  236146. l->imageReceived (image);
  236147. }
  236148. }
  236149. QTCaptureDevice* device;
  236150. QTCaptureDeviceInput* input;
  236151. QTCaptureDevice* audioDevice;
  236152. QTCaptureDeviceInput* audioInput;
  236153. QTCaptureSession* session;
  236154. QTCaptureMovieFileOutput* fileOutput;
  236155. QTCaptureDecompressedVideoOutput* imageOutput;
  236156. QTCaptureCallbackDelegate* callbackDelegate;
  236157. String openingError;
  236158. Array<CameraDevice::Listener*> listeners;
  236159. CriticalSection listenerLock;
  236160. };
  236161. END_JUCE_NAMESPACE
  236162. @implementation QTCaptureCallbackDelegate
  236163. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236164. internalDev: (QTCameraDeviceInteral*) d
  236165. {
  236166. [super init];
  236167. owner = owner_;
  236168. internal = d;
  236169. firstPresentationTime = 0;
  236170. averageTimeOffset = 0;
  236171. return self;
  236172. }
  236173. - (void) dealloc
  236174. {
  236175. [super dealloc];
  236176. }
  236177. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236178. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236179. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236180. fromConnection: (QTCaptureConnection*) connection
  236181. {
  236182. if (internal->listeners.size() > 0)
  236183. {
  236184. const ScopedAutoReleasePool pool;
  236185. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236186. CVPixelBufferGetWidth (videoFrame),
  236187. CVPixelBufferGetHeight (videoFrame));
  236188. }
  236189. }
  236190. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236191. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236192. fromConnection: (QTCaptureConnection*) connection
  236193. {
  236194. const Time now (Time::getCurrentTime());
  236195. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236196. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236197. #else
  236198. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236199. #endif
  236200. int64 presentationTime = (hosttime != nil)
  236201. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236202. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236203. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236204. if (firstPresentationTime == 0)
  236205. {
  236206. firstPresentationTime = presentationTime;
  236207. averageTimeOffset = timeDiff;
  236208. }
  236209. else
  236210. {
  236211. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236212. }
  236213. }
  236214. @end
  236215. BEGIN_JUCE_NAMESPACE
  236216. class QTCaptureViewerComp : public NSViewComponent
  236217. {
  236218. public:
  236219. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236220. {
  236221. const ScopedAutoReleasePool pool;
  236222. captureView = [[QTCaptureView alloc] init];
  236223. [captureView setCaptureSession: internal->session];
  236224. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236225. setView (captureView);
  236226. }
  236227. ~QTCaptureViewerComp()
  236228. {
  236229. setView (0);
  236230. [captureView setCaptureSession: nil];
  236231. [captureView release];
  236232. }
  236233. QTCaptureView* captureView;
  236234. };
  236235. CameraDevice::CameraDevice (const String& name_, int index)
  236236. : name (name_)
  236237. {
  236238. isRecording = false;
  236239. internal = new QTCameraDeviceInteral (this, index);
  236240. }
  236241. CameraDevice::~CameraDevice()
  236242. {
  236243. stopRecording();
  236244. delete static_cast <QTCameraDeviceInteral*> (internal);
  236245. internal = 0;
  236246. }
  236247. Component* CameraDevice::createViewerComponent()
  236248. {
  236249. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236250. }
  236251. const String CameraDevice::getFileExtension()
  236252. {
  236253. return ".mov";
  236254. }
  236255. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236256. {
  236257. stopRecording();
  236258. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236259. d->callbackDelegate->firstPresentationTime = 0;
  236260. file.deleteFile();
  236261. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236262. // out wrong, so we'll put some audio in there too..,
  236263. d->addDefaultAudioInput();
  236264. [d->session addOutput: d->fileOutput error: nil];
  236265. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236266. for (;;)
  236267. {
  236268. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236269. if (connection == 0)
  236270. break;
  236271. QTCompressionOptions* options = 0;
  236272. NSString* mediaType = [connection mediaType];
  236273. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236274. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236275. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236276. : @"QTCompressionOptions240SizeH264Video"];
  236277. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236278. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236279. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236280. }
  236281. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236282. isRecording = true;
  236283. }
  236284. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236285. {
  236286. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236287. if (d->callbackDelegate->firstPresentationTime != 0)
  236288. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236289. return Time();
  236290. }
  236291. void CameraDevice::stopRecording()
  236292. {
  236293. if (isRecording)
  236294. {
  236295. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236296. isRecording = false;
  236297. }
  236298. }
  236299. void CameraDevice::addListener (Listener* listenerToAdd)
  236300. {
  236301. if (listenerToAdd != 0)
  236302. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236303. }
  236304. void CameraDevice::removeListener (Listener* listenerToRemove)
  236305. {
  236306. if (listenerToRemove != 0)
  236307. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236308. }
  236309. const StringArray CameraDevice::getAvailableDevices()
  236310. {
  236311. const ScopedAutoReleasePool pool;
  236312. StringArray results;
  236313. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236314. for (int i = 0; i < (int) [devs count]; ++i)
  236315. {
  236316. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236317. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236318. }
  236319. return results;
  236320. }
  236321. CameraDevice* CameraDevice::openDevice (int index,
  236322. int minWidth, int minHeight,
  236323. int maxWidth, int maxHeight)
  236324. {
  236325. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236326. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236327. return d.release();
  236328. return 0;
  236329. }
  236330. #endif
  236331. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236332. #endif
  236333. #endif
  236334. END_JUCE_NAMESPACE
  236335. #endif
  236336. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236337. #elif JUCE_ANDROID
  236338. /*** Start of inlined file: juce_android_NativeCode.cpp ***/
  236339. /*
  236340. This file wraps together all the android-specific code, so that
  236341. we can include all the native headers just once, and compile all our
  236342. platform-specific stuff in one big lump, keeping it out of the way of
  236343. the rest of the codebase.
  236344. */
  236345. #if JUCE_ANDROID
  236346. #undef JUCE_BUILD_NATIVE
  236347. #define JUCE_BUILD_NATIVE 1
  236348. BEGIN_JUCE_NAMESPACE
  236349. #define JUCE_INCLUDED_FILE 1
  236350. // Now include the actual code files..
  236351. /*** Start of inlined file: juce_android_SystemStats.cpp ***/
  236352. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  236353. // compiled on its own).
  236354. #if JUCE_INCLUDED_FILE
  236355. END_JUCE_NAMESPACE
  236356. extern JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication(); // (from START_JUCE_APPLICATION)
  236357. BEGIN_JUCE_NAMESPACE
  236358. class AndroidJavaCallbacks
  236359. {
  236360. public:
  236361. AndroidJavaCallbacks() : env (0)
  236362. {
  236363. }
  236364. void initialise (JNIEnv* env_, jobject activity)
  236365. {
  236366. env = env_;
  236367. activityClass = (jclass) env->NewGlobalRef (env->GetObjectClass (activity));
  236368. printToConsole = env->GetStaticMethodID (activityClass, "printToConsole", "(Ljava/lang/String;)V");
  236369. jassert (printToConsole != 0);
  236370. }
  236371. void shutdown()
  236372. {
  236373. if (env != 0)
  236374. {
  236375. env->DeleteGlobalRef (activityClass);
  236376. }
  236377. }
  236378. JNIEnv* env;
  236379. jclass activityClass;
  236380. jmethodID printToConsole;
  236381. };
  236382. static AndroidJavaCallbacks androidEnv;
  236383. #define JUCE_JNI_CALLBACK(className, methodName, returnType, params) \
  236384. extern "C" __attribute__ ((visibility("default"))) returnType Java_com_juce_launch_ ## className ## _ ## methodName params
  236385. JUCE_JNI_CALLBACK (JuceAppActivity, launchApp, void, (JNIEnv* env, jobject activity))
  236386. {
  236387. androidEnv.initialise (env, activity);
  236388. JUCEApplication::createInstance = &juce_CreateApplication;
  236389. initialiseJuce_GUI();
  236390. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  236391. exit (0);
  236392. }
  236393. JUCE_JNI_CALLBACK (JuceAppActivity, quitApp, void, (JNIEnv* env, jobject activity))
  236394. {
  236395. JUCEApplication::appWillTerminateByForce();
  236396. androidEnv.shutdown();
  236397. }
  236398. void PlatformUtilities::beep()
  236399. {
  236400. // TODO
  236401. }
  236402. void Logger::outputDebugString (const String& text)
  236403. {
  236404. androidEnv.env->CallStaticVoidMethod (androidEnv.activityClass, androidEnv.printToConsole,
  236405. androidEnv.env->NewStringUTF (text.toUTF8()));
  236406. }
  236407. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  236408. {
  236409. return Android;
  236410. }
  236411. const String SystemStats::getOperatingSystemName()
  236412. {
  236413. return "Android";
  236414. }
  236415. bool SystemStats::isOperatingSystem64Bit()
  236416. {
  236417. #if JUCE_64BIT
  236418. return true;
  236419. #else
  236420. return false;
  236421. #endif
  236422. }
  236423. namespace AndroidStatsHelpers
  236424. {
  236425. // TODO
  236426. const String getCpuInfo (const char* const key)
  236427. {
  236428. StringArray lines;
  236429. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  236430. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  236431. if (lines[i].startsWithIgnoreCase (key))
  236432. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  236433. return String::empty;
  236434. }
  236435. }
  236436. const String SystemStats::getCpuVendor()
  236437. {
  236438. return AndroidStatsHelpers::getCpuInfo ("vendor_id");
  236439. }
  236440. int SystemStats::getCpuSpeedInMegaherz()
  236441. {
  236442. return roundToInt (AndroidStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  236443. }
  236444. int SystemStats::getMemorySizeInMegabytes()
  236445. {
  236446. // TODO
  236447. struct sysinfo sysi;
  236448. if (sysinfo (&sysi) == 0)
  236449. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  236450. return 0;
  236451. }
  236452. int SystemStats::getPageSize()
  236453. {
  236454. // TODO
  236455. return sysconf (_SC_PAGESIZE);
  236456. }
  236457. const String SystemStats::getLogonName()
  236458. {
  236459. // TODO
  236460. const char* user = getenv ("USER");
  236461. if (user == 0)
  236462. {
  236463. struct passwd* const pw = getpwuid (getuid());
  236464. if (pw != 0)
  236465. user = pw->pw_name;
  236466. }
  236467. return String::fromUTF8 (user);
  236468. }
  236469. const String SystemStats::getFullUserName()
  236470. {
  236471. return getLogonName();
  236472. }
  236473. void SystemStats::initialiseStats()
  236474. {
  236475. // TODO
  236476. const String flags (AndroidStatsHelpers::getCpuInfo ("flags"));
  236477. cpuFlags.hasMMX = flags.contains ("mmx");
  236478. cpuFlags.hasSSE = flags.contains ("sse");
  236479. cpuFlags.hasSSE2 = flags.contains ("sse2");
  236480. cpuFlags.has3DNow = flags.contains ("3dnow");
  236481. // TODO
  236482. cpuFlags.numCpus = AndroidStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  236483. }
  236484. void PlatformUtilities::fpuReset() {}
  236485. uint32 juce_millisecondsSinceStartup() throw()
  236486. {
  236487. // TODO
  236488. timespec t;
  236489. clock_gettime (CLOCK_MONOTONIC, &t);
  236490. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  236491. }
  236492. int64 Time::getHighResolutionTicks() throw()
  236493. {
  236494. // TODO
  236495. timespec t;
  236496. clock_gettime (CLOCK_MONOTONIC, &t);
  236497. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  236498. }
  236499. int64 Time::getHighResolutionTicksPerSecond() throw()
  236500. {
  236501. // TODO
  236502. return 1000000; // (microseconds)
  236503. }
  236504. double Time::getMillisecondCounterHiRes() throw()
  236505. {
  236506. return getHighResolutionTicks() * 0.001;
  236507. }
  236508. bool Time::setSystemTimeToThisTime() const
  236509. {
  236510. jassertfalse;
  236511. return false;
  236512. }
  236513. #endif
  236514. /*** End of inlined file: juce_android_SystemStats.cpp ***/
  236515. // (must be first)
  236516. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  236517. /*
  236518. This file contains posix routines that are common to both the Linux and Mac builds.
  236519. It gets included directly in the cpp files for these platforms.
  236520. */
  236521. CriticalSection::CriticalSection() throw()
  236522. {
  236523. pthread_mutexattr_t atts;
  236524. pthread_mutexattr_init (&atts);
  236525. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  236526. #if ! JUCE_ANDROID
  236527. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236528. #endif
  236529. pthread_mutex_init (&internal, &atts);
  236530. }
  236531. CriticalSection::~CriticalSection() throw()
  236532. {
  236533. pthread_mutex_destroy (&internal);
  236534. }
  236535. void CriticalSection::enter() const throw()
  236536. {
  236537. pthread_mutex_lock (&internal);
  236538. }
  236539. bool CriticalSection::tryEnter() const throw()
  236540. {
  236541. return pthread_mutex_trylock (&internal) == 0;
  236542. }
  236543. void CriticalSection::exit() const throw()
  236544. {
  236545. pthread_mutex_unlock (&internal);
  236546. }
  236547. class WaitableEventImpl
  236548. {
  236549. public:
  236550. WaitableEventImpl (const bool manualReset_)
  236551. : triggered (false),
  236552. manualReset (manualReset_)
  236553. {
  236554. pthread_cond_init (&condition, 0);
  236555. pthread_mutexattr_t atts;
  236556. pthread_mutexattr_init (&atts);
  236557. #if ! JUCE_ANDROID
  236558. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236559. #endif
  236560. pthread_mutex_init (&mutex, &atts);
  236561. }
  236562. ~WaitableEventImpl()
  236563. {
  236564. pthread_cond_destroy (&condition);
  236565. pthread_mutex_destroy (&mutex);
  236566. }
  236567. bool wait (const int timeOutMillisecs) throw()
  236568. {
  236569. pthread_mutex_lock (&mutex);
  236570. if (! triggered)
  236571. {
  236572. if (timeOutMillisecs < 0)
  236573. {
  236574. do
  236575. {
  236576. pthread_cond_wait (&condition, &mutex);
  236577. }
  236578. while (! triggered);
  236579. }
  236580. else
  236581. {
  236582. struct timeval now;
  236583. gettimeofday (&now, 0);
  236584. struct timespec time;
  236585. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  236586. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  236587. if (time.tv_nsec >= 1000000000)
  236588. {
  236589. time.tv_nsec -= 1000000000;
  236590. time.tv_sec++;
  236591. }
  236592. do
  236593. {
  236594. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  236595. {
  236596. pthread_mutex_unlock (&mutex);
  236597. return false;
  236598. }
  236599. }
  236600. while (! triggered);
  236601. }
  236602. }
  236603. if (! manualReset)
  236604. triggered = false;
  236605. pthread_mutex_unlock (&mutex);
  236606. return true;
  236607. }
  236608. void signal() throw()
  236609. {
  236610. pthread_mutex_lock (&mutex);
  236611. triggered = true;
  236612. pthread_cond_broadcast (&condition);
  236613. pthread_mutex_unlock (&mutex);
  236614. }
  236615. void reset() throw()
  236616. {
  236617. pthread_mutex_lock (&mutex);
  236618. triggered = false;
  236619. pthread_mutex_unlock (&mutex);
  236620. }
  236621. private:
  236622. pthread_cond_t condition;
  236623. pthread_mutex_t mutex;
  236624. bool triggered;
  236625. const bool manualReset;
  236626. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  236627. };
  236628. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  236629. : internal (new WaitableEventImpl (manualReset))
  236630. {
  236631. }
  236632. WaitableEvent::~WaitableEvent() throw()
  236633. {
  236634. delete static_cast <WaitableEventImpl*> (internal);
  236635. }
  236636. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  236637. {
  236638. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  236639. }
  236640. void WaitableEvent::signal() const throw()
  236641. {
  236642. static_cast <WaitableEventImpl*> (internal)->signal();
  236643. }
  236644. void WaitableEvent::reset() const throw()
  236645. {
  236646. static_cast <WaitableEventImpl*> (internal)->reset();
  236647. }
  236648. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  236649. {
  236650. struct timespec time;
  236651. time.tv_sec = millisecs / 1000;
  236652. time.tv_nsec = (millisecs % 1000) * 1000000;
  236653. nanosleep (&time, 0);
  236654. }
  236655. const juce_wchar File::separator = '/';
  236656. const String File::separatorString ("/");
  236657. const File File::getCurrentWorkingDirectory()
  236658. {
  236659. HeapBlock<char> heapBuffer;
  236660. char localBuffer [1024];
  236661. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  236662. int bufferSize = 4096;
  236663. while (cwd == 0 && errno == ERANGE)
  236664. {
  236665. heapBuffer.malloc (bufferSize);
  236666. cwd = getcwd (heapBuffer, bufferSize - 1);
  236667. bufferSize += 1024;
  236668. }
  236669. return File (String::fromUTF8 (cwd));
  236670. }
  236671. bool File::setAsCurrentWorkingDirectory() const
  236672. {
  236673. return chdir (getFullPathName().toUTF8()) == 0;
  236674. }
  236675. namespace
  236676. {
  236677. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236678. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  236679. #else
  236680. typedef struct stat juce_statStruct;
  236681. #endif
  236682. bool juce_stat (const String& fileName, juce_statStruct& info)
  236683. {
  236684. return fileName.isNotEmpty()
  236685. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236686. && (stat64 (fileName.toUTF8(), &info) == 0);
  236687. #else
  236688. && (stat (fileName.toUTF8(), &info) == 0);
  236689. #endif
  236690. }
  236691. // if this file doesn't exist, find a parent of it that does..
  236692. bool juce_doStatFS (File f, struct statfs& result)
  236693. {
  236694. for (int i = 5; --i >= 0;)
  236695. {
  236696. if (f.exists())
  236697. break;
  236698. f = f.getParentDirectory();
  236699. }
  236700. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  236701. }
  236702. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  236703. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  236704. {
  236705. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  236706. {
  236707. juce_statStruct info;
  236708. const bool statOk = juce_stat (path, info);
  236709. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  236710. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  236711. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  236712. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  236713. }
  236714. if (isReadOnly != 0)
  236715. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  236716. }
  236717. }
  236718. bool File::isDirectory() const
  236719. {
  236720. juce_statStruct info;
  236721. return fullPath.isEmpty()
  236722. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  236723. }
  236724. bool File::exists() const
  236725. {
  236726. juce_statStruct info;
  236727. return fullPath.isNotEmpty()
  236728. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236729. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  236730. #else
  236731. && (lstat (fullPath.toUTF8(), &info) == 0);
  236732. #endif
  236733. }
  236734. bool File::existsAsFile() const
  236735. {
  236736. return exists() && ! isDirectory();
  236737. }
  236738. int64 File::getSize() const
  236739. {
  236740. juce_statStruct info;
  236741. return juce_stat (fullPath, info) ? info.st_size : 0;
  236742. }
  236743. bool File::hasWriteAccess() const
  236744. {
  236745. if (exists())
  236746. return access (fullPath.toUTF8(), W_OK) == 0;
  236747. if ((! isDirectory()) && fullPath.containsChar (separator))
  236748. return getParentDirectory().hasWriteAccess();
  236749. return false;
  236750. }
  236751. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  236752. {
  236753. juce_statStruct info;
  236754. if (! juce_stat (fullPath, info))
  236755. return false;
  236756. info.st_mode &= 0777; // Just permissions
  236757. if (shouldBeReadOnly)
  236758. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  236759. else
  236760. // Give everybody write permission?
  236761. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  236762. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  236763. }
  236764. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  236765. {
  236766. modificationTime = 0;
  236767. accessTime = 0;
  236768. creationTime = 0;
  236769. juce_statStruct info;
  236770. if (juce_stat (fullPath, info))
  236771. {
  236772. modificationTime = (int64) info.st_mtime * 1000;
  236773. accessTime = (int64) info.st_atime * 1000;
  236774. creationTime = (int64) info.st_ctime * 1000;
  236775. }
  236776. }
  236777. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  236778. {
  236779. juce_statStruct info;
  236780. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  236781. {
  236782. struct utimbuf times;
  236783. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  236784. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  236785. return utime (fullPath.toUTF8(), &times) == 0;
  236786. }
  236787. return false;
  236788. }
  236789. bool File::deleteFile() const
  236790. {
  236791. if (! exists())
  236792. return true;
  236793. if (isDirectory())
  236794. return rmdir (fullPath.toUTF8()) == 0;
  236795. return remove (fullPath.toUTF8()) == 0;
  236796. }
  236797. bool File::moveInternal (const File& dest) const
  236798. {
  236799. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  236800. return true;
  236801. if (hasWriteAccess() && copyInternal (dest))
  236802. {
  236803. if (deleteFile())
  236804. return true;
  236805. dest.deleteFile();
  236806. }
  236807. return false;
  236808. }
  236809. void File::createDirectoryInternal (const String& fileName) const
  236810. {
  236811. mkdir (fileName.toUTF8(), 0777);
  236812. }
  236813. int64 juce_fileSetPosition (void* handle, int64 pos)
  236814. {
  236815. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  236816. return pos;
  236817. return -1;
  236818. }
  236819. void FileInputStream::openHandle()
  236820. {
  236821. totalSize = file.getSize();
  236822. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  236823. if (f != -1)
  236824. fileHandle = (void*) f;
  236825. }
  236826. void FileInputStream::closeHandle()
  236827. {
  236828. if (fileHandle != 0)
  236829. {
  236830. close ((int) (pointer_sized_int) fileHandle);
  236831. fileHandle = 0;
  236832. }
  236833. }
  236834. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  236835. {
  236836. if (fileHandle != 0)
  236837. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  236838. return 0;
  236839. }
  236840. void FileOutputStream::openHandle()
  236841. {
  236842. if (file.exists())
  236843. {
  236844. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  236845. if (f != -1)
  236846. {
  236847. currentPosition = lseek (f, 0, SEEK_END);
  236848. if (currentPosition >= 0)
  236849. fileHandle = (void*) f;
  236850. else
  236851. close (f);
  236852. }
  236853. }
  236854. else
  236855. {
  236856. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  236857. if (f != -1)
  236858. fileHandle = (void*) f;
  236859. }
  236860. }
  236861. void FileOutputStream::closeHandle()
  236862. {
  236863. if (fileHandle != 0)
  236864. {
  236865. close ((int) (pointer_sized_int) fileHandle);
  236866. fileHandle = 0;
  236867. }
  236868. }
  236869. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  236870. {
  236871. if (fileHandle != 0)
  236872. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  236873. return 0;
  236874. }
  236875. void FileOutputStream::flushInternal()
  236876. {
  236877. if (fileHandle != 0)
  236878. fsync ((int) (pointer_sized_int) fileHandle);
  236879. }
  236880. const File juce_getExecutableFile()
  236881. {
  236882. #if JUCE_ANDROID
  236883. // TODO
  236884. return File::nonexistent;
  236885. #else
  236886. Dl_info exeInfo;
  236887. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  236888. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  236889. #endif
  236890. }
  236891. int64 File::getBytesFreeOnVolume() const
  236892. {
  236893. struct statfs buf;
  236894. if (juce_doStatFS (*this, buf))
  236895. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  236896. return 0;
  236897. }
  236898. int64 File::getVolumeTotalSize() const
  236899. {
  236900. struct statfs buf;
  236901. if (juce_doStatFS (*this, buf))
  236902. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  236903. return 0;
  236904. }
  236905. const String File::getVolumeLabel() const
  236906. {
  236907. #if JUCE_MAC
  236908. struct VolAttrBuf
  236909. {
  236910. u_int32_t length;
  236911. attrreference_t mountPointRef;
  236912. char mountPointSpace [MAXPATHLEN];
  236913. } attrBuf;
  236914. struct attrlist attrList;
  236915. zerostruct (attrList);
  236916. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  236917. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  236918. File f (*this);
  236919. for (;;)
  236920. {
  236921. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  236922. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  236923. (int) attrBuf.mountPointRef.attr_length);
  236924. const File parent (f.getParentDirectory());
  236925. if (f == parent)
  236926. break;
  236927. f = parent;
  236928. }
  236929. #endif
  236930. return String::empty;
  236931. }
  236932. int File::getVolumeSerialNumber() const
  236933. {
  236934. int result = 0;
  236935. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  236936. char info [512];
  236937. #ifndef HDIO_GET_IDENTITY
  236938. #define HDIO_GET_IDENTITY 0x030d
  236939. #endif
  236940. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  236941. {
  236942. DBG (String (info + 20, 20));
  236943. result = String (info + 20, 20).trim().getIntValue();
  236944. }
  236945. close (fd);*/
  236946. return result;
  236947. }
  236948. void juce_runSystemCommand (const String& command)
  236949. {
  236950. int result = system (command.toUTF8());
  236951. (void) result;
  236952. }
  236953. const String juce_getOutputFromCommand (const String& command)
  236954. {
  236955. // slight bodge here, as we just pipe the output into a temp file and read it...
  236956. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  236957. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  236958. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  236959. String result (tempFile.loadFileAsString());
  236960. tempFile.deleteFile();
  236961. return result;
  236962. }
  236963. class InterProcessLock::Pimpl
  236964. {
  236965. public:
  236966. Pimpl (const String& name, const int timeOutMillisecs)
  236967. : handle (0), refCount (1)
  236968. {
  236969. #if JUCE_MAC
  236970. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  236971. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  236972. #else
  236973. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  236974. #endif
  236975. temp.create();
  236976. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  236977. if (handle != 0)
  236978. {
  236979. struct flock fl;
  236980. zerostruct (fl);
  236981. fl.l_whence = SEEK_SET;
  236982. fl.l_type = F_WRLCK;
  236983. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  236984. for (;;)
  236985. {
  236986. const int result = fcntl (handle, F_SETLK, &fl);
  236987. if (result >= 0)
  236988. return;
  236989. if (errno != EINTR)
  236990. {
  236991. if (timeOutMillisecs == 0
  236992. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  236993. break;
  236994. Thread::sleep (10);
  236995. }
  236996. }
  236997. }
  236998. closeFile();
  236999. }
  237000. ~Pimpl()
  237001. {
  237002. closeFile();
  237003. }
  237004. void closeFile()
  237005. {
  237006. if (handle != 0)
  237007. {
  237008. struct flock fl;
  237009. zerostruct (fl);
  237010. fl.l_whence = SEEK_SET;
  237011. fl.l_type = F_UNLCK;
  237012. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  237013. {}
  237014. close (handle);
  237015. handle = 0;
  237016. }
  237017. }
  237018. int handle, refCount;
  237019. };
  237020. InterProcessLock::InterProcessLock (const String& name_)
  237021. : name (name_)
  237022. {
  237023. }
  237024. InterProcessLock::~InterProcessLock()
  237025. {
  237026. }
  237027. bool InterProcessLock::enter (const int timeOutMillisecs)
  237028. {
  237029. const ScopedLock sl (lock);
  237030. if (pimpl == 0)
  237031. {
  237032. pimpl = new Pimpl (name, timeOutMillisecs);
  237033. if (pimpl->handle == 0)
  237034. pimpl = 0;
  237035. }
  237036. else
  237037. {
  237038. pimpl->refCount++;
  237039. }
  237040. return pimpl != 0;
  237041. }
  237042. void InterProcessLock::exit()
  237043. {
  237044. const ScopedLock sl (lock);
  237045. // Trying to release the lock too many times!
  237046. jassert (pimpl != 0);
  237047. if (pimpl != 0 && --(pimpl->refCount) == 0)
  237048. pimpl = 0;
  237049. }
  237050. void JUCE_API juce_threadEntryPoint (void*);
  237051. void* threadEntryProc (void* userData)
  237052. {
  237053. JUCE_AUTORELEASEPOOL
  237054. juce_threadEntryPoint (userData);
  237055. return 0;
  237056. }
  237057. void Thread::launchThread()
  237058. {
  237059. threadHandle_ = 0;
  237060. pthread_t handle = 0;
  237061. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  237062. {
  237063. pthread_detach (handle);
  237064. threadHandle_ = (void*) handle;
  237065. threadId_ = (ThreadID) threadHandle_;
  237066. }
  237067. }
  237068. void Thread::closeThreadHandle()
  237069. {
  237070. threadId_ = 0;
  237071. threadHandle_ = 0;
  237072. }
  237073. void Thread::killThread()
  237074. {
  237075. if (threadHandle_ != 0)
  237076. {
  237077. #if JUCE_ANDROID
  237078. jassertfalse; // pthread_cancel not available!
  237079. #else
  237080. pthread_cancel ((pthread_t) threadHandle_);
  237081. #endif
  237082. }
  237083. }
  237084. void Thread::setCurrentThreadName (const String& /*name*/)
  237085. {
  237086. }
  237087. bool Thread::setThreadPriority (void* handle, int priority)
  237088. {
  237089. struct sched_param param;
  237090. int policy;
  237091. priority = jlimit (0, 10, priority);
  237092. if (handle == 0)
  237093. handle = (void*) pthread_self();
  237094. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  237095. return false;
  237096. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  237097. const int minPriority = sched_get_priority_min (policy);
  237098. const int maxPriority = sched_get_priority_max (policy);
  237099. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  237100. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  237101. }
  237102. Thread::ThreadID Thread::getCurrentThreadId()
  237103. {
  237104. return (ThreadID) pthread_self();
  237105. }
  237106. void Thread::yield()
  237107. {
  237108. sched_yield();
  237109. }
  237110. /* Remove this macro if you're having problems compiling the cpu affinity
  237111. calls (the API for these has changed about quite a bit in various Linux
  237112. versions, and a lot of distros seem to ship with obsolete versions)
  237113. */
  237114. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  237115. #define SUPPORT_AFFINITIES 1
  237116. #endif
  237117. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  237118. {
  237119. #if SUPPORT_AFFINITIES
  237120. cpu_set_t affinity;
  237121. CPU_ZERO (&affinity);
  237122. for (int i = 0; i < 32; ++i)
  237123. if ((affinityMask & (1 << i)) != 0)
  237124. CPU_SET (i, &affinity);
  237125. /*
  237126. N.B. If this line causes a compile error, then you've probably not got the latest
  237127. version of glibc installed.
  237128. If you don't want to update your copy of glibc and don't care about cpu affinities,
  237129. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  237130. */
  237131. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  237132. sched_yield();
  237133. #else
  237134. /* affinities aren't supported because either the appropriate header files weren't found,
  237135. or the SUPPORT_AFFINITIES macro was turned off
  237136. */
  237137. jassertfalse;
  237138. (void) affinityMask;
  237139. #endif
  237140. }
  237141. /*** End of inlined file: juce_posix_SharedCode.h ***/
  237142. /*** Start of inlined file: juce_android_Files.cpp ***/
  237143. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237144. // compiled on its own).
  237145. #if JUCE_INCLUDED_FILE
  237146. bool File::copyInternal (const File& dest) const
  237147. {
  237148. // TODO
  237149. FileInputStream in (*this);
  237150. if (dest.deleteFile())
  237151. {
  237152. {
  237153. FileOutputStream out (dest);
  237154. if (out.failedToOpen())
  237155. return false;
  237156. if (out.writeFromInputStream (in, -1) == getSize())
  237157. return true;
  237158. }
  237159. dest.deleteFile();
  237160. }
  237161. return false;
  237162. }
  237163. void File::findFileSystemRoots (Array<File>& destArray)
  237164. {
  237165. // TODO
  237166. destArray.add (File ("/"));
  237167. }
  237168. bool File::isOnCDRomDrive() const
  237169. {
  237170. return false;
  237171. }
  237172. bool File::isOnHardDisk() const
  237173. {
  237174. return true;
  237175. }
  237176. bool File::isOnRemovableDrive() const
  237177. {
  237178. return false;
  237179. }
  237180. bool File::isHidden() const
  237181. {
  237182. // TODO
  237183. return getFileName().startsWithChar ('.');
  237184. }
  237185. namespace
  237186. {
  237187. const File juce_readlink (const String& file, const File& defaultFile)
  237188. {
  237189. const int size = 8192;
  237190. HeapBlock<char> buffer;
  237191. buffer.malloc (size + 4);
  237192. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  237193. if (numBytes > 0 && numBytes <= size)
  237194. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  237195. return defaultFile;
  237196. }
  237197. }
  237198. const File File::getLinkedTarget() const
  237199. {
  237200. // TODO
  237201. return juce_readlink (getFullPathName().toUTF8(), *this);
  237202. }
  237203. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  237204. const File File::getSpecialLocation (const SpecialLocationType type)
  237205. {
  237206. // TODO
  237207. switch (type)
  237208. {
  237209. case userHomeDirectory:
  237210. {
  237211. const char* homeDir = getenv ("HOME");
  237212. if (homeDir == 0)
  237213. {
  237214. struct passwd* const pw = getpwuid (getuid());
  237215. if (pw != 0)
  237216. homeDir = pw->pw_dir;
  237217. }
  237218. return File (String::fromUTF8 (homeDir));
  237219. }
  237220. case userDocumentsDirectory:
  237221. case userMusicDirectory:
  237222. case userMoviesDirectory:
  237223. case userApplicationDataDirectory:
  237224. return File ("~");
  237225. case userDesktopDirectory:
  237226. return File ("~/Desktop");
  237227. case commonApplicationDataDirectory:
  237228. return File ("/var");
  237229. case globalApplicationsDirectory:
  237230. return File ("/usr");
  237231. case tempDirectory:
  237232. {
  237233. File tmp ("/var/tmp");
  237234. if (! tmp.isDirectory())
  237235. {
  237236. tmp = "/tmp";
  237237. if (! tmp.isDirectory())
  237238. tmp = File::getCurrentWorkingDirectory();
  237239. }
  237240. return tmp;
  237241. }
  237242. case invokedExecutableFile:
  237243. if (juce_Argv0 != 0)
  237244. return File (String::fromUTF8 (juce_Argv0));
  237245. // deliberate fall-through...
  237246. case currentExecutableFile:
  237247. case currentApplicationFile:
  237248. return juce_getExecutableFile();
  237249. case hostApplicationPath:
  237250. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  237251. default:
  237252. jassertfalse; // unknown type?
  237253. break;
  237254. }
  237255. return File::nonexistent;
  237256. }
  237257. const String File::getVersion() const
  237258. {
  237259. return String::empty;
  237260. }
  237261. bool File::moveToTrash() const
  237262. {
  237263. if (! exists())
  237264. return true;
  237265. // TODO
  237266. return false;
  237267. }
  237268. class DirectoryIterator::NativeIterator::Pimpl
  237269. {
  237270. public:
  237271. Pimpl (const File& directory, const String& wildCard_)
  237272. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  237273. wildCard (wildCard_),
  237274. dir (opendir (directory.getFullPathName().toUTF8()))
  237275. {
  237276. wildcardUTF8 = wildCard.toUTF8();
  237277. }
  237278. ~Pimpl()
  237279. {
  237280. if (dir != 0)
  237281. closedir (dir);
  237282. }
  237283. bool next (String& filenameFound,
  237284. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237285. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237286. {
  237287. if (dir != 0)
  237288. {
  237289. for (;;)
  237290. {
  237291. struct dirent* const de = readdir (dir);
  237292. if (de == 0)
  237293. break;
  237294. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  237295. {
  237296. filenameFound = String::fromUTF8 (de->d_name);
  237297. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  237298. if (isHidden != 0)
  237299. *isHidden = filenameFound.startsWithChar ('.');
  237300. return true;
  237301. }
  237302. }
  237303. }
  237304. return false;
  237305. }
  237306. private:
  237307. String parentDir, wildCard;
  237308. const char* wildcardUTF8;
  237309. DIR* dir;
  237310. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  237311. };
  237312. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  237313. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  237314. {
  237315. }
  237316. DirectoryIterator::NativeIterator::~NativeIterator()
  237317. {
  237318. }
  237319. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  237320. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237321. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237322. {
  237323. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  237324. }
  237325. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  237326. {
  237327. }
  237328. void File::revealToUser() const
  237329. {
  237330. }
  237331. #endif
  237332. /*** End of inlined file: juce_android_Files.cpp ***/
  237333. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  237334. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237335. // compiled on its own).
  237336. #if JUCE_INCLUDED_FILE
  237337. struct NamedPipeInternal
  237338. {
  237339. String pipeInName, pipeOutName;
  237340. int pipeIn, pipeOut;
  237341. bool volatile createdPipe, blocked, stopReadOperation;
  237342. static void signalHandler (int) {}
  237343. };
  237344. void NamedPipe::cancelPendingReads()
  237345. {
  237346. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  237347. {
  237348. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237349. intern->stopReadOperation = true;
  237350. char buffer [1] = { 0 };
  237351. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  237352. (void) bytesWritten;
  237353. int timeout = 2000;
  237354. while (intern->blocked && --timeout >= 0)
  237355. Thread::sleep (2);
  237356. intern->stopReadOperation = false;
  237357. }
  237358. }
  237359. void NamedPipe::close()
  237360. {
  237361. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237362. if (intern != 0)
  237363. {
  237364. internal = 0;
  237365. if (intern->pipeIn != -1)
  237366. ::close (intern->pipeIn);
  237367. if (intern->pipeOut != -1)
  237368. ::close (intern->pipeOut);
  237369. if (intern->createdPipe)
  237370. {
  237371. unlink (intern->pipeInName.toUTF8());
  237372. unlink (intern->pipeOutName.toUTF8());
  237373. }
  237374. delete intern;
  237375. }
  237376. }
  237377. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  237378. {
  237379. close();
  237380. NamedPipeInternal* const intern = new NamedPipeInternal();
  237381. internal = intern;
  237382. intern->createdPipe = createPipe;
  237383. intern->blocked = false;
  237384. intern->stopReadOperation = false;
  237385. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  237386. siginterrupt (SIGPIPE, 1);
  237387. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  237388. intern->pipeInName = pipePath + "_in";
  237389. intern->pipeOutName = pipePath + "_out";
  237390. intern->pipeIn = -1;
  237391. intern->pipeOut = -1;
  237392. if (createPipe)
  237393. {
  237394. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  237395. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  237396. {
  237397. delete intern;
  237398. internal = 0;
  237399. return false;
  237400. }
  237401. }
  237402. return true;
  237403. }
  237404. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  237405. {
  237406. int bytesRead = -1;
  237407. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237408. if (intern != 0)
  237409. {
  237410. intern->blocked = true;
  237411. if (intern->pipeIn == -1)
  237412. {
  237413. if (intern->createdPipe)
  237414. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  237415. else
  237416. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  237417. if (intern->pipeIn == -1)
  237418. {
  237419. intern->blocked = false;
  237420. return -1;
  237421. }
  237422. }
  237423. bytesRead = 0;
  237424. char* p = static_cast<char*> (destBuffer);
  237425. while (bytesRead < maxBytesToRead)
  237426. {
  237427. const int bytesThisTime = maxBytesToRead - bytesRead;
  237428. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  237429. if (numRead <= 0 || intern->stopReadOperation)
  237430. {
  237431. bytesRead = -1;
  237432. break;
  237433. }
  237434. bytesRead += numRead;
  237435. p += bytesRead;
  237436. }
  237437. intern->blocked = false;
  237438. }
  237439. return bytesRead;
  237440. }
  237441. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  237442. {
  237443. int bytesWritten = -1;
  237444. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237445. if (intern != 0)
  237446. {
  237447. if (intern->pipeOut == -1)
  237448. {
  237449. if (intern->createdPipe)
  237450. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  237451. else
  237452. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  237453. if (intern->pipeOut == -1)
  237454. {
  237455. return -1;
  237456. }
  237457. }
  237458. const char* p = static_cast<const char*> (sourceBuffer);
  237459. bytesWritten = 0;
  237460. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  237461. while (bytesWritten < numBytesToWrite
  237462. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  237463. {
  237464. const int bytesThisTime = numBytesToWrite - bytesWritten;
  237465. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  237466. if (numWritten <= 0)
  237467. {
  237468. bytesWritten = -1;
  237469. break;
  237470. }
  237471. bytesWritten += numWritten;
  237472. p += bytesWritten;
  237473. }
  237474. }
  237475. return bytesWritten;
  237476. }
  237477. #endif
  237478. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  237479. /*** Start of inlined file: juce_android_Threads.cpp ***/
  237480. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237481. // compiled on its own).
  237482. #if JUCE_INCLUDED_FILE
  237483. /*
  237484. Note that a lot of methods that you'd expect to find in this file actually
  237485. live in juce_posix_SharedCode.h!
  237486. */
  237487. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  237488. void Process::setPriority (ProcessPriority prior)
  237489. {
  237490. // TODO
  237491. struct sched_param param;
  237492. int policy, maxp, minp;
  237493. const int p = (int) prior;
  237494. if (p <= 1)
  237495. policy = SCHED_OTHER;
  237496. else
  237497. policy = SCHED_RR;
  237498. minp = sched_get_priority_min (policy);
  237499. maxp = sched_get_priority_max (policy);
  237500. if (p < 2)
  237501. param.sched_priority = 0;
  237502. else if (p == 2 )
  237503. // Set to middle of lower realtime priority range
  237504. param.sched_priority = minp + (maxp - minp) / 4;
  237505. else
  237506. // Set to middle of higher realtime priority range
  237507. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  237508. pthread_setschedparam (pthread_self(), policy, &param);
  237509. }
  237510. void Process::terminate()
  237511. {
  237512. // TODO
  237513. exit (0);
  237514. }
  237515. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  237516. {
  237517. return false;
  237518. }
  237519. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  237520. {
  237521. return juce_isRunningUnderDebugger();
  237522. }
  237523. void Process::raisePrivilege() {}
  237524. void Process::lowerPrivilege() {}
  237525. #endif
  237526. /*** End of inlined file: juce_android_Threads.cpp ***/
  237527. /*** Start of inlined file: juce_android_Network.cpp ***/
  237528. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237529. // compiled on its own).
  237530. #if JUCE_INCLUDED_FILE
  237531. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  237532. {
  237533. // TODO
  237534. }
  237535. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  237536. const String& emailSubject,
  237537. const String& bodyText,
  237538. const StringArray& filesToAttach)
  237539. {
  237540. // TODO
  237541. return false;
  237542. }
  237543. class WebInputStream : public InputStream
  237544. {
  237545. public:
  237546. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  237547. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237548. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  237549. {
  237550. // TODO
  237551. openedOk = false;
  237552. }
  237553. ~WebInputStream()
  237554. {
  237555. }
  237556. bool isExhausted()
  237557. {
  237558. return true; // TODO
  237559. }
  237560. int64 getPosition()
  237561. {
  237562. return 0; // TODO
  237563. }
  237564. int64 getTotalLength()
  237565. {
  237566. return -1; // TODO
  237567. }
  237568. int read (void* buffer, int bytesToRead)
  237569. {
  237570. // TODO
  237571. return 0;
  237572. }
  237573. bool setPosition (int64 wantedPos)
  237574. {
  237575. // TODO
  237576. return false;
  237577. }
  237578. bool openedOk;
  237579. private:
  237580. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  237581. };
  237582. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  237583. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237584. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  237585. {
  237586. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  237587. progressCallback, progressCallbackContext,
  237588. headers, timeOutMs, responseHeaders));
  237589. return wi->openedOk ? wi.release() : 0;
  237590. }
  237591. #endif
  237592. /*** End of inlined file: juce_android_Network.cpp ***/
  237593. /*** Start of inlined file: juce_android_Messaging.cpp ***/
  237594. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237595. // compiled on its own).
  237596. #if JUCE_INCLUDED_FILE
  237597. void MessageManager::doPlatformSpecificInitialisation()
  237598. {
  237599. }
  237600. void MessageManager::doPlatformSpecificShutdown()
  237601. {
  237602. }
  237603. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  237604. {
  237605. // TODO
  237606. /*
  237607. The idea here is that this will check the system message queue, pull off a
  237608. message if there is one, deliver it, and return true if a message was delivered.
  237609. If the queue's empty, return false.
  237610. If the message is one of our special ones (i.e. a Message object being delivered,
  237611. this must call MessageManager::getInstance()->deliverMessage() to deliver it
  237612. */
  237613. return true;
  237614. }
  237615. bool juce_postMessageToSystemQueue (Message* message)
  237616. {
  237617. // TODO
  237618. return true;
  237619. }
  237620. class AsyncFunctionCaller : public AsyncUpdater
  237621. {
  237622. public:
  237623. static void* call (MessageCallbackFunction* func_, void* parameter_)
  237624. {
  237625. if (MessageManager::getInstance()->isThisTheMessageThread())
  237626. return func_ (parameter_);
  237627. AsyncFunctionCaller caller (func_, parameter_);
  237628. caller.triggerAsyncUpdate();
  237629. caller.finished.wait();
  237630. return caller.result;
  237631. }
  237632. void handleAsyncUpdate()
  237633. {
  237634. result = (*func) (parameter);
  237635. finished.signal();
  237636. }
  237637. private:
  237638. WaitableEvent finished;
  237639. MessageCallbackFunction* func;
  237640. void* parameter;
  237641. void* volatile result;
  237642. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  237643. : result (0), func (func_), parameter (parameter_)
  237644. {}
  237645. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  237646. };
  237647. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  237648. {
  237649. return AsyncFunctionCaller::call (func, parameter);
  237650. }
  237651. void MessageManager::broadcastMessage (const String&)
  237652. {
  237653. }
  237654. #endif
  237655. /*** End of inlined file: juce_android_Messaging.cpp ***/
  237656. /*** Start of inlined file: juce_android_Fonts.cpp ***/
  237657. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237658. // compiled on its own).
  237659. #if JUCE_INCLUDED_FILE
  237660. const StringArray Font::findAllTypefaceNames()
  237661. {
  237662. StringArray results;
  237663. // TODO
  237664. return results;
  237665. }
  237666. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  237667. {
  237668. // TODO
  237669. defaultSans = "Verdana";
  237670. defaultSerif = "Times";
  237671. defaultFixed = "Lucida Console";
  237672. defaultFallback = "Tahoma";
  237673. }
  237674. class AndroidTypeface : public Typeface
  237675. {
  237676. public:
  237677. AndroidTypeface (const Font& font)
  237678. : Typeface (font.getTypefaceName())
  237679. {
  237680. // TODO
  237681. }
  237682. float getAscent() const
  237683. {
  237684. return 0; // TODO
  237685. }
  237686. float getDescent() const
  237687. {
  237688. return 0; // TODO
  237689. }
  237690. float getStringWidth (const String& text)
  237691. {
  237692. // TODO
  237693. return 0;
  237694. }
  237695. void getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets)
  237696. {
  237697. // TODO
  237698. }
  237699. bool getOutlineForGlyph (int glyphNumber, Path& destPath)
  237700. {
  237701. // TODO
  237702. return false;
  237703. }
  237704. private:
  237705. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidTypeface);
  237706. };
  237707. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  237708. {
  237709. return new AndroidTypeface (font);
  237710. }
  237711. #endif
  237712. /*** End of inlined file: juce_android_Fonts.cpp ***/
  237713. /*** Start of inlined file: juce_android_GraphicsContext.cpp ***/
  237714. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237715. // compiled on its own).
  237716. #if JUCE_INCLUDED_FILE
  237717. // TODO
  237718. class AndroidLowLevelGraphicsContext : public LowLevelGraphicsContext
  237719. {
  237720. public:
  237721. AndroidLowLevelGraphicsContext()
  237722. {
  237723. }
  237724. ~AndroidLowLevelGraphicsContext()
  237725. {
  237726. }
  237727. bool isVectorDevice() const { return false; }
  237728. void setOrigin (int x, int y)
  237729. {
  237730. }
  237731. void addTransform (const AffineTransform& transform)
  237732. {
  237733. }
  237734. float getScaleFactor()
  237735. {
  237736. return 1.0f;
  237737. }
  237738. bool clipToRectangle (const Rectangle<int>& r)
  237739. {
  237740. return false;
  237741. }
  237742. bool clipToRectangleList (const RectangleList& clipRegion)
  237743. {
  237744. return false;
  237745. }
  237746. void excludeClipRectangle (const Rectangle<int>& r)
  237747. {
  237748. }
  237749. void clipToPath (const Path& path, const AffineTransform& transform)
  237750. {
  237751. }
  237752. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  237753. {
  237754. }
  237755. bool clipRegionIntersects (const Rectangle<int>& r)
  237756. {
  237757. return true;
  237758. }
  237759. const Rectangle<int> getClipBounds() const
  237760. {
  237761. return Rectangle<int>();
  237762. }
  237763. bool isClipEmpty() const
  237764. {
  237765. return false;
  237766. }
  237767. void saveState()
  237768. {
  237769. }
  237770. void restoreState()
  237771. {
  237772. }
  237773. void beginTransparencyLayer (float opacity)
  237774. {
  237775. }
  237776. void endTransparencyLayer()
  237777. {
  237778. }
  237779. void setFill (const FillType& fillType)
  237780. {
  237781. }
  237782. void setOpacity (float newOpacity)
  237783. {
  237784. }
  237785. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  237786. {
  237787. }
  237788. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  237789. {
  237790. }
  237791. void fillPath (const Path& path, const AffineTransform& transform)
  237792. {
  237793. }
  237794. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles)
  237795. {
  237796. }
  237797. void drawLine (const Line <float>& line)
  237798. {
  237799. }
  237800. void drawVerticalLine (int x, float top, float bottom)
  237801. {
  237802. }
  237803. void drawHorizontalLine (int y, float left, float right)
  237804. {
  237805. }
  237806. void setFont (const Font& newFont)
  237807. {
  237808. }
  237809. const Font getFont()
  237810. {
  237811. return Font();
  237812. }
  237813. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  237814. {
  237815. }
  237816. private:
  237817. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidLowLevelGraphicsContext);
  237818. };
  237819. #endif
  237820. /*** End of inlined file: juce_android_GraphicsContext.cpp ***/
  237821. /*** Start of inlined file: juce_android_Windowing.cpp ***/
  237822. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  237823. // compiled on its own).
  237824. #if JUCE_INCLUDED_FILE
  237825. class AndroidComponentPeer : public ComponentPeer
  237826. {
  237827. public:
  237828. AndroidComponentPeer (Component* const component, const int windowStyleFlags)
  237829. : ComponentPeer (component, windowStyleFlags)
  237830. {
  237831. // TODO
  237832. }
  237833. ~AndroidComponentPeer()
  237834. {
  237835. }
  237836. void* getNativeHandle() const
  237837. {
  237838. return 0; // TODO
  237839. }
  237840. void setVisible (bool shouldBeVisible)
  237841. {
  237842. }
  237843. void setTitle (const String& title)
  237844. {
  237845. }
  237846. void setPosition (int x, int y)
  237847. {
  237848. // TODO
  237849. }
  237850. void setSize (int w, int h)
  237851. {
  237852. }
  237853. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  237854. {
  237855. // TODO
  237856. }
  237857. const Rectangle<int> getBounds() const
  237858. {
  237859. // TODO
  237860. return Rectangle<int>();
  237861. }
  237862. const Point<int> getScreenPosition() const
  237863. {
  237864. // TODO
  237865. return Point<int>();
  237866. }
  237867. const Point<int> localToGlobal (const Point<int>& relativePosition)
  237868. {
  237869. // TODO
  237870. return relativePosition + getScreenPosition();
  237871. }
  237872. const Point<int> globalToLocal (const Point<int>& screenPosition)
  237873. {
  237874. // TODO
  237875. return screenPosition - getScreenPosition();
  237876. }
  237877. void setMinimised (bool shouldBeMinimised)
  237878. {
  237879. // TODO
  237880. }
  237881. bool isMinimised() const
  237882. {
  237883. }
  237884. void setFullScreen (bool shouldBeFullScreen)
  237885. {
  237886. // TODO
  237887. }
  237888. bool isFullScreen() const
  237889. {
  237890. // TODO
  237891. return false;
  237892. }
  237893. void setIcon (const Image& newIcon)
  237894. {
  237895. // TODO
  237896. }
  237897. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  237898. {
  237899. // TODO
  237900. return isPositiveAndBelow (position.getX(), component->getWidth())
  237901. && isPositiveAndBelow (position.getY(), component->getHeight());
  237902. }
  237903. const BorderSize<int> getFrameSize() const
  237904. {
  237905. // TODO
  237906. return BorderSize<int>();
  237907. }
  237908. bool setAlwaysOnTop (bool alwaysOnTop)
  237909. {
  237910. // TODO
  237911. return false;
  237912. }
  237913. void toFront (bool makeActive)
  237914. {
  237915. // TODO
  237916. }
  237917. void toBehind (ComponentPeer* other)
  237918. {
  237919. // TODO
  237920. }
  237921. bool isFocused() const
  237922. {
  237923. // TODO
  237924. return false;
  237925. }
  237926. void grabFocus()
  237927. {
  237928. // TODO
  237929. }
  237930. void textInputRequired (const Point<int>& position)
  237931. {
  237932. // TODO
  237933. }
  237934. void repaint (const Rectangle<int>& area)
  237935. {
  237936. // TODO
  237937. }
  237938. void performAnyPendingRepaintsNow()
  237939. {
  237940. // TODO
  237941. }
  237942. void setAlpha (float newAlpha)
  237943. {
  237944. // TODO
  237945. }
  237946. private:
  237947. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer);
  237948. };
  237949. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  237950. {
  237951. return new AndroidComponentPeer (this, styleFlags);
  237952. }
  237953. bool Desktop::canUseSemiTransparentWindows() throw()
  237954. {
  237955. return true; // TODO
  237956. }
  237957. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  237958. {
  237959. // TODO
  237960. return upright;
  237961. }
  237962. void Desktop::createMouseInputSources()
  237963. {
  237964. // This creates a mouse input source for each possible finger
  237965. for (int i = 0; i < 10; ++i)
  237966. mouseSources.add (new MouseInputSource (i, false));
  237967. }
  237968. const Point<int> MouseInputSource::getCurrentMousePosition()
  237969. {
  237970. // TODO
  237971. return Point<int>();
  237972. }
  237973. void Desktop::setMousePosition (const Point<int>& newPosition)
  237974. {
  237975. // not needed
  237976. }
  237977. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  237978. {
  237979. // TODO
  237980. return false;
  237981. }
  237982. void ModifierKeys::updateCurrentModifiers() throw()
  237983. {
  237984. // not needed
  237985. }
  237986. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  237987. {
  237988. // TODO
  237989. return ModifierKeys();
  237990. }
  237991. bool Process::isForegroundProcess()
  237992. {
  237993. return true; // TODO
  237994. }
  237995. bool AlertWindow::showNativeDialogBox (const String& title,
  237996. const String& bodyText,
  237997. bool isOkCancel)
  237998. {
  237999. // TODO
  238000. }
  238001. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  238002. {
  238003. return createSoftwareImage (format, width, height, clearImage);
  238004. }
  238005. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  238006. {
  238007. // TODO
  238008. }
  238009. bool Desktop::isScreenSaverEnabled()
  238010. {
  238011. return true;
  238012. }
  238013. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  238014. {
  238015. }
  238016. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  238017. {
  238018. // TODO
  238019. monitorCoords.add (Rectangle<int> (0, 0, 640, 480));
  238020. }
  238021. const Image juce_createIconForFile (const File& file)
  238022. {
  238023. Image image;
  238024. // TODO
  238025. return image;
  238026. }
  238027. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  238028. {
  238029. return 0;
  238030. }
  238031. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  238032. {
  238033. }
  238034. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  238035. {
  238036. return 0;
  238037. }
  238038. void MouseCursor::showInWindow (ComponentPeer*) const {}
  238039. void MouseCursor::showInAllWindows() const {}
  238040. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  238041. {
  238042. return false;
  238043. }
  238044. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  238045. {
  238046. return false;
  238047. }
  238048. const int extendedKeyModifier = 0x10000;
  238049. const int KeyPress::spaceKey = ' ';
  238050. const int KeyPress::returnKey = 0x0d;
  238051. const int KeyPress::escapeKey = 0x1b;
  238052. const int KeyPress::backspaceKey = 0x7f;
  238053. const int KeyPress::leftKey = extendedKeyModifier + 1;
  238054. const int KeyPress::rightKey = extendedKeyModifier + 2;
  238055. const int KeyPress::upKey = extendedKeyModifier + 3;
  238056. const int KeyPress::downKey = extendedKeyModifier + 4;
  238057. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  238058. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  238059. const int KeyPress::endKey = extendedKeyModifier + 7;
  238060. const int KeyPress::homeKey = extendedKeyModifier + 8;
  238061. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  238062. const int KeyPress::insertKey = -1;
  238063. const int KeyPress::tabKey = 9;
  238064. const int KeyPress::F1Key = extendedKeyModifier + 10;
  238065. const int KeyPress::F2Key = extendedKeyModifier + 11;
  238066. const int KeyPress::F3Key = extendedKeyModifier + 12;
  238067. const int KeyPress::F4Key = extendedKeyModifier + 13;
  238068. const int KeyPress::F5Key = extendedKeyModifier + 14;
  238069. const int KeyPress::F6Key = extendedKeyModifier + 16;
  238070. const int KeyPress::F7Key = extendedKeyModifier + 17;
  238071. const int KeyPress::F8Key = extendedKeyModifier + 18;
  238072. const int KeyPress::F9Key = extendedKeyModifier + 19;
  238073. const int KeyPress::F10Key = extendedKeyModifier + 20;
  238074. const int KeyPress::F11Key = extendedKeyModifier + 21;
  238075. const int KeyPress::F12Key = extendedKeyModifier + 22;
  238076. const int KeyPress::F13Key = extendedKeyModifier + 23;
  238077. const int KeyPress::F14Key = extendedKeyModifier + 24;
  238078. const int KeyPress::F15Key = extendedKeyModifier + 25;
  238079. const int KeyPress::F16Key = extendedKeyModifier + 26;
  238080. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  238081. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  238082. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  238083. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  238084. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  238085. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  238086. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  238087. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  238088. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  238089. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  238090. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  238091. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  238092. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  238093. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  238094. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  238095. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  238096. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  238097. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  238098. const int KeyPress::playKey = extendedKeyModifier + 45;
  238099. const int KeyPress::stopKey = extendedKeyModifier + 46;
  238100. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  238101. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  238102. #endif
  238103. /*** End of inlined file: juce_android_Windowing.cpp ***/
  238104. /*** Start of inlined file: juce_android_FileChooser.cpp ***/
  238105. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238106. // compiled on its own).
  238107. #if JUCE_INCLUDED_FILE
  238108. void FileChooser::showPlatformDialog (Array<File>& results,
  238109. const String& title,
  238110. const File& currentFileOrDirectory,
  238111. const String& filter,
  238112. bool selectsDirectory,
  238113. bool selectsFiles,
  238114. bool isSaveDialogue,
  238115. bool warnAboutOverwritingExistingFiles,
  238116. bool selectMultipleFiles,
  238117. FilePreviewComponent* extraInfoComponent)
  238118. {
  238119. // TODO
  238120. }
  238121. #endif
  238122. /*** End of inlined file: juce_android_FileChooser.cpp ***/
  238123. /*** Start of inlined file: juce_android_Misc.cpp ***/
  238124. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238125. // compiled on its own).
  238126. #if JUCE_INCLUDED_FILE
  238127. void SystemClipboard::copyTextToClipboard (const String& text)
  238128. {
  238129. // TODO
  238130. }
  238131. const String SystemClipboard::getTextFromClipboard()
  238132. {
  238133. String result;
  238134. // TODO
  238135. return result;
  238136. }
  238137. #endif
  238138. /*** End of inlined file: juce_android_Misc.cpp ***/
  238139. /*** Start of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238140. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238141. // compiled on its own).
  238142. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  238143. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  238144. : browser (0),
  238145. blankPageShown (false),
  238146. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  238147. {
  238148. setOpaque (true);
  238149. }
  238150. WebBrowserComponent::~WebBrowserComponent()
  238151. {
  238152. }
  238153. void WebBrowserComponent::goToURL (const String& url,
  238154. const StringArray* headers,
  238155. const MemoryBlock* postData)
  238156. {
  238157. lastURL = url;
  238158. lastHeaders.clear();
  238159. if (headers != 0)
  238160. lastHeaders = *headers;
  238161. lastPostData.setSize (0);
  238162. if (postData != 0)
  238163. lastPostData = *postData;
  238164. blankPageShown = false;
  238165. }
  238166. void WebBrowserComponent::stop()
  238167. {
  238168. }
  238169. void WebBrowserComponent::goBack()
  238170. {
  238171. lastURL = String::empty;
  238172. blankPageShown = false;
  238173. }
  238174. void WebBrowserComponent::goForward()
  238175. {
  238176. lastURL = String::empty;
  238177. }
  238178. void WebBrowserComponent::refresh()
  238179. {
  238180. }
  238181. void WebBrowserComponent::paint (Graphics& g)
  238182. {
  238183. g.fillAll (Colours::white);
  238184. }
  238185. void WebBrowserComponent::checkWindowAssociation()
  238186. {
  238187. }
  238188. void WebBrowserComponent::reloadLastURL()
  238189. {
  238190. if (lastURL.isNotEmpty())
  238191. {
  238192. goToURL (lastURL, &lastHeaders, &lastPostData);
  238193. lastURL = String::empty;
  238194. }
  238195. }
  238196. void WebBrowserComponent::parentHierarchyChanged()
  238197. {
  238198. checkWindowAssociation();
  238199. }
  238200. void WebBrowserComponent::resized()
  238201. {
  238202. }
  238203. void WebBrowserComponent::visibilityChanged()
  238204. {
  238205. checkWindowAssociation();
  238206. }
  238207. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  238208. {
  238209. return true;
  238210. }
  238211. #endif
  238212. /*** End of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238213. /*** Start of inlined file: juce_android_OpenGLComponent.cpp ***/
  238214. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238215. // compiled on its own).
  238216. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  238217. // TODO
  238218. OpenGLContext* OpenGLComponent::createContext()
  238219. {
  238220. return 0;
  238221. }
  238222. void* OpenGLComponent::getNativeWindowHandle() const
  238223. {
  238224. return 0;
  238225. }
  238226. void juce_glViewport (const int w, const int h)
  238227. {
  238228. // glViewport (0, 0, w, h);
  238229. }
  238230. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  238231. OwnedArray <OpenGLPixelFormat>& results)
  238232. {
  238233. }
  238234. #endif
  238235. /*** End of inlined file: juce_android_OpenGLComponent.cpp ***/
  238236. /*** Start of inlined file: juce_android_Midi.cpp ***/
  238237. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238238. // compiled on its own).
  238239. #if JUCE_INCLUDED_FILE
  238240. const StringArray MidiOutput::getDevices()
  238241. {
  238242. StringArray devices;
  238243. return devices;
  238244. }
  238245. int MidiOutput::getDefaultDeviceIndex()
  238246. {
  238247. return 0;
  238248. }
  238249. MidiOutput* MidiOutput::openDevice (int index)
  238250. {
  238251. return 0;
  238252. }
  238253. MidiOutput::~MidiOutput()
  238254. {
  238255. }
  238256. void MidiOutput::reset()
  238257. {
  238258. }
  238259. bool MidiOutput::getVolume (float&, float&)
  238260. {
  238261. return false;
  238262. }
  238263. void MidiOutput::setVolume (float, float)
  238264. {
  238265. }
  238266. void MidiOutput::sendMessageNow (const MidiMessage&)
  238267. {
  238268. }
  238269. MidiInput::MidiInput (const String& name_)
  238270. : name (name_),
  238271. internal (0)
  238272. {
  238273. }
  238274. MidiInput::~MidiInput()
  238275. {
  238276. }
  238277. void MidiInput::start()
  238278. {
  238279. }
  238280. void MidiInput::stop()
  238281. {
  238282. }
  238283. int MidiInput::getDefaultDeviceIndex()
  238284. {
  238285. return 0;
  238286. }
  238287. const StringArray MidiInput::getDevices()
  238288. {
  238289. StringArray devs;
  238290. return devs;
  238291. }
  238292. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  238293. {
  238294. return 0;
  238295. }
  238296. #endif
  238297. /*** End of inlined file: juce_android_Midi.cpp ***/
  238298. /*** Start of inlined file: juce_android_Audio.cpp ***/
  238299. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238300. // compiled on its own).
  238301. #if JUCE_INCLUDED_FILE
  238302. class AndroidAudioIODevice : public AudioIODevice
  238303. {
  238304. public:
  238305. AndroidAudioIODevice (const String& deviceName)
  238306. : AudioIODevice (deviceName, "Audio"),
  238307. callback (0),
  238308. sampleRate (0),
  238309. numInputChannels (0),
  238310. numOutputChannels (0),
  238311. actualBufferSize (0),
  238312. isRunning (false)
  238313. {
  238314. numInputChannels = 2;
  238315. numOutputChannels = 2;
  238316. // TODO
  238317. }
  238318. ~AndroidAudioIODevice()
  238319. {
  238320. close();
  238321. }
  238322. const StringArray getOutputChannelNames()
  238323. {
  238324. StringArray s;
  238325. s.add ("Left"); // TODO
  238326. s.add ("Right");
  238327. return s;
  238328. }
  238329. const StringArray getInputChannelNames()
  238330. {
  238331. StringArray s;
  238332. s.add ("Left");
  238333. s.add ("Right");
  238334. return s;
  238335. }
  238336. int getNumSampleRates() { return 1;}
  238337. double getSampleRate (int index) { return sampleRate; }
  238338. int getNumBufferSizesAvailable() { return 1; }
  238339. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  238340. int getDefaultBufferSize() { return 1024; }
  238341. const String open (const BigInteger& inputChannels,
  238342. const BigInteger& outputChannels,
  238343. double sampleRate,
  238344. int bufferSize)
  238345. {
  238346. close();
  238347. lastError = String::empty;
  238348. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  238349. activeOutputChans = outputChannels;
  238350. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  238351. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  238352. activeInputChans = inputChannels;
  238353. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  238354. numInputChannels = activeInputChans.countNumberOfSetBits();
  238355. // TODO
  238356. actualBufferSize = 0; // whatever is possible based on preferredBufferSize
  238357. isRunning = true;
  238358. return lastError;
  238359. }
  238360. void close()
  238361. {
  238362. if (isRunning)
  238363. {
  238364. isRunning = false;
  238365. // TODO
  238366. }
  238367. }
  238368. int getOutputLatencyInSamples()
  238369. {
  238370. return 0; // TODO
  238371. }
  238372. int getInputLatencyInSamples()
  238373. {
  238374. return 0; // TODO
  238375. }
  238376. bool isOpen() { return isRunning; }
  238377. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  238378. int getCurrentBitDepth() { return 16; }
  238379. double getCurrentSampleRate() { return sampleRate; }
  238380. const BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  238381. const BigInteger getActiveInputChannels() const { return activeInputChans; }
  238382. const String getLastError() { return lastError; }
  238383. bool isPlaying() { return isRunning && callback != 0; }
  238384. // TODO
  238385. void start (AudioIODeviceCallback* newCallback)
  238386. {
  238387. if (isRunning && callback != newCallback)
  238388. {
  238389. if (newCallback != 0)
  238390. newCallback->audioDeviceAboutToStart (this);
  238391. const ScopedLock sl (callbackLock);
  238392. callback = newCallback;
  238393. }
  238394. }
  238395. void stop()
  238396. {
  238397. if (isRunning)
  238398. {
  238399. AudioIODeviceCallback* lastCallback;
  238400. {
  238401. const ScopedLock sl (callbackLock);
  238402. lastCallback = callback;
  238403. callback = 0;
  238404. }
  238405. if (lastCallback != 0)
  238406. lastCallback->audioDeviceStopped();
  238407. }
  238408. }
  238409. private:
  238410. CriticalSection callbackLock;
  238411. AudioIODeviceCallback* callback;
  238412. double sampleRate;
  238413. int numInputChannels, numOutputChannels;
  238414. int actualBufferSize;
  238415. bool isRunning;
  238416. String lastError;
  238417. BigInteger activeOutputChans, activeInputChans;
  238418. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  238419. };
  238420. // TODO
  238421. class AndroidAudioIODeviceType : public AudioIODeviceType
  238422. {
  238423. public:
  238424. AndroidAudioIODeviceType()
  238425. : AudioIODeviceType ("Android Audio")
  238426. {
  238427. }
  238428. void scanForDevices()
  238429. {
  238430. }
  238431. const StringArray getDeviceNames (bool wantInputNames) const
  238432. {
  238433. StringArray s;
  238434. s.add ("Android Audio");
  238435. return s;
  238436. }
  238437. int getDefaultDeviceIndex (bool forInput) const
  238438. {
  238439. return 0;
  238440. }
  238441. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  238442. {
  238443. return device != 0 ? 0 : -1;
  238444. }
  238445. bool hasSeparateInputsAndOutputs() const { return false; }
  238446. AudioIODevice* createDevice (const String& outputDeviceName,
  238447. const String& inputDeviceName)
  238448. {
  238449. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  238450. return new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  238451. : inputDeviceName);
  238452. return 0;
  238453. }
  238454. private:
  238455. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  238456. };
  238457. AudioIODeviceType* juce_createAudioIODeviceType_Android()
  238458. {
  238459. return new AndroidAudioIODeviceType();
  238460. }
  238461. #endif
  238462. /*** End of inlined file: juce_android_Audio.cpp ***/
  238463. /*** Start of inlined file: juce_android_CameraDevice.cpp ***/
  238464. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238465. // compiled on its own).
  238466. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  238467. // TODO
  238468. class AndroidCameraInternal
  238469. {
  238470. public:
  238471. AndroidCameraInternal()
  238472. {
  238473. }
  238474. ~AndroidCameraInternal()
  238475. {
  238476. }
  238477. private:
  238478. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidCameraInternal);
  238479. };
  238480. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  238481. : name (name_)
  238482. {
  238483. internal = new AndroidCameraInternal();
  238484. // TODO
  238485. }
  238486. CameraDevice::~CameraDevice()
  238487. {
  238488. stopRecording();
  238489. delete static_cast <AndroidCameraInternal*> (internal);
  238490. internal = 0;
  238491. }
  238492. Component* CameraDevice::createViewerComponent()
  238493. {
  238494. // TODO
  238495. return 0;
  238496. }
  238497. const String CameraDevice::getFileExtension()
  238498. {
  238499. return ".m4a"; // TODO correct?
  238500. }
  238501. void CameraDevice::startRecordingToFile (const File& file, int quality)
  238502. {
  238503. // TODO
  238504. }
  238505. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  238506. {
  238507. // TODO
  238508. return Time();
  238509. }
  238510. void CameraDevice::stopRecording()
  238511. {
  238512. // TODO
  238513. }
  238514. void CameraDevice::addListener (Listener* listenerToAdd)
  238515. {
  238516. // TODO
  238517. }
  238518. void CameraDevice::removeListener (Listener* listenerToRemove)
  238519. {
  238520. // TODO
  238521. }
  238522. const StringArray CameraDevice::getAvailableDevices()
  238523. {
  238524. StringArray devs;
  238525. // TODO
  238526. return devs;
  238527. }
  238528. CameraDevice* CameraDevice::openDevice (int index,
  238529. int minWidth, int minHeight,
  238530. int maxWidth, int maxHeight)
  238531. {
  238532. // TODO
  238533. return 0;
  238534. }
  238535. #endif
  238536. /*** End of inlined file: juce_android_CameraDevice.cpp ***/
  238537. END_JUCE_NAMESPACE
  238538. #endif
  238539. /*** End of inlined file: juce_android_NativeCode.cpp ***/
  238540. #endif
  238541. #endif